Category Archives: Silverlight

AdControl, Animations and the Back Key

Sometimes things don’t make sense, but bugs in software hardly do. In a new Windows Phone application I am implementing a fully functional trial mode that displays advertisements using Microsoft’s AdControl. I made sure to use the latest version of the AdControl (which is version 6.1.320.0). On one of the pages inside the application has both a list and detail view. If an item is selected from a list, the list disappears in the center of the page and detail information zooms in, making use of a few animations. Since the detail view seems to be a new page (even though it isn’t), I am overriding default hardware Back button behavior. If details are displayed when the hardware Back button is pressed, the list view becomes visible again. If the list view was already visible, I simply navigate back to the previous page. All in all, this functionality is straight forward and it is not uncommon to reuse pages for different views.

However, when I was testing the application, I ran into some unexpected behavior. With the AdControl visible, the animation that was supposed to run on pressing the hardware Back button did not run smoothly and sometimes it didn’t run at all. However, with the AdControl not visible, the animation was always running nice and smoothly.

This code is executed on pressing the hardware Back button:

Switching from detail to list
  1. protected override void OnBackKeyPress(CancelEventArgs e)
  2. {
  3.     if (lastActiveListBox != null)
  4.     {
  5.         e.Cancel = true;
  6.         lastActiveListBox = null;
  7.         VisualStateManager.GoToState(this, "TreeListState", true);
  8.     }
  9.     base.OnBackKeyPress(e);
  10. }

The following video shows the application in action, once with an AdControl on the page and once without the AdControl:

The AdControl influences animations

Of course this behavior is unacceptable for my application, so the next step is trying to work around the issue. After investigating a bit further, it seems that the combination of showing an AdControl and triggering an animation on the hardware Back button causes the problem. For instance, executing exactly the same code, but this time when tapping on the title bar (after adding a tap event handler), always results in smooth animations, independent of displaying an AdControl.

  1. protected override void OnBackKeyPress(CancelEventArgs e)
  2. {
  3.     if (lastActiveListBox != null)
  4.     {
  5.         e.Cancel = true;
  6.         lastActiveListBox = null;
  7.         VisualStateManager.GoToState(this, "TreeListState", true);
  8.     }
  9.     base.OnBackKeyPress(e);
  10. }
  11.  
  12. private void ApplicationTitle_Tap(object sender, System.Windows.Input.GestureEventArgs e)
  13. {
  14.     if (lastActiveListBox != null)
  15.     {
  16.         lastActiveListBox = null;
  17.         VisualStateManager.GoToState(this, "TreeListState", true);
  18.     }
  19. }

Triggering the animation on the hardware Back button still shows the same behavior though:

The AdControl in combination with the Back Key influences animations

I am not sure what causes the problem. However, the fact that the animation runs smoothly when triggered in another way got me thinking about a more or less acceptable work around with not too much additional code involved. Since starting the animation on another event got rid of my problem, I came to the following solution. When the hardware Back button is pressed in my detailed view, I start a Timer that expires immediately. In the Tick event of the timer I am simply stopping the timer and I am starting the animation. This resulted in the following code:

Start animation on timer tick
  1. private DispatcherTimer timer;
  2.  
  3. public TreePage()
  4. {
  5.     InitializeComponent();
  6.  
  7.     if (App.ShowAds)
  8.     {
  9.         timer = new DispatcherTimer();
  10.         timer.Tick += new EventHandler(timer_Tick);
  11.         ah = new AdHelper(AdPlaceHolder, true);
  12.         this.Loaded += new RoutedEventHandler(ah.PhoneApplicationPage_Loaded);
  13.     }
  14.  
  15. }
  16.  
  17. void timer_Tick(object sender, EventArgs e)
  18. {
  19.     timer.Stop();
  20.     VisualStateManager.GoToState(this, "TreeListState", true);
  21. }
  22.  
  23. protected override void OnBackKeyPress(CancelEventArgs e)
  24. {
  25.     if (lastActiveListBox != null)
  26.     {
  27.         e.Cancel = true;
  28.         lastActiveListBox = null;
  29.         if (App.ShowAds)
  30.         {
  31.             timer.Start();
  32.         }
  33.         else
  34.         {
  35.             VisualStateManager.GoToState(this, "TreeListState", true);
  36.         }
  37.     }
  38.     base.OnBackKeyPress(e);
  39. }

This time the animation displays smoothly, independent of the presence or absence of an AdControl as is shown in the following video:

Animations are smooth when started on a Timer Tick

It would have been great if I could have explained why the AdControl in combination with the hardware Back button influences animations. For right now I assume this is a bug in the AdControl. At least, the work around shown in the blog entry is relatively simple and is not a big influence on either the memory footprint or the performance of your Windows Phone application. When a new version of the AdControl is available, I will make sure to test the identical scenario again and update this blog entry when results have changed.

Advertisements

EvenTiles and Push Notifications

In the previous part of EvenTiles, you saw that applications running on 256-MB Devices cannot use Periodic Agents. Of course the application is still working, but the content of the backside of a Secondary Tile, when pinned to the start screen, does not alter. Since 256-MB Windows Phone Devices fully support Push Notifications, it is possible to change the Secondary Tile content with a little extra effort. In this episode of EvenTiles we will take a look at adding Tile Notifications to the application. Those Tile Notifications are delivered to individual Windows Phone devices through the Microsoft Push Notification Service, just like all other Push Notifications.

In this blog entry we will concentrate on the client side, mainly providing code that registers the application. To test the application, we will make use of a little ASP.NET application that is based on the sample that is introduced in the How to Send and Receive Tile Notifications for Windows Phone article. It is beyond the scope of this blog entry to show how to host a web service (for instance by making use of Azure functionality).

NOTE: The ASP.NET test application cannot be created using Visual Studio 2010 Express for Windows Phone. You either need at least Visual Studio 2010 Professional or the free Visual Web Developer 2010 Express to create the test application.

Push Notifications on Secondary Tiles

Something that is not entirely clear in the referred How to article, or in the documentation around Push Notifications on MSDN is the fact that sending Tile Updates through Push Notifications is not limited to the Application Tile, but you can also use the same approach to update Secondary Tiles. Since we are dealing with a Secondary Tile in the EvenTiles application, we will focus on updating a Secondary Tile. In the ASP.NET test application we will create the following message to update our tile:

Updating a Seondary Tile
  1. // Create the Tile message.
  2. string tileMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
  3. "<wp:Notification xmlns:wp=\"WPNotification\">" +
  4.     "<wp:Tile ID=\"/MainPage.xaml?TileId=Secondary\">" +
  5.       "<wp:BackContent>" + TextBoxBackContent.Text + "</wp:BackContent>" +
  6.       "<wp:Count>" + nrRuns.ToString() + "</wp:Count>" +
  7.    "</wp:Tile> " +
  8. "</wp:Notification>";

By explicitly specifying the ID of a tile you can inform the Push Notification Service that you want to update a specific (Secondary) Tile. Omitting the ID passes the update to the Application Tile. Since EvenTiles creates the Secondary Tile as shown below, passing the Tile Notification message as shown above will update the Secondary Tile if it is pinned to the Start Screen. In the sample we only update the BackContent of the Secondary Tile and the count on the front of it, but it is possible to update more properties of the Secondary Tile. Of course it is important to use the same URI for the Secondary Live Tile when updating it through a Tile Notification.

Creating a Secondary Tile
  1. private void btnInstall_Click(object sender, RoutedEventArgs e)
  2. {
  3.     StandardTileData NewTileData = new StandardTileData
  4.     {
  5.         BackgroundImage = new Uri("Background.png", UriKind.Relative),
  6.         Title = "EvenTiles",
  7.         Count = 0,
  8.         BackBackgroundImage = new Uri("BackBackTile.png", UriKind.Relative),
  9.         BackTitle = "EvenTiles",
  10.         BackContent = App.ActualSecBackContent
  11.     };
  12.     ShellTile.Create(new Uri("/MainPage.xaml?TileId=Secondary", UriKind.Relative), NewTileData);
  13. }

In order to receive Tile Notifications in EvenTiles, the application needs to create a HttpNotificationChannel or attach to an already created channel if the application is started again on a particular Windows Phone device. The following code snippet shows how to setup a new notification channel. If the channel is successfully opened, it will pass a URI through the ChannelUriUpdated event handler. This URI is used to send notifications to the particular Windows Phone Device that received this URI from the Push Notification Service. This URI is unique for the application and the phone on which the application is running. If the channel already exists, this method simply starts listening for channel changes or errors through the ChannelUriUpdated and ErrorOccurred events respectively.

Getting a Notification Channel
  1. public class TileNotifications
  2. {
  3.     public const string tileNotificationChannel = "EvenTilesChannel";
  4.  
  5.     public void SetupChannel()
  6.     {
  7.         var pushChannel = HttpNotificationChannel.Find(tileNotificationChannel);
  8.         if (pushChannel == null)
  9.         {
  10.             pushChannel = new HttpNotificationChannel(tileNotificationChannel);
  11.             pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
  12.             pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
  13.             pushChannel.Open();
  14.             pushChannel.BindToShellTile();
  15.         }
  16.         else
  17.         {
  18.             pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
  19.             pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
  20.  
  21.             // Display the URI for testing purposes. Normally, the URI would be passed back to a web service.
  22.             System.Diagnostics.Debug.WriteLine(pushChannel.ChannelUri.ToString());
  23.         }
  24.     }

If you want to send out push notifications from a web service, the Windows Phone application typically would send this URI to a web service, that in turn uses it to deliver the push notifications to the registered device. In our test application we simply display the URI in the debug windows of Visual Studio to be able to copy it to our ASP.NET test application.

If you are no longer interested in receiving Tile Notifications for your application, you can close a previously opened HttpNotificationChannel, make sure to dispose of it and also make sure to unsubscribe to events to prevent against leaking memory. The following code snippet shows how you can stop receiving Tile Notifications:

Closing a Notification Channel
  1. public void CloseChannel()
  2. {
  3.     var pushChannel = HttpNotificationChannel.Find(tileNotificationChannel);
  4.     if (pushChannel != null)
  5.     {
  6.         pushChannel.ChannelUriUpdated -= PushChannel_ChannelUriUpdated;
  7.         pushChannel.ErrorOccurred -= PushChannel_ErrorOccurred;
  8.         pushChannel.Close();
  9.         pushChannel.Dispose();
  10.         App.GetLiveTileNotifications = false;
  11.     }
  12. }

Finally, in our EvenTiles application we implement some simplified event handling to react on push channel changes and errors. This implementation is for demonstration purposes only and can be used to manually pass a channel URI to an ASP.NET application or to close down / reinitialize the push channel on certain errors. The following code snippet shows how we simply write the channel URI to the Output Window of Visual Studio.

Handling Push Channel Events
  1. void PushChannel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
  2. {
  3.     switch (e.ErrorType)
  4.     {
  5.         case ChannelErrorType.ChannelOpenFailed:
  6.             App.GetLiveTileNotifications = false;
  7.             break;
  8.         case ChannelErrorType.PayloadFormatError:
  9.             SetupChannel();
  10.             break;
  11.         default:
  12.             CloseChannel();
  13.             break;
  14.     }
  15. }
  16.  
  17. void PushChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
  18. {
  19.     System.Diagnostics.Debug.WriteLine(e.ChannelUri.ToString());
  20.     App.GetLiveTileNotifications = true;
  21. }

imageTo send Tile Notifications to EvenTiles, make sure to run EvenTiles and enable Tile Notifications through the Settings Page. Once Tile Notifications are enabled, you can copy the channel URI from the Visual Studio Output Window and paste it in the ASP.NET test application. After this step, you can send tile updates to EvenTiles.

 

imageThe ASP.NET test application does so in a ThreadPool thread. You can specify the number of updates and the time between updates. Each time another update is send, the count property that will be displayed on the front side of the Secondary Tile that EvenTiles pinned on the start screen will be updated.

Even though Background Agents are not supported on 256-MB devices, we have a nice workaround by making use of Push Notifications because they are fully supported. Of course this means that you need to invest more in server side programming, but it also means that the end user experience of a Windows Phone application can be very similar on both a 512-MB device and a 256-MB device. For this to work, the target device must have a network connection.

The complete sample code for EvenTiles so far can be downloaded here. If you want to test the application on a 256-MB device (emulator), you will need to download and install the Windows Phone 7.1.1 SDK Update as well. The ASP.NET test application is also available as a separate download. In order to run this test application, you need a version of Visual Studio 2010 that supports creating  and debugging ASP.NET applications.

The following video shows how to subscribe to Tile Notifications from within the EvenTiles application and how to test the newly added functionality by means of an APS.NET test application.

Using Push Notifications to update Live Tiles on Windows Phone

MessageBox, Navigation and Application Life Cycle

One of our applications failed certification today because of an issue I should have known about. Even though the scenario in which an exception occurs is fairly easy, solving the problem properly involves a little work and a little thinking. Other blog entries have been written about this particular problem, although suggested solutions did not seem to work for me. Let me first show the original code:

MessageBox and Navigation
  1. private void TurnCard_Click(object sender, System.Windows.RoutedEventArgs e)
  2. {
  3.     MessageBoxResult mr = MessageBoxResult.Cancel;
  4.  
  5.     if (nrTimesClicked > 2)
  6.     {
  7.         mr = MessageBox.Show("Continuing now might confuse you. Try again tomorrow?",
  8.             "Continuing tomorrow?", MessageBoxButton.OKCancel);
  9.     }
  10.  
  11.     if (mr == MessageBoxResult.OK)
  12.     {
  13.         NavigationService.GoBack();
  14.     }
  15.     else
  16.     {
  17.         Random r = new Random();
  18.         int card = r.Next(cardPages.Length);
  19.         NavigationService.Navigate(new Uri(cardPages[card], UriKind.Relative));
  20.         nrTimesClicked++;
  21.     }
  22. }

Running this code and clicking the Start button on the phone while the MessageBox is visible results in the following exception when running with the debugger attached (it results in an application termination when running stand-alone):

image

The NavigationFailed event is raised. This is caused by the fact that the MessageBox returns when clicking the phone’s Start button with a return value of MessageBoxResult.Cancel. Since in the above code fragment, the Cancel button is used to navigate to some page, even though the application is supposed to go to the background in order to display the start screen on the phone, navigation fails. The interesting part is that the application does not have a clue that the user pressed the Start button on the phone. So some thinking is required to fix this issue.

Single stepping through the problematic method TurnCard_Click showed another behavior:

image

This at least made clear that indeed the call to the NavigationService caused the problem. To solve the problem, what can be done is protecting calls to the NavigationService by catching this particular exception:

Protecting the Navigate method
  1. private void TurnCard_Click(object sender, System.Windows.RoutedEventArgs e)
  2. {
  3.     MessageBoxResult mr = MessageBoxResult.Cancel;
  4.  
  5.     if (nrTimesClicked > 2)
  6.     {
  7.         mr = MessageBox.Show("Continuing now might confuse you. Try again tomorrow?",
  8.             "Continuing tomorrow?", MessageBoxButton.OKCancel);
  9.     }
  10.  
  11.     if (mr == MessageBoxResult.OK)
  12.     {
  13.         NavigationService.GoBack();
  14.     }
  15.     else
  16.     {
  17.         Random r = new Random();
  18.         int card = r.Next(cardPages.Length);
  19.         try
  20.         {
  21.             NavigationService.Navigate(new Uri(cardPages[card], UriKind.Relative));
  22.         }
  23.         catch (InvalidOperationException)
  24.         {
  25.             ;
  26.         }
  27.         nrTimesClicked++;
  28.     }
  29. }

This does solve the problem, although I don’t like it that an exception is thrown in a situation that the operating system should somehow prevent us against (maybe by returning some other value when the MessageBox returns without the user clicking on one of its buttons). If you want to have a little more flexibility, and don’t mind coding a bit more, there is another possible solution. Instead of using a MessageBox, you can make use of the Guide.BeginShowMessageBox method that is defined in the XNA Framework. This method is a bit more complex, but also much more flexible then its Silverlight counterpart. BeginShowMessageBox is asynchronous, which means that you need to take care with calling code that is supposed to run on the UI Thread.

Using BeginShowMessageBox
  1. private void TurnCard_Click(object sender, System.Windows.RoutedEventArgs e)
  2. {
  3.     if (nrTimesClicked > 2)
  4.     {
  5.         ShowContinueMessage();
  6.     }
  7.     else
  8.     {
  9.         Random r = new Random();
  10.         int card = r.Next(cardPages.Length);
  11.         nrTimesClicked++;
  12.         NavigationService.Navigate(new Uri(cardPages[card], UriKind.Relative));
  13.     }
  14. }
  15.  
  16. private void ShowContinueMessage()
  17. {
  18.     List<string> mbOptions = new List<string>();
  19.     mbOptions.Add("OK");
  20.     mbOptions.Add("Cancel");
  21.     string msg = "Continuing now might confuse you. Try again tomorrow?";
  22.     string title = "Continuing tomorrow?";
  23.     Guide.BeginShowMessageBox(title, msg, mbOptions, 0, MessageBoxIcon.Alert, EnteredAnswer, null);
  24.     messageBoxVisible = true;
  25. }
  26.  
  27. private void EnteredAnswer(IAsyncResult ar)
  28. {
  29.     int? result = Guide.EndShowMessageBox(ar);
  30.  
  31.     if (result != null)
  32.     {
  33.         messageBoxVisible = false;
  34.     }
  35.  
  36.     if (result != null && result == 0)
  37.     {
  38.         this.Dispatcher.BeginInvoke(delegate
  39.         {
  40.             NavigationService.GoBack();
  41.         });
  42.     }
  43.     else if (result != null)
  44.     {
  45.         Random r = new Random();
  46.         int card = r.Next(cardPages.Length);
  47.         this.Dispatcher.BeginInvoke(delegate
  48.         {
  49.             NavigationService.Navigate(new Uri(cardPages[card], UriKind.Relative));
  50.         });
  51.     }
  52. }

The interesting code can be found in the EnteredAnswer method, where we retrieve the key the user entered in the message box. Since EndShowMessageBox returns a nullable integer, it has this nice way of using null in those cases where the user did not click any key (in other words, for instance when the message box is removed as a result of the application going to the background). So now we have a way of detecting if we can navigate (result has a value other then null). The sample code also sets a boolean variable messageBoxVisible, which is used in combination with PhoneApplicationPage.State to display the message box again when the user returns to the application. Hopefully this time the application will pass certification.

EvenTiles from Start to Finish–Part 14

In the previous episode of this series about how to develop a Windows Phone application from scratch we found out that special care must be taken when data must be passed between an application and its PeriodicTask. You learned how data can be protected against mutual access by using a Mutex object. You also learned that you cannot pass data directly from one to another, because the application and its PeriodicTask execute inside different processes.

In this episode of EvenTiles you will learn how you can make use of IsolatedStorage to pass data from the application to the PeriodicTask. Since we already created a separate project in the EvenTiles solution that is taking care of passing data, we can simply modify functionality in that project (EvenTilesComm) to use a file to pass data between the application and its PeriodicTask. Data protection against mutual access is already in place, so we can concentrate on file access. Hopefully the design decision in part 13 to make use of private methods that are called each time we access a public property inside the TileData class starts to make sense now.

What we want to achieve is the following:

  • From inside the application we can store a string containing content for the backside of a Secondary Tile in a file at any time
  • Our PeriodicTask executes approximately once per 30 minutes and it either displays the string passed by the application on the backside of the Secondary Tile or it displays a default string that is defined inside the PeriodicTask
  • The content of the backside of the Secondary Tile needs to toggle each time the PeriodicTask executes
  • If the EvenTiles user modifies the string to be displayed inside the Settings page, it will immediately be displayed on the Secondary Tile (if it exists)

In order to pass data between the application and the PeriodicTask we will extend the private retrieve / store methods inside the TileData class by adding a call to a couple of other private methods. Those new private methods will use a file in IsolatedStorage to read / write data from, meaning we can effectively pass data between the application and its PeriodicTask.

Properties to access Tile Data
  1. private static string RetrieveSecondaryBackContent()
  2. {
  3.     mtx.WaitOne();
  4.  
  5.     try
  6.     {
  7.         RetrieveTileContent();
  8.         return secondaryBackContent;
  9.     }
  10.     finally
  11.     {
  12.         mtx.ReleaseMutex();
  13.     }
  14. }
  15.  
  16. private static void StoreSecondaryBackContent(string content)
  17. {
  18.     mtx.WaitOne();
  19.  
  20.     try
  21.     {
  22.         secondaryBackContent = content;
  23.         PersistTileContent();
  24.     }
  25.     finally
  26.     {
  27.         mtx.ReleaseMutex();
  28.     }
  29. }

A new string to be displayed on the back side of a Secondary Tile will be stored by the application each time users modify their own tile text in the Settings Page of the EvenTiles application (something that will also be done initially when the application starts). The PeriodicTask simply retrieves that data (since now the data is persisted in a file this will work properly) and displays it on the back side of the Secondary Tile. Each time data needs to be stored a new file is created in IsolatedStorage or an existing file is overwritten. Each time data needs to be retrieved, we check if a file containing that data exists. There are small ways to optimize data access in the TileData class, because right now we simply read / write all file content when retrieving / storing single property values. However, this approach simplifies the code and the overhead with only two different variables is very small.

Using IsolatedStorage
  1. private const string contentFileName = "EvenTileContent.txt";
  2.  
  3. private static void PersistTileContent()
  4. {
  5.     using (var store = IsolatedStorageFile.GetUserStoreForApplication())
  6.     {
  7.         using (var contentStream = new StreamWriter(store.CreateFile(contentFileName)))
  8.         {
  9.             contentStream.WriteLine(showDefaultSecondaryBackContent.ToString());
  10.             contentStream.WriteLine(secondaryBackContent);
  11.         }
  12.     }
  13. }
  14.  
  15. private static void RetrieveTileContent()
  16. {
  17.     using (var store = IsolatedStorageFile.GetUserStoreForApplication())
  18.     {
  19.         if (store.FileExists(contentFileName))
  20.         {
  21.             using (var contentStream = new StreamReader(store.OpenFile(contentFileName, FileMode.Open)))
  22.             {
  23.                 showDefaultSecondaryBackContent = Convert.ToBoolean(contentStream.ReadLine());
  24.                 secondaryBackContent = contentStream.ReadToEnd();
  25.             }
  26.         }
  27.     }
  28. }

With the way we organized the functionality inside the TileData class in the previous episode of this development series, these are the only new methods necessary in order to pass data. When the user installs a Secondary Tile for the EvenTiles application and modifies its back string content through the Settings page, this is the result (changing the back content of the Secondary Tile every 30 minutes):

image

The following video shows EvenTiles in action with proper transfer of data between the application and its PeriodicTask.

Data transfer between an Application and a PeriodicTask through IsolatedStorage

To be able to experiment with this working implementation of EvenTiles, especially to understand how the application interacts with the PeriodicTask through a file in IsolatedStorage, the sample code is available for dowload here.

Right now we have the basic functionality of EvenTiles more or less ready, although the About Page still needs to get some content. That is something we will work on in the next part of EvenTiles. After that we will cover much more in the upcoming episodes of EvenTiles including but not limited to

  • using ads in the application
  • retrieving location information inside the application
  • taking pictures
  • modifying pictures
  • using alarms and notifications
  • using Visual Studio’s integrated Performance Analysis to find performance bottlenecks inside the application
  • submitting the application for certification

EvenTiles will continue soon so stay tuned for the next episode.

EvenTilesIf you want to see EvenTiles already in action on your Windows Phone, you can also install the latest version from Marketplace. Remember that this application is not meant to be extremely useful, although it contains similar functionality that “serious” applications have. 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 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 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.

Windows Phone Application Development & Debugging – Deactivation versus Tombstoning

While creating an update of an existing application I ran into a problem that sometimes occurred when the application was moved to the background. It turned out that the application behaved consistent with no exceptions raised when it was tombstoned after being moved to the background. However, the application sometimes crashed when it was deactivated and immediately became the executing application again without being tombstoned. In a later post I will explain the specific problem that caused the application to crash, for now I want to focus on ways to easily test deactivation scenarios.

Visual Studio 2010 has great support to test tombstoning scenarios for Windows Phone applications. Simply start debugging an application on a device or on device emulator and click the start button on the device (emulator). You will notice that the application moves to the background but that Visual Studio does not terminate its debugging session. Putting a breakpoint inside Activated / Deactivated event handlers shows us that the application is indeed being tombstoned / resurrected.

Visual Studio and Tombstoning

The debugger shows that the application is still running even though the application is no longer visible on the device. By using the back key on the device, it is possible to return to the application and to continue debugging it. However, if you start the application again on the device (so not using the back key), the debugger terminates. This means that a brand new instance of the application was started. Inside an application, it is possible to distinguish between a new instance being started and resurrection from being tombstoned by acting on the Launching or Activated events respectively. In both cases, the constructor of the page that becomes visible will be executed. More information about the application life cycle of a Windows Phone application can be found in this excellent series of blog entries by Yochay Kiriaty.

There are situations where an application is moved to the background without being tombstoned. In those situations, the application simply remains resident in memory, with its process being kept alive. When the application is activated again, it simply continues running without the need to create a new physical instance of the application. For end users the behavior is identical to tombstoning, after all, the application becomes invisible when another application starts executing. For developers there is a difference though, because no Launching or Activated event is raised and no constructor code (for instance for the currently visible page) is executed. To be able to consistently test application deactivation requires some additional work. One of the ways to ‘force’ deactivation over tombstoning is by starting a PhotoChooserTask. In my own application I simply use the application bar to add a new ApplicationBarIconButton to display a PhotoChooserTask.

To assure that this ApplicationBarIconButton is only visible in Debug mode, a bit of conditional compilation is needed. The following code snippet shows how to create a new ApplicationBarIconButton programmatically, add it to the ApplicationBar and add an event handler to its click event.

Adding an ApplicationBar Item
  1. #if DEBUG
  2. PhotoChooserTask _pt;
  3. #endif
  4.  
  5. public MainPage()
  6. {
  7.     InitializeComponent();
  8.  
  9. #if DEBUG
  10.     _pt = new PhotoChooserTask();
  11.  
  12.     this.ApplicationBar.IsVisible = true;
  13.  
  14.     ApplicationBarIconButton pauseButton = new ApplicationBarIconButton
  15.     {
  16.         Text = "Pause App",
  17.         IconUri = new Uri("/Images/appbar.transport.pause.rest.png", UriKind.Relative),
  18.         IsEnabled = true
  19.     };
  20.  
  21.     pauseButton.Click += new EventHandler(pauseButton_Click);
  22.     this.ApplicationBar.Buttons.Add(pauseButton);
  23. #endif
  24. }

Of course, adding a button to an existing ApplicationBar only works if the application has 3 or less ApplicationBarButtonIcons in use. An alternative could for instance be adding a MouseLeftButtonDown event handler to the application’s title. When clicking the ApplicationBarButtonIcon you created specifically for debug purposes, what you now can do is display the PictureChooserTask. This results in your application being pushed to the background, without being tombstoned.

Forcing us to the background
  1. void pauseButton_Click(object sender, EventArgs e)
  2. {
  3.     _pt.Show();
  4. }

This approach makes it relatively easy to test the different scenarios for your application going to the background and returning to the foreground again. Here are the results in a little test application.

TombstoningOrNot

In the left screen you can see the application immediately after the main page became visible. In the center screen you see the result of clicking the pause button, after which a PhotoChooserTask was activated and closed again. What you can see is that there is no Application_Deactivated / Application_Activated combination. You can also see that no constructor is called after returning from the PhotoChooserTask. In other words, the application is not tombstoned while the PhotoChooserTask is active. Finally, the right screen shows how the application returns from being tombstoned. In this case constructors are called and Application_Activated is raised.

The issue I had in one of my applications had to do with counting on constructors to be called to dynamically add a few controls to my visual tree.

Note: This blog entry is applicable for Windows Phone 7. For the next version of Windows Phone (codenamed Mango), developers can choose between tombstoning and fast application switching by setting the corresponding property in the project settings. Fast application switching could be considered as another state in the application’s life cycle, being very similar to the situation that was described in this post using the PhotoChooserTask.

A new Windows Phone 7 Device (Emulator)?

Just a few hours ago, the Windows Phone Developer Tools Update was released by Microsoft. This update is specifically for Windows Phone application developers to allow them to build apps that are ready for the upcoming Windows Phone OS update. After installation of the tools update, you can test copy and paste functionality on the (also updated) emulator.

In order to start working with the updated tools, you will need to download the Windows Phone Developer Tool update and a separate Visual Studio 2010 update. Also make sure to read the Release Notes for the update. The order of installation for the separate tools is not important but you have to install them both. A little more background information about the latest WPDT update can be found on the Windows Phone Developer Blog.

It is expected that all existing apps that are already published in Marketplace will continue to work, both on phones that will be updated to the new version of the OS that will be available later, but also on phones that are not updated. To show the new copy and paste feature of Windows Phone 7 in action I have created a small application that takes a URL and allows that URL to be copied in Internet Explorer on the Windows Phone Emulator. To see this little application in action, just take a look at this video.

Windows Phone 7 Copy and Paste with the WPDT January Update.