Windows 8 Consumer Preview and Visual Studio 11 Beta – Live tiles, toasts, badges and Push Notifications (Part 10/11)

February 29, 2012

Windows 8 provides interesting way to “interact” with user even when application is not active anymore.

 

Push Notifications

Windows Push Notifications (WNS) in Windows 8 is quite similar to the Windows Phone 7 Push Notification (MPNS) model. It uses cloud-based push notification services to deliver notifications to registered clients.

To enable application receiving push notifications developer must register it at Windows Push Notifications & Live Connect site. The process is very simple – developer provides Package display name and publisher found in application manifest:

image

and site provides with updated package name (looks like BUILD.XXXXXXXX-XXXX-XXXX-XXXX), client secret code and package security identifier (SID, looks like ms-app://s-1-15-2-2289547533-2580522492-1560851697-4285800683-875472074-159972757-1111111111). Developer must modify package name in application manifest. Created applications can be managed Live App management site and retrieve information about any registered application, usage, caps, etc.

image

After application registered and ready to receive notifications from WNS, let’s overview how the whole process works:

image

1. Metro style application uses WinRT APIs (Notification Client Platform on diagram) to open new channel to server (or reconnect with previously created channel). At the end of the process, application receives unique URI which will be used in next step.

2. Any 3rd party application (Metro, classic, WPF, cloud-based service), which has URI obtained in previous step + client secret/SID combination can request Authorization token from WNS and then POST message to provided URI using received authorization token.

3. 3rd party application (in my simplest case – console app) requests authorization token using client secret and SID, prepares XML payload (the message which WNS sends to client) and sends POST message to URI (from 1st step)

4. WNS verifies provided information, alters Windows 8 client machine and delivers the message payload to client notification platform. Client notification platform responsible on updating tile/badge, showing toast notification, updating lock screen (if application has lock screen access) and deliver notifications to Metro app if still active.

Now let’s see the application described in step 2. It has 2 main functions – GetAccessToken and Push:

private static Stream GetAccessToken(string sid, string secret)
{
    string url = "https://login.live.com/accesstoken.srf";
    var request = (HttpWebRequest)WebRequest.Create(url);

    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    string content = "grant_type=client_credentials&client_id={0}&client_secret={1}&scope=notify.windows.com";
    string data = string.Format(content, sid, secret);
    byte[] notificationMessage = Encoding.Default.GetBytes(data);

    request.ContentLength = notificationMessage.Length;

    using (Stream requestStream = request.GetRequestStream())
    {
        requestStream.Write(notificationMessage, 0, notificationMessage.Length);
    }

    var response = (HttpWebResponse)request.GetResponse();
    Stream result = response.GetResponseStream();

    return result;
}

private static HttpStatusCode Push(string pushUri, string accessToken, string type, string notificationData)
{
    var subscriptionUri = new Uri(pushUri);
    var request = (HttpWebRequest)WebRequest.Create(subscriptionUri);

    request.Method = "POST";
    request.ContentType = "text/xml";
    request.Headers = new WebHeaderCollection();
    request.Headers.Add("X-WNS-Type", type);
    request.Headers.Add("Authorization", "Bearer " + accessToken);


    byte[] notificationMessage = Encoding.Default.GetBytes(notificationData);
    request.ContentLength = notificationMessage.Length;

    using (Stream requestStream = request.GetRequestStream())
    {
        requestStream.Write(notificationMessage, 0, notificationMessage.Length);
    }

    var response = (HttpWebResponse)request.GetResponse();
    return response.StatusCode;
}

The functions are pretty simple – first returns stream with Authorization token, second uses URI obtained in step 1 (see diagram) + authorization token + notification type (set as custom header, X-WNS-Type) and sends notification payload using HTTP PUSH method.

The main function:

static void Main(string[] args)
{
    string pushUri = args.Length > 0 ? args[0] : "https://db3.notify.windows.com/?token=AQQAAABS%2bAYaiRtCeOtc9bhaC2xYXo7lv5A5fHEIWuDUePmnl6fxnKMf6wTMgXKp7NqSdSZ3kygzJrak%2fnGhtYV0iqJ1jIuSRJx0%2ftc6tzao1rIX2awu0p4SnYn7K5PItwKeBcY%3d";
    string secret = HttpUtility.UrlEncode("MY_APP_SECRET");
    string sid = HttpUtility.UrlEncode("MY_APP_SID");

    var obj = System.Json.JsonObject.Load(GetAccessToken(sid, secret));
    string accessToken = obj["access_token"].ToString();

    HttpStatusCode status;

    //Send Badge notification
    string badgeNotification = "<?xml version='1.0' encoding='utf-8'?><badge value=\"2\"/>";
    status = Push(pushUri, accessToken, "wns/badge", badgeNotification);
    Console.WriteLine("Badge notification send reault: " + status.ToString());

    //Send Toast notification
    string tostNotification = "<?xml version='1.0' encoding='utf-8'?><toast><visual><binding template=\"ToastImageAndText02\"><image id=\"1\" src=\"Images/Love.png\" alt=\"Placeholder image\"/><text id=\"1\">Love is in the air (PUSHED)!</text><text id=\"2\">Someone sends you love waves!</text></binding></visual></toast>";
    status = Push(pushUri, accessToken, "wns/toast", tostNotification);
    Console.WriteLine("Toast notification send reault: " + status.ToString());

    //Send Tile notification
    string tileNotification = "<?xml version='1.0' encoding='utf-8'?><tile><visual><binding template=\"TileWideSmallImageAndText03\"><image id=\"1\" src=\"ms-appx:///Images/LoveInTheAir.jpg\"/><text id=\"1\">Someone loves you from the distance!</text></binding></visual></tile>";
    status = Push(pushUri, accessToken, "wns/tile",tileNotification);
    Console.WriteLine("Tile notification send reault: " + status.ToString());

    Console.WriteLine("Press ENTER to exit...");
    Console.ReadLine();
}

Also this code is pretty simple it has some important information – the notification payload XML formats. In case of Toast and Tile notification this format actually dictates which information and how it will be presented to user. To learn more about Toast/Tile formats please refer to documentation.

Now when external parts are ready, let’s write Metro app functionality.

Updating tiles/toasts/badges

Tile:

imageimage

Note: Windows 8 enables developer to provide two tiles sizes. Please refer to documentation for full templates list.

Toast:

image

Note: WinRT provides multiple tile and toasts templates. Please refer to documentation for full templates list.

Badges:

image

Badge notification can be either number or one of pre-defined glyphs:

image

Note: The location of badge is predefined.

Let’s get started with updating those items. First I will show how to open push notification channel and obtain URI:

async Task SetupPushNotifications()
{
    var pushNotificationChannel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
    var channelUri = pushNotificationChannel.Uri;
    System.Diagnostics.Debug.WriteLine(channelUri); //This URI will be used in application described above

    //Optional for my sample - not really used
    //pushNotificationChannel.PushNotificationReceived += pushNotificationChannel_PushNotificationReceived;
}

void pushNotificationChannel_PushNotificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs args)
{
    switch (args.NotificationType)
    {
        case PushNotificationType.Badge:
            //Not used in sample, but usefull to process incoming badge notification messages
            //notificationContent = args.BadgeNotification.Content.GetXml(); 
            //...
            break;
        case PushNotificationType.Tile:
            //Not used in sample, but usefull to process incoming tile notification messages
            //notificationContent = args.TileNotification.Content.GetXml();
            //...
            break;
        case PushNotificationType.Toast:
            //Not used in sample, but usefull to process incoming toast notification messages
            //notificationContent = args.ToastNotification.Content.GetXml();
            //...
            break;
    }

    // prevent the notification from being delivered to the UI
    args.Cancel = true;
}

The code snippet creates push notification channel for main application tile and prints out received URI to debug console. I will be using this URI in app described above. Usually, application subscribes to received push notification messages using PushNotificationReceived event, but in my simple case I just provided the code snippet which is not really used.

Note: If application uses secondary tiles (additional tiles created from within application code – will be covered later in this post), it must use CreatePushNotificationChannelForSecondaryTileAsync method of PushNotificationChannelManager to get unique URI for the tile. As described above, delivered notification will be processed by client push notification platform and presented on main screen.

Now let’s see how to issue an update from within the application.

Generally, updating all the of tiles/badges/toasts boils down to creating correct XML according to selected template, populating values and invoking Update method of desired UpdaterManager. Example of building such XML (in this case toast notification):

StringBuilder builder = new StringBuilder("<toast");
if (!String.IsNullOrEmpty(Launch))
{
    builder.AppendFormat(" launch='{0}'", Util.HttpEncode(Launch));
}
if (Duration != ToastDuration.Short)
{
    builder.AppendFormat(" duration='{0}'", Duration.ToString().ToLowerInvariant());
}
builder.Append(">");

builder.AppendFormat("<visual version='{0}'", Util.NOTIFICATION_CONTENT_VERSION);
if (!String.IsNullOrWhiteSpace(Lang))
{
    builder.AppendFormat(" lang='{0}'", Util.HttpEncode(Lang));
}
if (!String.IsNullOrWhiteSpace(BaseUri))
{
    builder.AppendFormat(" baseUri='{0}'", Util.HttpEncode(BaseUri));
}
builder.Append(">");
            
builder.AppendFormat("<binding template='{0}'>{1}</binding>", TemplateName, SerializeProperties(Lang, BaseUri));
builder.Append("</visual>");

AppendAudioTag(builder);
            
builder.Append("</toast>");

return builder.ToString();//...

protected string SerializeProperties(string globalLang, string globalBaseUri)
{
    globalLang = (globalLang != null) ? globalLang : String.Empty;
    globalBaseUri = String.IsNullOrWhiteSpace(globalBaseUri) ? null : globalBaseUri;

    StringBuilder builder = new StringBuilder(String.Empty);
    for (int i = 0; i < m_Images.Length; i++)
    {
        if (!String.IsNullOrEmpty(m_Images[i].Src))
        {
            string escapedSrc = Util.HttpEncode(m_Images[i].Src);
            if (!String.IsNullOrWhiteSpace(m_Images[i].Alt))
            {
                string escapedAlt = Util.HttpEncode(m_Images[i].Alt);
                builder.AppendFormat("<image id='{0}' src='{1}' alt='{2}'/>", i + 1, escapedSrc, escapedAlt);
            }
            else
            {
                builder.AppendFormat("<image id='{0}' src='{1}'/>", i + 1, escapedSrc);
            }
        }
    }

    for (int i = 0; i < m_TextFields.Length; i++)
    {
        if (!String.IsNullOrWhiteSpace(m_TextFields[i].Text))
        {
            string escapedValue = Util.HttpEncode(m_TextFields[i].Text);
            if (!String.IsNullOrWhiteSpace(m_TextFields[i].Lang) && !m_TextFields[i].Lang.Equals(globalLang))
            {
                string escapedLang = Util.HttpEncode(m_TextFields[i].Lang);
                builder.AppendFormat("<text id='{0}' lang='{1}'>{2}</text>", i + 1, escapedLang, escapedValue);
            }
            else
            {
                builder.AppendFormat("<text id='{0}'>{1}</text>", i + 1, escapedValue);
            }
        }
    }

    return builder.ToString();
}

To ease on routine work, updated version of Metro samples includes reusable library named “NotificationsExtensions” which greatly simplifies this work. My sample uses this library and all the “ContentFactory” classes in code below are defined there:

//Update badge
BadgeNumericNotificationContent badgeContent = new BadgeNumericNotificationContent();
if (badgeCount > 0)
    badgeContent.Number = badgeCount;
BadgeUpdateManager.CreateBadgeUpdaterForApplication().Update(badgeContent.CreateNotification());

//Update application's main tile
ITileWideSmallImageAndText03 tileContent = TileContentFactory.CreateTileWideSmallImageAndText03();
tileContent.TextBodyWrap.Text = message;
tileContent.Image.Src = "ms-appx:///Images/" + image;
tileContent.RequireSquareContent = false;
TileUpdateManager.CreateTileUpdaterForApplication().Update(tileContent.CreateNotification());

//Fire toast notification
IToastImageAndText02 templateContent = ToastContentFactory.CreateToastImageAndText02();
templateContent.TextHeading.Text = "Love is in the air!";
templateContent.TextBodyWrap.Text = message;
templateContent.Image.Src = "Images/Love.png";
templateContent.Image.Alt = "Placeholder image";
IToastNotificationContent toastContent = templateContent;

ToastNotification toast = toastContent.CreateNotification();
ToastNotificationManager.CreateToastNotifier().Show(toast);

Once XXX_Content populated with data this code snippet uses relevant UpdateManager to update/show relevant item.

Secondary Tiles

Updating secondary tiles:

Uri logo = new Uri("ms-appx:///images/Love.png");
Uri wideLogo = new Uri("ms-appx:///images/WideSecondary.png");

SecondaryTile secondaryTile = new SecondaryTile("LoveCatcher.SecondaryTile",
                                _isABoy.Value ? "A Boy" : "A Girl",
                                _isABoy.Value ? "Lonely Boy" : "Lonely Girl",
                                "pinnedID=" + (_isABoy.Value ? "BOY" : "GIRL"),
                                TileOptions.ShowNameOnWideLogo | TileOptions.ShowNameOnLogo,
                                logo,
                                wideLogo);
bool isPinned = await secondaryTile.RequestCreateForSelectionAsync(GetElementRect(this));
txtStatus.Text = isPinned ? "Secondary tile successfully pinned." : "Secondary tile not pinned.";

User receives request to pin secondary tile and must approve/dismiss this request. Optionally he can change tile title:

image

If both tiles provided (regular and wide), the user can switch between them:

imageimage

Pinned tile arguments can be used to provide alternative loading path – more about it in next post.

Enabling lock screen access

Content published at application’s tile (tile text and badge) can be presented also when PC is locked. To enable application work under lock screen and present badge/tile, application can require user agreement by invoking the following code:

BackgroundAccessStatus status = await BackgroundExecutionManager.RequestAccessAsync();
switch (status)
{
    case BackgroundAccessStatus.AllowedWithRealTimeConnectivity:
        //Allowed to work under lock screen (and in background) with real-time connectivity
        //...
        break;
    case BackgroundAccessStatus.AllowedWithoutRealTimeConnectivity:
        //Allowed to work under lock screen (and in background), but without real-time connectivity
        //...
        break;
    case BackgroundAccessStatus.Denied:
        //User declined to work under lock screen 
        //...
        break;
    case BackgroundAccessStatus.Unspecified:
        //The access status not known yet. Good indication to request it
        //...
        break;
}

If access status is not defined yet, user will be presented with system message:

image

Anytime application can request background access:

switch (BackgroundExecutionManager.GetAccessStatus())
{
    case BackgroundAccessStatus.AllowedWithRealTimeConnectivity:
        //...
        break;
    case BackgroundAccessStatus.AllowedWithoutRealTimeConnectivity:
        //...
        break;
    case BackgroundAccessStatus.Denied:
        //...
        break;
    case BackgroundAccessStatus.Unspecified:
        //...
        break;
}

Alternatively user can add/remove supporting application using control panel:

image

Badge and tile notification shown on lock screen:

image

Note: Lock screen tile notification includes only texts. If original tile notification had some graphics it will not be presented on lock screen.

 

Working demo:

Live tiles, toast notification and badges. Lock screen notifications

 

 

That’s it for now. Stay tuned to last part.

Alex

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*

one comment

  1. FrenchJanuary 30, 2013 ב 7:57

    You have made some really good points there.
    I checked on the internet for additional information about the issue
    and found most individuals will go along with your views
    on this web site.

    Reply