Freigeben über


How to send and receive raw notifications for Windows Phone 8

[ This article is for Windows Phone 8 developers. If you’re developing for Windows 10, see the latest documentation. ]

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 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.

Creating a push client to receive raw notifications

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 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.

Sending a raw 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" %>
  1. Add the following using directives to the top of the SendRaw.aspx.cs file.

    using System.Net;
    using System.IO;
    using System.Text;
    
  2. 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();
                }
    
            }
    

Running the raw notification sample

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.

Tip

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.

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

  2. Switch to the SendRaw project and run it.

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

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

  5. 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.

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

See Also

Other Resources

Push notifications for Windows Phone 8

Setting up your app to receive push notifications for Windows Phone 8

Sending push notifications for Windows Phone 8