Article: Windows Phone 7 Push Notifications
by Sgt. Conker
In this article I will explain how to use the Push Notification features of Windows Phone 7 using 2 very simple samples.
The push notification features of Windows Phone 7 enable you to push a message to a mobile device with 3 options.
- Tile notification – This lets you change the main application tile on the Start experience.
- Toast notification – This lets you popup a message on the device even if your application is not running.
- Raw notification – This lets you send raw data to the running application which you can receive via an event.
For this sample, we’re going to concentrate on Toast notification. While Tile notifications will be cool, we unfortunately can’t make use of them with the current build of the emulator.
As a teaser, here is the result we want.
A toast notification contains 2 text properties. These could be considered as a header and details. The toast notification also shows the icon from the application on the left hand side.
There are 2 parts to this sample. The first is the WP7 application itself. This must first open a communication channel with the soap service and bind the notification to a toast. Firstly we can try to find an existing channel and if that fails, we open a new one.
Once opened, we call the BindToShellNotification method on the channel so that the result ends up as an actual Toast notification.
Here’s some sample code.
channel = HttpNotificationChannel.Find(channelName);
if (channel != null)
{
Debug.WriteLine(channel.ChannelUri.ToString());
}
else
{
channel = new HttpNotificationChannel(channelName);
channel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(channel_ChannelUriUpdated);
channel.Open();
channel.BindToShellNotification();
}
Once we’ve found a channel or created a new one, we need to retrieve the unique URL generated for this communication. In this sample we will simply print it out to the debug console. Later in the article I will explain a real world scenario for how this type of communication may be used.
Subscribe to the ChannelUriUpdated event and print out the Url.
channel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(channel_ChannelUriUpdated);
void channel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
{
Debug.WriteLine(e.ChannelUri);
}
That’s all we need in the WP7 sample code to show you how notifications work. In short, the WP7 application doesn’t have to do much at all. Once the channel is successfully created that is enough for the device to receive a toast notification.
Now we need a way of sending a push notification to the device.
To do this we need to send a HTTP POST method to the Url given by the WP7 device application. You will find this in the output window of Visual Studio
We need to add a custom header to set the notification class and we also need to fill up the payload with some specially formatted data so that the toast will be received.
The format of this data should be as follows. [NOTE: The MSDN documentation is not correct, notice where I put the xmlns and also where I use the X-NotificationClass header]
X-WindowsPhone-Target: toast
<?xml version="1.0" encoding="utf-8" ?>
<wp:PushNotification xmlns:wp="WindowsPhonePushNotification">
<wp:Toast>
<wp:Text1>{0}</wp:Text1>
<wp:Text2>{1}</wp:Text2>
</wp:Toast>
</wp:PushNotification>
Replacing the {0} and {1} with the data you want to show on the device.
A couple of things to be aware of here. There must be a blank line between the X-WindowsPhone-Target and the xml. Also, this format contradicts the documentation on MSDN. The documentation is wrong for all formats.
Here is how I get this payload ready in code.
string ToastPushXML = "X-WindowsPhone-Target: toast\r\n\r\n" +
"<?xml version='1.0' encoding='utf-8'?>" +
"<wp:PushNotification xmlns:wp='WindowsPhonePushNotification'>" +
"<wp:Toast>" +
"<wp:Text1>{0}</wp:Text1>" +
"<wp:Text2>{1}</wp:Text2>" +
"</wp:Toast>" +
"</wp:PushNotification>";
string str = string.Format(ToastPushXML, textBox2.Text, textBox3.Text);
We also need to convert this to a byte array so we can fill the HTTP Request.
Here’s the complete code to send the notification.
string ToastPushXML = "X-WindowsPhone-Target: toast\r\n\r\n" +
"<?xml version='1.0' encoding='utf-8'?>" +
"<wp:PushNotification xmlns:wp='WindowsPhonePushNotification'>" +
"<wp:Toast>" +
"<wp:Text1>{0}</wp:Text1>" +
"<wp:Text2>{1}</wp:Text2>" +
"</wp:Toast>" +
"</wp:PushNotification>";
string url = [URL GIVEN BY WP7 APP];
string str = string.Format(ToastPushXML, textBox2.Text, textBox3.Text);
HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest.Create(url);
sendNotificationRequest.Method = "POST";
sendNotificationRequest.Headers = new WebHeaderCollection();
sendNotificationRequest.ContentType = "text/xml";
sendNotificationRequest.Headers.Add("X-NotificationClass", "2"); //- 2/12/22 are for toasts
byte[] strBytes = new UTF8Encoding().GetBytes(str);
sendNotificationRequest.ContentLength = strBytes.Length;
using (Stream requestStream = sendNotificationRequest.GetRequestStream())
{
requestStream.Write(strBytes, 0, strBytes.Length);
}
If we now run the WP7 application, we will see the URL appear in the Debug output window. Select and copy this complete URL.
Now put this URL into the test push application, enter some text in the 2 fields and press the push button.
With a bit of luck the cloud service will be responsive and you will receive the toast notification on the device almost instantly. I was told by someone at Microsoft that these are subject to delays depending on how busy the service is at that time. That’s ok though, it’s understood that Push notifications are not a guaranteed form of communication anyway, they’re just cool.
The source code shown above was purely to give you an idea on how to use this. Download the full source code sample at the bottom of this article.
One thing to be aware of with the WP7 device application is that it may error on trying to open a channel on the first few tries. I’ve not figured out why this is yet, but just keep trying and once it succeeds once, it should succeed from there on out.
Real World Scenario
Here’s a real world scenario on why you may use Toast push notifications.
I’m playing a game with my good friend X-Tatic, we’re playing WP7 Battle Ships. I’ve just take out his small boat when I need to check my emails and diary and make a phone call.
So I exit the game and get back to work on my device. At this point, the application will open a communication channel, or if it did it previously in the app, we just make a note of the URL we got created and send this to the WP7 Battle Ship server. The Server will store this so that if it needs to send a toast to this user/device, this is the URL it will use.
While I’m reading my truck load of emails I suddenly see a toast notification popup.
At this point I’m like… UH!! WAH!! WTF!!! So I hit the toast, it fires up WP7 Battleships taking me right back into the game we were playing and I proceed to sink the rest of X-Tatics ships.
There are many many more useful scenarios for this and I would love to see and hear about them. Please keep Sgt. Conker informed of any cool things you do with Windows Phone 7 Push Notifications.
References
Push Notifications Overview
How to: Set Up a Notification Channel
How to: Send a Push Notification




March 27th, 2010 - 15:19
You wouldn’t be able to sink my remaining ships without you aircraft carrier… Your toast failed to inform you that you are screwed.
March 27th, 2010 - 17:19
Too much work to just send a notify
March 27th, 2010 - 21:13
If you’re smart, you’ll only have to write most of this code once, and then reuse it.
March 28th, 2010 - 18:10
i know, but i think most of this code should have been written by MS developers. Leaving for us reusage part only. And i’m almost sure that this part of framework is not finished yet
March 28th, 2010 - 23:34
Great Article!!!
How can i use the code of WP7 Push Tool in a WP7 App? I get a error when i tried to create a new Header in the sendNotificationRequest object.
Thanks
March 29th, 2010 - 13:20
What’s the error you get?
If you download the sample code it should just run :S
March 29th, 2010 - 13:28
I Misread your comment, Why would you want to do the pushing from within the WP7 App ?
The idea is you would send your generated URL to a web service in the cloud, and then the cloud service would do the pushing.
Weather service, news service, soccer service are just some examples of web services ideal for push notifications
March 29th, 2010 - 17:57
I’ve been waiting for an article that sums things up like this. Thanks!
April 1st, 2010 - 13:18
Is the push service still running? I downloaded your sample and i get a these errors in the output window:
A first chance exception of type ‘Microsoft.Phone.Notification.NotificationChannelNotFoundException’ occurred in Microsoft.Phone.Notification.dll
A first chance exception of type ‘Microsoft.Phone.Notification.NotificationChannelOpenException’ occurred in Microsoft.Phone.Notification.dll
April 1st, 2010 - 18:05
Alex,
Can you elaborate on which pieces you feel should be in the platform? We’ve tried to make it as simple as possible with the current API the only code that you have to write is the stuff that’s very specific to your application:
1) Only you know when you want to create a channel, so you have to do that
2) Only you know how to send the channel URI to your backend service, so you need to do that (in this case, sending to debug spew)
3) Only you control your back-end service and how it should send notifications, so you need to do that too
One thing I can think of is a helper class for the your service (not on the phone) that does the String.Format and UTF8 byte encoding for you… but other than that I don’t see much room for simplification (and you can just copy the implementation above and call it good
).
If you have any suggestions, please send to the forums (http://social.msdn.microsoft.com/Forums/en-US/windowsphone7series/)
April 2nd, 2010 - 03:40
Ramesis,
This is due to a bug in the current API, where the Find() in some cases throws an exception instead of just returning null. Expect in the final release to only get a null return.
Also, the OpenException you are seing is due a another bug in the emulator. The result of this is that you should wait for 2 minutes after emulator boot (due to a networking issue) before you open a channel. This will be fixed for next release (Note, this is mentioned in the release notes).
Hope thi helps!
April 4th, 2010 - 20:23
Hi,
If the mobile is on telephone network, does the url remains valid also in case of change of the phone ip address?
I mean, have you to repeat all for each ip address change?
Thanx
-Claudio
April 6th, 2010 - 13:28
Hi,
I have downloaded your sample and trying to execute. 1. I ran the tool first then Push notification Sample project. I am not getting the URL in output window and in Push notification Sample…i am not able to open the channel. Could please eloborate your code more step by step. I am reallyin need of this example.
April 6th, 2010 - 13:30
Just keep trying. It sometimes takes a few goes before it starts to work. I believe this is a bug in the CTP.
Once it starts to produce a url, it almost always works after that.
April 7th, 2010 - 05:14
Thanks for your reply. I have my service running in Cloud with some Namespace. I want to consume my cloud service using this sample. So, What should i give as a channel name and how it identifies my service uri. I am providing some “xxxx” as channel name and my service bus uri as service name while creating the object to HttpNotificationChannel but channel is coming null and not able to open.
So, please guide me how to call my cloud service in this sample.
April 7th, 2010 - 08:30
Rather than try to help in a comment i’ll try find time to setup a real example where a sample cloud service sends the notification. I’ll then post it as an article.
April 7th, 2010 - 16:18
Thanks..waiting for your article…
April 8th, 2010 - 04:37
How dos the notification actually get delivered to the phone? When the channel is created, does WP7 maintain a persistent connection to the cloud? or does it do some periodic polling for the notification?
April 8th, 2010 - 07:47
hi,
Could you please include the X509Certificate senario also…in your artcile. How WP7 is using HTTP post method how is communicates with HTTPS based services?
April 8th, 2010 - 13:14
When the WP7 phone subscribed a token will be given from the Microsoft notification service. Using this token your service will be in touch with the phone and any thing is received to the service that will be intimated to all the phone those subscribed with this token.
April 8th, 2010 - 13:16
Is it possible to receive multiple notifications from multiple service to my phone. if so, how to do the configuration?
April 8th, 2010 - 15:32
is current version of CTP allowing the security with certificates? Are there any other ways to implement the security?
Thanks
RK
April 9th, 2010 - 06:22
Is there any way to attach the X509certificate to HttpNotificationChannel from the WP7 Application?
Thanks
RK
April 9th, 2010 - 12:43
Yes there is, it says it in the documentation
http://msdn.microsoft.com/en-us/library/ff402545(v=VS.92).aspx
// If the cloud service sending this request is authenticated, it needs to send its certificate.
// Otherwise, this step is not needed.
X509Certificate certificate = new X509Certificate();
// replace new X509Certificate() with your code that gets your certificate
sendNotificationRequest.ClientCertificates.Add(certificate);
April 12th, 2010 - 03:29
Yes this is from pushing side…But at the same time we need to give the certificate details with WP7 Application. So, i didnt find any way to attach/bind the certificates to WP7 or HttpNotificationChannel.
I need it at receiving side WP7 or HttpNotificationChannel. In some of the fourms i read that, the current CTP is not supporting this feature.
http://www.natmac.org/9am/tfeed?id=64760E8AC11918D18B8B3549A7FC49732DA64E76
http://www.uxmagic.com/blog/post/2010/03/20/Setting-up-a-Push-Notification-Channel-on-the-Windows-Phone-7-series.aspx
April 13th, 2010 - 11:04
For some reason the push tool always fails with a 404, although I’ve made sure I copied the full URL generated from the mobile client as instructed.
I think it just doesn’t like me
April 14th, 2010 - 04:16
I have created one more sample using all three notifications. i dont see any option here to upload the Code.
Thanks
RK
May 1st, 2010 - 15:36
Is this sample supposed to run on the April Refresh CTP? It doesn’t.
May 1st, 2010 - 16:12
Doesnt work with the latest CTP
May 2nd, 2010 - 01:59
Neil: There are changes to Push Notification that apply to the April Refresh CTP that likely weren’t made to this article considering how old it is. I’ll see if I can prod Sgt. Conker into updating the sample. If you’re technologically inclined, you can find what has changed via this link: http://msdn.microsoft.com/en-us/library/ff402545%28v=VS.92%29.aspx. Look specifically for the parts in yellow that say “The below example applies only for the Windows Phone OS 7.0 CTP Refresh…”
May 2nd, 2010 - 09:21
Yeah, I can’t upgrade to the new April refresh to figure this out just yet. As soon as I’m updated I will update this post.
May 2nd, 2010 - 18:42
In order to get this sample to work with the April Refresh, you need to add you publisher name to the app element in wmappmanifest. Once you do that, it should work again. http://download.microsoft.com/download/D/9/A/D9A6B6ED-D1CF-4FB3-86BD-62A55959175F/ReleaseNotes.htm
May 2nd, 2010 - 19:43
Thanks for the comments. Meanwhile the answer was found in the forum.
http://social.msdn.microsoft.com/Forums/en-US/windowsphone7series/thread/369669cf-4339-4137-b435-ab1bdb516ce5
It may also be found in the April release notes
Regards
May 3rd, 2010 - 10:51
OK, it’s post-CTP refresh and I’m still having problems.
The emulator seems to make the connection successfully, I paste the generated url into the push tool and give it some parameters to play with, and it makes the connection – the push tool reports notifcation status as “Received”, and almost instantaneously the WP7 app throws a NotificationChannelUnexpectedException. So it’s receiving the message and going splat anyway.
May 3rd, 2010 - 11:47
Ignore my last comment – I’d missed the change from PushNotification to Notification. Eejit.