Windows Phone 7 – Toast Notification Using Windows Azure Cloud Service
Windows Phone 7 – Step by Step how to create WP7 Toast Notification using Windows Azure Cloud Service with WCF Service Web Role

Content
- Introduction
- MyCloudService - Windows Azure Cloud Service With WCF Service Web Role
- WpfAppNotificationComposer - WPF Application To Send Notification
- WindowsPhoneToast – Windows Phone Application To Receive Notification
- History
- My Other Posts In CodeProject
Introduction

In this post I am going to show the step by step approach to create the Toast Notificaton on Wndows Phone7.
Before that you need to understand what is Microsoft Push Notification, to understand Windows Phone 7 notifications and flow please go through my earlier post from the below link
Microsoft Push Notification in Windows Phone 7 - In Code Project
Please Go Through The 2 Minutes Youtube Demo
Toast - Microsoft Push Noification In Windows Phone 7 (WP7)
MyCloudService - Windows Azure Cloud Service With WCF Service Web Role
First Let us start by creating the “Windows Azure Cloud Service with WCF Service Web Role” Start Visual Studio 2010 with (UAC Account)

In the menu File->New->Projects Choose the project templete “Windows Azure Cloud Service” and name it as MyCloudService accordingly.
In the new Cloud Service project dialog, select the WCF Service web role and add to cloud service solution list and Click on Ok button.

In the IService1.cs interface file just clear the auto generated code related to Composite type that is [DataContract] and methods that is [OperationContract] and create 2 interface methods [OperationContract] as shown below… One is to subscribe from windows phone 7 and other is used to sendNotification from WPF Application.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace WCFServiceWebRole1
{
[ServiceContract]
public interface IService1
{
[OperationContract]
void Subscribe(string uri);
[OperationContract]
string SendToastNotification(string message);
}
}
Create the class DeviceRef ChannelURI with public property.
public class DeviceRef
{
public DeviceRef(string channelURI)
{
ChannelURI = channelURI;
}
public string ChannelURI { get; set; }
}
In the Service1.svc.cs file we need to implement interface methods. below is the complete code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
//add the following references
using System.Collections.ObjectModel; //for Collection<t>
using System.Net; //for HttpWebRequest,HttpWebResponse
using System.IO; //for stream
namespace WCFServiceWebRole1
{
public class Service1 : IService1
{
//add the static collection to hold the subscribed URIs
static Collection<deviceref> DeviceRefCollection = new Collection<deviceref>();
//implementation of the Subscribe method
//which accept channelURI as a parameter, in this example called from Window Mobile 7 application
public void Subscribe(string channelURI)
{
DeviceRefCollection.Add(new DeviceRef(channelURI));
}
//implementation of the SendToastNotification method
//which accept message as a parameter, in this example called from WPF application
public string SendToastNotification(string message)
{
string notificationStatus = "";
string notificationChannelStatus = "";
string deviceConnectionStatus = "";
//loop through deviceref to get the ChannelURI and send toast for each device/windows phone app subscribed.
foreach (DeviceRef item in DeviceRefCollection)
{
//create the HttpWebRequest to Microsoft Notification Server
//this require internet connection
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(item.ChannelURI);
request.Method = "POST";
request.ContentType = "text/xml; charset=utf-8";
request.Headers["X-MessageID"] = Guid.NewGuid().ToString();
request.Headers.Add("X-NotificationClass", "2");
request.Headers.Add("X-WindowsPhone-Target", "toast");
//toast message templete
string notificationData = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<wp:Notification xmlns:wp=\"WPNotification\">" +
"<wp:Toast>" +
"<wp:Text1>WP7 TOAST</wp:Text1>" +
"<wp:Text2>" + message + "</wp:Text2>" +
"</wp:Toast>" +
"</wp:Notification>";
byte[] contents = Encoding.Default.GetBytes(notificationData);
request.ContentLength = contents.Length;
//write to request stream
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(contents, 0, contents.Length);
}
//get the HttpWebResponse status from Microsoft Notification Server
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
notificationStatus = response.Headers["X-NotificationStatus"];
notificationChannelStatus = response.Headers["X-SubscriptionStatus"];
deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];
}
}
//return the status to WPF Application
return notificationStatus + " : " + notificationChannelStatus + " : " + deviceConnectionStatus;
}
}
public class DeviceRef
{
public DeviceRef(string channelURI)
{
ChannelURI = channelURI;
}
public string ChannelURI { get; set; }
}
}
Build the Windows Azure Cloud Service project and run. On the system tray the below icon will appear related to cloud development fabric and development storage.

Verify the IP address with port in the development fabric.

The browser will be launched with same IP address and port number, please provide the servicename for example service1.svc at the end of the url if Service1.svc is not found.

Now the “Windows Azure cloud service with WCF web role” is ready to serve.
WpfAppNotificationComposer - WPF Application To Send Notification
Second Let us create the new project “WPF Application to send Notification”
Create new WPF Application with the name “WPFNotificationComposer” as shown below

Go to reference in the solution explorer and right click on that and choose Add Service Reference… In the popup menu as shown below.

In the Add Service Reference Dialog, Enter the URL of the cloud service in the Address:, in this case it is http://127.0.0.1:81/Service1.svc
Give the name to the Namespace: ServiceReference1
Click on Go button and then Click on Ok button once the Service1 is listed as below in the Services:.
MainWindow.xaml
In the MainWindow.xaml just add 4 controls, label,textbox,button and listview and design as shown below.

Below is the complete MainWindow.xaml code
<Window x:Class="WpfAppNotificationComposer.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="ToastComposer" Height="350" Width="525">
<Grid>
<TextBox Height="23" HorizontalAlignment="Left" Margin="12,35,0,0" Name="txtToast" VerticalAlignment="Top" Width="398" />
<Button Content="Send" Height="23" HorizontalAlignment="Right" Margin="0,34,12,0" Name="btnSend" VerticalAlignment="Top" Width="75" Click="btnSend_Click" />
<Label Content="Toast Message" Height="28" HorizontalAlignment="Left" Margin="12,12,0,0" Name="lblToast" VerticalAlignment="Top" />
<ListView Margin="0,64,0,0" x:Name="lvStatus">
<ListView.View>
<GridView>
<GridViewColumn Width="200" Header="Toast Message" DisplayMemberBinding="{Binding Path=ToastMessage}" />
<GridViewColumn Width="100" Header="NotificationStatus" DisplayMemberBinding="{Binding Path=NotificationStatus}" />
<GridViewColumn Width="100" Header="ChannelStatus" DisplayMemberBinding="{Binding Path=ChannelStatus}" />
<GridViewColumn Width="100" Header="DeviceStatus" DisplayMemberBinding="{Binding Path=DeviceStatus}" />
</GridView>
</ListView.View>
</ListView>
</Grid>
</Window>
MainWindow.xaml.cs created a class ToastStatus and created a Service1Client object for cloud service. and on the send button click event called the cloud service and added the status to listview accordingly.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfAppNotificationComposer
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
//Service1 client for cloud service.
private ServiceReference1.Service1Client proxy = null;
public MainWindow()
{
InitializeComponent();
}
private void btnSend_Click(object sender, RoutedEventArgs e)
{
if (proxy == null)
{
proxy = new ServiceReference1.Service1Client();
}
string status = proxy.SendToastNotification(txtToast.Text);
string[] words = status.Split(':');
lvStatus.Items.Add(new ToastStatus(txtToast.Text.Trim(), words[0].Trim(), words[1].Trim(), words[2].Trim()));
}
}
public class ToastStatus
{
public ToastStatus(string toastMessage,string notificationStatus,string channelStatus,string deviceStatus)
{
ToastMessage = toastMessage;
NotificationStatus = notificationStatus;
ChannelStatus = channelStatus;
DeviceStatus = deviceStatus;
}
public string ToastMessage { get; set; }
public string NotificationStatus { get; set; }
public string ChannelStatus { get; set; }
public string DeviceStatus { get; set; }
}
}
Just build and Run the project.
Now the “WPF Application to send notification” is ready to Compose & Send toast message.
WindowsPhoneToast – Windows Phone Application To Receive Notification
Third and finally Let us create the new project “Windows Phone Application to receive notification”
Start Visual Studio 2010 as administrator (UAC Account)
In the new projects templete choose the “Windows phone Application”
name it as “WindowsPhoneToast” and click on Ok button.
Add service reference Cloud Service in the same way we added in the WpfAppNotificationComposer project, Give the name to the Namespace: MyCloudServiceReference1
In the app.xaml.cs add the following reference
//add namespace
using Microsoft.Phone.Notification; //for HttpNotificationChannel
using System.Diagnostics; //for debug.writeline
Declare class level channel variable
//declare NotificationChannel variable.
public static HttpNotificationChannel channel;
In the public App() constructor just add the notification related code below InitializePhoneApplication();
// Phone-specific initialization
InitializePhoneApplication();
//HttpNotificationChannel , find the channel name this is our own channel name
//here I have given "MyChannel" first, find the existing channel if not found
//then create the new channel
channel = HttpNotificationChannel.Find("MyChannel");
if (channel == null)
{
//create new channel
channel = new HttpNotificationChannel("MyChannel");
//once if we initialize the channel it will take some time to fire the ChannelUriUpdated event
//this will connect to microsoft push notification cloud service/some microsoft service and bring the unique channel URI,
//for this Internet connection to your system is required.
System.Threading.Thread.Sleep((30 * 1000));// wait for some time to happen this proocess
channel.ChannelUriUpdated += new EventHandler<notificationchannelurieventargs>(channel_ChannelUriUpdated);
channel.Open();
}
if (!channel.IsShellToastBound)
channel.BindToShellToast();
channel.ErrorOccurred += new EventHandler<notificationchannelerroreventargs>(channel_ErrorOccurred);
}
Add the following event handlers accordingly
void channel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
{
Debug.WriteLine("An error occured while initializing the notification channel");
Debug.WriteLine(e.Message);
}
void channel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
{
MyCloudServiceReference1.Service1Client proxy = new MyCloudServiceReference1.Service1Client();
//write the channel uri on output window
Debug.WriteLine(e.ChannelUri.AbsoluteUri);
proxy.SubscribeCompleted += new EventHandler<system.componentmodel.asynccompletedeventargs>(proxy_SubscribeCompleted);
proxy.SubscribeAsync(e.ChannelUri.AbsoluteUri);
}
void proxy_SubscribeCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
//write the subscription status on output window
Debug.WriteLine("Successfully Subscribed");
}
We are done with the coding now launch the the windows phone 7 app on the emulator.
While running the this Windows Phone 7 Application, it will generate the unique URI from Microsoft Cloud Service as shown below and also it will subscribe the unique URI generated from Microsoft Cloud Service to the cloud service written above. and if cloud service created above is not running we have to first launch the cloud service created above.

Once the application is running on the Emulator we have to pin the windows phone application to the start/home screen. please go through my earlier post.
How to Pin/Un Pin applications to Start/Home Screen on Windows Phone 7/Tiles on Windows Phone 7
Stay in the start page of the windows phone 7 after pinning the WindowsPhoneToast application.
Now run the ToastComposer – the WPF application created above
Enter the toast message and click on send button

To understand the status please go through the
Push Notification Service Response Codes for Windows Phone from MSDN
Now go back to the Windows Phone 7 Emulator and verify the toast message, even when application is not running we are able to receive the toast if the application is pinned to start.

Thank You, Enjoy Madi!
History
Initial Posting 10th December 2010.
My Other Posts In CodeProject
Please Go Through The Related Post From The Below Link
Microsoft Push Notification in Windows Phone 7
WPF based articles are as follows...
( WPF, C# ) 216 Web Safe Colors On Rotating 3D Cube using Dynamic/Generic and Relative color pallet.
发表评论
yxURzg your e-mail subscription link or e-newsletter service.
OHQiB1 I\ ave been looking for something that does all those things you just mentioned. Can you recommend a good one?
IiLsxk Thank you for your article.Thanks Again. Cool.
I32bI6 Yay google is my queen assisted me to find this great internet site!.
Thanks for the blog post.Really thank you! Awesome.
COR47T Really enjoyed this article post.Much thanks again. Really Great.
Y7oY8J Wow! This could be one particular of the most useful blogs We have ever arrive across on this subject. Basically Great. I am also a specialist in this topic so I can understand your effort.
HkFtG4 Muchos Gracias for your blog article. Will read on
2KRg5N Incredible! This blog looks just like my old one! It as on a completely different subject but it has pretty much the same page layout and design. Great choice of colors!
8ZMd3I Looking forward to reading more. Great article post.Really looking forward to read more. Keep writing.
65t968 mais de fois qui. Alors, dormir dehors, des homicides ou, le meilleur et, fringues se nai
NSHBMX Thanks for the blog post.Really thank you! Fantastic.
X9ulkz Really appreciate you sharing this blog post.Really thank you! Want more.
GWqcpG Remarkable! Its actually awesome post, I have got much clear idea
unwHjE This is just what I ave been looking for all day long. Don at stop updating your blog.
sexBi6 Really appreciate you sharing this blog. Cool.
lCQb3D It as exhausting to search out educated people on this topic, but you sound like you already know what you are talking about! Thanks
I truly appreciate this blog.Really looking forward to read more. Really Cool.
oCACkS Wow, incredible blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your web site is wonderful, let alone the content!
8NdOwD I went over this internet site and I conceive you have a lot of great information, saved to favorites (:.
1C8AJQ Thanks for every other fantastic post. Where else may anyone get that type of information in such a perfect way of writing? I have a presentation next week, and I am at the search for such info.
iGihhq
ilstiV very good put up, i definitely love this web site, carry on it
mD8czq Im grateful for the article.Really looking forward to read more. Cool.
7cwk4Y Spot on with this write-up, I actually think this web site wants rather more consideration. I'll probably be once more to read far more, thanks for that info.
6JPpbY Hello there, I found your web site by the use of Google even as looking for a comparable topic, your site got here up, it appears to be like great. I've bookmarked it in my google bookmarks.
w0s79a Heya i'm for the primary time here. I found this board and I in finding It truly helpful & it helped me out much. I am hoping to offer one thing again and aid others such as you aided me.
AYxJh4 I like what you guys are up too. Such clever work and reporting! Keep up the excellent works guys I have incorporated you guys to my blogroll. I think it will improve the value of my web site :)
ynwZ25 you are really a good webmaster. The site loading speed is incredible. It seems that you're doing any unique trick. Also, The contents are masterwork. you have done a fantastic job on this topic!
EfCgK3 A round of applause for your blog post.Really thank you! Fantastic.
kUgroS F*ckin' remarkable things here. I am very glad to see your article. Thanks a lot and i'm looking forward to contact you. Will you please drop me a e-mail?
jNBO0T Im grateful for the blog.Really thank you! Will read on...
aQ2Bkt Im grateful for the blog post.Really thank you! Awesome.
WjSQXg Major thankies for the blog post.Much thanks again. Much obliged.
tg3UBq I truly appreciate this post.Much thanks again. Cool.
Q8IpUZ Very informative article post. Want more.
dYM4JZ Looking forward to reading more. Great blog post.Really thank you! Great.
LCkqhO I loved your article post. Cool.
Bzq8Uq Thanks a lot for the blog.Much thanks again. Cool.
Rys4H1 Very good blog.Really looking forward to read more. Really Cool.
rhaSJV Thanks again for the blog. Keep writing.
krPQbN Im obliged for the post.Much thanks again. Fantastic.
SziKr0 A round of applause for your article post. Much obliged.
yKeXup Say, you got a nice article post.Much thanks again. Will read on...