How to send and receive raw notifications for Windows Phone 8

August 06, 2014

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 raw notifications to the Microsoft Push Notification Service and how to receive them in your app running on a Windows Phone. Push notifications for Windows Phone 8 has information on raw notifications and how they are used.

You can download the complete Raw Notification Sample.

Important noteImportant Note:

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

This topic contains the following sections.

In this section, we create an app that runs on a Windows Phone that creates a push notification channel and handles raw 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 app.

To create a push client to receive raw notifications

  1. Create a new Windows Phone app.

  2. Name the project RawNotificationClient.

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

    
    using Microsoft.Phone.Notification;
    
    
    
  4. Replace the MainPage constructor with the following code. This code looks to see whether a raw notification channel has already been set up in a previous instance of the app. 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 = "RawSampleChannel";
    
                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.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(PushChannel_HttpNotificationReceived);
    
                    pushChannel.Open();
    
                }
                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);
                    pushChannel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(PushChannel_HttpNotificationReceived);
    
                    // 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()));
    
                }
            }
    
    
    
    
  5. 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()));
                    
                });
            }
    
    
  6. 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))
                        );
            }
    
    
  7. The last event handler is for receiving your raw notification. The use of this data is entirely app specific.

               void PushChannel_HttpNotificationReceived(object sender, HttpNotificationEventArgs e)
            {
                string message;
    
                using (System.IO.StreamReader reader = new System.IO.StreamReader(e.Notification.Body))
                {
                    message = reader.ReadToEnd();
                }
    
    
                Dispatcher.BeginInvoke(() =>
                    MessageBox.Show(String.Format("Received Notification {0}:\n{1}",
                        DateTime.Now.ToShortTimeString(), message))
                        );
            }
    
    

The Windows Phone 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 raw notification by using the URI that is returned when the push channel is created on the device.

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

To create an ASP.NET page for sending raw notifications

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

  2. Name the project SendRaw.

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

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

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

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

    Control type

    Control ID

    Text for control

    TextBox

    TextBoxUri

    Enter URI:

    TextBox

    TextBoxValue1

    Enter Value 1:

    TextBox

    TextBoxValue2

    Enter Value 2:

    Button

    ButtonSendRaw

    Send Raw Notification

    TextBox

    TextBoxResponse

    Response:

    The Send Raw button will have a ButtonSendRaw_Click event handler. Replace the contents of SendRaw.aspx with the following code to create these controls.

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SendRaw.aspx.cs" Inherits="SendRaw.SendRaw" %>
    
    <!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">
    <head id="Head1" runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
        
            <br />
            Enter URI:</div>
        <asp:TextBox ID="TextBoxUri" runat="server" Width="666px"></asp:TextBox>
        <br />
        <br />
        Enter Value 1:<br />
        <asp:TextBox ID="TextBoxValue1" runat="server"></asp:TextBox>
        <br />
        <br />
        Enter Value 2:<br />
        <asp:TextBox ID="TextBoxValue2" runat="server"></asp:TextBox>
        <br />
        <br />
        <br />
        <asp:Button ID="ButtonSendRaw" runat="server" onclick="ButtonSendRaw_Click" 
            Text="Send Raw 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 SendRaw.aspx.cs file.

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

                 protected void ButtonSendRaw_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 raw notification to the Microsoft Push Notification Service.
                    // HTTP POST is the only method allowed to send the notification.
                    sendNotificationRequest.Method = "POST";
    
                    // Create the raw message.
                    string rawMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                    "<root>" +
                        "<Value1>" + TextBoxValue1.Text.ToString() + "<Value1>" +
                        "<Value2>" + TextBoxValue2.Text.ToString() + "<Value2>" +
                    "</root>";
    
                    // Set the notification payload to send.
                    byte[] notificationMessage = Encoding.Default.GetBytes(rawMessage);
    
                    // Set the web request content length.
                    sendNotificationRequest.ContentLength = notificationMessage.Length;
                    sendNotificationRequest.ContentType = "text/xml";
                    sendNotificationRequest.Headers.Add("X-NotificationClass", "3");
    
    
                    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 will then use this URI in the webpage to send the raw notification.

To run the sample

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

    AP_Push_OutputWindow
    TipTip:

    In Visual Studio 2010 Express 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. Switch to the SendRaw project and run it.

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

  5. Enter a couple of values for the raw notification data. Click the Send Raw button.

    AP_Push_SendRaw
  6. In your Windows Phone app running on the emulator, you should receive the raw notification. You receive the notification only if your app is running.

    AP_Push_RawEvent

You have now learned how to pass raw data from an ASP.NET page to an app running on a Windows Phone.

Show:
© 2014 Microsoft