In this section you will learn about two additional notification types – Toast and Tile notification. This lab covers the backend server that posts data to MSPNS, as well as how to register and handle these events on your Windows Phone 7 Application.
Tiles and toast notifications are two mechanisms that enable a cloud service to deliver relevant, actionable feedback to users outside an application’s own user interface. Additionally, a cloud service can send a raw notification request. Depending on the type of notification sent, the notification will be routed either to the application or the shell.
Tile Notifications
A tile is a visual, dynamic representation of an application or its content within the Quick Launch area of the phone’s Start experience. For example, a weather application may choose to display the user’s local time and climate conditions in a tile. Because a cloud service can alter its tile’s appearance at any time, this mechanism can be used to communicate information to the user on an ongoing basis. Each application that the user can launch on the phone is associated with a single tile, but only the user can control which of these tiles are pinned to the Quick Launch area.
A cloud service can control a tile's background image, counter (or 'badge'), and title properties. These properties are configured using the Windows Phone Developer Tools. Animation and sound properties are controlled by how the platform is configured, not by the application. For example, if the platform is configured to animate and beep upon any tile update, that is what will occur for any tile.
A tile's background image can reference either a local resource, which is part of the application deployment, or a cloud resource. By referencing a resource in the cloud, applications are enabled to dynamically update a tile's background image. This enables scenarios which require processing of the background image before it is displayed. In most scenarios, the application package should include all needed background images for the tile, since this is the best solution for performance and battery life.
Toast Notifications
A cloud service can generate a special kind of push notification known as a toast notification, which displays as an overlay onto the user’s current screen. For example, a weather application may wish to display a toast notification if a severe weather alert is in effect. If the user decides to click the toast notification, the application can launch and perform other actions.
A cloud service can control a toast notification’s title and sub-title. The toast notification will also display the application’s icon that is included in the application’s deployment package.
Best Practices
- Toast notifications should be personally relevant and time critical.
- Toast notifications should primarily be focused on peer-to-peer communication.
Task 1 – Implementing Server Side of Sending Tiles & Toasts
- Open Microsoft Visual Studio 2010 Express for Windows Phone from Start | All Programs | Microsoft Visual Studio 2010 Express | Microsoft Visual Studio 2010 Express for Windows Phone.
Note:Visual Studio 2010: Open Visual Studio 2010 from Start | All Programs | Microsoft Visual Studio 2010. Important note: In order to run self-hosted WCF services within Visual Phone 2010 Express for Windows Phone or Microsoft Visual Studio 2010 it should be opened in Administrative Mode. For reference about creating and hosting self-hosted WCF services see MSDN article (http://msdn.microsoft.com/en-us/library/ms731758.aspx). In order to open Visual Studio 2010 Express for Windows Phone or Visual Studio 2010 in Administrative Mode locate the Microsoft Visual Studio 2010 Express for Windows Phone shortcut at Start | All Programs | Microsoft Visual Studio 2010 Express or Microsoft Visual Studio 2010 shortcut at Start | All Programs | Microsoft Visual Studio 2010, right-click on the icon and select “Run as administrator” from the opened context menu. The UAC notification will pop up. Click “Yes” in order to allow running the Visual Studio 2010 Express for Windows Phone or Visual Studio 2010 with elevated permissions. - Open the Begin.sln starter solution from the Source\Ex2-TileToastNotifications\Begin folder of this lab. Alternatively, you can continue working on the solution created in previous exercise.
- Open the NotificationSenderUtility.cs file located under the NotificationSenderUtility project.
- Toast and Tile notification are system defined notification in Windows Phone 7 platform. This is different from RAW notifications, where all applications could create their own payload format and parse it accordingly. During next couple steps you will create
general functionality to create Tile & Toast messages payload – this payload will work for any Windows Phone 7 application. In addition you will expose public functionality to send such messages and connect WPF Push Notification Client’s buttons events to
it. Locate the SendXXXNotification functionality region. Add the following public functions to the region (they will be used by the WPF application later):
(Code Snippet – Using Push Notifications – NotificationSenderUtility – SendXXXNotification functions)
public void SendToastNotification(List<Uri> Uris, string message1, string message2, SendNotificationToMPNSCompleted callback) { byte[] payload = prepareToastPayload(message1, message2); foreach (var uri in Uris) SendNotificationByType(uri, payload, NotificationType.Toast, callback); } public void SendTileNotification(List<Uri> Uris, string TokenID, string BackgroundImageUri, int Count, string Title, SendNotificationToMPNSCompleted callback) { byte[] payload = prepareTilePayload(TokenID, BackgroundImageUri, Count, Title); foreach (var uri in Uris) SendNotificationByType(uri, payload, NotificationType.Token, callback); } - Next you’ll create a new region with two functions – first to prepare the Toast notification payload, and second for Tile notification payload preparation.
Tile notification message should be in the following format. Notice that the <background image path>, <count>and <title> elements are in a string format.
Content-Type: text/xml X-WindowsPhone-Target: token <?xml version="1.0" encoding="utf-8"?> <wp:Notification xmlns:wp="WPNotification"> <wp:Tile> <wp:BackgroundImage><background image path></wp:BackgroundImage> <wp:Count><count></wp:Count> <wp:Title><title></wp:Title> </wp:Tile> </wp:Notification>
Toast notification message from the other side should be in the following format. Notice that <Text1> and <Text2> are in string format.
Content-Type: text/xml X-WindowsPhone-Target: toast <?xml version="1.0" encoding="utf-8"?> <wp:Notification xmlns:wp="WPNotification"> <wp:Toast> <wp:Text1><string></wp:Text1> <wp:Text2><string></wp:Text2> </wp:Toast> </wp:Notification>
- Create the Prepare Payload family of functions according to the following code snippet:
(Code Snippet – Using Push Notifications – NotificationSenderUtility – Prepare Payload functions)
#region Prepare Payloads private static byte[] prepareToastPayload(string text1, string text2) { MemoryStream stream = new MemoryStream(); XmlWriterSettings settings = new XmlWriterSettings() { Indent = true, Encoding = Encoding.UTF8 }; XmlWriter writer = XmlWriter.Create(stream, settings); writer.WriteStartDocument(); writer.WriteStartElement("wp", "Notification", "WPNotification"); writer.WriteStartElement("wp", "Toast", "WPNotification"); writer.WriteStartElement("wp", "Text1", "WPNotification"); writer.WriteValue(text1); writer.WriteEndElement(); writer.WriteStartElement("wp", "Text2", "WPNotification"); writer.WriteValue(text2); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndDocument(); writer.Close(); byte[] payload = stream.ToArray(); return payload; } private static byte[] prepareTilePayload(string tokenId, string backgroundImageUri, int count, string title) { MemoryStream stream = new MemoryStream(); XmlWriterSettings settings = new XmlWriterSettings() { Indent = true, Encoding = Encoding.UTF8 }; XmlWriter writer = XmlWriter.Create(stream, settings); writer.WriteStartDocument(); writer.WriteStartElement("wp", "Notification", "WPNotification"); writer.WriteStartElement("wp", "Tile", "WPNotification"); writer.WriteStartElement("wp", "BackgroundImage", "WPNotification"); writer.WriteValue(backgroundImageUri); writer.WriteEndElement(); writer.WriteStartElement("wp", "Count", "WPNotification"); writer.WriteValue(count.ToString()); writer.WriteEndElement(); writer.WriteStartElement("wp", "Title", "WPNotification"); writer.WriteValue(title); writer.WriteEndElement(); writer.WriteEndElement(); writer.Close(); byte[] payload = stream.ToArray(); return payload; } #endregion - Open MainWindow.xaml.cs from the Weather project.
- Locate the sendToast function. This function should get the Toast message from the Push Notification Client UI and send it to all the subscribers. Add the following code snippet in the function body:
(Code Snippet – Using Push Notifications – MainWindow.xaml.cs –sendToast function body)
private void sendToast() { string msg = txtToastMessage.Text; txtToastMessage.Text = ""; List<Uri> subscribers = RegistrationService.GetSubscribers(); ThreadPool.QueueUserWorkItem((unused) => notifier.SendToastNotification(subscribers, "WEATHER ALERT", msg, OnMessageSent)); } - Locate the sendTile function. This function should get the parameters from Push Notification Client UI and send it to all the subscribers. Add the following code snippet in the function body:
(Code Snippet – Using Push Notifications – MainWindow.xaml.cs –sendTile function body)
private void sendTile() { string weatherType = cmbWeather.SelectedValue as string; int temperature = (int)sld.Value; string location = cmbLocation.SelectedValue as string; List<Uri> subscribers = RegistrationService.GetSubscribers(); ThreadPool.QueueUserWorkItem((unused) => notifier.SendTileNotification(subscribers, "PushNotificationsToken", "/Images/" + weatherType + ".png", temperature, location, OnMessageSent)); } - Compile and run the applications. Check that messages are dispatched to the Push Notification Service.

Figure 36 WPF Push Notifications Client log
Note:If you’ve started this exercise from the Begin solution instead of continuing with the previous exercise solution, to run the application, you first need to define multiple startup projects for this solution in order to run WPF Push Notification Client and Windows Phone 7 Push client together. In order to do this, in Solution Explorer right-click on the solution name and select Properties from the context menu. Select the Startup Projects page from Common Properties (if not selected automatically), select Multiple startup projects and set the PushNotifications and Weather projects as Start from the Action drop-down list. 
This step concludes the task.
Task 2 – Processing Tile & Toast Notifications on the Phone
- Open MainPage.xaml.cs in the PushNotifications project.
- In the next few steps you will subscribe to Tile and Toast notification events and will handle those events. Locate the
Subscriptions region and add the following code snippet:
(Code Snippet – Using Push Notifications – MainPage.xaml.cs – SubscribeToNotifications function)
private void SubscribeToNotifications() { ////////////////////////////////////////// // Bind to Toast Notification ////////////////////////////////////////// try { if (httpChannel.IsShellToastBound == true) { Trace("Already bounded (register) to to Toast notification"); } else { Trace("Registering to Toast Notifications"); httpChannel.BindToShellToast(); } } catch (Exception ex) { // handle error here } ////////////////////////////////////////// // Bind to Tile Notification ////////////////////////////////////////// try { if (httpChannel.IsShellTileBound == true) { Trace("Already bounded (register) to Tile Notifications"); } else { Trace("Registering to Tile Notifications"); // you can register the phone application to receive tile images from remote servers [this is optional] Collection<Uri> uris = new Collection<Uri>(); uris.Add(new Uri("http://jquery.andreaseberhard.de/pngFix/pngtest.png")); httpChannel.BindToShellTile(uris); } } catch (Exception ex) { //handle error here } } - Now locate the SubscribeToChannelEvents function and add the following blue-highlighted code snippet to the function body:
(Code Snippet – Using Push Notifications – MainPage.xaml.cs – SubscribeToChannelEvents function body)
private void SubscribeToChannelEvents() { //Register to UriUpdated event - occurs when channel successfully opens httpChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(httpChannel_ChannelUriUpdated); //Subscribed to Raw Notification httpChannel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(httpChannel_HttpNotificationReceived); //general error handling for push channel httpChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(httpChannel_ExceptionOccurred); //subscrive to toast notification when running app httpChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(httpChannel_ShellToastNotificationReceived); } - Locate the Channel event handlers region and add the following function to handle the events:
(Code Snippet – Using Push Notifications – MainPage.xaml.cs – Tile and Toast notifications event handler function)
void httpChannel_ShellToastNotificationReceived(object sender, NotificationEventArgs e) { Trace("==============================================="); Trace("Toast/Tile notification arrived:"); foreach (var key in e.Collection.Keys) { string msg = e.Collection[key]; Trace(msg); Dispatcher.BeginInvoke(() => UpdateStatus("Toast/Tile message: " + msg)); } Trace("==============================================="); }
Note:In our simple case the functions just tracing the message payload, but in real-world application you could use it to perform any business logic. - Lastly, add the following code snippet to the following number of locations:
(Code Snippet – Using Push Notifications – MainPage.xaml.cs – Subscribe toNotifications call)
SubscribeToNotifications();
The locations to add this code snippet are the following:
- In the DoConnect function, in the try block, between “SubscribeToService();” and “Dispatcher.BeginInvoke();”
if (null != httpChannel) { Trace("Channel Exists - no need to create a new one"); SubscribeToChannelEvents(); Trace("Register the URI with 3rd party web service"); SubscribeToService(); Trace("Subscribe to the channel to Tile and Toast notifications"); SubscribeToNotifications(); Dispatcher.BeginInvoke(() => UpdateStatus("Channel recovered")); } - In the httpChannel_ChannelUriUpdated function, between “SubscribeToService();” and “Dispatcher.BeginInvoke(…);”
void httpChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e) { Trace("Channel opened. Got Uri:\n" + httpChannel.ChannelUri.ToString()); Dispatcher.BeginInvoke(() => SaveChannelInfo()); Trace("Subscribing to channel events"); SubscribeToService(); SubscribeToNotifications(); Dispatcher.BeginInvoke(() => UpdateStatus("Channel created successfully")); }
- In the DoConnect function, in the try block, between “SubscribeToService();” and “Dispatcher.BeginInvoke();”
- Press F5 to compile and run the applications. On the phone emulator, click the Back button (
)
to exit the Push Notification application and go to the Quick Launch area. - In the Quick Launch area, click the Right Arrow button to get to the “All Applications” screen.

Figure 37 Opening the installed applications screen
- Locate the PushNotifications item, push it down and hold until context menu pops-up. Click
Pin to Start.

Figure 38 Pinning tile to Start screen
- The emulator will automatically go back to the Quick Launch area where you’ll notice the
PushNotifications tile pinned.

Figure 39 PushNotifications Tile
- On WPF Push Notification Client, change some notifications parameters and click the
Send Tile button. Observe the Tile change in emulator. If you click the
Toast message you will be taken back to the application.

Figure 40 Tile Notification arrived on emulator
- On the WPF Push Notification Client enter some message and click the Send Toast button. Observe how the Toast message arrives to the phone. Click the
Toast message to switch back to the application.

Figure 41 Toast message on phone emulator

Figure 42 Toast message on Windows Phone Application
This step concludes the task.
Task 3 – Processing Scheduled Tile Notifications on the Phone
Note: You can also update the application’s tile by using a shell tile schedule represented by the Microsoft.Phone.Shell.ShellTileSchedule class. This special class allows an application to schedule updates of its tile's background image by setting the background image fully qualified URI and its related scheduler recurrence and interval attributes. When the phone starts the tile schedule instance, it automatically sends a tile notification to the application that then fetches the image based on the qualified URI, and updates the tile.
- In the next few steps you will create an instance of a ShellTileSchedule class that performs updates of the application tile under the hood.
- Open App.xaml.cs in the PushNotifications project.
- Locate the application’s constructor - App method, and insert the following code fragment right after it:
(Code Snippet – Using Push Notifications – MainPage.xaml.cs – CreateShellTileScheduleFunction)
// To store the instance for the application lifetime private ShellTileSchedule shellTileSchedule; /// <summary> /// Create the application shell tile schedule instance /// </summary> private void CreateShellTileSchedule() { shellTileSchedule = new ShellTileSchedule(); shellTileSchedule.Recurrence = UpdateRecurrence.Interval; shellTileSchedule.Interval = UpdateInterval.EveryHour; shellTileSchedule.StartTime = DateTime.Now; shellTileSchedule.RemoteImageUri = new Uri(@"http://cdn3.afterdawn.fi/news/small/windows-phone-7-series.png"); shellTileSchedule.Start(); }
Note:Note that you can only provide a RemoteImageUri. Therefore you must provide an online and available URI that represents an image to download and display. You can’t reference URI from your local application. The image size can NOT exceed 80KB, and download time can NOT exceed 60 sec. - Now, locate the App() function and call the CreateShellTileSchedule function from it (see the highlighted line):
(Code Snippet – Using Push Notifications – MainPage.xaml.cs – CreateShellTileScheduleFunction)
// Constructor public App() { // Global handler for uncaught exceptions. // Note that exceptions thrown by ApplicationBarItem.Click will not get caught here. UnhandledException += Application_UnhandledException; // Standard Silverlight initialization InitializeComponent(); // Phone-specific initialization InitializePhoneApplication(); // Create the shell tile schedule instance CreateShellTileSchedule(); }You just provided the application with the object that will update the application tile according to the schedule properties.
- You have set the property:
- Recurrent to the value Interval, which causes the tile to be periodically updated. The other possible value for this property is OneTime, which causes the tile to update only once.
- Interval to the value EveryHour, which causes the tile to be updated every 60 minutes. It is worth mentioning that an hour is the minimum possible value for the update interval. This restriction is in place to save phone resources.
- RemoteImageUri to the address where you want to get tile image updates from.
And after all that, you have called the Start method to start updating the tile. Be aware that the first update may delay for an hour because this class invokes updates on full hours. The tile update schedule is kind of funky. Even if you set StartTime to now, you’ll need to wait for the phone update, which occurs up to every 60 minutes. Unfortunately, this is a system limitation, so if you want to debug this code, you have to wait for that one hour. I usually debug this code overnight.
- Press F5 to compile and run the applications. On the phone emulator, click the Back button (
)
to exit the Push Notification application and go to the Quick Launch area. - Verify that your application tile is pinned in the Quick Launch area, else pin it according to the procedure defined in steps 7-9 of Task 2.
- The PushNotifications tile image now will be updated according to the ShellTileSchedule definitions. So when the first schedule interval expires sometime in the next hour, the application tile will display the image located at the address stored in RemoteImageUri
property,
http://cdn3.afterdawn.fi/news/small/windows-phone-7-series.png.

Figure 43 Scheduled Tile Image
This concludes the exercise and the lab.
Note:The complete solution for this exercise is provided at the following location: Source\Ex2-TileToastNotifications\End.