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
- Sending a raw notification
- Running the raw notification sample
- Related Topics
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
Create a new Windows Phone app.
Name the project RawNotificationClient.
Add the following using directive to the top of the MainPage.xaml.cs file.
using Microsoft.Phone.Notification;
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())); } }
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())); }); }
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 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
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.
Name the project SendRaw.
Add a new web form to the project by right-clicking the SendRaw project name, selecting Add, then New Item…, and then Web Form.
Name the form SendRaw and click the Add button.
Make the SendRaw form the start page by right-clicking SendRaw.aspx in the Solution Explorer and then selecting Set as Start Page.
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: |
Add the following using directives to the top of the SendRaw.aspx.cs file.
using System.Net; using System.IO; using System.Text;
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
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.
The notification channel has now been created. Copy the URI from the Visual Studio debugger Output window to the clipboard.
Switch to the SendRaw project and run it.
In the URI text box, paste the URI that you copied from the previous project.
Enter a couple of values for the raw notification data. Click the Send Raw button.
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