Push Notifications with SharePoint 2013-based Windows Phone apps

Setting up push notifications for your SharePoint Windows Phone app is fairly straight-forward. Push notifications with SharePoint uses the same Microsoft Push Notification Service (MSPNS) to create a communications channel from the server to the device. The following code sets up an MSPNS channel:

public void Register(ClientContext context)
{
    _currentContext = context;

    HttpNotificationChannel channel = HttpNotificationChannel.Find(CHANNEL_NAME);

    if (channel == null)
    {
        channel = new HttpNotificationChannel(CHANNEL_NAME);

        channel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(channel_ChannelUriUpdated);
        channel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(channel_ErrorOccurred);
        channel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(channel_ShellToastNotificationReceived);

        channel.Open();
        channel.BindToShellToast();
    }
    else
    {
        channel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(channel_ChannelUriUpdated);
        channel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(channel_ErrorOccurred);
        channel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(channel_ShellToastNotificationReceived);
    }
}

 

If a channel hasn't yet been created, then we create it, add event handlers for events that we need to handle and then open the channel. The event handler ShellToastNotificationReceived is used so that we can handle the notification while the app is running. If the app is not running, the toast will be handled automatically by calling BindToShellToast().

When MSPNS has created a channel and assigned it a URI, we need to then create a notification subscription in SharePoint:

void channel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
{
    Web web = _currentContext.Web;
    string channelUri = e.ChannelUri.ToString();

    PushNotificationSubscriber subscriber;

    if (!web.DoesPushNotificationSubscriberExist(App.Settings.AppDeviceID).Value)
    {
        subscriber = web.RegisterPushNotificationSubscriber(App.Settings.AppDeviceID, channelUri);
    }
    else
    {
        subscriber = web.GetPushNotificationSubscriber(App.Settings.AppDeviceID);
        subscriber.ServiceToken = channelUri;
    }

    subscriber.SubscriberType = SUBSCRIBER_TYPE;
    subscriber.Update();

    _currentContext.ExecuteQueryAsync(null,null);
}

 

First we check to see if the notification subscriber already exists. Subscriptions are stored in a list in SharePoint called PushNotificationSubscriptionStore. This is a hidden list that you can't get to through the UI; however, it does show up in the ListData.svc OData service. To see what fields are in the list, review the service's metadata (ex/ http://mobile-apps.fabrikam.com/sites/Team%20Site/_vti_bin/listdata.svc/$metadata). This list contains PushNotificationSubscriptionStoreItem items. The DeviceIdentifier field is what you can use to store the GUID that was generated for the device/app and the ServiceToken field should be used to store the channel URI. Also note that you should probably come up with distinct SubscriberType values. Since all of these notification subscriptions are stored in a single list, this is the simplest way for you to distinguish which notification to send for each application notification. Once these fields are set, we use ClientContext.ExecuteQueryAsync() to save the values.  One other thing to mention, don’t forget to activate the Push Notifications site feature on the site where you’ll be using push notifications (this should actually be the first thing you do).

To handle unregistering for the push notification, you need to unregister the notification subscription from SharePoint:

private void ButtonClear_Click(object sender, RoutedEventArgs e)
{
    App.Settings.ClearSettings();
    PushNotificationRegistration registration = new PushNotificationRegistration();
    registration.Unregister();
}

 

The Unregister method of my PushNotificationRegistration class closes and disposes the channel I created when the user initially registered:

public void Unregister()
{
    HttpNotificationChannel channel = HttpNotificationChannel.Find(CHANNEL_NAME);
    if (channel != null)
    {
        channel.Close();
        channel.Dispose();
    }
}

Once this is ready, then on the server, all you have to do is to find all the notification subscribers that you need to send a notification to and send the notification out using the same code you'd normally use to send push notifications out to other Windows Phone apps. For this app, I decided to handle this in an Event Receiver and send notifications out when an item is added or updated in the Products list:

public class ProductsListEventReceiver : SPItemEventReceiver
{
    /// <summary>
    /// An item is being added.
    /// </summary>
    public override void ItemAdding(SPItemEventProperties properties)
    {
        base.ItemAdding(properties);
        SendNotification("New Product Added", properties); 
    }

    /// <summary>
    /// An item is being updated.
    /// </summary>
    public override void ItemUpdating(SPItemEventProperties properties)
    {
        base.ItemUpdating(properties);
        SendNotification("Product Updated", properties); 
    }

    private void SendNotification(string title, SPItemEventProperties properties)
    {
        SPPushNotificationSubscriberCollection subscribers = properties.Web.PushNotificationSubscribers;
        foreach (SPPushNotificationSubscriber subscriber in subscribers)
        {
            if (!string.IsNullOrEmpty(subscriber.SubscriberType) && subscriber.SubscriberType.Equals(
"ProductAlerts", StringComparison.InvariantCultureIgnoreCase))
            {
                HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest.Create(subscriber.ServiceToken);
                sendNotificationRequest.Method = "POST";
                string toastMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                "<wp:Notification xmlns:wp=\"WPNotification\">" +
                "<wp:Toast>" +
                "<wp:Text1>" + title + "</wp:Text1>" +
                "<wp:Text2>" + properties.ListItem.Title + "</wp:Text2>" +
                "</wp:Toast> " +
                "</wp:Notification>";
                byte[] notificationMessage = Encoding.Default.GetBytes(toastMessage);
                sendNotificationRequest.ContentLength = notificationMessage.Length;
                sendNotificationRequest.ContentType = "text/xml";
                sendNotificationRequest.Headers.Add("X-WindowsPhone-Target", "toast");
                sendNotificationRequest.Headers.Add("X-NotificationClass", "2");
                try
                {
                    using (Stream requestStream = sendNotificationRequest.GetRequestStream())
                    {
                        requestStream.Write(notificationMessage, 0, notificationMessage.Length);
                    }
                    HttpWebResponse response = (HttpWebResponse)sendNotificationRequest.GetResponse();
                }
                catch
                {
                    //TODO: log error 
                }
            }
        }
    } 

}
 

Note that it's probably not a good idea to do a foreach loop over the SPPushNotificationSubscriberCollectionif there's going to be thousands of items in that list. I did this for the sake of simplicity. Also, LINQ to SharePoint won't work on this list. The only way you might be able to do a more efficient filtering is through a CAML query, though I didn't test this.

Once this feature is installed and the user has registered for push notifications in this app, the results look like this:

toast

One thing to be aware of is that with Windows Phone apps, there's no event notification for when your app is uninstalled. Given this, you probably need some way to determine on the server if a notification subscription should be deleted (if it hasn't been used in a while). Otherwise, you might be flooding MPNS with attempts to send a notification to a channel that is no longer accessible.

If you want the full source code to this, please tweet a link to this post and then send me an email (bart.tubalinal at deviantpoint dot com). I will then email you the source code for both the phone app project and the event receiver project.