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:
Create a Windows Phone 7 Notification client application. This application will establish a notification channel.
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.
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. .
Launch
Visual Studio 2010 Express for Windows Phone and create a new Windows
Phone Application project. Name it "RawNotificationPNClient."
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.
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.
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;
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)
{
SetupChannel();
}
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);
Here's the complete implementation of the SetupChannel function. Add the code to your project:
private void SetupChannel()
{
HttpNotificationChannel httpChannel = null;
string channelName = "DemoChannel";
try
{
//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)
{
httpChannel.UnbindToShellToast();
httpChannel.Close();
SetupChannel();
return;
}
else
{
ChannelUri = httpChannel.ChannelUri;
//wiring up the raw notifications event handler
httpChannel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(httpChannel_HttpNotificationReceived);
}
}
else
{
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);
httpChannel.Open();
}
}
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.
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
System.IO.StreamReader(e.Notification.Body);
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.
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;
}
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; }
set
{
channelUri = value;
OnChannelUriChanged(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:
Open the PNServer project and open code for the Form1.cs file (right-click Form1.cs in Solution Explorer and select View Code).
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");
return;
}
if (txtTitle.Text == string.Empty || txtText.Text == string.Empty)
{
MessageBox.Show("Please enter text and title to send");
return;
}
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:
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.
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.
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.