Monthly Archives: November 2011

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.

Advertisements

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

Windows Embedded Compact in the (near) future

This week, Kevin Dallas, General Manager Windows Embedded at Microsoft, confirmed there will be a next version of Windows Embedded Compact, to be released in the second half of 2012. Even though Windows 8 will have ARM support and even though the next version of Windows Embedded Standard will most likely be based upon the Windows 8 bits, having a separate, light weight and hard real-time operating system makes a lot of sense. Especially if you take a look at Kevin’s vision of intelligent systems that are built from different building blocks, amongst which of course also embedded systems with a variety of different footprints and form factors.

The announcement that there will be a Windows Embedded Compact v.next is great news for everybody who is currently working on solution based on Windows Embedded Compact. It means that you can safely continue to invest in knowledge around Windows Embedded Compact. It also means that Windows Embedded Compact will make use of Visual Studio 2010 in its next version and that Windows CE will be amongst us for at least another 15 years, probably even longer.

Where is that Mutex?

In the continuous story of Live Tiles I wanted to write about updating the Application Tile by using a PeriodicTask. This is a very nice way to update the tile without having to make use of a remote service. However, the PeriodicTask needs to get some data that is available in my application. The way to go is to store that data in a file in IsolatedStorage in the application and have the PeriodicTask retrieve the data from that same file, since it has access to IsolatedStorage.

Since the application might update data that the PeriodicTask needs and since both of them are executing independently from each other, it is a good idea to protect the data by means of a synchronization object. The documentation for Background Agents even suggests using a Mutex for this purpose.

And this is where the fun started for me. I tried to create a Mutex inside my application, and time and again I ran into an issue. The Mutex object was clearly unknown in my application, even though I did add a using directive for System.Threading.

image

It took me quite some time to figure out what was going on here, especially since the PeriodicTask that I was perfectly capable of using a Mutex. Both are Windows Phone projects, both have access to more or less the same namespaces. And yet, there was this difference in recognizing a Mutex object.

image

Taking another look at the documentation for the Mutex did not really help me, although it should have helped me, because there is a hint in the documentation that I completely missed.

image

Even though I was reading the above documentation several times, I didn’t get it. I know I had access to the System.Threading namespace and I still could not use the Mutex. So I started searching for a solution on the Internet and I was not really successful in that, although I got the indication that folks are using Mutex objects in Windows Phone Mango applications. All in all I guess I wasted at least one hour when I decided to compare references to assemblies in both the application and the PeriodicTask projects. Here I found one subtle difference.

image

The difference between the two projects is a reference to mscorlib.extensions. After adding a reference to that assembly in my application’s project, I could use the Mutex. Of course it simply comes back to reading the documentation, because it does indicate that the necessary assembly is mscorelib.extensions (in mscorlib.Extensions.dll). Ignoring that one little sentence delayed me for at least one hour. Hopefully you don’t fall in the same trap.

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

My previous post about Live Tiles showed you how to use both sides of the Application Tile in Windows Phone Mango and how to initialize it in the WMAppManifest.xml file. You also learned how to add local language support.

Now we will focus on how to update the Application Tile within your application. Even though this is considered to be a live update of the tile, the update is not triggered by a schedule. This means that the Application Tile for the sample application will not be updated spontaneously when you are looking at it on the start screen of your device. However, it will alternate between front and back side and it will show relevant information on the back.

In order to show you how to update the Application Tile from within your own application, we again take the same sample application, Clicker, and extend its functionality. Each time the game is played, we will check for a new best time. If there is a new best time, it will be visible on the back side of the Application Tile, together with the date. In order to update an Application Tile, two steps are necessary.

First you need to get access to the Application Tile. This is possible by retrieving the first tile from the generic IEnumerable collection of active tiles that belong to the application. The first tile is always the Application Tile. This tile always exists (even if the user has not pinned the Application Tile to the start screen). Optionally, one or more Secondary Tiles can also be part of the collection of Active Tiles. In order to easily get to a particular tile in the collection of ActiveTiles, methods on the Enumerable class can be called. Since this class is implemented in the System.Linq namespace, you must also add a using directive to System.Linq. Omitting to do so results in compilation errors.

Assuming you have retrieved the Application Tile from the collection, you can modify it by creating a new StandardTileData class and initializing it with the data items that you want to change on the tile. It is sufficient to set only changed properties to an instance of the StandardTileData class. In our sample, we will only update the BackContent property, but it is also possible to change the entire appearance of (both sides of) the tile if you want to do so.

Finally, you need to modify the Application Tile by calling the Update method on the found ApplicationTile, passing the newly created instance of the StandardTileData. I decided to create a static class with one method to update the Application Tile. The reason to do so is that this class will be re-used in a few similar, but different applications.

Updating the Application Tile
  1. using System;
  2. using System.Linq;
  3. using System.Text;
  4. using Clicker.Controls.Localization;
  5. using Microsoft.Phone.Shell;
  6. using System.Globalization;
  7.  
  8. namespace Clicker.Controls
  9. {
  10.     public static class LiveTile
  11.     {
  12.         public static void UpdateLiveTile(TimeSpan bestTime, DateTime bestTimeDate)
  13.         {
  14.             // Application Tile is always the first Tile, even if it is not pinned to Start.
  15.             ShellTile TileToFind = ShellTile.ActiveTiles.First();
  16.  
  17.             if (TileToFind != null)
  18.             {
  19.                 StringBuilder sb = new StringBuilder();
  20.                 sb.AppendLine(ControlResources.BestTime);
  21.                 sb.AppendLine(bestTime.TotalSeconds.ToString("N2", CultureInfo.CurrentCulture.NumberFormat));
  22.                 sb.AppendLine(ControlResources.BestTimeDate);
  23.                 sb.AppendLine(bestTimeDate.ToString("d", CultureInfo.CurrentCulture.DateTimeFormat));
  24.  
  25.                 StandardTileData NewTileData = new StandardTileData
  26.                 {
  27.                     BackContent = sb.ToString(),
  28.                 };
  29.  
  30.                 TileToFind.Update(NewTileData);
  31.             }
  32.         }
  33.     }
  34. }

The result after playing the came a few times now looks like this:

image

The UpdateLiveTile method uses localization and is called each time the user has a high score. The only down side of a localized tile that I can think of is the fact that the tile does not automatically change to another local language when the user changes the language of the device. The tile will be modified if the application has executed one time, but if the application has not been executed, the tile will keep the original local language. The reason for that is that the tile is only updated inside the application, so the application has to run in order to display modified content on the tile. Since I don’t expect users to frequently change local languages on devices, I don’t think this is much of a limitation. In my first post about tiles, I wrote that the Mango update of Clicker will be available with this blog post. Unfortunately that is not the case, so I will make sure to send out a tweet when the updated  version of Clicker hits Marketplaces all over the world.

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

Live Tiles have been one of the nice differentiators of Windows Phone. In Mango, Live Tiles even got better, as a matter of facts, way better for end users and for 3rd party application developers. Today, applications can benefit from multiple secondary tiles that allow deep linking into the application. With Mango, all tiles have a front and a back that can contain different information. On the home screen, tiles with information stored on both the front and the back side will regularly flip over to see both sides of the tile.

In this article you will learn how even the simplest applications can benefit from live tiles, with the possibility to update the information presented on the tile locally.

Each application has at least one tile, the application tile. It is up to the user to pin this tile to the start screen on their phone. By default, this tile is single sided, meaning it will not flip over to show the back to the user.

In order to use both sides of a tile, you can initially add the appropriate properties to the WMAppManifest.xml file. The cool part of completely defining your double sided application tile in the WMAppManifest.xml file is that the tile starts rotating immediately when the user pins the tile to the start screen, even if the application has never been started by the user. That is the starting point of this blog entry.

image

One of my sample applications that is available through the Windows Phone Marketplace is a simple game called Clicker. In its original form it of course has an application tile, that simply looks like this. The tile only shows the application title and uses transparency to display some areas using the selected theme color on the phone.

Initially, the backside of the tile will contain a text inviting a user to play a game.  Therefore an initial backside of the tile is created in the WMAppManifest.xml file as follows:

  1. <Tokens>
  2.   <PrimaryToken TokenID="ClickerToken" TaskName="_default">
  3.     <TemplateType5>
  4.       <BackgroundImageURI IsRelative="true" IsResource="false">Background.png</BackgroundImageURI>
  5.       <Count>0</Count>
  6.       <Title>Clicker</Title>
  7.       <BackBackgroundImageUri IsRelative="true" IsResource="false">Images/BackBackground.png</BackBackgroundImageUri>
  8.       <BackTitle>Clicker</BackTitle>
  9.       <BackContent>Play and beat your own high score!</BackContent>
  10.     </TemplateType5>
  11.   </PrimaryToken>
  12. </Tokens>

imageEven though this is an acceptable first approach, the end user experience could still be improved. Clicker is a localized application with support for a few different languages. The message on the back of the application tile should therefore be localized as well for the different supported languages. With a little extra effort that can be achieved as well.

In order to put localized strings in the manifest file, you need to provide a native resource DLL for each local language that your application supports. If you are using Visual Studio 2010 Professional or better to develop your Windows Phone applications, you can literally follow the actions that are described in this MSDN How to page. However, if you are using the express edition  of Visual Studio 2010 to develop your Windows Phone applications, you cannot create a native Win32 DLL. In that situation, you might be able to use the tool that Patrick Getzman created to localize application tiles. I am not sure if this tool currently supports creating localized BackTitle and BackContent strings though. If not you either have to kindly ask Patrick for support or you can make use of the free Visual C++ 2010 Express version to create the resource DLL.

Here are the two different string tables that I created in a neutral language resource DLL and in a Dutch language resource DLL.

ID Value Caption
AppTitle 100 Clicker
AppTileString 200 Clicker
AppTileBackString 300 Clicker
AppTileBackContent 400 Play clicker and beat your own high score!

Neutral Language String Table in AppResLib.dll

ID Value Caption
AppTitle 100 Clicker
AppTileString 200 Clicker
AppTileBackString 300 Clicker
AppTileBackContent 400 Speel en verbeter je beste score!

Dutch Language String Table in AppResLib.dll.0413.mui

After changing the WMAppManifest.xml file’s TemplateType5 content to the following, the application tile now appears in Dutch on a Dutch Windows Phone 7.5 device and in US English on any other device.

  1. <Tokens>
  2.   <PrimaryToken TokenID="ClickerToken" TaskName="_default">
  3.     <TemplateType5>
  4.       <BackgroundImageURI IsRelative="true" IsResource="false">Background.png</BackgroundImageURI>
  5.       <Count>0</Count>
  6.       <Title>@AppResLib.dll,-200</Title>
  7.       <BackBackgroundImageUri IsRelative="true" IsResource="false">Images/BackBackground.png</BackBackgroundImageUri>
  8.       <BackTitle>@AppResLib.dll,-300</BackTitle>
  9.       <BackContent>@AppResLib.dll,-400</BackContent>
  10.     </TemplateType5>
  11.   </PrimaryToken>
  12. </Tokens>

And here is the result:

image

The next blog entry will dig deeper into live tiles and shows you how to update the high score for this game on the backside of the application tile. At that time, the Mango update of the Clicker application will also be available through Marketplace. If you can’t wait to start playing with the application, the current version (without live tiles) is available here for download or at your own local Windows Phone Marketplace.

Other parts in this series:

  1. Setting the stage and Initializing the Application Tile
  2. Updating an Application Tile from inside your application
  3. Using a Background Agent to periodically updating Tiles
  4. Creating and using Secondary Tiles
  5. Setting the stage for EvenTiles

If you want to learn more on how to develop a Windows Phone Application, make sure to take a look at EvenTiles, a series on Windows Phone Application Development with articles, videos and source code available for download.

Device Development Rocks!

At a first glance, developing software for mobile and embedded devices does not seem to differ much from developing software for the desktop. If I limit myself to developing applications for Windows CE based devices, you can use the same development tools as desktop developers. However, there are a number of interesting differences. For starters, Windows CE is a much smaller operating system, meaning for instance that we only have a subset of the Win32 API’s available. The same is true for developers who like to write managed code; the .NET Compact Framework is a subset of the full .NET Framework. Another important difference is the amount of memory available on the device. Quite often you find yourself dealing with low memory situations. If you are allocating memory, you might not get the memory you asked for. Are you dealing properly with this situation? Also, devices typically have slower processors than desktop machines. Therefore it is very important to write efficient code or you will run into performance issues. And then there is the whole category of battery powered devices. Each statement that is executed inside your application will drain the battery a little. So again, writing efficient code is very important. Let’s even move up the bar a bit. Desktop machines are typically frequently restarted. Embedded devices often will stay on, always, 24 hours a day and 365 days a year. This means the code you write should not only be efficient, but it should be correct as well. Especially if you take a look at allocating and freeing up memory, you might get into trouble. If you are leaking memory, even only a couple of bytes / hour, you might end eating up all available memory. Another area where you need specific skills is for creating systems that need hard real-time functionality. Windows CE is a hard real-time operating system, meaning response times can be guaranteed. But you have to know a lot about how to synchronize threads, potential deadlocks, priority inversion and many other things. And of course, still keep efficient and correct programming in mind. If you are thrilled by all these things and you are still writing desktop applications, perhaps it is time for you to look into embedded development.