How to send and receive Tile notifications for Windows Phone 8

Applies to: Windows Phone 8 and Windows Phone Silverlight 8.1 | Windows Phone OS 7.1

This topic introduces you to the steps needed to send Tile notifications to the Microsoft Push Notification Service so that a pinned Tile for your application on a Windows Phone will be updated. Push notifications for Windows Phone 8 has information on Tile notifications and how they are used.

You can download the complete Tile Notification Sample.

Important noteImportant Note:

The section of this topic that sends a Tile notification from an ASP.NET webpage running on a web server requires either the full version of Visual Studio or the free Visual Studio Express for Web.

This topic contains the following sections.

In this section, we create an application that runs on a Windows Phone that creates a push notification channel and handles notification events.

Important noteImportant Note:

For simplicity, we copy and paste the toast notification URI to our webpage that sends the notification. Normally, this URI is passed to a web service that you have created for your application.

To create a push client to receive Tile notifications

  1. Create a new Windows Phone app.

  2. Name the project TileNotificationClient.

  3. Add the following using directive to the top of the MainPage.xaml.cs file.

    
    using Microsoft.Phone.Notification;
    
    
  4. Create two or three graphics for images to update the Tile with. For example, you can use Microsoft Paint to create three .jpg files that are 173 x 173 pixels and are a solid color of red, green, and blue. Name them Red.jpg, Green.jpg, and Blue.jpg.

  5. Add the graphics files to the project by right-clicking the TileNotificationSample project name and selecting Add..., and then Existing Item. Select the three images you created and add them to the project.

  6. Select Red.jpg in the Solution Explorer. In the Properties window, set its Build Action to Content to include the graphic as part of the .xap file. Repeat these steps for the other .jpg files.

  7. Replace the MainPage constructor with the following code. This code looks to see whether a Tile notification channel has already been set up in a previous instance of the application. If the notification channel is found, it connects to the notification events. If the notification channel is not found, it is created and then connects to the notification events.

    
            public MainPage()
            {
                /// Holds the push channel that is created or found.
                HttpNotificationChannel pushChannel;
    
                // The name of our push channel.
                string channelName = "TileSampleChannel";
    
                InitializeComponent();
    
                // Try to find the push channel.
                pushChannel = HttpNotificationChannel.Find(channelName);
    
                // If the channel was not found, then create a new connection to the push service.
                if (pushChannel == null)
                {
                    pushChannel = new HttpNotificationChannel(channelName);
    
                    // Register for all the events before attempting to open the channel.
                    pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
                    pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
    
                    pushChannel.Open();
    
                    // Bind this new channel for Tile events.
                    pushChannel.BindToShellTile();
    
    
                }
                else
                {
                    // The channel was already open, so just register for all the events.
                    pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
                    pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
    
                    // Display the URI for testing purposes. Normally, the URI would be passed back to your web service at this point.
                    System.Diagnostics.Debug.WriteLine(pushChannel.ChannelUri.ToString());
                    MessageBox.Show(String.Format("Channel Uri is {0}",
                        pushChannel.ChannelUri.ToString()));
    
                }
            }
    
    
    
  8. Next, we add the code for the event handlers. The first event handler is for the ChannelUriUpdated event. For simplicity, the channel URI is displayed here, but normally this URI would be sent back to your web service.

            void PushChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
            {
    
                Dispatcher.BeginInvoke(() =>
                {
                    // Display the new URI for testing purposes. Normally, the URI would be passed back to your web service at this point.
                    System.Diagnostics.Debug.WriteLine(e.ChannelUri.ToString());
                    MessageBox.Show(String.Format("Channel Uri is {0}",
                        e.ChannelUri.ToString()));
                    
                });
            }
    
    
  9. The next event handler is for error handling. Your code should gracefully handle notification errors, because data connections can vary depending on the location and services of the phone.

            void PushChannel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
            {
                // Error handling logic for your particular application would be here.
                Dispatcher.BeginInvoke(() =>
                    MessageBox.Show(String.Format("A push notification {0} error occurred.  {1} ({2}) {3}",
                        e.ErrorType, e.Message, e.ErrorCode, e.ErrorAdditionalData))
                        );
            }
    
    

The push client code is now complete. We will run this code after we have completed our webpage that sends the notification.

In this section, we create an ASP.NET webpage that sends a Tile notification by using the URI that is returned when the push channel is created on the device.

Important noteImportant Note:

If you need to use remote Internet URIs for Tile images, you must take the following steps:

  1. Ensure the remote image file size is less than 150 KB.

  2. Ensure the image can be downloaded in 60 seconds or less.

  3. On your HttpNotificationChannel object, you must specify the remote base URIs in the BindToShellTile(Collection<Uri>) method.

To create an ASP.NET project, you need the full version of Visual Studio or the free Visual Studio Express for Web.

To create an ASP.NET page for sending Tile notifications

  1. Open another instance of Visual Studio and create a new application. The template should be a ASP.NET Empty Web Application under the Web C# categories.

  2. Name the project SendTile.

  3. Add a new web form to the project by right-clicking the SendTile project name, selecting Add, then New Item…, and then Web Form.

  4. Name the form SendTile and click the Add button.

  5. Make the SendTile form the start page by right-clicking SendTile.aspx in the Solution Explorer and then selecting Set as Start Page.

  6. The next step is to add the following controls to the SendTile.aspx web form.

    Control type

    Control ID

    Text for control

    TextBox

    TextBoxUri

    Enter Uri:

    TextBox

    TextBoxTitle

    Enter Title:

    TextBox

    TextBoxBackgroundImage

    Enter Image:

    TextBox

    TextBoxCount

    Enter Count:

    TextBox

    TextBoxBackTitle

    Enter Back Title:

    TextBox

    TextBoxBackBackgroundImage

    Enter Back Background Image:

    TextBox

    TextBoxBackContent

    Enter Back Content:

    Button

    ButtonSendTile

    Send Tile Notification:

    TextBox

    TextBoxResponse

    Response:

    The Send Tile button will have a ButtonSendTile_Click event handler. Replace the contents of SendTile.aspx with the following code to create these controls.

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SendTile.aspx.cs" Inherits="SendTile.SendTile" %>
    <!-- 
        Copyright (c) 2011 Microsoft Corporation.  All rights reserved.
        Use of this sample source code is subject to the terms of the Microsoft license 
        agreement under which you licensed this sample source code and is provided AS-IS.
        If you did not accept the terms of the license agreement, you are not authorized 
        to use this sample source code.  For the terms of the license, please see the 
        license agreement between you and Microsoft.
    -->
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    
    <body>
        <form id="form1" runat="server">
        <div>
        
            <br />
            Enter URI:</div>
        <asp:TextBox ID="TextBoxUri" runat="server" Width="666px"></asp:TextBox>
        <br />
        <br />
        Enter Front Title:<br />
        <asp:TextBox ID="TextBoxTitle" runat="server"></asp:TextBox>
        <br />
        <br />
        Enter Front Background Image:<br />
        <asp:TextBox ID="TextBoxBackgroundImage" runat="server"></asp:TextBox>
        <br />
        <br />
        Enter Front Count:<br />
        <asp:TextBox ID="TextBoxCount" runat="server"></asp:TextBox>
        <br />
        <br />
        <br />
        Enter Back Title:<br />
        <asp:TextBox ID="TextBoxBackTitle" runat="server"></asp:TextBox>
        <br />
        <br />
        Enter Back Background Image:<br />
        <asp:TextBox ID="TextBoxBackBackgroundImage" runat="server"></asp:TextBox>
        <br />
        <br />
        Enter Back Content:<br />
        <asp:TextBox ID="TextBoxBackContent" runat="server"></asp:TextBox>
        <br />
        <br />
        <br />
        <asp:Button ID="ButtonSendTile" runat="server" onclick="ButtonSendTile_Click" 
            Text="Send Tile Notification" />
        <br />
        <br />
        Response:<br />
        <asp:TextBox ID="TextBoxResponse" runat="server" Height="78px" Width="199px"></asp:TextBox>
        </form>
    </body>
    </html>
    
    
  7. Add the following using directives to the top of the SendTile.aspx.cs file.

    
    using System.Net;
    using System.IO;
    using System.Text;
    
    
  8. Add the code for the ButtonSendTile_Click event handler. This code gets the URI that was entered in the first TextBox, form the Tile notification message, and then post it to the Microsoft Push Notification Service.

                 protected void ButtonSendTile_Click(object sender, EventArgs e)
            {
    
    
                try
                {
                    // Get the URI that the Microsoft Push Notification Service returns to the Push Client when creating a notification channel.
                    // Normally, a web service would listen for URIs coming from the web client and maintain a list of URIs to send
                    // notifications out to.
                    string subscriptionUri = TextBoxUri.Text.ToString();
    
    
                    HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest.Create(subscriptionUri);
    
                    // Create an HTTPWebRequest that posts the Tile notification to the Microsoft Push Notification Service.
                    // HTTP POST is the only method allowed to send the notification.
                    sendNotificationRequest.Method = "POST";
    
                    // The optional custom header X-MessageID uniquely identifies a notification message. 
                    // If it is present, the same value is returned in the notification response. It must be a string that contains a UUID.
                    // sendNotificationRequest.Headers.Add("X-MessageID", "<UUID>");
    
                    // Create the Tile message.
                      string tileMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                      "<wp:Notification xmlns:wp=\"WPNotification\">" +
                          "<wp:Tile>" +
                            "<wp:BackgroundImage>" + TextBoxBackgroundImage.Text + "</wp:BackgroundImage>" +
                            "<wp:Count>" + TextBoxCount.Text + "</wp:Count>" +
                            "<wp:Title>" + TextBoxTitle.Text + "</wp:Title>" +
                            "<wp:BackBackgroundImage>" + TextBoxBackBackgroundImage.Text + "</wp:BackBackgroundImage>" +
                            "<wp:BackTitle>" + TextBoxBackTitle.Text + "</wp:BackTitle>" +
                            "<wp:BackContent>" + TextBoxBackContent.Text + "</wp:BackContent>" +
                         "</wp:Tile> " +
                      "</wp:Notification>";
     
                    // Set the notification payload to send.
                    byte[] notificationMessage = Encoding.Default.GetBytes(tileMessage);
    
                    // Set the web request content length.
                    sendNotificationRequest.ContentLength = notificationMessage.Length;
                    sendNotificationRequest.ContentType = "text/xml";
                    sendNotificationRequest.Headers.Add("X-WindowsPhone-Target", "token");
                    sendNotificationRequest.Headers.Add("X-NotificationClass", "1");
    
    
                    using (Stream requestStream = sendNotificationRequest.GetRequestStream())
                    {
                        requestStream.Write(notificationMessage, 0, notificationMessage.Length);
                    }
    
                    // Send the notification and get the response.
                    HttpWebResponse response = (HttpWebResponse)sendNotificationRequest.GetResponse();
                    string notificationStatus = response.Headers["X-NotificationStatus"];
                    string notificationChannelStatus = response.Headers["X-SubscriptionStatus"];
                    string deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];
    
                    // Display the response from the Microsoft Push Notification Service.  
                    // Normally, error handling code would be here. In the real world, because data connections are not always available,
                    // notifications may need to be throttled back if the device cannot be reached.
                    TextBoxResponse.Text = notificationStatus + " | " + deviceConnectionStatus + " | " + notificationChannelStatus;
                }
                catch (Exception ex)
                {
                    TextBoxResponse.Text = "Exception caught sending update: " + ex.ToString();
                }
    
            }
    
    
    

To run the sample, we first run the push client code to create the channel and get the URI. We then use this URI in the webpage to send the Tile.

To run the sample

  1. Go back to the TileNotificationClient project and run it. Windows Phone Emulator initializes, and then the application starts. After a moment or two, the application should display a message with the URI. This URI also will be displayed in the Visual Studio debugger Output window.

    AP_Push_OutputWindow
    TipTip:

    In Microsoft Visual Studio Express 2012 for Windows Phone, the default setting is to not display the Output window during a debugging session. You can display the Output window by going to the Debug menu, selecting Windows, and then selecting Output. Scroll the window to find the URI.

  2. The notification channel has now been created. Copy the URI from the Visual Studio debugger Output window to the clipboard.

  3. In your Windows Phone application running on the emulator, pin the Tile for your application to Start by tapping and holding the TileNotificationClient name in the application list and then selecting pin to start. This is the Tile that will be updated.

  4. Switch to the SendTile project and run it.

  5. In the URI text box, paste the URI that you copied from the previous project.

  6. Enter a title, count, and image for the Tile. Use the full name of the .jpg file, such as Red.jpg, for the image name.

    AP_Push_SendTile

    Note that you can also send URIs to remote image files by using the BindToShellTile(Collection<Uri>) method.

  7. Click the Send Tile button. The Tile that you pinned to Start should update. If you set any properties of the back of the Tile, the Tile will flip over after a couple of seconds to show the back of the Tile. If you leave a field blank, such as Title, then that field will not update.

    AP_PushTileUpdate

You have now learned how to update a Tile by using an ASP.NET page to send a notification to a Windows Phone.

Show:
© 2014 Microsoft