Monthly Archives: December 2011

EvenTiles from Start to Finish–Part 11

In the previous episode of this series about how to develop a Windows Phone application from scratch we started talking about using a PeriodicTask to perform background processing for our application. You learned how to create a Windows Phone Scheduled Task Agent, a separate project that became part of the EvenTiles solution to host a PeriodicTask. You also learned how the PeriodicTask relates to the EvenTiles to enable background processing for the application. In this episode of EvenTiles we will take a look at how to debug the PeriodicTask.

When you have added a PeriodicTask to your application you may have noticed that the behavior of Visual Studio’s debugger did change. Instead of detaching the debugger if you terminate the application, the debugger remains attached. This allows you to debug the PeriodicTask when the application is no longer executing. This is of course important because typically the PeriodicTask executes without our application being active. Under normal circumstances, a PeriodicTask will run once every 30 minutes for a few seconds. This schedule can not be changed for released applications and is determined by the operating system. Of course debugging a PeriodicTask would be unproductive in this way. Therefore there is a possibility to run your PeriodicTask more frequent under test.

If you take a look at the ScheduledActionService class, you will see that it contains a static method called LaunchForTest. This method allows you to schedule a Periodic Task to run at the time you specify. Since you will only use this method for testing Periodic Tasks, draining the battery by frequently executing code in the background is not really an issue. However, you will must not forget to remove the call to LaunchForTest in your production code. You can for instance do this by making use of conditional compilation. What I like to do is to define a separate symbol (to be used in combination with DEBUG) to control execution of LaunchForTest. Usually in Debug mode you want to test your Periodic Task frequently, but by defining a separate symbol, you can also easily disable calling LaunchForTest, even in Debug mode. The following code fragment defines the DEBUG_TASK constant:

Conditionally defined constant
  1. #if DEBUG
  2. #define DEBUG_TASK
  3. #endif

Since this constant is not defined in Release mode, you don’t have to worry about accidentally adding a call to LaunchForTest in your released application. If you want to test your Periodic Agent with a normal schedule in Debug mode, you can simply change the name of the constant, for instance into NDEBUG_TASK. To make sure that the Periodic Agent will be called more frequent then usual, you can make use of the following code (inside the #if and #endif directives):

Calling Periodic Agent faster
  1. private void StartPeriodicAgent()
  2. {
  3.     RemovePeriodicAgent();
  4.  
  5.     evenTilesPeriodicTask = new PeriodicTask(evenTilesPeriodicTaskName);
  6.     evenTilesPeriodicTask.Description = "EvenTilesPeriodicTask";
  7.  
  8.     try
  9.     {
  10.         ScheduledActionService.Add(evenTilesPeriodicTask);
  11. #if DEBUG_TASK
  12.         ScheduledActionService.LaunchForTest(evenTilesPeriodicTaskName, TimeSpan.FromSeconds(30));
  13. #endif
  14.     }
  15.     catch (InvalidOperationException ex)
  16.     {
  17.         if (ex.Message.Contains("BNS Error: The action is disabled"))
  18.         {
  19.             MessageBox.Show("Background agents for this application are disabled.");
  20.         }
  21.     }
  22. }

As a result, the Periodic Task will now be executed approximately 30 seconds after this statement is executed. After that, the Periodic Task will execute on its normal 30 minute schedule, unless you add the call to LaunchForTest in the DoInvoke method of the Periodic Task as well:

Relaunching Periodic Agent
  1. protected override void OnInvoke(ScheduledTask task)
  2. {
  3.     //TODO: Add code to perform your task in background
  4.  
  5. #if DEBUG_TASK
  6.     ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(30));
  7. #endif
  8.  
  9.     NotifyComplete();
  10. }

The following video shows you how to use the LaunchForTest method inside the EvenTiles application and how to make use of the Visual Studio debugger to test the Periodic Agent:

Debugging a Windows Phone Application’s PeriodicTask using LaunchForTest.

Of course the functionality of the Periodic Agent is still to be determined. In part 12 of EvenTiles we will work on adding functionality for the Periodic Agent.

EvenTiles from Start to Finish–Part 10

In the previous episode of this series about how to develop a Windows Phone application from scratch we talked about creating a Secondary Tile programmatically inside our application and showing different content on both the front and the back of the Secondary Tile.

This time we will introduce the concept of Background Agents for Windows Phone. A Background Agent is a piece of application code that can execute, even when the application is not running. Background Agents can be used to periodically perform some actions. Depending on the type of action and the type of scheduling, Background Agents can be of type PeriodicTask (which runs regularly for short amounts of time) or of type ResourceIntensiveTask (which runs for a longer amount of time, but not on a regular interval). Each application can have at most one PeriodicTask and one ResourceIntensiveTask. There are restrictions in using both PeriodicTask and ResourceIntensiveTask. One of the more important things to keep in mind is that a PeriodicTask will run approximately every 30 minutes for at most a couple of seconds, and it will continue running roughly twice an hour for 14 days in a row (assuming the PeriodicTask does not crash). If the application has not renewed the PeriodicTask within those 14 days, the PeriodicTask will be removed from the schedule. Thinking about it, that makes sense. If a user is not using your application for such a long time, it is probably not necessary to continue executing code for that application in the background.

For EvenTiles we will make use of a PeriodicTask, to allow updating of our Secondary Tile on a regular interval. Since updating the Secondary Tile is a relatively simple action, this is a perfect candidate for a PeriodicTask. In this way we can bring our Secondary Tile to life (after all, things will change to it on the start screen of the user’s phone), regardless of the execution state of our application. This technique can for instance be used to update weather information, or number of newly available emails to simply keep the user informed. In our sample application, we will use a PeriodicTask to simply display different strings on the back of the Secondary Tile. The reason to chose something so simple is to be able to concentrate on the bare functionality of the PeriodicTask, its relation to the application and ways to exchange data between the application and its Periodic Task.

To make use of a PeriodicTask, we need to add a new project to our solution. Visual Studio already contains a template for a Windows Phone Scheduled Task Agent, as shown in the next figure:

image

In the newly created PeriodicTask you will find a method called OnInvoke. That is the method into which you will add the functionality you like to have executed in the background. It is important to call the NotifyComplete method as last statement inside your OnInvoke method. Each time your code executes, it will execute in a separate thread. Since the PeriodicTask runs independent from the application (once the application has started the PeriodicTask), it can not update the User Interface of the application it belongs to.

To be able to start the PeriodicTask from inside your application, the first thing you will do is add a reference to the PeriodicTask in your application’s project:

image

When you have added the reference to the PeriodicTask, you have effectively made a connection between it and the application. This is visible inside the WPAppManifest.xml file:

PeriodicTask in Manifest
  1. <Tasks>
  2.   <DefaultTask Name="_default" NavigationPage="MainPage.xaml" />
  3.   <ExtendedTask Name="BackgroundTask">
  4.     <BackgroundServiceAgent Specifier="ScheduledTaskAgent"
  5.                             Name="EvenTilesScheduledTaskAgent"
  6.                             Source="EvenTilesScheduledTaskAgent"
  7.                             Type="EvenTilesScheduledTaskAgent.ScheduledAgent" />
  8.   </ExtendedTask>
  9. </Tasks>

The next thing that needs to be done is starting the PeriodicTask from inside the application. Of course it is good practice to keep the user in control, so we are going to create the PeriodicTask as a result of a user action. In episode 9 of EvenTiles we added a button to the MainPage to create a Secondary Tile. Since we want this Secondary Tile to change its backside text regularly (even without the application being active), it makes sense to create the PeriodicTask as part of the same Click event handler. The code to create and to remove the PeriodicTask looks like this:

Create and Remove PeriodicTask
  1. private void StartPeriodicAgent()
  2. {
  3.     RemovePeriodicAgent();
  4.  
  5.     evenTilesPeriodicTask = new PeriodicTask(evenTilesPeriodicTaskName);
  6.     evenTilesPeriodicTask.Description = "EvenTilesPeriodicTask";
  7.  
  8.     try
  9.     {
  10.         ScheduledActionService.Add(evenTilesPeriodicTask);
  11.     }
  12.     catch (InvalidOperationException ex)
  13.     {
  14.         if (ex.Message.Contains("BNS Error: The action is disabled"))
  15.         {
  16.             MessageBox.Show("Background agents for this application are disabled.");
  17.         }
  18.     }
  19. }
  20.  
  21. private void RemovePeriodicAgent()
  22. {
  23.     var runningPeriodicTask = ScheduledActionService.Find(evenTilesPeriodicTaskName) as PeriodicTask;
  24.     if (runningPeriodicTask != null)
  25.     {
  26.         ScheduledActionService.Remove(evenTilesPeriodicTaskName);
  27.     }
  28. }

Note how we make use of ExceptionHandling to catch an InvalidOperationException. This exception will typically be thrown if the user has disabled background processing for our application, which they can do from inside the Phone Settings. The following picture shows how the user can enable / disable background processing for our application:

image

Calling the methods to create / remove our PeriodicTask from inside our Click event handler is of course a simple action, although you should note that we create the PeriodicTask before creating a Secondary Tile. The reason for that is to allow the PeriodicTask to display a MessageBox to the user in case of problems. By first creating the Secondary Tile we force our application to immediately go to the background, and with that, not being able to show the MessageBox to the user.

Starting/Stopping Agent
  1. private void btnInstall_Click(object sender, RoutedEventArgs e)
  2. {
  3.     if (secondaryTileInstalled)
  4.     {
  5.         var secondaryTile = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.ToString().Contains("TileId=Secondary"));
  6.         if (secondaryTile != null)
  7.         {
  8.             RemovePeriodicAgent();
  9.             secondaryTile.Delete();
  10.             btnInstall.Content = txtInstallTile;
  11.             secondaryTileInstalled = false;
  12.         }
  13.     }
  14.     else
  15.     {
  16.         StartPeriodicAgent();
  17.         StandardTileData NewTileData = new StandardTileData
  18.         {
  19.             BackgroundImage = new Uri("Background.png", UriKind.Relative),
  20.             Title = "EvenTiles",
  21.             Count = 0,
  22.             BackBackgroundImage = new Uri("BackBackTile.png", UriKind.Relative),
  23.             BackTitle = "EvenTiles",
  24.             BackContent = App.ActualSecBackContent
  25.         };
  26.         ShellTile.Create(new Uri("/MainPage.xaml?TileId=Secondary", UriKind.Relative), NewTileData);
  27.     }
  28. }

Since we did not add functionality to our PeriodicTask, it will wake up every 30 minutes to immediately terminate again, because the only thing we are doing inside the PeriodicTask’s OnInvoke method is calling the NotifyComplete method:

An ‘Empty’ PeriodicTask
  1. protected override void OnInvoke(ScheduledTask task)
  2. {
  3.     //TODO: Add code to perform your task in background
  4.     NotifyComplete();
  5. }

I strongly encourage you to take a look at the following video, that shows all the functionality we have so far in action:

PeriodicTask for Background Processing inside a Windows Phone Application

One thing is annoying in our solution so far. If we want to debug our PeriodicTask, we would have to wait 30 minutes each time until code in the PeriodicTask will be executed. How to overcome this problem will be topic of part 11 of our ongoing series around EvenTiles.

EvenTiles from Start to Finish–Part 9

In the previous episode of this series about how to develop a Windows Phone application from scratch we talked about restoring the entire page state after the application returns from the background. Today we finally are going to add a Secondary Tile to our application.

Each application has at least one tile, the Application Tile, which end users can pin to the start screen on their phone. In the very first episode of this series we defined the contents for the backside of the Application Tile in the manifest file of our application. Each application can also create one or more Secondary Tiles. Once a Secondary Tile is created programmatically, it will immediately be pinned to the start screen. Secondary Tiles can be removed again programmatically, but the end user can also remove Secondary Tiles from the start screen of their phone.

To add a Secondary Tile to the start screen, our application’s MainPage will host a button. When the user clicks the button, a new Secondary Tile is created. After creation, our application is moved to the background by the operating system in order to show the start screen with our newly created secondary tile, that is initialized in such a way that it contains both a front- and backside.

image

You can see the Secondary Tile being pinned on the start screen. You can also see that the Secondary Tile has two different sides, each with their own image and the backside containing an additional string, the string that the user can enter in the SettingsPage of the application. If the user returns to the application when the Secondary Tile is installed, they have the possibility to remove the Secondary Tile again from the start screen programmatically.

To find out if our Secondary Tile is currently visible on the start screen of the phone, we just check if it is defined in our application’s collection of tiles. This collection of ActiveTiles always contains at least the Application Tile and optionally all Secondary Tiles that were created in the application. When we are navigating to the MainPage of the application, we can find out if our Secondary Tile is available by executing the following code:

Secondary Tile Active?
  1. protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
  2. {
  3.     base.OnNavigatedTo(e);
  4.  
  5.     secondaryTileInstalled = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.ToString().Contains("TileId=Secondary")) != null;
  6.     btnInstall.Content = secondaryTileInstalled ? txtRemoveTile : txtInstallTile;
  7. }

In this code snippet, we use a lambda expression on the static collection of ActiveTiles to find the first tile that contains the following string in its Uri: TileId=Secondary. The Application Tile does not contain this additional information, so if we find a tile with this string being part of its Uri, we can safely assume that this is our Secondary Tile. In that case, we set a boolean variable to true. Depending on the presence or absence of a Secondary Tile we also modify the Content property of the button. Of course we also need to create / delete the Secondary Tile, which is something that we will do inside the Click event handler of the button we created on the MainPage:

Creating / Deleting Sec. Tiles
  1. private void btnInstall_Click(object sender, RoutedEventArgs e)
  2. {
  3.     if (secondaryTileInstalled)
  4.     {
  5.         var secondaryTile = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.ToString().Contains("TileId=Secondary"));
  6.         if (secondaryTile != null)
  7.         {
  8.             secondaryTile.Delete();
  9.             btnInstall.Content = txtInstallTile;
  10.             secondaryTileInstalled = false;
  11.         }
  12.     }
  13.     else
  14.     {
  15.         StandardTileData newTileData = new StandardTileData
  16.         {
  17.             BackgroundImage = new Uri("Background.png", UriKind.Relative),
  18.             Title = "EvenTiles",
  19.             Count = 0,
  20.             BackBackgroundImage = new Uri("Backbackground.png", UriKind.Relative),
  21.             BackTitle = "EvenTiles",
  22.             BackContent = App.ActualSecBackContent
  23.         };
  24.         ShellTile.Create(new Uri("/MainPage.xaml?TileId=Secondary", UriKind.Relative), newTileData);
  25.     }
  26. }

In the above code snippet the first thing we do is verify if a Secondary Tile is installed. If so, we simply call the Delete method on it to remove it from the start screen on the phone. As visual feedback to the user, we immediately change the content property of the button to show a string to add another Secondary Tile. If we don’t have a Secondary Tile, what we are going to do is create and initialize a new instance of StandardTileData. Through its properties, this object will hold the complete characteristics of our new Secondary Tile. To create the Secondary Tile, we simply call the static Create method of the ShellTile class, passing a navigation string, indicating to which page we should go in our application when the user clicks the Secondary Tile. In this way, you can use Secondary Tiles to link to any page inside your application. You can also pass your own parameters to the navigation URI, which can help you take different actions if a page is invoked from a Secondary Tile. Together with the navigation URI, you also pass the StandardTileData to create the Secondary Tile. Immediately after calling the ShellTile.Create method, our application is moved to the background by the operating system and the start screen with our newly created Secondary Tile becomes visible. If you click on the phone’s back button, our application returns to the foreground (from either a tombstoning or dormant state). On the other hand, if the user clicks on the Secondary Tile, a new instance of our application is started and the instance of our application that was still available in the background is removed. This behavior implies that we don’t have to modify the text of the button in case of creating a live tile, because OnNavigatedTo will always execute before our MainPage becomes visible again.

The following video shows step-by-step how to create and delete Secondary Tiles programmatically. It also shows our Secondary Tile in action. Of course, this sample application is very simple, but hopefully you can see the potential, not only for having Live Tiles available for an application, but also to make use of Secondary Tiles to allow the user to immediately navigate to a particular page of your application.

Creating and Deleting Secondary Tiles Programmatically

If you want to take a look at the source code that we have available for EvenTiles so far, you can download the entire solution belonging to this episode:

Download EvenTiles Episode 9 Source Code

After downloading and unzipping the sample code, you can open the EvenTiles solution in Visual Studio 2010 Express for Windows Phone. You must have the Windows Phone SDK 7.1 installed on your development system to do so. If you have a developer unlocked phone you can deploy the application to your phone, if you don’t have a developer unlocked phone you can still experiment with this application inside the emulator.

In the next episode of EvenTiles we will introduce a more advanced topic when we are beginning to talk about making use of a background agent to allow our application to execute some code, even when it is not in the foreground.

EvenTiles from Start to Finish–Part 8

In the previous episode of this series about how to develop a Windows Phone application from scratch we talked about Fast Application Switching and Tombstoning. We saw how Visual Studio 2010 can help us testing Tombstoning scenarios. We also covered how to preserve application data when the application is interrupted by other applications and how to restore that data when returning to the foreground.

Right now we will extend our knowledge about Fast Application Switching and Tombstoning by trying to exactly restore a page after the application returns from the background. For that, we will take a look at the following scenario.

imageThe user is entering data in the textbox inside the SettingsPage. This means that a keyboard is visible and that the textbox has input focus and a blinking cursor at the location where data is entered. Sometime in the middle of entering text, the user hits the start button to activate another application, to return to our application only after a while. Even though we have stored all data the user entered (because we are saving the contents of the textbox when navigating away from the SettingsPage), the text box does not have focus when the user returns to the SettingsPage, nor a cursor positioned at the right location. In order to restore the exact same situation, we need to store additional data when navigating away from the SettingsPage. This leads to another challenge. To store the local page state when we are navigating away from the SettingsPage we can use the following code:

Saving the Page State
  1. protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
  2. {
  3.     if (!e.IsNavigationInitiator)
  4.     {
  5.         TextBox tb = FocusManager.GetFocusedElement() as TextBox;
  6.  
  7.         if (tb != null)
  8.         {
  9.             this.State[keySelectionLength] = tb.SelectionLength;
  10.             this.State[keySelectionStart] = tb.SelectionStart;
  11.         }
  12.     }
  13.     App.ActualSecBackContent = tbBackContent.Text;
  14.     base.OnNavigatedFrom(e);
  15. }

Each time OnNavigatedFrom is called, there is a possibility that the application is moved to the background. If so, the property IsNavigationInitiator is false. If the application is moved to the background, we check if the textbox currently has focus. If so, we will store the location of the cursor by adding entries for both the SelectionStart (location where the cursor is) and SelectionLength. If on the other hand the textbox does not have focus, we don’t have to store page state information, just the Text property of the textbox.

Retrieving page state information back can be done in the OnNavigatedTo method as follows:

Restore the Page State
  1. protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
  2. {
  3.     tbBackContent.Text = App.ActualSecBackContent;
  4.     btnRestore.Visibility = tbBackContent.Text.Equals(App.DefaultSecBackContent) ?
  5.         System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible;
  6.  
  7.     if (this.State.ContainsKey(keySelectionLength))
  8.     {
  9.         tbBackContent.SelectionLength = (int)this.State[keySelectionLength];
  10.         tbBackContent.SelectionStart = (int)this.State[keySelectionStart];
  11.         focusToTextBox = true;
  12.     }
  13.     base.OnNavigatedTo(e);
  14. }

However, it is not possible to get the focus back to the textbox control in the OnNavigatedTo method, because the different UI elements are not yet initialized when OnNavigatedTo is called. That is the reason to set a boolean variable to true and actually give the textbox focus when the Loaded event on the page is fired. If the application is returning from the background and focusToTextBox is set to true, the tbBackContent textbox will get focus:

Restore textbox input focus
  1. private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
  2. {
  3.     if (focusToTextBox)
  4.     {
  5.         tbBackContent.Focus();
  6.     }
  7. }

If an application would always be tombstoned, this would be sufficient to store / restore state information for the page and to restore the input focus if the textbox had focus when the application was put in the background. However, with Windows Phone Mango, applications can benefit from the Dormant state, where they stay in memory even though being in the background. There is not really a clear distinction from a developer’s point of view between Dormant and Tombstoned, except for the fact that in case of returning from being Tombstoned, the page constructor is executed, something that is not the case when the application returns from Dormant since the application was still in memory. As a consequence, returning from the Dormant state also means that the Loaded event on the page is not fired. So, even though returning to the foreground is faster if we were in the Dormant state, we need some additional logic to give the textbox focus in this case. In order to distinguish between Dormant and Tombstoned, it is possible to set a boolean variable in the constructor of a page to true and check that variable in the OnNavigatedTo method:

Dormant vs Tombstoned
  1. private bool focusToTextBox;
  2. private bool pageConstructed;
  3.  
  4. public SettingsPage()
  5. {
  6.     InitializeComponent();
  7.     pageConstructed = true;
  8. }

The value of the pageConstructed variable determines if we are returning from a Dormant state to the foreground (false) or not. If we are not returning from a Dormant state, we need to determine in OnNavigatedTo if we returned from a Tombstoned state in order to optionally set the focus to the textbox. However, if we are returning from a Dormant situation, the OnNavigatedTo method itself must be used to set focus to the textbox if needed. The modified OnNavigatedTo method looks like this:

Complete Page Reconstruction
  1. protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
  2. {
  3.     tbBackContent.Text = App.ActualSecBackContent;
  4.     btnRestore.Visibility = tbBackContent.Text.Equals(App.DefaultSecBackContent) ?
  5.         System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible;
  6.  
  7.     if (this.State.ContainsKey(keySelectionLength))
  8.     {
  9.         tbBackContent.SelectionLength = (int)this.State[keySelectionLength];
  10.         tbBackContent.SelectionStart = (int)this.State[keySelectionStart];
  11.         if (!pageConstructed)
  12.         {
  13.             tbBackContent.Focus();
  14.         }
  15.         else
  16.         {
  17.             focusToTextBox = true;
  18.         }
  19.     }
  20.     base.OnNavigatedTo(e);
  21. }

The following video shows how to save and restore the page state for the SettingsPage of EvenTiles for the different application execution states:

Saving Page State and restoring Textbox Focus

Update after video creation: Even though it seems in the video that the application is working properly both when returning from Dormant and from Tombstoning states, this is not entirely the case. Even though the focus of the Textbox is restored properly when needed, the Textbox will also get focus each and every time we return from the background, with the exception of the first time. The reason for that is that the dictionary entries in the Page.State collection were not deleted after usages in the OnNavigatedTo method. The source code for EvenTiles contains a fix for this undocumented application feature.

If you want to take a look at the source code that we have available for EvenTiles so far, you can download the entire solution belonging to this episode:

Download EvenTiles Episode 8 Source Code

After downloading and unzipping the sample code, you can open the EvenTiles solution in Visual Studio 2010 Express for Windows Phone. You must have the Windows Phone SDK 7.1 installed on your development system to do so. If you have a developer unlocked phone you can deploy the application to your phone, if you don’t have a developer unlocked phone you can still experiment with this application inside the emulator.

In the next episode of EvenTiles we will finally get to the heart and soul of the application, when we are going to create a Secondary Tile.

EvenTiles from Start to Finish–Part 7

In the previous episode of this series about how to develop a Windows Phone application from scratch we used the Isolated Storage Explorer Tool to take a look at the contents of the ApplicationSettings, stored in IsolatedStorage on the device or emulator. This time we continue dealing with our application settings, because we are going to talk about Fast Application Switching and Tombstoning.

As you probably know, only one application can be running in the foreground on a Windows Phone. That application can use as much resources as it needs and should be as responsive as possible to give end users a great experience. Typically, users switch often between applications. They might not even think about different applications, because they are most likely very task oriented. To give end users the best experience, our applications share a responsibility with other applications and with the operating system.

If our application is currently running in the foreground, there are two important reasons for our application to stop running in the foreground:

  1. The user terminates our application by pressing the Back Key on the phone until the entire back stack of pages for our application is empty.
  2. Our application is interrupted because some sort of an event occurred.

The first situation is simple. When our application is terminating, it is our responsibility to store information that we want to persist until the next time our application is running. This is what we did for EvenTiles in part 5 of the series, using the Application_Launching and Application_Closing methods that are defined in the App.xaml.cs file.

NOTE: The description of Fast Application Switching and Tombstoning in this article is valid for Windows Phone Mango, not for previous versions of the operating system.

The following picture shows our application running over time. The user navigated to the SettingsPage on EvenTiles, modified the string value and decided to use the Start Key on the phone to start another application. After a while, the user returns to our application by pressing the Back Key until our SettingsPage is visible again.

image

For the user, this experience is great, because when they come back to our application, it shows up exactly as it was when they moved our application to the background. The operating system simply keeps our application in memory. There are some restrictions with regards to applications using certain resources like the camera. To keep our story lean and mean we will omit those. When the user starts many applications (thus putting more and more applications in the background), at some time the amount of available memory gets so low that another application can no longer be started. In this situation, the operating system decides to remove the oldest application in the background from memory, saving just minimal state information for that application. In this situation, the application that was just removed from memory is said to be Tombstoned. To restore our application from being tombstoned, we not only need to reload our application settings (as we did on the Application_Launching event), but most likely we also need to restore additional data. The Operating System ‘remembers’ the page in our application the user had visible when we were tombstoned. It is our responsibility to restore data that the user entered on that page (for instance the contents of a Textbox).

When our application is send to the background, several things happen. On the page that is currently visible, an OnNavigatedFrom event will occur. Also, the Application_Deactivated method in the App.xaml.cs file will be called. When an application is switched to the background, basically three things can happen to it:

  1. The application will become the foreground application again without having entered the tombstone state. In this situation the application can benefit from Fast Application Switching.
  2. The application got tombstoned, but it will become the foreground application after a while. In this situation the application must restore more state information.
  3. The user starts the application again by clicking its icon or tile on the start screen. In this situation, the previous instance of the application is removed and the user should see the application in its initial state.

dump3When you are debugging your application in Visual Studio, the default behavior when the application is moved to the background is for it to remain in memory. However, by modifying one of the project properties (as shown in the screen dump on the left), you can force the application to become tombstoned, regardless from the amount of free memory on the device (emulator). In this way, we as developers have the possibility to test our applications in either state they enter when being moved to the background. You should make sure that you test the tombstone scenario for your application. For instance, if EvenTiles with its current functionality is tested for tombstoning it will crash. This currently has to do with the way that data is initialized. In EvenTiles, we have a string property defined in App.xaml.cs that will later be used to write information to the back side of our Secondary Tile. The SettingsPage already makes use of this property. However, we are initializing this property, named ActualBackSecContent when the application is started in the Application_Launching method.

Activating and Terminating
  1. // Code to execute when the application is launching (eg, from Start)
  2. // This code will not execute when the application is reactivated
  3. private void Application_Launching(object sender, LaunchingEventArgs e)
  4. {
  5.     if (!appSettings.Contains(keyActSecBackContent))
  6.     {
  7.         appSettings[keyActSecBackContent] = DefaultSecBackContent;
  8.     }
  9.     ActualSecBackContent = (string)appSettings[keyActSecBackContent];
  10. }
  11.  
  12. // Code to execute when the application is activated (brought to foreground)
  13. // This code will not execute when the application is first launched
  14. private void Application_Activated(object sender, ActivatedEventArgs e)
  15. {
  16. }
  17.  
  18. // Code to execute when the application is deactivated (sent to background)
  19. // This code will not execute when the application is closing
  20. private void Application_Deactivated(object sender, DeactivatedEventArgs e)
  21. {
  22. }
  23.  
  24. // Code to execute when the application is closing (eg, user hit Back)
  25. // This code will not execute when the application is deactivated
  26. private void Application_Closing(object sender, ClosingEventArgs e)
  27. {
  28.     appSettings[keyActSecBackContent] = ActualSecBackContent;
  29. }

Even though our application is removed from memory when it is tombstoned, if the user navigates through the back stack using the back key on the phone, eventually they will return back to a page of our application. In order to make this happen in case our application was tombstoned, it has to be reloaded again to memory to become active. In this situation, minimal state information was stored by the imageoperating system (for instance which page was the last page the user saw when our application got tombstoned). On returning from tombstoning we will return to that page, but since the application needs to be started completely, classes have to be newly created and code in constructors of those classes will therefor be executed. To distinguish between starting a fresh copy of the application or returning from the background, Application_Launching (fresh restart) or Application_Activated (tombstoning or fast application switching) is called in our App.xaml.cs file. If our application was still in memory, there is no problem, after all, the property ActualSecBackContent still holds its value. If we are returning from a tombstoning situation we do have a problem, since Application_Activated will be called instead of Application_Launching. That is why the exception that is shown in the screen dump above was thrown.

You might think that this problem could easily be solved by initializing the ActualSecBackContent property in the constructor of our App class, but that would mean that we don’t benefit from fast application switching (the situation where our application remains in memory, even though it is in the background). A better solution is to make use of the Application_Activated event as follows:

Switching between BG and FG
  1. // Code to execute when the application is activated (brought to foreground)
  2. // This code will not execute when the application is first launched
  3. private void Application_Activated(object sender, ActivatedEventArgs e)
  4. {
  5.     if (!e.IsApplicationInstancePreserved)
  6.     {
  7.         // The application was not preserved in memory, so we were tombstoned
  8.         // Only in this case we need to re-initialize ActualSecBackContent
  9.         ActualSecBackContent = (string)appSettings[keyActSecBackContent];
  10.     }
  11. }
  12.  
  13. // Code to execute when the application is deactivated (sent to background)
  14. // This code will not execute when the application is closing
  15. private void Application_Deactivated(object sender, DeactivatedEventArgs e)
  16. {
  17.     appSettings[keyActSecBackContent] = ActualSecBackContent;
  18. }

If the application is becoming the foreground application, we check if we were still available in memory. If so (e.IsApplicationInstancePreserved == true) we don’t do anything, otherwise we just initialize the ActualSecBackContent property. There is nothing else to do, because we know that a value with that particular Settings key already is available, since the application was launched at some time before Application_Activated was called. If an application is moved to the background you want to make sure to save everything in such a way that you assume that your application will never return to the background. After all, the application can stay in memory, it might be tombstoned but there is also a possibility that the user starts a brand new instance of the application from the start menu. In the latter case, the existing instance of the application in the background will be removed by the operating system.

NOTE: If you are upgrading an existing application for Mango, at the very least (after converting your project in Visual Studio) you need to only retrieve stored data in the Application_Activated method when e.IsApplicationInstancePreserved is false. In that way your application will immediately benefit from fast application switching.

The following video shows the actions we took to prevent the EvenTiles application from crashing after being reactivated from a tombstoned state:

Fast Application Switching and Tombstoning (1)

With the changes that were described so far added to our application, it no longer crashes if we are returning from a tombstone state. There are however more things that need to be considered when the application is brought back from background to foreground. In the next Episode of EvenTiles we will take a look at restoring Focus on an input control when returning from the background.

If you want to see EvenTiles already in action on your Windows Phone, you can install the latest release from Marketplace. Remember that this application is not meant to be extremely useful, although it contains similar functionality that “serious” applications have. All functionality that you can find in the released version of EvenTiles will be covered in the upcoming episodes of this blog series, together with all source code. Just go ahead and get your free copy of EvenTiles from Marketplace at this location: http://www.windowsphone.com/en-US/search?q=EvenTiles (or search on your phone for EvenTiles in the Marketplace application).

EvenTiles from Start to Finish–Part 6

In the previous episode of this series about how to develop a Windows Phone application from scratch we used IsolatedStorage to persist some data. Since IsolatedStorage is a file store on a Windows Phone device, for exclusive use by a single application, it can be a challenge to look at its contents. Luckily, the Windows Phone 7.1 SDK has a tool available to explore IsolatedStorage contents. In this episode of EvenTiles we will explore this Isolated Storage Explorer Tool.

The Isolated Storage Explorer Tool is a command line tool, which is installed together with the Windows Phone 7.1 SDK in the following folder:

C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v7.1\Tools (64 bit OS)
or
C:\Program Files\Microsoft SDKs\Windows Phone\v7.1\Tools (32 bit OS)

The tool itself has a lot of parameters, to get contents from IsolatedStorage, to write contents to IsolatedStorage, to specify an application and to specify a device. In a command prompt some limited help information is available:

image

In order to retrieve our ApplicationSettings from IsolatedStorage for EvenTiles, the first thing we need to know is the ProductID for our application. This ide can be found in the WMAppManifest.xml file.

WMAppManifest.xml
  1. <Deployment xmlns="http://schemas.microsoft.com/windowsphone/2009/deployment" AppPlatformVersion="7.1">
  2.   <App xmlns="" ProductID="{883385e6-52e5-4835-83db-8a17499b5767}" Title="EvenTiles"

The next thing we need to do is make sure that the Emulator is started (or a physical device is connected). Either should have the application installed, but it is not necessary to have the application running. After passing the following command,

image

the folder C:\iso will contain a snapshot of our application’s IsolatedStorage.

image

When we drag and drop the _ApplicationSettings file to Visual Studio 2010, you can see that its contents are XML data, representing a Dictionary with one single entry defined in it, matching our Secondary Tile’s back side string.

image

You might not like using a command line tool to explorer IsolatedStorage. In that case, there is good news for you. If you browse to http://wptools.codeplex.com/, you will find the Windows Phone Power Tools for download. This handy collection of tools embeds the different SDK tools including the Isolated Storage Explorer Tool inside a Windows application. With that application you can explore your application’s IsolatedStorage as well. Using the power tool, it is also easy to write new or modified files to your application’s IsolatedStorage. The latter makes a lot of sense if you want to test new versions of applications against old contents in IsolatedStorage, for instance to migrate old files to new versions.

image

The following video shows the Isolated Storage Explorer Tool and the Windows Phone Power Tools in action.

Using the Isolated Storage Explorer Tool and the Windows Phone Power Tools

So this time we did not add functionality to our EvenTiles application, but it is important to learn about useful tools to help us develop our applications as well. In the next episode we will talk about Tombstoning and Fast Application switching and what we need to do in our application to support these two important execution states on Windows Phone devices.

imageIf you want to see EvenTiles already in action on your Windows Phone, you can install the latest release from Marketplace. Remember that this application is not meant to be extremely useful, although it contains similar functionality that “serious” applications have. All functionality that you can find in the released version of EvenTiles will be covered in the upcoming episodes of this blog series, together with all source code. Just go ahead and get your free copy of EvenTiles from Marketplace at this location: http://www.windowsphone.com/en-US/search?q=EvenTiles (or search on your phone for EvenTiles in the Marketplace application).

EvenTiles from Start to Finish–Part 5

In episode number four of this series about how to develop a Windows Phone application from scratch we created the SettingsPage using a combination of Expression Blend and Visual Studio 2010. The SettingsPage has limited functionality, but it can modify a string that will eventually be displayed on the backside of a Secondary Tile. In this episode we will take a look at how to store data in IsolatedStorage.

If you watched the video of episode 4 you have noticed that the string containing the text to be eventually displayed on the Secondary Tile’s backside was not saved when the application was closed, because a default string showed up when the application was started again. In order to store the string so it will be available when the application starts again, we are going to store it into a specific part of the our IsolatedStorage. IsolatedStorage can be used to store files and system settings. It just acts as a hard drive with one little but important difference. IsolatedStorage is …. isolated. Everything that is stored in IsolatedStorage is exclusively available for the application that owns it, so other applications can not access it.

When a Windows Phone application starts, it will be running in the foreground, with its MainPage visible. As long as the user is working with the application, it remains n the foreground. An application can be terminated by the user by pressing the Back key on the phone until the last page of the application will be closed. An application can also be moved to the background. This happens when the user activates another application, or for instance when the user answers a phone call. On starting, a Launching event is raised. The App.xaml.cs file already has event handlers defined for the Launching and Closing events. These are the events that we are going to use to store / retrieve our string containing the backside text for our Secondary Tile.

NOTE: The sample code, retrieving and storing data in the Launching / Closing event works fine. However, all code executing upon firing those events has a time limit of 10 seconds. If an event handler takes longer to execute, the application will be immediately terminated. If you have much data to store / retrieve, you should take an alternative approach. You can for instance make use of a separate thread in those situations to retrieve / store information. To keep our sample lean and mean, we will directly retrieve / store data into IsolatedStorage from within the Launching / Closing event handlers.

Since all functionality is already available inside the SettingsPage to store the backside text of the Secondary Tile, we are only adding some functionality to the App.xaml.cs file. First thing to do is get access to the IsolatedStorageSettings for our application, which is in fact a dictionary in which values can be stored / retrieved through a key. The IsolatedStorageSettings are implemented as a singleton and are created the first time we try to access them. IsoloatedStorageSettings can be accessed from inside our entire application, although right now we will only use IsolatedStorageSettings inside the App.xaml.cs file.

IsolatedStorageSettings
  1. public const string DefaultSecBackContent = "Having an even # of tiles on my StartScreen";
  2. public const string keyActSecBackContent = "K_ASBC";
  3.  
  4. public static string ActualSecBackContent { get; set; }
  5.  
  6. private IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings;

In the code snippet you can see a declaration of a key (just a string variable) that is used to store / retrieve the string containing content for the back side of a Secondary Tile. You can also see how a private variable is declared that is initialized with the one and only instance of our application’s settings in IsolatedStorage.

Application_Launching
  1. // Code to execute when the application is launching (eg, from Start)
  2. // This code will not execute when the application is reactivated
  3. private void Application_Launching(object sender, LaunchingEventArgs e)
  4. {
  5.     if (!appSettings.Contains(keyActSecBackContent))
  6.     {
  7.         appSettings[keyActSecBackContent] = DefaultSecBackContent;
  8.     }
  9.     ActualSecBackContent = (string)appSettings[keyActSecBackContent];
  10. }

Each time the application is started, the Application_Launching method will be executed. In this method we check if an object is stored under the key keyActSecBackContent. If this is not the case, we create a new entry in the dictionary of application settings and assign it with a default text that can be written to the back side of the Secondary Tile. If an entry already exists (which is basically always after creating one during the very first time), we retrieve the actual string from that entry. Since an application settings dictionary stores objects, we need to cast the actual value to a string.

When the application is terminated, the contents of the string that contains the text for the back side of the Secondary Tile might have been changed in the SettingsPage. That is the reason why we store that string always when the application ends.

Application_Closing
  1. // Code to execute when the application is closing (eg, user hit Back)
  2. // This code will not execute when the application is deactivated
  3. private void Application_Closing(object sender, ClosingEventArgs e)
  4. {
  5.     appSettings[keyActSecBackContent] = ActualSecBackContent;
  6. }

It looks like we now have stored our application settings properly. However, that is not entirely the case, since our application might be temporarily interrupted because the user can start other applications without terminating our application. In those situations we have to take a look at the life cycle of an application. That will be topic of another episode of EvenTiles. It is also interesting to take a look at exactly what information is stored in IsolatedStorage. In order to do that, you can make use of the Isolated Storage Explorer Tool, a handy little tool that will be covered in episode six of EvenTiles.

In the following video you can see all the steps that you need to make application settings persistent and to retrieve them each time the application starts again.

Using IsolatedStorage to store ApplicationSettings

Note: Every now and then I will make sure that you can download all source code that we created so far. I strongly recommend you to do so and to start experimenting with that code. After all, looking at real code, modifying it and understanding your modifications will hopefully help you to become a great Windows Phone developer fast.

If you want to keep up with the code of EvenTiles that is available until now, you can download it as a Zip file from this location. After downloading and unzipping it, you can open the EvenTiles solution in Visual Studio 2010 Express for Windows Phone. You must have the Windows Phone SDK 7.1 installed on your development system to do so. If you have a developer unlocked phone you can deploy the application to your phone, if you don’t have a developer unlocked phone you can still experiment with this application inside the emulator.

EvenTiles from Start to Finish–Part 4

In the third part of this series about how to develop a Windows Phone application from scratch we looked at the Silverlight Toolkit for Windows Phone and page transitions. Today we will work on some functionality in the Settings Page of our application. We will take off where we finished in Part 3, and start with an empty SettingsPage (except for the application name and page title).

The purpose of our complete sample application is to create a Secondary Tile programmatically and pin that to the Start Screen of the user. The Secondary Tile has a front and a back. The text on the backside of the tile can be modified by the end user. EvenTiles is not meant to be extremely useful, it is there to help introduce lots of programming aspects to develop Windows Phone applications.

In this episode we will add a few UI Elements to the SettingsPage to realize the follow functionality:

  • The text that will be displayed on the backside of the Secondary Tile is visible;
  • The backside text can be modified;
  • If the backside text differs from a default text, a button is displayed to allow easy restoration of the default backside text, otherwise the button is invisible.

The SettingsPage gets the following layout:

image

The layout of the UI is relatively simple. In the ContentPanel of the PhoneApplicationPage we have a StackPanel containing 3 different items (a TextBlock, a TextBox plus a hidden Button) and a ToggleSwitch (that is defined in the Silverlight Toolkit for Windows Phone). The ToggleSwitch is already visible but does currently not have any functionality associated to it. The ContentPanel itself is a Grid. Initially, a Grid has one row and one column. To place UI Elements in the Grid and to position them at a particular location you typically make use of multiple rows and/or multiple columns that you first have to define. To get the desired layout, the Grid contains 3 separate rows. In the first row (being row number 0), the StackPanel is hosted. This row takes the height it needs to display all visible UI Elements of the StackPanel. The next row on the Grid takes up whatever space is left on the grid and the last row takes precisely the height it needs to display the ToggleSwitch. The XAML for the ContentPanel looks like this:

SettingsPage UI
  1. <!–ContentPanel – place additional content here–>
  2. <Grid x:Name="ContentPanel"
  3.         Grid.Row="1"
  4.         Margin="12,0,12,0">
  5.     <Grid.RowDefinitions>
  6.         <RowDefinition Height="Auto" />
  7.         <RowDefinition />
  8.         <RowDefinition Height="Auto" />
  9.     </Grid.RowDefinitions>
  10.     <StackPanel>
  11.         <TextBlock HorizontalAlignment="Left"
  12.                     TextWrapping="Wrap"
  13.                     Text="Set your own tile text (approx. 45 characters)"
  14.                     VerticalAlignment="Top"
  15.                     Margin="12,0" />
  16.         <TextBox x:Name="tbBackContent"
  17.                     TextWrapping="Wrap"
  18.                     MaxLength="45"
  19.                     d:LayoutOverrides="Height"
  20.                     TextChanged="tbBackContent_TextChanged" />
  21.         <Button x:Name="btnRestore"
  22.                 Content="Restore Default Text"
  23.                 Margin="0,0,0,3"
  24.                 d:LayoutOverrides="Height"
  25.                 Click="btnRestore_Click"
  26.                 Visibility="Collapsed" />
  27.     </StackPanel>
  28.     <toolkit:ToggleSwitch Header=""
  29.                             Grid.Row="2"
  30.                             Content="Allow using Location?" />
  31. </Grid>

You can see our Grid.RowDefinitions being defined. There is also a possibility to define Grid.ColumnDefinitions, but for this particular simple UI we only need rows. Scrolling through the XAML you can see all individual UI Elements being defined. The TextBox and the Button connect events to event handlers. For the Button, the Click event is connected to a method called btnRestore_Click. Each time the user Clicks the Button, the code that is defined in btnRestore_Click will execute. That code is defined in C#. We will take a look at the code later. The TextBox uses the TextChanged event, that will be fired each time the value of the Text property of the TextBox changes. If this happens, code inside the method tbBackContent_TextChanged will execute.

In Part 2 of EvenTiles we looked at the NavigationService that can be used to navigate from one PhoneApplicationPage to another PhoneApplicationPage. Each time the user navigates to a particular page, the OnNavigatedTo method on that page is called. You can override that method to extend its functionality. When the user navigates away from a PhoneApplication, a similar method (OnNavigatedFrom) is called that you again can override to add specific functionality you need on a particular page. In the SettingsPage of EvenTiles we are overriding both these methods to add some functionality:

OnNavigated …
  1. protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
  2. {
  3.     base.OnNavigatedTo(e);
  4.     tbBackContent.Text = App.ActualSecBackContent;
  5.     btnRestore.Visibility = tbBackContent.Text.Equals(App.DefaultSecBackContent) ? Visibility.Collapsed : Visibility.Visible;
  6. }
  7.  
  8. protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
  9. {
  10.     base.OnNavigatedFrom(e);
  11.     App.ActualSecBackContent = tbBackContent.Text;
  12. }

Both these methods contain a call to a similar method, preceded by the keyword base. These methods execute functionality that is defined in the base class of our derived PhoneApplicationPage class. To make sure that we don’t skip that code (which might contain important functionality for page navigation) we have to call those methods. Immediately under the call to the base class methods, our own functionality is added. When we are navigating to the SettingsPage, we initialize the TextBox with the currently stored backside content for a Secondary Tile that we will create later in this series. This content is defined in a string property in the App.xaml.cs file. Next we determine if the Button that can be used to restore a default text needs to be visible. This is only the case when the TextBox displays something different from a default text that is also defined in App.xaml.cs. In App.xaml.cs the default text is assigned to the actual text.

When the user is leaving the SettingsPage (for instance by pressing the Back button on the phone), we simply store the current content of the TextBox for later use.

Let’s now take a look at the event handlers for both the Button and the TextBox:

Event Handlers
  1. private void tbBackContent_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
  2. {
  3.     btnRestore.Visibility = tbBackContent.Text.Equals(App.DefaultSecBackContent) ? Visibility.Collapsed : Visibility.Visible;
  4. }
  5.  
  6. private void btnRestore_Click(object sender, System.Windows.RoutedEventArgs e)
  7. {
  8.     tbBackContent.Text = App.DefaultSecBackContent;
  9. }

If the text in the TextBox changes, the TextChanged event handler code will execute. Just like in the OnNavigatedTo method, we determine if the Button that can be used to restore a default text needs to be visible. If the Button is clicked, we simply restore the default text. Since this also fires a TextChanged event (after all, the text of the TextBox is changed), executing code in the TextChanged event handler will now result in the Button to be hidden.

In the following video you can see all the steps that are needed to add the described functionality to the SettingsPage.

Extending the SettingsPage for EvenTiles

We are still far away from having all functionality in place to actually make a Secondary Tile visible on the Start Screen. However, we need to understand a few fundamental concepts in order to create successful Windows Phone applications, so we will continue with the ground work for another couple of episodes. In the next episode we will look at persisting data in IsolatedStorage to make sure that we store data when the user stops using our application.

EvenTiles from Start to Finish–Part 3

In the second part of this series about how to develop a Windows Phone application from scratch we looked at the ApplicationBar and Page Navigation. Today we will introduce the Silverlight Toolkit for Windows Phone, show how to use it inside an application and add page transitions to the application. We will take off where we finished in Part 2.

The Silverlight Toolkit for Windows Phone is a separate assembly that you can install after downloading it. It installs in the same location where the Windows Phone SDK’s are installed, making it very easy to add a reference to it in order to use functionality that can be found in the toolkit.

imageAfter you have installed the toolkit, you can add a reference to it inside your application by right-clicking the references field your project and selecting the toolkit in the dialog box that appears. After adding the toolkit to the references, you will see it under references inside solution explorer. The first thing we are going to do is adding page transitions. If you look at the video, you will see that the pages of our application are currently simply appearing without any animations. However, page transitions inside many applications are similar to turning pages in a book. This is for instance the case with applications that are already installed on your Windows Phone. The Silverlight Toolkit contains functionality to make it very easy to incorporate similar page transitions inside your own applications. There are many different transitions to choose from, but we will use the same page turning transitions that you probably already know when you activate an application from the start screen.

To add page transitions inside your own application, it is important to change the PhoneApplicationFrame for your application into a TransitionFrame. The latter is defined in the Silverlight toolkit and allows for page transitions. The RootFrame is a container to hold all pages that you will create inside your application. You will have to search for the method InitializePhoneApplication inside the source file App.xaml.cs that Visual Studio created for you when you created the EvenTiles project. Inside this method, you can see that a new RootFrame is created of type PhoneApplicationFrame. You will have to change this into a TransitionFrame in order to get your page transitions working.

Using a TransitionFrame
  1. // Do not add any additional code to this method
  2. private void InitializePhoneApplication()
  3. {
  4.     if (phoneApplicationInitialized)
  5.         return;
  6.  
  7.     // Create the frame but don't set it as RootVisual yet; this allows the splash
  8.     // screen to remain active until the application is ready to render.
  9.     // RootFrame = new PhoneApplicationFrame();
  10.     RootFrame = new TransitionFrame();
  11.     RootFrame.Navigated += CompleteInitializePhoneApplication;
  12.  
  13.     // Handle navigation failures
  14.     RootFrame.NavigationFailed += RootFrame_NavigationFailed;
  15.  
  16.     // Ensure we don't initialize again
  17.     phoneApplicationInitialized = true;
  18. }

In order to get page transitions working, the next thing you have to do is add some XAML that defines the different page transitions to each page on which you want to make use of page transitions. Instead of adding individual pieces of XAML for each page, you can also create a new style that you use inside all pages that you want to make use of page transitions. That is the approach we are taking in this sample. First thing to do is add the following XAML to the App.xaml file:

PageTransition Style
  1. <!–Application Resources–>
  2. <Application.Resources>
  3.     <Style x:Key="DefaultPageWithTransitions"
  4.             TargetType="phone:PhoneApplicationPage">
  5.         <Setter Property="sltk:TransitionService.NavigationInTransition">
  6.             <Setter.Value>
  7.                 <sltk:NavigationInTransition>
  8.                     <sltk:NavigationInTransition.Backward>
  9.                         <sltk:TurnstileTransition Mode="BackwardIn" />
  10.                     </sltk:NavigationInTransition.Backward>
  11.                     <sltk:NavigationInTransition.Forward>
  12.                         <sltk:TurnstileTransition Mode="ForwardIn" />
  13.                     </sltk:NavigationInTransition.Forward>
  14.                 </sltk:NavigationInTransition>
  15.             </Setter.Value>
  16.         </Setter>
  17.         <Setter Property="sltk:TransitionService.NavigationOutTransition">
  18.             <Setter.Value>
  19.                 <sltk:NavigationOutTransition>
  20.                     <sltk:NavigationOutTransition.Backward>
  21.                         <sltk:TurnstileTransition Mode="BackwardOut" />
  22.                     </sltk:NavigationOutTransition.Backward>
  23.                     <sltk:NavigationOutTransition.Forward>
  24.                         <sltk:TurnstileTransition Mode="ForwardOut" />
  25.                     </sltk:NavigationOutTransition.Forward>
  26.                 </sltk:NavigationOutTransition>
  27.             </Setter.Value>
  28.         </Setter>
  29.     </Style>
  30. </Application.Resources>

Here we define different transitions that will run when you are navigating to and from pages inside the application. The transitions that you can see in the code snippet are all TurnStileTransitions which are commonly used for page transitions inside a Windows Phone application. The Silverlight Toolkit contains other transition types as well.

imageAfter having defined the transitions and after having changed the RootFrame to be able to host transitions, the only thing that is left to do is assigning newly created transition style to each individual page. This can for instance be done using Expression Blend. When you now would run the application, it will blend in perfectly with applications that came with your Windows Phone. Navigating from page to page inside our application is now identical to navigating inside for instance the different settings on the Windows Phone. Of course it is not necessary to make use of page transitions, but it does make your application look better and even more professional.

 

The Silverlight Toolkit for Windows Phone contains much more useful items, like a number of cool user interface elements. To see already one of them in action, we are adding it to the Settings Page. On the SettingsPage we later need a switch that can enable / disable reading of location data. Right now we are just going to enter a dummy switch and we are choosing a nice control from the Silverlight Toolkit, the ToggleSwitch. This control looks like a light switch and has (like a CheckBox) two different states, checked and unchecked. This control looks extremely good inside a Windows Phone application, as you can see in the following screenshot:

image

Inside Visual Studio 2010 Express Edition you can see the SettingsPage in designer mode. In it, you can also see a ToggleSwitch (in checked mode). The ToggleSwitch is added to the content grid, filling up as much space as it needs in the last row of the grid. How to layout UI controls inside a grid and in other container controls is something we will cover later in this series about Windows Phone Application Development.

In the following video you can see all the steps that are needed to add transitions to your Windows Phone Application and how to be able to use functionality from the Silverlight Toolkit inside your own application.

Using the Silverlight Toolkit to add Page Transitions to EvenTiles

LiveTiles will be extended soon. In the next episode we will create the SettingsPage UI and make sure that we can store data entered on the SettingsPage. Make sure to lookout for part four in this series about Windows Phone application development which will be published soon.