WP7 Push Notification on Azure – Part 1

Posted: June 18, 2011 in Uncategorized

As I talked before about the relation between WP7 and the cloud in a previous blog, I will show you now how to begin coding to start using the different push notification using a WCF Service hosted on a cloud application.

The usual connection to the internet or to the cloud is made first by the mobile or in this case the WP7. In the following examples the cloud will initiate and send a notification to the mobile device id and only if the mobile is registered into the service or the channel.

The first kind of the push notification is the Toast. It is a simple notification sent to the WP7 it looks a bit like the SMS but it depends on the internet connection and the WP7 must be subscribed in the Notification channel. In other words, this application mainly has 2 parts: one hosted on the cloud and the second one is installed on the device. It is simply subscribe the device to the channel or the service. This type of notification doesn’t require you to be running the application. Here is some code:
[OperationContract]
void sendtoast(string message, string channeluri)
{
try
{
//create the HttpWebRequest to Microsoft Notification Server
//this require internet connection
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(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);
}
}
catch
{
}
}

If you press on the notification sent, it navigates you to the application itself.
All the above examples are implemented in a WCF service hosted in a cloud application. The following is the code required to be in the mobile application in the app.xaml.cs

public App()

{


// Global handler for uncaught exceptions.

UnhandledException += Application_UnhandledException;


// Show graphics profiling information while debugging.


if (System.Diagnostics.Debugger.IsAttached)

{


// Display the current frame rate counters.


Application.Current.Host.Settings.EnableFrameRateCounter = false;


// Show the areas of the app that are being redrawn in each frame.


//Application.Current.Host.Settings.EnableRedrawRegions = true;


// Enable non-production analysis visualization mode,


// which shows areas of a page that are being GPU accelerated with a colored overlay.


//Application.Current.Host.Settings.EnableCacheVisualization = true;

}


// Standard Silverlight initialization

InitializeComponent();


// Phone-specific initialization

InitializePhoneApplication();


// Create the shell tile schedule instance

CreateShellTileSchedule();

}


// To store the instance for the application lifetime


private
ShellTileSchedule shellTileSchedule;


///
<summary>


/// Create the application shell tile schedule instance


///
</summary>


private
void CreateShellTileSchedule()

{

shellTileSchedule = new
ShellTileSchedule();

shellTileSchedule.Recurrence = UpdateRecurrence.Interval;

shellTileSchedule.Interval = UpdateInterval.EveryHour;

shellTileSchedule.StartTime = DateTime.Now;

shellTileSchedule.RemoteImageUri = new
Uri(@”http://cdn3.afterdawn.fi/news/small/windows-phone-7-series.png&#8221;);

shellTileSchedule.Start();

}


// Code to execute when the application is launching (eg, from Start)


// This code will not execute when the application is reactivated


private
void Application_Launching(object sender, LaunchingEventArgs e)

{

}


// Code to execute when the application is activated (brought to foreground)


// This code will not execute when the application is first launched


private
void Application_Activated(object sender, ActivatedEventArgs e)

{

}


// Code to execute when the application is deactivated (sent to background)


// This code will not execute when the application is closing


private
void Application_Deactivated(object sender, DeactivatedEventArgs e)

{

}


// Code to execute when the application is closing (eg, user hit Back)


// This code will not execute when the application is deactivated


private
void Application_Closing(object sender, ClosingEventArgs e)

{

}


// Code to execute if a navigation fails


private
void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)

{


if (System.Diagnostics.Debugger.IsAttached)

{


// A navigation has failed; break into the debugger

System.Diagnostics.Debugger.Break();

}

}


// Code to execute on Unhandled Exceptions


private
void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)

{


if (System.Diagnostics.Debugger.IsAttached)

{


// An unhandled exception has occurred; break into the debugger

System.Diagnostics.Debugger.Break();

}

}

#region Phone application initialization


// Avoid double-initialization


private
bool phoneApplicationInitialized = false;


// Do not add any additional code to this method


private
void InitializePhoneApplication()

{


if (phoneApplicationInitialized)


return;


// Create the frame but don’t set it as RootVisual yet; this allows the splash


// screen to remain active until the application is ready to render.

RootFrame = new
PhoneApplicationFrame();

RootFrame.Navigated += CompleteInitializePhoneApplication;


// Handle navigation failures

RootFrame.NavigationFailed += RootFrame_NavigationFailed;


// Ensure we don’t initialize again

phoneApplicationInitialized = true;

}


// Do not add any additional code to this method


private
void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)

{


// Set the root visual to allow the application to render


if (RootVisual != RootFrame)

RootVisual = RootFrame;


// Remove this handler since it is no longer needed

RootFrame.Navigated -= CompleteInitializePhoneApplication;

}

#endregion

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s