Sunday 22 February 2015

Chapter Three : Windows store app's lifecycle

 Know about Windows store app's lifecycle:


Before starting development of a windows store app,one must be familiar with the lifecycle of the app;Let’s begin to learn about various lifecycle states,trying to comprehend these states expatiation  in one place to learn in one go.
Hope you will have happy learning with my handouts :)

A metro style app is in one of 4 lifecycle states at any given time: not running, running, suspended or terminated.

All Metro style apps move through these states as users launch apps, switch among them, and close them. Your app will likely move between the running and suspended states quite often as users switch between apps. Event
From

To

Activated
not running
running
suspending or checkpoint
Running
suspended
Resuming
Suspended
running

There are two types of data for you to manage in app:

  • App data
  • Session data.

Step 1: Using SuspensionManager
SuspensionManager is a helper class that simplifies lifecycle management for the app. It does several things for you. It saves and restores the navigation state of the Frame that hosts the app pages.
SuspensionManager serializes the page state data and writes it to an XML file in your app's local storage.
To use SuspensionManager
Double-click App.xaml.csvb in Solution Explorer to open it.
In the OnLaunched method, call the SuspensionManager.RegisterFrame method to register the root Frame.
C#, VB

Add this code after the new Frame is created, as shown here.
C#,VB

if (rootFrame == null)
     {
 Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
HelloWorld.Common.SuspensionManager.RegisterFrame(rootFrame, "appFrame");



Step 2: Save the app's state
to the cloud in the background for you. You can also use the local settings app data container (LocalSettings), but you should only use it when you want to store machine-specific info.
Save persistent app data as often as it makes sense in your application. Here, you handle the TextBox.TextChanged event and save the user name as the user enters it.
To save app data:
Double-click MainPage.xaml in Solution Explorer to open it.
In Extensible Application Markup Language (XAML) or design view, select the nameInputTextBox that you added to MainPage.xaml.
In the Properties panel, click the Events button ().
Find the TextChanged event in the event list. In the text box for the event, type "NameInput_TextChanged" as the name of the function that handles the TextChanged event.
Press Enter. The event handler method is created and opened in the code editor so you can add code that's executed when the event occurs.
Add this code to the event handler in the code behind page. In the event handler, you save the nameInput text in roamingSettings.
C#,VB

Windows.Storage.ApplicationDataContainerroamingSettings =
Windows.Storage.ApplicationData.Current.RoamingSettings;
roamingSettings.Values["userName"] = nameInput.Text;

Press F5 to build and run the app. Your name is saved as you enter it into the text box.
Session data is temporary data that is relevant to the user’s current session in your app. A session ends when the user closes the app using the close gesture or Alt + F4, reboots the computer, or logs off the computer.
The App.xaml.cs/vb file contains a handler for the Application.Suspending event. This event handler gets called when Windows is about to suspend your app. This is your opportunity to save the state of the app in case it gets terminated.
To save the session state
Double-click App.xaml.csvb in Solution Explorer to open it.
In App.xaml.csvb, add the async keyword to the OnSuspending method signature.
For more info about asynchronous programming, see Quickstart: using the await operator for asynchronous programming.
In the OnSuspending method, call the SuspensionManager.SaveAsync method.
C#, VB
AwaitHelloWorld.Common.SuspensionManager.SaveAsync();
Calling SaveAsync saves the navigation state of the Frame and then gives your Page the opportunity to save its content.

Here's the full OnSuspending method with the updates made.
C#, VB
<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>

privateasyncvoidOnSuspending(object sender, SuspendingEventArgs e)
        {
var deferral = e.SuspendingOperation.GetDeferral();
TODO: Save application state and stop any background activity
awaitHelloWorld.Common.SuspensionManager.SaveAsync();
deferral.Complete();
        }

Double-click MainPage.xaml.csvb in Solution Explorer to open it.
In MainPage.xaml.csvb, add this code to the SaveState method to save the page state.
C#, VB
pageState["greetingOutputText"] = greetingOutput.Text;
The SuspensionManager class serializes and saves the pageState dictionary to an XML file. Data saved in pageState is saved only for this session. You save the greetingOutput text here.
Here's the full code of the SaveState method.
C#,VB
<summary>
 Preserves state associated with this page in case the application is suspended or the
 page is discarded from the navigation cache.  Values must conform to the serialization
 requirements of <see cref="SuspensionManager.SessionState">.
<summary>
<param name="pageState">An empty dictionary to be populated with serializable state.<param>

protectedoverridevoidSaveState(Dictionary<String, Object>pageState)
        {
pageState["greetingOutputText"] = greetingOutput.Text;

 The user name is already saved, so you don't need to save it here.
        }

Click Build>Build solution to make sure the app builds with no errors.
That's all you need to do to save your app's state before your app is terminated. Now you need to learn how to restore your app's state the next time the user launches the app.
Step 3: Restore the app's state
There are many different ways to activate an app Here we look at the Launch activation and the OnLaunched method.
C#,VB

Frame rootFrame = Window.Current.Contentas Frame;

If the window already contains a Frame, that indicates that the app is already initialized, so initializing the Frame is skipped.
If the app isn't initialized, the code creates a Frame to host the app pages. You register the Frame with the SuspensionManager. This is the code you added in Step 1.
When the previous execution state is Terminated it means that the last time the app ran, Windows successfully suspended the app and then terminated it. In that case, you need to restore the app's state.
C#, VB
 Do not repeat app initialization when the Window already has content,
 just ensure that the window is active
if (rootFrame == null)
            {
 //Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
HelloWorld.Common.SuspensionManager.RegisterFrame(rootFrame, "appFrame");

if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
TODO: Load state from previously suspended application
                }

 //Place the frame in the current Window
Window.Current.Content = rootFrame;

Next, the code checks if the Frame contains any content. If the app is already running, or the navigation state was restored, the Frame already has content. Otherwise, the Frame navigates to the first page in the app. In this case, it navigates to MainPage.
C#, VB

if (rootFrame.Content == null)
            {
 //When the navigation stack isn't restored navigate to the first page,
 configuring the new page by passing required information as a navigation
 parameter
if (!rootFrame.Navigate(typeof(MainPage), args.Arguments))
                {
thrownew Exception("Failed to create initial page");
                }
            }


C#, VB

// Ensure the current window is active
Window.Current.Activate();


Now that you know what happens when the app is launched, let's look at how to restore the app state.
To restore the app's state
In App.xaml.csvb, add the async keyword to the OnLaunched method signature.
C#, VB
protectedasyncoverridevoidOnLaunched(LaunchActivatedEventArgsargs)

If the app was terminated, call the SuspensionManager.RestoreAsync method.
Calling RestoreAsync restores the navigation state of the Frame and then gives the Page the opportunity to restore its content.
C#, VB
if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
            {
TODO: Load state from previously suspended application

awaitHelloWorld.Common.SuspensionManager.RestoreAsync();
            }

In MainPage.xaml.csvb, add code to the LoadState method to restore the page state.
First, check to see if the pageState dictionary exists and has a key named greetingOutputText. If the key exists, use it to restore the greetingOutput text.


C#,VB

 Restore values stored in session state.
if (pageState != null&&pageState.ContainsKey("greetingOutputText"))
 {
greetingOutput.Text = pageState["greetingOutputText"].ToString();
 }
Next, load the user name. Because you want the user name data to persist over multiple sessions, you store it in the RoamingSettings app data container. Let's add some code to see whether the user name exists and, if it does, display it.
C#, VB
 Restore values stored in app data.
Windows.Storage.ApplicationDataContainerroamingSettings = Windows.Storage.ApplicationData.Current.RoamingSettings;
if (roamingSettings.Values.ContainsKey("userName"))
 {
nameInput.Text = roamingSettings.Values["userName"].ToString();
            }
C#,VB
<summary>
Populates the page with content passed during navigation.  Any saved state is also
 provided when recreating a page from a prior session.
<summary>
<param name="navigationParameter">The parameter value passed to
<see cref="Frame.Navigate(Type, Object)"> when this page was initially requested.
<param>
<param name="pageState">A dictionary of state preserved by this page during an earlier
 session.  This will be null the first time a page is visited.<param>

protectedoverridevoidLoadState(Object navigationParameter, Dictionary<String, Object>pageState)
        {
 Restore values stored in session state.
if (pageState != null&&pageState.ContainsKey("greetingOutputText"))
            {
greetingOutput.Text = pageState["greetingOutputText"].ToString();
            }

 Restore values stored in app data.
Windows.Storage.ApplicationDataContainerroamingSettings =
Windows.Storage.ApplicationData.Current.RoamingSettings;
if (roamingSettings.Values.ContainsKey("userName"))
            {
nameInput.Text = roamingSettings.Values["userName"].ToString();
            }
        }

To simulate suspending, terminating, and restoring an app in Visual Studio
Press F5 to run the app in debug mode.
Enter your name in the input box and click "Say "Hello"". The greeting is displayed.
Press Alt+Tab to return to Visual Studio.
Open the drop down menu next to the Suspend button on the Debug Location toolbar.
The Debug Location toolbar appears by default while the debugger is running. If you don't see it, click View>Toolbars>Debug Location to show it.

Select Suspend and shutdown.
Visual Studio simulates suspending and terminating your app, so the Suspending event occurs and your state management code is executed.
Press F5 to run the app again. The app is restored to its previous state.
Change the name in the text box, and click "Say "Hello"".
Press Alt+Tab to return to Visual Studio.
Close the app by selecting Debug>Stop Debugging.
Press F5 to run the app again.



By:
Khushbu Wadhwani,
Senior Windows app developer,
References:MSDN,Microsoft developer forum

No comments:

Post a Comment