Category Archives: Mango

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.

EvenTiles from Start to Finish–Part 2

In the first part of this series about how to develop a Windows Phone application from scratch we looked at the initial project and how to initialize the Application Tile by setting elements in the manifest file. Today we will add an ApplicationBar to our application and we will add page navigation as well. We simply take off where we finished in Part 1. Adding an application bar is actually easier from within Expression Blend. This tool can be used to design and prototype Windows Phone applications. The advantages of using Expression Blend to add the application bar are:

  • immediate visual feedback;
  • simple selection / insertion of application bar icons
  • simple reordering possibilities for application bar icons en menu items.

imageVisual Studio can work closely together with Expression Blend. Changes in one environment will be visible in the other environment (usually changed files must only be saved or a project must be rebuilt in order to achieve this). If a solution is already open in Visual Studio, you can start Expression Blend from within the Project Menu as shown. Even though you can use Expression Blend to add code to your Windows Phone pages, you probably want to limit doing so, since you don’t have Intellisense available, which is one of the great features of Visual Studio that really makes entering code easy. You can immediately see that you are in a different environment when looking at Expression Blend. Its default theme color is dark. Something else that is immediately noticeable is the large amount of windows, options and choices available inside Expression Blend. It surely will take you some time to feel comfortable in this powerful design tool.

image

What you can see here is Expression Blend showing the MainPage of our EvenTiles application. You can also see how to select an ApplicationBarIcon in the collection of ApplicationBarIcon buttons. Besides concentrating on creating a (static) UI for a Windows Phone application, Expression Blend is also a fantastic tool to create different visual states and animations. We are still in the early stages of application development in this series, but more in depth usage of Expression Blend will definitely follow later on. For now we will just add a little bit of functionality to our application. Using Expression Blend, two new pages have been added to the project, a Settings Page and an About Page. Both these pages only contain a filled title section. Right now, the only functionality that will be added to the application is code to navigate to each of the two empty pages when the corresponding ApplicationBar buttons are clicked. The following code snippet shows the ApplicationBar that was created with Expression Blend in XAML, and already includes Click event handlers:

ApplicationBar on MainPage
  1. <phone:PhoneApplicationPage.ApplicationBar>
  2.     <shell:ApplicationBar Opacity="0">
  3.         <shell:ApplicationBarIconButton IconUri="/icons/appbar.feature.settings.rest.png"
  4.                                         IsEnabled="True"
  5.                                         Text="settings"
  6.                                         Click="Settings_Click" />
  7.         <shell:ApplicationBarIconButton IconUri="/icons/appbar.questionmark.rest.png"
  8.                                         IsEnabled="True"
  9.                                         Text="about"
  10.                                         Click="About_Click" />
  11.     </shell:ApplicationBar>
  12. </phone:PhoneApplicationPage.ApplicationBar>

To add code to the Click event handers, we are using the C# code behind file, belonging to the MainPage.

image

To create entries in the code behind file for both Click event handlers (and in that way connecting XAML to code), you can right click on the event handler in XAML and selecting Navigate to Event Handler entry from the shown popup menu. The code in the event handlers is very simple, using the NavigationService to navigate to another page by providing a Uri that contains the page name.

Navigating to other pages
  1. private void Settings_Click(object sender, EventArgs e)
  2. {
  3.     NavigationService.Navigate(new Uri("/SettingsPage.xaml", UriKind.Relative));
  4. }
  5.  
  6. private void About_Click(object sender, EventArgs e)
  7. {
  8.     NavigationService.Navigate(new Uri("/AboutPage.xaml", UriKind.Relative));
  9. }

After deploying the application to the emulator, the Main Page shows an ApplicationBar. Clicking on either of the two ApplicationBar buttons results in navigating to another page inside the application. The following video shows all steps to create the ApplicationBar, the additional pages and the code to navigate from page to page:

Adding an ApplicationBar and showing page navigation

LiveTiles will be extended soon. In the next episode we will take a look at the Silverlight toolkit, Page Transitions and additional controls that are available in the Silverlight toolkit. Make sure to lookout for part three in this series about Windows Phone application development.

EvenTiles from Start to Finish–Part 1

As I promised a few days ago, in between other blog entries I will show you how to create a complete Windows Phone application from scratch. This project starts with running Visual Studio to create an initial solution and it stops after having updated the application a few times and successfully submitted each different version to MarketPlace. Initially I will focus on creating the application without thinking too much about testability and reusability. I just show you the possibilities of Visual Studio, the Emulator and later on Expression Blend, Marketplace and additional tools. Later in this project we shift focus towards creating a more maintainable application, also using modern design patterns like MVVM. This series of articles is not meant to be a complete programming course for Windows Phone. If you want to know more about developing applications in C#, you should take a look at the Rob MilesYellow Book. Not only an excellent resource to learn the C# programming language but also fun to read. If you want to learn more about Windows Phone application development, I can highly recommend Rob Miles’ Blue Book, and Charles Petzold’s book titled Programming Windows Phone 7. The good news is that all these books can be downloaded for free and they are all very valuable resources.

Ok, back to application development. In this first part, you will learn how to create the initial solution for your project, how to modify the default Application Tile, how to write something on the back of the Application Tile through the manifest file and how to modify the default Icon. You will also see the application in action for the first time. All steps that are necessary are not only documented, but also accompanied by a short video that can be viewed in this blog entry as well. If you already want to have a sneak preview of the application we are going to develop, it will be published on Marketplace soon. I will update this line with the link to the application once it has been certified.

To begin with, we create a new Windows Phone Silverlight Application, call it EvenTiles and modify both the ApplicationIcon.png and the Background.png files to have a transparent icon for the application and a transparent Application Tile. The cool part about adding transparency is that the area’s of the art work that are transparent show up in the theme accent color that is selected by the user of the phone. Of course we are also setting the application name and a page name on the application’s main page.

image

For this first version of EvenTiles we are not going to add additional functionality, although we will change the behavior of the Application Tile. Instead of showing a static Application Tile, we want it to alternate between displaying the front and the back. We can achieve this by providing back side content for the Application Tile. This can actually be done in code, but also by adding definitions for background content to the application’s manifest file. Each Windows Phone application has a manifest file with the name WMAppManifest.xml that contains information about the application, including an optional definition of content that needs to be displayed on the back side of the Application Tile. We will modify the WMAppManifest file to specify what we want to see on the back side of the Application Tile (as shown in the following code snippet):

Defining the Application Tile
  1. <Tokens>
  2.   <PrimaryToken TokenID="EvenTilesToken" TaskName="_default">
  3.     <TemplateType5>
  4.       <BackgroundImageURI IsRelative="true" IsResource="false">Background.png</BackgroundImageURI>
  5.       <Count>0</Count>
  6.       <Title>EvenTiles</Title>
  7.       <BackBackgroundImageUri IsRelative="true" IsResource="false">Backbackground.png</BackBackgroundImageUri>
  8.       <BackTitle>EvenTiles</BackTitle>
  9.       <BackContent>Click me to start EvenTiles</BackContent>
  10.     </TemplateType5>
  11.   </PrimaryToken>
  12. </Tokens>

In order to clearly see the content on the back side of the Application Tile, it’s image is simply an entirely transparent image, meaning it will show a solid theme color as background of the back side content.

If you deploy this application to the emulator or to a real device, you will see a rotating Application Tile after you have pinned the application to the start screen. You can watch the application being created in this video:

EvenTIles:Part 1 – Add a back side to the Application Tile

So far, the following additional EvenTiles episodes have been published:

  1. Introducing the EvenTiles application
  2. ApplicationBar and Page Navigation
  3. Using the Silverlight Toolkit for Windows Phone
  4. Creating a Settings Page
  5. Storing Application Settings in IsolatedStorage
  6. Using the Isolated Storarage Explorer Tool
  7. Fast Application Switching and Tombstoning
  8. More on Tombstoning
  9. Creating a Secondary Tile
  10. Background Agents
  11. Debugging Background Agents
  12. The lifetime of a PeriodicTask
  13. Communication with a PeriodicTask
  14. Exchanging data with a PeriodicTask
  15. Adding an About Page
  16. Accessing Marketplace from within a Windows Phone Application
  17. Implementing Trial Mode 

Every Live Tile deserves a Windows Phone Application

Over the last week I have been writing about Live Tiles in Windows Phone Mango, how you can create Secondary Live Tiles and how you can display information on the back of Live Tiles and periodically change that information. There is more to write about Live Tiles, but I think it is time to change the topic slightly.

In part 4 of the Live Tile mini series, I introduced an application that adds a Secondary Tile to the Start Screen of your phone. That application is now almost finished in its first version. This free application has a Secondary Tile, it contains an AdControl, deals with location awareness and periodically updates the Secondary Tile. It also can access Marketplace, both to submit a review for the application and to display other applications that are published by me. All in all it is a complete application, yet its functionality is very simple. It is simple enough to explain it almost entirely. That is exactly what I am planning to do over the upcoming weeks.

Initially, the application makes use of code behind. In a later version it will be changed, making use of MVVM and Unit Testing. The application will also act as a sample to show profiling, debugging background agents and many more topics. I will combine blog entries and videos to show how to create this application, how to test it and hopefully how to publish it to Marketplace. As soon as the application is available for download, I will let you know in this blog entry. Here is a sneak preview of EvenTiles.

dump1This application is very simple, yet it contains lots of functionality that you can use inside a Windows Phone application. When the application is started, it checks if a Secondary Tile exists. Actually, it can even be started by clicking on its Secondary Tile when available. If no Secondary Tile is pinned to the start screen, the user has the option to create a Secondary Tile and automatically pin it to the Start Screen. When the Secondary Tile is already pinned on the Start Screen, the user has the possibility to remove it from the Start Screen. You can also see that the application has advertisements. In order to allow for localized advertisements, the application reads the current location of the device once (if the user allows doing that). The application has a Settings Page that can be reached through the ApplicationBar as well as an About Page. To preserve data, the application makes of of Isolated Storage. To transfer data between the application and its background agent, a file in IsolatedStorage is used that is protected by a Mutex. So even though the application itself is very simple, it contains many pieces of functionality that you can use in very complex applications as well. As such, this application is hopefully a starting point that allows you to develop fantastic Windows Phone Applications. Stay tuned for the first part of EvenTiles from Start to Finish – Part 1, which shows you how to create the initial solution and how to create a Secondary Live tile.

Every Windows Phone application deserves Live Tiles (part 4)

My previous post about Live Tiles showed you how you can use a PeriodicTask to update your Application’s Live Tile periodically from inside the phone. Now we are going to move a little beyond Application Tiles and move towards Secondary Tiles.

image_thumb2Matthijs Hoekstra, Microsoft’s Dutch Windows Phone Champ, inspired me to create the following sample application. The application creates a single Secondary Tile and that is about it. This application is great to make the number of tiles on the phone’s start screen even (which simply looks better). At the same time, the application has limited functionality, making it easier to concentrate on functionality that is needed to create and update the Secondary Tile.

Each application can create multiple Secondary Tiles. These Secondary Tiles are created programmatically, and will be pinned on the user’s start screen after they are created. They do have the same properties and update possibilities as Application Tiles. However, an application always has an Application Tile, regardless from it being pinned on the start screen or not. Secondary Tiles are completely optional. End users of course have the possibility to unpin the Secondary Tile again from the start screen, so you should not automatically assume that a Secondary Tile you created inside your application will live on the phone’s Start Screen forever. One important difference between the Application Tile and a Secondary Tile is the possibility for a Secondary Tile to specify a navigation URI. With this URI it is possible to immediately navigate to a particular page inside an application and / or to pass additional data to a particular page. Because users can unpin Secondary Tiles, it is not wise to only allow navigating to a particular page through a Secondary Tile, even though this would be technically possible.

Let’s take a look how to create a Secondary Tile inside an application. The sample code that you will see is all part of the sample application that simply creates a Secondary Tile. The application also has a few options to change the appearance of the tile, which will be described in future blog entries around Live Tiles. In the sample application, a Secondary Tile is created when the user clicks a button. Technically, this could also be done automatically, for instance in the constructor of the MainPage. This code snippet is responsible for creating a Secondary Tile:

Creating a Secondary Tile
  1. private void btnInstall_Click(object sender, RoutedEventArgs e)
  2. {
  3.     ShellTile TileToFind = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.ToString().Contains("TileId=Secondary"));
  4.  
  5.     if (TileToFind == null)
  6.     {
  7.         StandardTileData NewTileData = new StandardTileData
  8.         {
  9.             BackgroundImage = new Uri("Tile.png", UriKind.Relative),
  10.             Title = "Even Tiles",
  11.             Count = 0,
  12.             BackBackgroundImage = new Uri("Tile.png", UriKind.Relative),
  13.             BackTitle = "Even Tiles",
  14.             BackContent = "Show even # of tiles on Start Screen",
  15.         };
  16.  
  17.         ShellTile.Create(new Uri("/MainPage.xaml?TileId=Secondary", UriKind.Relative), NewTileData);
  18.         btnInstall.Content = removeText;
  19.     }
  20.     else
  21.     {
  22.         TileToFind.Delete();
  23.         btnInstall.Content = addText;
  24.     }
  25. }

In the above code snippet we first check if the Secondary Tile currently exists. If not, a new Secondary Tile will be created containing both foreground and background information. The Secondary Tile also contains a Uri, containing the address of the MainPage, but it also passes additional data so we can determine if the MainPage was started from the Secondary Tile or not. If, on the other hand a Secondary Tile does exist, it will be deleted and the user has the possibility to create another Secondary Tile. As you can see, the ShellTile class is used to create or access the Secondary Tile. Identical to Application Tiles, the StandardTileData class is used to modify properties on the tile.

In the OnNavigatedTo method the reason for navigating to the MainPage is determined by checking if the Secondary Tile caused this. If so, the user has the possibility to delete the Secondary Tile. If the application was started traditionally, we are checking for an existing Secondary Tile and set Button Content accordingly. This is shown in the next code snippet:

Secondary Tile Navigation?
  1. protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
  2. {
  3.     base.OnNavigatedTo(e);
  4.  
  5.     btnInstall.Content = addText;
  6.  
  7.     if (NavigationContext.QueryString.ContainsKey("TileId"))
  8.     {
  9.         btnInstall.Content = removeText;
  10.     }
  11.     else
  12.     {
  13.         ShellTile TileToFind = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.ToString().Contains("TileId=Secondary"));
  14.         if (TileToFind != null)
  15.         {
  16.             btnInstall.Content = removeText;
  17.         }
  18.     }
  19. }

The initial version of the sample application looks like this:

image_thumb13

image_thumb12

 

 

 

 

 

In the next part of this series we will take a look at additional possibilities you have to update your Live Tiles.

Every Windows Phone application deserves a Live Tile (part 3)

My previous post about Live Tiles showed you how to update the back side of the Application Tile inside an application. The big drawback of this approach is that your tile will only be updated as a result of your application being executed. Depending on the information you want to display on your tile, you might want to take another approach to update your application’s tiles.

This time we will make use of a Background Agent to periodically update the Application Tile without the need for the application to actually run. We again work on the same sample application, Clicker, and extend its functionality by adding a PeriodicTask. A PeriodicTask is supposed to be lightweight and will run at fixed intervals. A PeriodicTask will not run forever, but it expires after at most 14 days. From within the running application, the PeriodicTask can be renewed before the expiration date. In this way, applications that are not used will not continue to use precious device resources through a PeriodicTask forever.

Back to our tile though. The scenario we want to implement is the following. The backside of the tile already displays the high score. It would be nice to alternate between showing the game’s high score and showing the amount of time the game has not been played. To implement this functionality, a PeriodicTask is ideal.

In order to make use of a PeriodicTask, a new project of type Windows Phone Scheduled Task Agent must be added to the solution containing the Clicker application. This newly created project already contains an OnInvoke method that is called each time the PeriodicTask executes. Inside the OnInvoke method, the back side of the live tile is updated. The PeriodicTask will execute approximately once every 30 minutes. It is important to determine how data can be exchanged between the application and the PeriodicTask. The PeriodicTask has access to the application’s IsolatedStorage. In Clicker, a file is used to save the high score, which in turn is read by the PeriodicTask. Since the OnInvoke method will execute on a thread and will be terminated after being executed, data needed for the PeriodicTask must also be persisted in IsolatedStorage. To store and retrieve high scores, a static class is available inside the Clicker application. This class will be used in the application to store high scores. The same class will also be used in the PeriodicTask to retrieve high scores. Together with the high score, also a boolean variable is stored, indicating if the high score or an informational message should be stored on the back of the Application Tile.

Retrieving HighScore info
  1. public static string GetLiveTileBack()
  2. {
  3.     string highScore = string.Empty;
  4.     bool showHighScore;
  5.  
  6.     using (var store = IsolatedStorageFile.GetUserStoreForApplication())
  7.     {
  8.         mtx.WaitOne();
  9.         if (store.FileExists(highScoreFileName))
  10.         {
  11.             string storedHighScore;
  12.  
  13.             using (var highScoreStream = new StreamReader(store.OpenFile(highScoreFileName, FileMode.Open)))
  14.             {
  15.                 showHighScore = Convert.ToBoolean(highScoreStream.ReadLine());
  16.                 storedHighScore = highScoreStream.ReadToEnd();
  17.             }
  18.  
  19.             if (showHighScore)
  20.             {
  21.                 highScore = storedHighScore;
  22.             }
  23.  
  24.             using (var highScoreStream = new StreamWriter(store.CreateFile(highScoreFileName)))
  25.             {
  26.                 showHighScore = !showHighScore;
  27.                 highScoreStream.WriteLine(showHighScore.ToString());
  28.                 highScoreStream.WriteLine(storedHighScore.ToString());
  29.             }
  30.         }
  31.         mtx.ReleaseMutex();
  32.     }
  33.  
  34.     return highScore;
  35. }

The following code shows how the PeriodicTask is created / renewed and scheduled to update the Live Tile of the application.

Creating the PeriodicTask
  1. public static void PeriodicTileUpdater()
  2. {
  3.     PeriodicTask periodicTask = ScheduledActionService.Find(periodicTaskName) as PeriodicTask;
  4.  
  5.     if (periodicTask != null)
  6.     {
  7.         RemoveAgent(periodicTaskName);
  8.     }
  9.  
  10.     periodicTask = new PeriodicTask(periodicTaskName)
  11.     {
  12.         Description = "Periodic Task to Update the ApplicationTile"
  13.     };
  14.  
  15.     // Place the call to Add in a try block in case the user has disabled agents.
  16.     try
  17.     {
  18.         ScheduledActionService.Add(periodicTask);
  19.  
  20.         // If debugging is enabled, use LaunchForTest to launch the agent in one minute.
  21. #if DEBUG_TASK
  22.         ScheduledActionService.LaunchForTest(periodicTaskName, TimeSpan.FromSeconds(30));
  23. #endif
  24.     }
  25.     catch (InvalidOperationException)
  26.     {
  27.     }
  28. }

To make debugging easier, the PeriodicTask will execute every 30 seconds in debug mode, instead of every 30 minutes. The other important piece of functionality is in the PeriodicTask itself. The OnInvoke method is started every 30 minutes (every 30 seconds in debug mode). It retrieves the information to be displayed on the back of the Application Tile.

Heart of the PeriodicTask
  1. protected override void OnInvoke(ScheduledTask task)
  2. {
  3.     if (task.Name.Contains(clickerTaskName))
  4.     {
  5.         // Application Tile is always the first Tile, even if it is not pinned to Start.
  6.         ShellTile TileToFind = ShellTile.ActiveTiles.First();
  7.                
  8.         if (TileToFind != null)
  9.         {
  10.             string backContent = LiveTile.GetLiveTileBack();
  11.  
  12.             if (backContent == string.Empty)
  13.             {
  14.                 backContent = "Isn't it time to play again";
  15.             }
  16.  
  17.             StandardTileData NewTileData = new StandardTileData
  18.             {
  19.                 BackContent = backContent
  20.             };
  21.  
  22.             TileToFind.Update(NewTileData);
  23.         }
  24.  
  25. #if DEBUG_TASK
  26.         ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(30));
  27. #endif
  28.     }
  29.  
  30.     NotifyComplete();
  31. }

At the end of the OnInvoke method you will see a call to NotifyComplete. This call is important because it releases resources of the PeriodicTask. Omitting to do this means the PeriodicTask will not be rescheduled to run again after the specified interval in debug mode or after the fixed interval in release mode.

image