How to handle WNS Response codes and Expired Channels in your Windows Azure Mobile Service

When implementing push notification solutions for your Windows Store apps many people will implement the basic flow you typically see in a demo then consider their implementation as job done. While this works well in demos and apps that are running at a small scale with few users those that are successful will likely want to optimize their solution to be more efficient to reduce compute and storage costs. While this post is not a complete guide I am providing it to at least give you enough information to get you thinking about the right things.
A few quick up front questions you should ask yourself are:

  • Is push appropriate? Should I be using Local, Scheduled or Periodic notifications instead?
  • Do I need updates at a more granular frequency then every 30 minutes?
  • Am I sending notifications that are personalized for each recipient or am I sending a broadcast style notification with the same content to a group of users?

A typical implementation

If you figured out push is the right choice and implemented the basic flow it will normally look something like this:

 

  1. Requesting a channel
  2. using Windows.Networking.PushNotifications;
    …
    var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
    
  3. Registering that channel with your cloud service
  4. var token = Windows.System.Profile.HardwareIdentification.GetPackageSpecificToken(null);
    string installationId = Windows.Security.Cryptography.CryptographicBuffer.EncodeToBase64String(token.Id);
    
    var ch = new JObject();
    ch.Add("channelUri", channel.Uri);
    ch.Add("installationId", installationId);
    
    try
    {
       await App.pushdemoClient.GetTable("channels").InsertAsync(ch);
    }
    catch (Exception exception)
    {
       HandleInsertChannelException(exception);
    }
    
  5. Authenticate against WNS and sending a push notification
  6. //Note: Mobile Services handles your Auth against WNS for your, all you have to do is configure your Store app and the portal WNS credentials.
    
    function SendPush() {
        var channelTable = tables.getTable('channels');
        channelTable.read({
            success: function (channels) {
                channels.forEach(function (channel) {
                    push.wns.sendTileWideText03(channel.uri, {
                        text1: 'hello W8 world: ' + new Date().toString()
                    });
                });
            }
        });
    }
    

And for most people this is about as far as the push implementation goes. What many are not aware of is that WNS actually provides two useful pieces of information that you can use to make your push implementation more efficient – a Channel Expiry time and a WNS response that includes both notification status codes and device status codes using this information you can make your solution more efficient. Let’s take a look at the first one

Handling Expired Channels

When you request a channel from WNS it will return to you both a channel and an expiry time, typically 30 days from your request. Consider that your app over time is popular but you do have users that over time end up deciding either to not use your app for extended periods or delete it all together. Over time these channels will hit their expiry date and will no longer be of any use and there is no need to a) send notifications to these channels and b) keep these channels in your datastore. Let’s have a look at a simple implementation that will cleanup your expired channels.

Using a Scheduled Job in Mobile Services we can perform a simple clean of your channels but first we must send the Expiry to your Mobile Service. To do this you must update step 2 of the above implementation to pass up the channel expiry as a property in your JObject – you will find the channel expiration in the channel.ExpirationTime property. For my channel table I have called this Expiry.

Following that once you have created your scheduled push job at say an interval of X (I am using 15 minutes) you can then add a function that deletes the expired channels similar to the following

function cleanChannels() {
    var sql = "DELETE FROM channels WHERE Expiry < GetDate()";
    mssql.query(sql, {
        success: function (results) {
            console.log('deleting expired channels:', results)
        },
        error: function (error) {
            console.log(error);
        }
    });
}

As you can see there is no real magic here and you probably want to handle UTC dates – but in short it demonstrates the concept that the expired channels are not useful for sending notifications so delete them, flag them as deleted or anything else that keeps them out of the valid set that you will push to… moving on

Handling the WNS response codes

When you send a notification to a channel via WNS, WNS will send a response. Within this response are many useful response headers. Today i’ll just focus on X-WNS-NotificationStatus but it’s worth noting that you should also consider X-WNS-DeviceConnectionStatus – more details here

Let’s look at a typical response:

{
headers:
{ ‘x-wns-notificationstatus’: ‘received’,
‘x-wns-msg-id’: ’707E20A6167E338B’,
‘x-wns-debug-trace’: ‘BN1WNS1011532′ },
statusCode: 200,
channel: ‘https://bn1.notify.windows.com/?token=AgYAAACghhaYbZa4sqjJ23pWp3kGDcEOEb3JxxdeBahCINn15fc11TiG0mlTpR5heYQmEaQrgZc3TSSwoUllW9s4Lsn3eyvSn19DcrX%2bOvSOY4Bq%2bPKGWbdy3mjTmaRi2Yb1dIM%3d’
}

Of interest in this response is X-WNS-NotificationStatus which can be one of three different states:

  • received
  • dropped
  • channelthrottled

As you can probably guess if you are sending notifications when you are either throttled or dropped it is probably not a good use of your compute power and as such you should really handle channels that are not returning received status in a fitting way. Consider the following when the scheduled job runs delete any expired channels and send notifications to channels in (the status of received) OR (that are not in the status of received AND that last had a push sent over an hour ago). This can be easily achieved by tracking the X-WNS-NotificationStatus every time a notification is sent. Code follows:

function SendPush() {
    cleanChannels();
    doPush();
}

function cleanChannels() {
    var sql = "DELETE FROM channel WHERE Expiry < GetDate()";

    mssql.query(sql, {
        success: function (results) {
            console.log('deleting expired channels:', results)
        },
        error: function (error) {
            console.log(error);
        }
    });
}

function doPush() {
    //send only to received channels OR channels that are not in the state of received that last had a push sent over an hour ago 
    var sql = "SELECT * FROM channel WHERE notificationStatus IS NULL OR notificationStatus = 'received' 
                    OR ( notificationStatus <> 'received'
                           AND CAST(GetDate() - lastSend AS float) * 24 >= 1) ";

    mssql.query(sql, {
        success: function (channels) {
            channels.forEach(function (channel) {

                push.wns.sendTileWideText03(channel.uri, {
                    text1: 'hello W8 world: ' + new Date().toString()
                }, {
                    success: function (response) {
                        handleWnsResponse(response, channel);
                    },
                    error: function (error) {
                        console.log(error);
                    }
                });
            });
        }
    });
}

// keep track of the last know X-WNS-NotificationStatus status for a channel
function handleWnsResponse(response, channel) {
    console.log(response);

    var channelTable = tables.getTable('channel');

    // http://msdn.microsoft.com/en-us/library/windows/apps/hh465435.aspx
    channel.notificationStatus = response.headers['x-wns-notificationstatus'];
    channel.lastSend = new Date();

    channelTable.update(channel);
}

That’s about it I hope this post has helped you to start thinking about how to handle your Push Notification implementation beyond the basic 101 demo push implementation

Enjoy, Nick Harris

Sending Language specific Push Notifications to Windows 8 using the WnsRecipe

I was recently asked to help out with a MSDN forum post on how the WnsRecipe NuGet package can be used to send Push Notifications via WNS to Windows 8 Metro app clients.  Essentially here are the steps.

Note: This post assumes you have already created a client app, requested test credentials for WNS and received a notification channel in your cloud service.  If you have not yet done this I would recommend you watch this episode of cloud cover where I demonstrate the setup:

If you want to download the hi def version here is the direct link to Channel 9 for this episode .

Now that you have watched the pre-req the rest is really quite simple.

Install the WnsRecipe NuGet into your solution using the NuGet Package Manager

  • Right click on your project and select ‘Manage NuGet Packages’
  • Select Online and search for WnsRecipe and press Install
    using NotificationsExtensions; 
    using NotificationsExtensions.TileContent;
    
  • Use the recipe as per normal but recall to set the appropriate BCP 47 language code  for your wideTile.Lang and squareTile.Lang properties
    //new up an access token provider with your credentials
    IAccessTokenProvider tokenProvider = new WnsAccessTokenProvider("<your package sid>", "<your client secret>");     
    var uri = new Uri("<your endpoint uri>");
    
    //Create the wide tile
    ITileWideText09 wideTile = TileContentFactory.CreateTileWideText09();     
    wideTile.Lang = "de-DE";     
    wideTile.TextHeading.Text = "Test-Paket";     
    wideTile.TextBodyWrap.Text = "ä";
    
    // new up a square tile to send down with the wide tile
    // as you do not know if the user has pinned the tile to small or wide
    ITileSquareText02 squareTile = TileContentFactory.CreateTileSquareText02();     
    squareTile.Lang = "de-DE";     
    squareTile.TextHeading.Text = "Test-Paket";     
    squareTile.TextBodyWrap.Text = "ä";     
    
    // set the square tile content
    wideTile.SquareContent = squareTile;
    
    //Send notification - note you should pay attention to the Status codes coming back from the 
    //send operation in the result variable.
    var result = wideTile.Send(uri, tokenProvider);
    
  • And that’s basically it as mentioned above this is a somewhat fragment sample. Please do watch the Cloud Cover episode if you require more detail

For a full list with screenshots of the different tile template types please see this MSDN reference

Updated Windows Azure Toolkit for Windows 8 Consumer Preview

On Friday we released the an update to the Windows Azure Toolkit for Windows 8 Consumer Preview. This version of the toolkit adds a Service Bus sample, Raw Notification sample and Diagnostics to the WnsRecipe NuGet. You can download the self-extracting package on Codeplex from here.

If you are building Windows 8 Metro Style applications with Windows Azure and have not yet downloaded the toolkit I would encourage you to do so.  Why?, as a quick demonstration the following video shows how you can use the toolkit to build a Windows 8 Metro Style application that uses Windows Azure and the Windows Push Notification Service (WNS) to send Toast, Tile and Badge notifications to your Windows 8 Consumer Preview apps in under 4 minutes.


You can view/download the hi-def version of the video on channel 9 here

What’s in it?

  • Automated Install – Scripted install of all dependencies including Visual Studio 2010 Express and the Windows Azure SDK on Windows 8 Consumer Preview.
  • Project Templates – Client project templates for Windows 8 Metro Style apps in Dev 11 for both XAML/C# and HTML5/JS with a supporting server-side Windows Azure Project for Visual Studio 2010.
  • NuGet Packages – Throughout the development of the project templates we have extracted the functionality into NuGet Packages for example the WNSRecipe NuGet provides a simple managed API for authenticating against WNS, constructing notification payloads and posting the notification to WNS. This reduces the effort to send a Toast, Tile, Badge or Raw notification to about three lines of code. You can find a full list of the other packages created support Push Notifications and the sample ACS scenarios here and full source in the toolkit under /Libraries.
  • Samples  – Five sample applications demonstrating different ways Windows 8 Metro Style apps can use Push Notifications, ACS and Service Bus
  • Documentation – Extensive documentation including install, file new project walkthrough, samples and deployment to Windows Azure.

Want More?

If you would like to learn more about the Windows Push Notification Service and the Windows Azure Toolkit for Windows 8 check out the following videos.

Building Metro Style apps that use Windows Azure Service Bus

You can view/download the hi-def version of the video on channel 9 here

Sending Push Notifications to Windows 8 and Windows Phone 7 Devices using Windows Azure

You can view/download the hi-def version of the video on channel 9 here

Building Metro Style apps that use Push Notifications

You can view/download the hi-def version of the video on channel 9 here

Building Metro Style apps that use the Access Control Service

You can view/download the hi-def version of the video on channel 9 here

For more details, please refer to the following posts:

Please ping me on twitter to let me know if you have any feedback or questions @cloudnick

Enjoy,
Nick

Delivering Toast Tile and Badge Notifications to Windows 8 and Windows Phone using Windows Azure

Here is a recent talk I gave at TechDays Belgium.

Notifications extend the reach of your app to the desktop and device, but with a large user base timely delivery can be challenging without the right tools. In this session we’ll review the notification options available to Windows Phone and Windows Metro Style apps, demonstrate how you can deliver notifications using Windows Azure, and discuss features provided by Windows Azure to scale your notification solution. By the end of this session you will understand how to use Windows Azure to rapidly develop a notification enabled service for Windows Phone and Windows 8 apps.

or watch direct from channel 9

Enjoy,
Nick

Windows Azure Toolkit for Windows 8 Version 1.1.0 CTP Released

Today we released version 1.1.0 (CTP)of the Windows Azure Toolkit for Windows 8. This release includes the following changes to the Windows Azure toolkit for Windows 8:

  • Dependency Checker updated to reference latest releases.
  • MVC Website code cleanup and improvements to send notifications dialog
  • WNS Recipe Updated WNS Recipe to add Audio support.
  • NuGets project template refactored to make use of NuGets which people can also use directly in their existing apps.
  • notification.js created for client apps to easily communicate the Registration Service i.e WindowsAzure.Notifications NuGet.
  • Samples The samples are currently undergoing churn and will be updated in the coming drop. Added Margie’s Travel CTP as a Sample application

As a brief preview to the CTP toolkit check out this 3 minute video to see how you can get a jump start using Windows Azure Toolkit for Windows 8 to send Push Notifications with Windows Azure and the Windows Push Notification Service (WNS). This demonstration uses the Windows Azure Toolkit for Windows 8 that includes full end to end scenario for Tile and Badge notifications with Toast notifications only a drop down away :)

Note: This release is a ‘CTP’ release as it has not yet gone through our full QA process. We have released this as a CTP as it updates a number of key issues that users were facing with dependency checks and the file new project experience. We will be releasing a final version of the 1.1.x branch in the coming days once it has undergone the full QA tests and also has refreshed documentation. Until this updated drop is made the CTP is the recommended download for users to proceed with.

Enjoy,

Nick

Delivering Notifications using Windows Azure and Windows Push Notification Service

Over the past little while I have had the pleasure of building the Windows Azure Toolkit for Windows 8. The following is a re-post of my official post on the Windows Azure Blog.

The Windows Azure Toolkit for Windows 8 is designed to make it easier for developers to create a Windows Metro style application that can harness the power of Windows Azure Compute and Storage. It includes a Windows 8 Cloud Application project template for Visual Studio that makes it easier for developers to create a Windows Metro style application that utilizes services in Windows Azure. This template generates a Windows Azure project, an ASP.NET MVC 3 project, and a Windows Metro style JavaScript application project.  Immediately out-of-the-box the client and cloud projects integrate to enable push notifications with the Windows Push Notification Service (WNS). In Addition, the Windows Azure project demonstrates how to use the WNS recipe and how to leverage Windows Azure Blob and Table storage.

The Windows Azure Toolkit for Windows 8 is available for download.

Push Notification Cloud Service Architecture

For those of you who are familiar with working with Windows Phone 7 and the Microsoft Push Notification Service (MPNS), you will be happy to know that the Windows Push Notification service (WNS) is quite similar. Let’s take a look at a birds-eye architectural view of how WNS works.

Windows Push Notification Service and Windows Azure

The process of sending a notification requires few steps:

  1. Request a channel. Utilize the WinRT API to request a Channel Uri from WNS.  The Channel Uri will be the unique identifier you use to send notifications to an application instance.
  2. Register the channel with your Windows Azure cloud services. Once you have your channel you can then store your channel and associate it with any application specific data (e.g user profiles and such) until your services decide that it’s time to send a notification to the given channel
  3. Authenticate against WNS. To send notifications to your channel URI you are first required to Authenticate against WNS using OAuth2 to retrieve a token to be used for each subsequent notification that you push to WNS.
  4. Push notification to channel recipient. Once you have your channel, notification payload and WNS access token you can then perform an HttpWebRequest to post your notification to WNS for delivery to your client.

Fortunately, the Windows Azure Toolkit for Windows 8 accelerates development by providing a set of project templates that enable you to start delivering notifications from your Windows Azure cloud service with a simple file new project experience.  Let’s take a look at the toolkit components.

Toolkit Components

The Windows Azure Toolkit for Windows 8 contains a rich set of assets including a Dependency Checker, Windows Push Notification Service recipe, Dev 11 project templates, VS 2010 project templates and Sample Applications.

Dependency Checker

The dependency checker is designed to help identify and install those missing dependencies required to develop both Windows Metro style apps on and Windows Azure solutions on Windows 8.

Windows Push Notification Service and Windows Azure

Dev 11 Windows Metro style app

The Dev 11 Windows Metro style app provides a simple UI and all the code required to demonstrate how to request a channel from WNS using the WinRT API.  For example, the following listing requests a Channel URI from WNS:

var push = Windows.Networking.PushNotifications;
var promise = push.PushNotificationChannelManager.createPushNotificationChannelForApplicationAsync();

promise.then(function (ch) {
var uri = ch.uri;
var expiry = ch.expirationTime;
updateChannelUri(uri, expiry);
});

Once you have your channel, you then need to register this channel to your Windows Azure cloud service. To do this, the sample app calls into updateChannelUri where we construct a simple JSON payload and POST this up to our WCF REST service running in Windows Azure using the WinJS.xhr API.

function updateChannelUri(channel, channelExpiration) {
if (channel) {
var serverUrl = "https://myservice.com/register";
var payload = { Expiry: channelExpiration.toString(),
URI: channel };

var xhr = new WinJS.xhr({
type: "POST",
url: serverUrl,
headers: { "Content-Type": "application/json; charset=utf-8" },
data: JSON.stringify(payload)
}).then(function (req) { … });
} }

VS 2010 Windows Azure Cloud Project Template

The Windows Azure Cloud project provided by the solution demonstrates several assets for building a Windows Azure service for delivering push notifications.  These assets include:

1.  A WCF REST service for your client applications to register channels and demonstrates how to store them in Windows Azure Table Storage using a TableServiceContext. In the following code listing you can see the simple WCF REST interface exposed by the project.

[ServiceContract]
public interface IWNSUserRegistrationService
{
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare)]
void Register(WNSPushUserServiceRequest userChannel);

[WebInvoke(Method = "DELETE", BodyStyle = WebMessageBodyStyle.Bare)]
void Unregister(WNSPushUserServiceRequest userChannel);
}

2.  An ASP .NET MVC 3 portal to build and send Toast, Tile and Badge notifications to clients using the WNS recipe.

Send notifications using the Windows Push Notification Service and Windows Azure

3.  An example of how to utilize Blob Storage for Tile and Toast notification images.

Using Windows Azure Blob Storage for Tiles and Toast notifications

4.  A Windows Push Notification Recipe used by the portal that provides a simple managed API for authenticating against WNS, constructing payloads and posting the notification to WNS.

using Windows.Recipes.Push.Notifications;
using Windows.Recipes.Push.Notifications.Security;

...

//Construct a WNSAccessTokenProvider which will accquire an access token from WNS
IAccessTokenProvider _tokenProvider = new WNSAccessTokenProvider("ms-app%3A%2F%2FS-1-15-2-1633617344-1232597856-4562071667-7893084900-2692585271-282905334-531217761", "XEvTg3USjIpvdWLBFcv44sJHRKcid43QXWfNx3YiJ4g");

//Construct a toast notification for a given CchannelUrl
var toast = new ToastNotification(_tokenProvider)
{
ChannelUrl = "https://db3.notify.windows.com/?token=AQI8iP%2OtQE%3d";
ToastType = ToastType.ToastImageAndText02;
Image = "https://127.0.0.1/devstoreaccount1/tiles/WindowsAzureLogo.png";
Text = new List<string> {"Sending notifications from a Windows Azure WebRole"};
};

//Send the notification to WNS
NotificationSendResult result = toast.Send();

5.  As you can see the Windows Push Notification Recipe simplifies the amount of code required to send your notification down to 3 lines.

The net end result of each of these assets is a notification as demonstrated in the below screenshot of a Toast delivered using the Windows Azure Toolkit for Windows 8.

Sending Toast notifications on Windows 8

As an exercise, it is recommended to spend some time using the website to explore the rich set of templates available to each of the Toast, Tile and Badge notification types.

Sample applications

At present there are also two sample applications included in the toolkit that demonstrate the usage of other Windows Azure features:

  1. PNWorker: This sample demonstrates how you can utlize Windows Azure Storage Queues to offload the work of delivering notifications to a Windows Azure Worker Role.  For more details please see the CodePlex documentation.
  2. ACSMetroClient: An example of how to use ACS in your Windows Metro style applications.  For more details please see this post by Vittorio Bertocci.
  3. Margie’s Travel: As seen in the demo keynote by John Shewchuk, Margie’s Travel is a sample application that shows how a Metro style app can work with Windows Azure. For more details please see this post by Wade Wegner. This sample application will ship shortly after the //build conferene.

Summary

The Windows Azure Toolkit for Windows 8 provides developers a rich set of re-useable assets that demonstrate how to start using Windows Azure quickly from Metro style applications in Windows 8.  To download the toolkit and see a step by step walkthrough please see the Windows Azure Toolkit for Windows 8.

Please feel free to subscribe to my RSS or follow me on twitter at @cloudnick.