Push Notifications for Windows Phone 7 using SQL Azure and Cloud services - Part 3/3

DZone 's Guide to

Push Notifications for Windows Phone 7 using SQL Azure and Cloud services - Part 3/3

· Mobile Zone ·
Free Resource

In the  first part of this article series I created a WCF Web Service that manages interaction between a Windows Phone 7 application and a SQL Azure database containing push notification services data.   In the second part of this article series we created a WP7 application that consumed the WCF service we created in the first part and to let the back-end service know what push notifications were interesting as well as displayed toast notifications based on user selections in the WP7 application. In this part we will have a closer look at the WCF service and how subscription management, matching and scheduling are handled.

Notification subscription management

By following the steps above you now have a solution that lets the user manage his notification subscriptions from the application. The user can see what categories he is currently subscribing to and he can subscribe to new categories or remove subscription from categories he is already subscribing to.

In this example I have decided to create this solution from scratch by creating the database, creating the service (that is responsible for pushing notifications) and consuming the service in the WP7 app. If you want to create a more complex notification subscription solution you can check out SQL Server Notification Services or if you are working with BizTalk you can use the Adapter for SQL  Server Binding Properties. It is also possible to configure your WCF service to receive query notifications.

Matching content with subscriptions

Since the user is subscribing to categories we have a link to match his subscriptions with content. In this example content is news articles added for a given category. Until now we have had to manually invoke the PushToastNotification method and we want to change this now.

When a news article is added we want the service to automatically push a toast notification to all devices that are subscribing to the category the article belongs to. With the code base we now have this can be done very easy by adding a few more lines of code in the NewsReaderService.svc.cs class in the WCF service project.

In the AddNewsArticle method we add two lines of code at the end of the method and we add a new method called GetCategoryNameById. First we get the category name so we can display it in the toast message, then we call the PushToastNotification method. You can see the updated AddNewsArticle method and the new GetCategoryNameById method below.

public void AddNewsArticle(string header, string article, int categoryId)
using (var context = new NewsReaderEntities())
context.AddToNews((new News
Header = header,
Article = article,
CategoryId = categoryId,
AddedDate = DateTime.Now,
//Get category name
string categoryName = GetCategoryName(categoryId);
//Push toast notification
PushToastNotifications("New article", "Added in category: " +categoryName, categoryId);

private string GetCategoryName(int categoryId)
using (var context = new NewsReaderEntities())
var categoryName = (from o in context.Category
where o.CategoryId == categoryId
select o.Name).First();
return categoryName;

You can now redeploy the service and run you application. Use WCF Test Client to add a news article and you will immediate get a toast notification on your phone if you are subscribing to the category you added a news article for.

Scheduling notifications

In the solution we now have notifications are not scheduled, they are sent immediate when a new article is added. For many situations this is not a good thing to do, you do not want to spam your users with notifications and the load on the server will be quite heavy. In this section we will have a look at how we can schedule notifications.

To start with you can use the built in batch mechanism where you can choose if the notifications are to be pushed immediately, every 450 seconds or every 900 seconds. You can see this in the PushToastNotificationToSubscribers method. In this example I am using immediate (value 2), you can change this to 12 for 450 seconds batch or 22 for 900 seconds batch. By using the 900 seconds batch you can ensure that the user only receives notifications every 15 minute. This helps a bit but still your service is querying the database and generating push notification messages for each new article added.

Creating a notification scheduler

I will now show how you can create a thread that is responsible for pushing notifications. You can do this by creating a thread and a timer but I chose to use a open source project called Lightweight Task Scheduling for .NET/Silverlight.

Using Lightweight Task Scheduling for .NET/Silverlight

You find the project at codeplex and you need to download a .zip file containing the project. Extract the downloaded .zip file and open the project in Visual Studio. Build the project so you get the Hardcodet.Scheduling.dll file. Make sure that you target .NET Framework 4 when building the project, unless you can get some issues while using it in your WCF service. In your NewsReaderCloudService project add the Hardcodet.Scheduling.dll file as a reference. You are now ready to start using the Lightweight Task Scheduling in your WCF service.

Schedule to run every hour

I now want my service to check for new articles every hour and send notifications to subscribing devices. To acheive this you add the following code in your NewsReaderService.svc.cs class

private readonly Scheduler _scheduler = new Scheduler();

public NewsReaderService()

private void CheckForNotificationEveryHour()
//Configure the job to run every hour
Job consoleJob = new Job();

//submit the job with the callback to be invoked
//Will invoke the NotifySubscribers method
_scheduler.SubmitJob(consoleJob, j => NotifySubscribers());

private void NotifySubscribers()
var categoryIds = GetIdForAllCategories();
var newArticlesDictionary = new Dictionary<int, int>();

//Set last notification check to one hour back since we are running this job every hour
var lastNotificationCheck = new DateTime(DateTime.Now.Millisecond - (60 * 60 * 1000));

//Check for new articles within each category
foreach (int categoryId in categoryIds)
using (var context = new NewsReaderEntities())
IQueryable<int> numberOfArticles = from o in context.News
where o.AddedDate >= lastNotificationCheck
select o.NewsId;
foreach (KeyValuePair<int, int> keyValuePair in newArticlesDictionary)
//Get category name
string categoryName = GetCategoryName(keyValuePair.Key);
//Push notifications to subscribers
PushToastNotifications("New articles", keyValuePair.Value + " new articles in " +categoryName, keyValuePair.Key);

private List<int> GetIdForAllCategories()
var categories = new List<int>();
using (var context = new NewsReaderEntities())
IQueryable<int> selectedSubscriptions = from o in context.Subscription
select o.CategoryId;
return categories;

Be aware that in this code example the NewsReaderService constructor will not be called before one of the services are invoked.

Next step

You now have a good code base for scheduling notifications and you can extend it with the functionality you need. One extension that might come handy is to let the users chose their notification schedule when subscribing for notifications.

To do so you can add a new column in your Subscription table called Schedule. You extend the SubscribeToNotification method with a TimeSpan parameter.

void SubscribeToNotification(Guid deviceId, string channelURI, int categoryId, TimeSpan scheduling);

In NewsReaderService.svc.cs you also expand the SubscribeToNotification method so that the schedule TimeSpan is added to the database as well. Then you need to create a new Job for that subscription and add it to the Scheduler. That will look something like this

private void ScheduleJob(Guid deviceId, int categoryId, TimeSpan schedule)
Job scheduledJob = new Job();
_scheduler.SubmitJob(scheduledJob, job => NotifySubscriber(deviceId, categoryId, schedule));

private void NotifySubscriber(Guid deviceId, int categoryId, TimeSpan schedule)
//Check for new articles within the given category and
//push notification to the given device

I hope these series gave you a better understanding on how to work with push notifications for Windows Phone 7 and how you can manage the notification subscriptions on the server-side. For additional background on Microsoft Push Notifications, please check out this sample at AppHub as well:
Recipe: Push Notification Server Side Helper for WP7

You can read my blog at www.breathingtech.com and follow me on twitter @PerOla



Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}