Windows Phone 7 Development : Push Notifications - Implementing Raw Notifications

5/24/2011 3:52:04 PM
Raw notifications represent the third and final type of push notification available on the Windows Phone 7 platform. Unlike tile and toast notifications, however, raw notifications are available to a Windows Phone 7 application only if that application is running in the foreground. If the application is not running in the foreground, even if the application's icon is pinned to the phone's Start screen, raw notifications are simply dropped.

You will implement raw notifications following the same three general steps as implementing toast and tile notifications, namely the following:

  1. Create a Windows Phone 7 Notification client application. This application will establish a notification channel.

  2. Create and execute a Windows Forms client. You will take the URI of the notification channel that you established in Step 1, paste it into the "Push Notifications URL" text box, and submit a push notification to the application.

  3. Verify that you are able to receive raw notifications in your Windows Phone 7 application.

1. Creating a Client Application

You will create the RawNotificationPNClient application to accept raw notifications. .

  1. Launch Visual Studio 2010 Express for Windows Phone and create a new Windows Phone Application project. Name it "RawNotificationPNClient."

  2. From the Toolbox, drag and drop a text box on the design surface. Rename the text box to txtURI, adjust its width to be the full width of the screen, and adjust its height to be about a quarter of screen's height. Set the text box's TextWrapping property to "Wrap" and clear out its Text property.

  3. From the Toolbox, drag and drop a button on the design surface. Rename the button to btnCreateChannel and set the Content property to "Create Channel." Once again, your Windows Phone 7 design surface should now look like Figure 3.

  4. TheMicrosoft.Phone.Notificationnamespace contains the functionality necessary to establish a push notification channel and receive push notifications; therefore you need to add the following using directive at the top of the MainPage.xaml.cs file:

    using Microsoft.Phone.Notification;
    using System.Diagnostics;

  5. You will now program the button click event handler to create the push notification URL. In the Windows Phone 7 design surface, double-click the "Create Channel" button and make that button's click event handler look like the following:

    private void btnCreateChannel_Click(object sender, RoutedEventArgs e)

The SetupChannel function, which follows, is responsible for creating a channel within MPNS to receive updates from the server, as well as to wire up event handlers to fire when the error occurs during communication and when the raw notification is received. Remember that raw notifications are available to the application only when it's running; therefore an event handler must be defined in code that processes raw notifications as they come in. The code that binds the raw notification received event to the httpChannel_HttpNotificationReceived event handler function lives inside the SetupChannel function:

httpChannel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(httpChannel_HttpNotificationReceived);

  1. Here's the complete implementation of the SetupChannel function. Add the code to your project:

    private void SetupChannel()
    HttpNotificationChannel httpChannel = null;
    string channelName = "DemoChannel";

    //if channel exists, retrieve existing channel
    httpChannel = HttpNotificationChannel.Find(channelName);
    if (httpChannel != null)
    //If you can't get it, then close and reopen it.
    if (httpChannel.ChannelUri == null)
    ChannelUri = httpChannel.ChannelUri;

    //wiring up the raw notifications event handler
    httpChannel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(httpChannel_HttpNotificationReceived);
    httpChannel = new HttpNotificationChannel(channelName);
    httpChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(httpChannel_ChannelUriUpdated);
    httpChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(httpChannel_ExceptionOccurred);

    //wiring up the raw notifications event handler
    httpChannel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(httpChannel_HttpNotificationReceived);

    catch (Exception ex)


What you do with raw notifications received is totally up to you: raw notifications can be simple status messages to be shown in the Windows Phone 7 client application, or they can be directives to the application to perform a given task. In this application, you will simply print a message into the text box with the text of raw notifications received.

  1. To print the raw notification, add the following code:

    void httpChannel_HttpNotificationReceived(object sender, HttpNotificationEventArgs e)
    if (e.Notification.Body != null && e.Notification.Headers != null)
    System.IO.StreamReader reader = new
    Dispatcher.BeginInvoke(() =>
    txtURI.Text = "Raw Notification Message Received: " + reader.ReadToEnd();

You are very close to completing the client application; what remains is to write an error handling function that will fire off when any errors during communication occur. You will also write a simple event handler that will fire off when the push notification channel URI gets updated.

  1. Add the following code to your application:

    void httpChannel_ExceptionOccurred(object sender, NotificationChannelErrorEventArgs e)
    //Display Message on error
    Debug.WriteLine ( e.Message);

    void httpChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
    //You get the new Uri (or maybe it's updated)
    ChannelUri = e.ChannelUri;

  2. Finally, add the following helper code to the top of the MainPage class. This code will print the push notification channel URI into the Debug window; you will need that URI to test the application shortly:

    Uri channelUri;

    public Uri ChannelUri
    get { return channelUri; }
    channelUri = value;

    private void OnChannelUriChanged(Uri value)

    Dispatcher.BeginInvoke(() =>
    txtURI.Text = "changing uri to " + value.ToString();

    Debug.WriteLine("changing uri to " + value.ToString());

With the client application complete, press F5 to make sure that the application compiles and runs. In the next section, you will be building a server piece to send raw notifications to this client application.

2. Creating an Application to Send Notifications

Sending raw notifications from the server is simpler than sending Tiles or Toasts: there are no XML templates for message formatting for raw notifications. You will reuse the PNServer project created in the prior sections and edit the button click event handler for raw notifications processing. Follow these steps to accomplish that:

  1. Open the PNServer project and open code for the Form1.cs file (right-click Form1.cs in Solution Explorer and select View Code).

  2. Replace the btnSendNotification_Click event handler with the following code. Note how the X-NotificationClass header value is set to "3" and how the X-WindowsPhone-Targe header value is left blank to indicate that this is a raw notification.

    private void btnSendNotification_Click(object sender, EventArgs e)
    if (txtURL.Text == string.Empty)
    MessageBox.Show("Please enter a url");

    if (txtTitle.Text == string.Empty || txtText.Text == string.Empty)
    MessageBox.Show("Please enter text and title to send");

    HttpWebRequest sendNotificationRequest =(HttpWebRequest)WebRequest.Create(txtURL.Text);

    sendNotificationRequest.Method = "POST";
    sendNotificationRequest.Headers = new WebHeaderCollection();
    sendNotificationRequest.ContentType = "text/xml";

    sendNotificationRequest.Headers.Add("X-WindowsPhone-Target", "");
    sendNotificationRequest.Headers.Add("X-NotificationClass", "3"); //- raw
    string str = string.Format(txtTitle.Text + "\r\n" + txtText.Text);
    byte[] strBytes = new UTF8Encoding().GetBytes(str);
    sendNotificationRequest.ContentLength = strBytes.Length;

    using (Stream requestStream = sendNotificationRequest.GetRequestStream())
    requestStream.Write(strBytes, 0, strBytes.Length);

    HttpWebResponse response = (HttpWebResponse)sendNotificationRequest.GetResponse();
    string notificationStatus = response.Headers["X-NotificationStatus"];
    string deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];
    lblStatus.Text = "Status: " + notificationStatus + " : " + deviceConnectionStatus;

That is all the code necessary to send raw notifications to Windows Phone 7 clients. You are now ready to test raw notifications on the Windows Phone 7 emulator.

3. Testing Delivery of Raw Notifications

Testing raw notifications is very straightforward: there are no applications to pin to the Start screen—simply start both the client and the server pieces of the application, make sure that the push notification URL is available to both, and fire away! The walkthrough here gives more details on testing raw notifications:

  1. Just as with toast and tile notifications, you need to obtain the URI of the notification channel. Open the RawNotificationPNClient project, make sure that you have a connection to the Internet, and press F5 to run the project. Click the Create Channel button and, after seeing the URI printed on the screen, copy it to the clipboard from the Output window.

  2. Switch to the PNServer Windows Forms project and press F5 to run it. In the Push Notifications URL text box, paste the URI obtained in Step 1. In the Push Notifications Title and Push Notifications Text text boxes, enter "Hello" and "World" correspondingly. Click the Send Notification button.

  3. You should now see the message stating that the raw notification has been received and the "Hello World" message on the Windows Phone 7 emulator screen.

As you can see, implementing raw notifications is very similar to implementing tile and toast notifications, albeit a bit simpler. Each one of the notification types has its purposes; use the most appropriate notification type for your circumstances.

You may be shaking your head by now, thinking that the copy and paste method of communicating the push notification channel URL between the client and the server is completely unrealistic for any commercial application. We agree, and we will show you how to automate that communication piece in the next section.

  •  Windows Phone 7 Development : Push Notifications - Implementing Tile Notifications
  •  Windows Phone 7 Development : Push Notifications - Implementing Toast Notifications
  •  iPhone Application Development : Creating a Navigation-Based Application
  •  Windows Phone 7 Development : Push Notifications - Introducing the Push Notifications Architecture
  •  Windows Phone 7 Development : Push Notifications - Understanding Push Notifications
  •  Windows Phone 7 Development : Handling Multiple Concurrent Requests with Rx.NET
  •  WAP and Mobile HTML Security : Application Attacks on Mobile HTML Sites
  •  WAP and Mobile HTML Security : Authentication on WAP/Mobile HTML Sites & Encryption
  •  iPhone Application Development : Displaying and Navigating Data Using Table Views - Building a Simple Table View Application
  •  iPhone Application Development : Understanding Table Views and Navigation Controllers
  •  Windows Phone 7 Development : Revising WeatherRx to Manage Slow Data Connections
  •  Windows Phone 7 Development : Handling Data Connection Issues with Rx.NET
  •  Windows Phone 7 Development : Handling Errors in Rx.NET
  •  Windows Phone 7 Development : Using Rx.NET with Web Services to Asynchronously Retrieve Weather Data
  •  Windows Phone 7 Development : Media - Adding Sounds to an Application
  •  iPhone Application Development : Building a Multi-View Tab Bar Application (part 4) - Implementing the Summary View
  •  iPhone Application Development : Building a Multi-View Tab Bar Application (part 3) - Implementing the Volume View
  •  iPhone Application Development : Building a Multi-View Tab Bar Application (part 2) - Implementing the Area View
  •  iPhone Application Development : Building a Multi-View Tab Bar Application (part 1)
  •  Windows Phone 7 Development : Working with Video (part 2) - Coding the Application
    Top 10
    Operating System Options (Part 2)
    Operating System Options (Part 1)
    Adobe Premiere Elements 11.0
    Dragon NaturallySpeaking 12.0 Premium
    Expert Computing Advice – January 2013 (Part 2)
    Expert Computing Advice – January 2013 (Part 1)
    Managing Your Files In Windows 8
    Kindle Fire HD - Amazon’s Kindle e-Reader
    Versus Touchpad 9.7 - Attractive Pre-Loaded Software
    The Fourth-Generation iPad Review
    Most View
    BizTalk 2006 : Editing and Resubmitting Suspended Messages (part 2) - Pseudo-Walkthrough to Perform Edits and Resubmits
    The Language of Apple Platforms : Memory Management
    IIS 7.0 : Securing Communications with Secure Socket Layer (SSL)
    ASP.NET and AJAX
    Microsoft Windows Home Server 2011 : Automating Client Logons
    Nexus 7 Vs Kindle Fire
    Showdown: lOS vs Android vs WP7 (Part 2)
    100 Windows Speed-Up Tips (Part 7) - Five ways Jump Lists can save your time
    Use Photoshop Touch To Edit Your Photos
    Exchange Server 2007 : Configure the Client Access Server - Create and Apply ActiveSync Mailbox Policies
    MySQL Server Monitoring (part 1) - SQL Commands
    Intel vs AMD - The Choice Is Harder Than Ever (Part 1)
    Corsair Vengeance C70 Mid - Tower Gaming Case
    Programming Microsoft SQL Server 2005: Using the Data Mining Wizard and Data Mining Designer (part 5) - Viewing Mining Models
    Ultrasone HFI-580 Headphone Review
    All About Compact System Cameras (Part 1) - Nikon 1 V1
    Choosing a super-zoom camera (part 7) - Nikon Coolpix S9100 & Olympus SZ-30MR
    Canon EOS 650D - Big Improvements (Part 1)
    Using Non-Windows Systems to Access Exchange Server 2010 : Configuring and Implementing Entourage for the Mac
    Enabling Presence Information in SharePoint with Microsoft Communications Server 2010