The Programming Model

Just like other Visual Studio development scenarios, application architecture for the Windows Phone platform consists of three major components:

Image Events, application user interfaces (APIs), UI elements, and code models exposed by the operating system

Image The runtime libraries for implementing functionality

Image Logic, custom code, and UI elements that you write (in other words, your app)

All those components are running on top of the operating system kernel itself (see Figure 24.4).

Image

FIGURE 24.4 Windows Phone architecture.

For Phone apps, there are two different runtimes that you can choose if you want to focus on managed code, XAML applications: the Silverlight framework or the Windows Runtime Library (WinRT). For either, you have the traditional C# and Visual Basic language options.

We focus this chapter on C#/XAML applications built using WinRT. Silverlight was the only framework option available for .NET developers with Windows Phone 7 through Windows Phone 7.5 and will be familiar to developers who have prior exposure to those platforms. However, WinRT is the roadmap focus for device development going forward given its cross-platform nature (Windows 8 and Windows Phone 8). This is also a crucial change point if you want to write Universal apps (applications that are capable of running on either Windows or Windows Phone).


Note

Silverlight started life as a modernized version of the Windows Presentation Framework, specifically designed for rich Internet application development. As a sort of WPF “light,” it was an ideal development framework for Windows Phone, which required extensive capabilities (including immersive UI elements) all while running in a resource-constrained device environment. WinRT is coming from the opposite direction: it was first delivered as a core component of Windows 8 and is now moving downstream to Windows Phone and other devices such as HoloLens.


Applications that target the Windows Phone runtime have unique attributes and a unique structure.

Application Anatomy

Windows Phone applications, just like a website, consist of one or more pages. Each of these pages (which are physically instances of System.Windows.Controls.Page) will have a XAML file and a code-behind file. They all run within the context of a “frame” (an instance of System.Windows.Controls.Frame). This is analogous to a web browser: it provides the system tray and application bar regions, and it displays the application page and page content (see Figure 24.5).

Image

FIGURE 24.5 An application’s frame, page, and page content areas.

Page Navigation

Users (or logic within your app) can navigate forward and backward through the pages of the app. As navigation happens, a stack of pages (called the back stack) is built up, in just the same way that your web browser maintains history when you browse the web. Clicking the Back button (a Back button is required on all Windows Phone devices) will cause the Windows Phone runtime to page back through that stack of pages.

As discussed in Chapter 23, you can also programmatically navigate between pages by using the Navigate method on the Frame class. For example, consider an application that helps you to file expense reports. The application may allow you to navigate from the main list of expense reports directly to a page that allows you to input notes. In this case, we might want to wire up the click event of a button to load that next page like this:

private void ButtonEditNotes_Click(object sender, RoutedEventArgs e)
{
    this.Frame.Navigate(typeof(ReportDetailPage));
}

You can also pass data between pages using an alternate form of the Navigate method. By supplying an object as a second parameter into Navigate, the target page can retrieve that object and act on it. We saw this in action with our sample Windows Store application from the previous chapter: selecting an image on the main page caused that image to be loaded onto a detail page. The image itself was passed as an object using the following code.

this.Frame.Navigate(typeof(ImagePage), image);

If we needed to pass a collection of objects, we would simply add those objects to a container collection object. (Any will do: List, Collection, Array, and so on.)

In the destination page, the passed object is available in the OnNavigatedTo. Retrieving it is as simple as pulling it from the NavigationEventArgs object.

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);

    //Retrieve the passed-in object, and cast as necessary.
    var myObject = e.Parameter as MyObject;
}

App Lifecycle

WinRT applications on the phone participate in the same, common lifecycle of WinRT Windows applications (Chapter 23); at any time, a Windows Phone application will be in one of three different states: Activated, Suspended, or Not Running:

Image Activated—The application is currently executing, although it may be idle.

Image Suspended—Applications reach this state when they are deactivated. This could happen as the result of many different actions. For example, the user may navigate out of the application. Suspended apps aren’t executing code, but they are still loaded into memory and can thus be quickly reactivated.

Image Not Running—Applications that have been terminated completely are, of course, not running.

Events are defined on the Windows.UI.Xaml.Application class (in other words, the App.Xaml and App.Xaml.cs code files) that correspond to these state changes. See Figure 24.6 for a visual map of the various states and the events that correspond to the state transitions.

Image

FIGURE 24.6 Application lifecycle and Application events.


Note

If you look at Figure 24.6, you will notice that there isn’t an event associated with the application moving to the Not Running state. The operating system will not notify your application that it is being terminated. This means that you have to take care of all state persistence when the application is suspended. In other words, you have to react as if the application is actually being terminated every time it is suspended because you have no control over that state transition.


Understanding the lifecycle is important because you will need to react to changes between states within your code. It is also important to recognize that you, the developer, are not in control of when your application moves between these states. The Windows Phone OS itself may choose to suspend or terminate an application based on memory conditions or other application activity. One simple example of this is the OS taking control and suspending the currently running app when a phone call comes in.

Reacting to State Change Events

Defensive programming is in order here. You need to know when these various state transitions happen; this, again, is a topic we covered in Chapter 23. The Windows Phone environment exposes the same set of state change events in App.Xaml.cs. The Suspending event handlers are connected for you by default within the App constructor, and you have to manually add the handler for Resuming.

public App()
{
    this.InitializeComponent();
    this.Suspending += OnSuspending;
    this.Resuming += OnResuming;
}

Note that the Resuming event handler is stubbed out with an exception that you must replace by your own implementation.

void OnResuming(object sender, object e)
{
    throw new NotImplementedException();
}

/// <summary>
/// Invoked when the application is launched normally by the end user.
/// </summary>
/// <param name="args">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs args)
{
}

/// <summary>
/// Invoked when application execution is being suspended.  Application state is
/// saved without knowing whether the application will be terminated or resumed
/// with the contents of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
    var deferral = e.SuspendingOperation.GetDeferral();
    //TODO: Save application state and stop any background activity
    deferral.Complete();
}


Note

As a reminder: keep in mind that the two different frameworks, Silverlight and WinRT, will have different lifecycles, APIs, events, and more. We are explicitly covering WinRT in this chapter.


Suspended Versus Terminated

If an application is put into the Suspended state and then reactivated, all of the objects that were previously loaded in memory will be automatically restored for you. There is no need to explicitly save any of their state information. There will be exceptions, however, where you need to do some extra lifting here. For example, you may have had a network connection open to a resource somewhere, and that network connection may have timed out during the period in which the app was dormant. Your reactivation code (for example, code within OnResuming) should try to correct this scenario before making assumptions about that network connection.

If an application is terminated, it is officially unloaded from memory. If the application is reactivated, you need to explicitly repopulate your app’s state (including navigation position). Clearly, this implies the need to “save state” at various points within an application’s life time to be able to restore it.

Application State and the Model-View-ViewModel Pattern

Windows Phone applications deal with both transient data (control state and “work in progress” un-saved data) and data that is meant to be persisted long term. Applications need to implement their own logic to save both types of data.

How and when to save transient data and persistent data is tightly reliant on the lifecycle events that we just discussed. Your app will need to be smart enough to store transient data along the way. If we have a list of string entries within our application, for example, we would want to save the state (contents) of that list when the app is suspended. In a similar fashion, when we move between pages, we want to save the transient data that might be represented within the page. For example, users will expect the contents of a text box that they just typed in to still be there if they navigate away from, and then back to, a page in your application. We also need to write persistent data so that the next time the app is launched, it will read in the prior saved data.

There is an architecture pattern that helps significantly with application data loading, saving, and binding: the Model-View-ViewModel (MVVM) pattern. MVVM is a terrific pattern for binding data within application pages and centralizing an application’s state so that it can be easily persisted and loaded. MVVM, as its name implies, consists of three different (but related) constructs:

Image Model—This represents a data entity used within an application. For an expense report application, one of the models would likely be an expense report. There is generally no logic contained within a model, and it is sometimes best implemented as a simple class with some properties.

Image View—This is the user interface for the application; for Windows Phone applications, this is manifested as the page .xaml files that define the various UI control elements on each page.

Image ViewModel—This is the glue that holds everything together in the MVVM architecture. Code within the ViewModel is responsible for handling events, performing data binding, encapsulating any business logic in the app, and encapsulating our Models.

MVVM (see Figure 24.7) is relevant to the state discussion with Windows Phone because it allows us to wrap up all the data entities that our app cares about (in other words, all the Models) into a single ViewModel. We can then load/save that single ViewModel in reaction to the various lifecycle events.

Image

FIGURE 24.7 The Model-View-ViewModel architecture.

We’ll pull all this together in a bit when we build our first sample application.


Note

Although its core concepts are simple, it can take some active development time with MVVM before you fully understand its moving parts. It’s beyond the scope of this chapter to furnish a full and in-depth treatment of MVVM, although it is core to Windows Phone—and XAML/WinRT development—in general. We recommend that you watch the brief video “Practical MVVM for Windows Phone” available on the Microsoft Channel 9 website (channel9.msdn.com).


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset