Archive for the ‘Windows Azure’ Category.

Adding Push Notification Support to Your Windows Phone Application

A couple days ago I wrote a post on outsourcing user authentication in a Windows Phone application, demonstrating how easy it is to leverage the Windows Azure Access Control service in your Windows Phone application. The solution is built using a set of NuGet packages that our team has built for Windows Phone + Windows Azure – they provide a similar development experience by allowing you to better manage dependencies and compose great application experiences on the Windows Phone.

Today I want to show a similar way to build support for sending push notifications to Windows Phone applications.

Push notifications provide you a way to deliver information to your applications that are installed on someone’s Windows Phone. It can help provide a key way to differentiate your application from other applications – especially when you tap into tile notifications and take advantage of background tiles, deep linking, and the like. There are a lot of great blog posts on this topic:

One problem I’ve observed with push notifications is most people aren’t sure what to do with the channel URI’s received from the Microsoft Push Notification Service (MPNS). Developers also don’t know where or how to send messages to the device—should it be a service, and if so, where does it run? This is where Windows Azure can provide a lot of help.

Through the Windows Azure Toolkit for Windows Phone, we’ve been providing push notification services for quite a long time. It’s a great solution, and one that has helped a lot of folks. However, it was also relatively difficult to take our samples and then update them such that they worked in your applications. This is where the NuGet packages come into play. We’ve completely refactored the underlying libraries and now deliver all the capabilities as individual NuGets – you can easily create a new Windows Phone application—or update an existing one—using these NuGets.

A few comments on how these NuGets collaborate with the Windows Phone and the MPNS:

  1. The Windows Phone Application registers in the MPNS: The Windows Phone application opens a notification channel to the MPNS and indicates that it wishes to receive push notification messages. The MPNS creates a subscription endpoint associated with that particular channel and forwards it to the Windows Phone device (and the specific application) using the channel it’s just opened. The MPNS sends the endpoint to the application so that the application can send it to the service from which it plans to receive notifications.
  2. The Windows Phone Client registers with the Web Role: The Windows Phone application invokes a service in the Web Role to register itself with the subscription endpoint received from the MPNS. This endpoint is the URI to which the cloud application will perform the HTTP POSTs to send push notification messages to the device.
  3. The Cloud Service sends a notification request to the MPNS: The cloud services sends a notification request by doing a HTTP POST in a specific XML format defined by the MPNS protocol to the subscription endpoint associated with the device it wants to notify.
  4. The MPNS sends the notification to the Windows Phone device: The MPNS transforms the notification request it received to a proper Push Notification to send to the Windows Phone device associated with the endpoint where it received the notification request. The notification request can ask for a toast, a tile, or a raw notification. Once the device receives the push notification via the Push Client it will route the notification to the Shell, which will take an action according to the status of the application. If the application is not running, the shell will either update the application tile, or show a toast. If the application is running, it will send the notification to the already running application.

This architectural picture should help explain the interactions:

Architecture

As with the Windows Phone and ACS example, I want to walk you through the whole process. There’s certainly more that you can do, but I think you’ll agree that the following is quite compelling.

  1. Create a new Windows Phone OS 7.1 application.
    NewWindowsPhoneApplication7.1
  2. From the Package Manager Console type the following to install the ACS base login page NuGet package for Windows Phone: Install-Package Phone.Notifications.BasePage.
    Phone.Notifications.BasePage
  3. Update the WMAppManifest.xml file so that the default page is the Push.xaml. This way the user will come to the login page before the MainPage.xaml.
    WMAppManifest
  4. Let’s create a page that we can use to demonstration deep linking with MPNS. Create a new Windows Phone Portrait Page called DeepLinkPage.xaml in the Pages folder.
  5. In the ContentPanel grid, add a TextBlock control. We’ll push a message to this control when sending a notification.
        <TextBlock x:Name="QueryString" Text="Query string" Margin="9,10,0,0"
            Style="{StaticResource PhoneTextTitle2Style}"/>
    
  6. We need to write the handler that will write the code to the TextBlock.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (this.NavigationContext.QueryString.ContainsKey("message"))
            {
                this.QueryString.Text = this.NavigationContext.QueryString["message"];
            }
            else
            {
                this.QueryString.Text = "no message was received.";
            }
        }
  7. That’s all there is to do in the Windows Phone client. Now we have to write the services that will store the Channel URI generated by MPNS and allow us to send notifications to the device. Add a new Windows Azure Project to the solution. Select the Internet Application template using the HTML 5 semantic markup.

    WindowsAzureProject

  8. From the Package Manager Console, change the default project to Web (or whatever you called your MVC 3 web application), and then type the following to install the MPNS push notifications services and libraries into the web applications: Install-Package WindowsAzure.Notifications. The services installed will let clients register (and unregister) for receiving push notification messages.

    WindowsAzure.Notifications

  9. At this point we don’t have any means for sending a notification. To make this easier, we’ve built a sample management UI for Windows Phone that allows you to manually send push notifications to registered devices. This registers a sample MVC Area called “Notifications” containing the UI and the MPNS Recipe for sending all the supported types of push notifications.

    WindowsPhone.Notifications.ManagementUI.Sample

  10. At this point you’re ready to roll! Hit Control-F5 to build and run. When your website starts browse to http://127.0.0.1:81/notifications and notice that you don’t have any clients currently registered.

    image

  11. In the Windows Phone emulator, click to Enable push notifications. Wait until you receive confirmation that the channel has successfully registered.

    RegisterChannel

  12. Reload the notifications page and you’ll see that you now have a registered channel.

    RegisteredChannel

  13. Click the Send Notification. Select the Raw notification type, type a message, and click send.

    SendRawMessage

  14. In your application on the Windows Phone emulator you should receive the message. This is great – we’ve just received a push notification message in our application.

    RawMessageReceived

  15. On the device emulator, click the Windows button, pan to the right, and pin the PushNotifications application to start.
  16. Now, from the website, click Send Notification. This time select a Tile notification type. Change the Title, set the Count, and choose a Background Image. Click Send.

    SendTileMessage

  17. Notice how the title, tile background, and count have now updated on the device!

    ReceivedTileMessage

  18. Lastly, from the website, click Send Notification. This time select a Toast notification type. Set a Title, Sub Title, and set the Target Page to: /Pages/DeepLinkPage.xaml?message=Hello. Click Send.

    SendToastMessage

  19. You’ll receive a toast message (i.e “Title Sub Title”) on the device. Click it. This will open up the DeepLink.xaml page and pass along the message “Hello” that was sent in the toast.

    ReceiveToastMessage

And that’s it! You can now quickly enrich your Windows Phone applications by leveraging push notifications.

While the Sample UI works great for development, you’ll most likely want to go a few steps further and write your own services or processes to generate notifications. Worker roles with queues work great in this space – I’ll definitely write about this in the future.

Long story short, the following three NuGet packages make it really easy to take advantage of Push Notifications on the Windows Phone using Windows Azure:

Give it a try and tell me if you agree.

I hope this helps!

Outsourcing User Authentication in a Windows Phone Application

Yesterday I shared all the NuGet packages we’re building to make it easy to build Windows Phone and Windows Azure applications. Today I wanted to share how easy it is to build a Windows Phone application that leverages the Windows Azure Access Control service.

The Phone.Identity.AccessControl.BasePage NuGet package includes a control for Window Phone that allows your phone applications to outsource user authentication to the Windows Azure Access Control service (ACS). This service enables your users to login by reusing their existing accounts from identity providers such as Windows Live ID, Google, Yahoo, Facebook, and even Active Directory. If you want to know more about ACS you can take a look at the dedicated hands-on labs in the Windows Azure Platform Training Course.

Using this NuGet package and the included control for ACS in your Windows Phone applications takes care of all the runtime interactions with ACS. Additionally, this package provides a base login page that uses the control and is easy to setup in your phone application. All that is left for you to do is to configure your ACS namespace via the management portal (i.e. specifying your preferences such as the identity providers you want to enable in your application) and integrate the login page into your existing Windows Phone application.

For more information on setting up ACS take a look at the resources at http://acs.codeplex.com/

To help simplify the process below, I’m making the assumption you already have ACS setup and configured. I’ll be using the following values in the below sample (no guarantee that they’ll be available when you read this post but I’ll do my best):

  • namespace: watwindowsphone
  • realm: uri:watwindowsphone

Without further ado, here are the steps to build a Windows Phone application that outsources authentication to ACS:

  1. Create a new Windows Phone OS 7.1 application.
    WindowsPhoneOS71
  2. From the Package Manager Console type the following to install the ACS base login page NuGet package for Windows Phone: Install-Package Phone.Identity.AccessControl.BasePage
    InstallPackage
  3. Update the AccessControlResources.xaml resources file to use your ACS namespace and the realm you have configured.
        <system:String x:Key="acsNamespace">watwindowsphone</system:String>
        <system:String x:Key="realm">uri:watwindowsphone</system:String>
    
  4. Update the WMAppManifest.xml file so that the default page is the LoginPage.xaml. This way the user will come to the login page before the MainPage.xaml.WMAManifiest
  5. Update the LoginPage.xaml.cs so that the user is navigated to the MainPage.xaml upon successfully logging into the application. Make sure to update Line 23 and Line 33.
     this.NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
  6. Let’s display some information from the Simple Web Token. Add a TextBlock control to the MainPage.xaml page. 
        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <TextBlock Name="DisplayLoginInfo" />
        </Grid>
    
  7. Add a Loaded event for the MainPage.xaml. In this event you’ll want to load the simpleWebTokenStore out of the application resources. You can then use it to grab resources like the name identifier or various other claim types (like Name). Finish by updating the DisplayLoginInfotextblock.
        using Microsoft.WindowsAzure.Samples.Phone.Identity.AccessControl;
    
        ...
    
        var simpleWebTokenStore = Application.Current.Resources["swtStore"]
            as SimpleWebTokenStore;
    
        var userNameIdentifier = simpleWebTokenStore.SimpleWebToken.NameIdentifier;
        var name = simpleWebTokenStore.SimpleWebToken.Claims[ClaimTypes.Name];
    
        this.DisplayLoginInfo.Text =
            "Identifier: " + userNameIdentifier + Environment.NewLine +
            "Name: " + name;
  8. Run the application. I’d recommend using Facebook, Google, or Yahoo! for the identity providers, as Live ID does not provide the name claim type in the SWT token.LoginExperience

And that’s it! You can now take advantage of the Identifier claim (and others) in your phone application for many things – tracking users, displaying additional user information, and so forth. Additionally, you can use these claims to authenticate against additional services running in Windows Azure – I’ll cover this token in a future post.

The Phone.Identity.AccessControl.BasePage NuGet package makes it really easy for you to take advantage of the Windows Azure Access Control service within your applications. ACS provides a great way for you to leverage your users existing identity providers when using your application.

I hope this helps!

Programmatically Installing and Using Your Management Certificate with the New .publishsettings File

Earlier this week we released the Windows Azure SDK 1.6, which includes a lot of great updates to the emulators, tools for Visual Studio, and libraries. One of my favorite additions is a new way to get a management certificate installed into Windows Azure and onto your machine. You can now browse to https://windows.azure.com/download/publishprofile.aspx and login with your Live ID; this process will do two things:

  1. Generate a management certificate that is installed into Windows Azures on your behalf.
  2. Prompts you to download a .publishsettings file which includes an encoded version of your certificate and all of your subscription IDs.

The new tools for Visual Studio let you easily important this file and immediately start working with your subscriptions from within Visual Studio. It’s a much simpler experience than in the past. In fact, on this weeks episode of the Cloud Cover Show (not yet published) Steve and I cover how to use this file from within your own code. While Steve beat me to it and published a great blog post showing some of the things you can do, I thought I’d take this a slightly different way and show you a couple different things:

  • How to install the certificate into your personal certificate store (which is exactly what Visual Studio is doing).
  • How to use the certificate from your person certificate store to make calls to the Service Management API.

The code is very similar. Take a look:

    var publishSettingsFile =
        @"C:\\temp\\CORP DPE Account-11-16-2011-credentials.publishsettings";
    
    XDocument xdoc = XDocument.Load(publishSettingsFile);
    
    var managementCertbase64string =
        xdoc.Descendants("PublishProfile").Single().Attribute("ManagementCertificate").Value;
    
    var importedCert = new X509Certificate2(
        Convert.FromBase64String(managementCertbase64string));

Now that we’ve imported the certificate, we can extract some information. I’ll grab the certificate thumbprint, which uniquely identifies the certificate—we’ll use it later in the post.

    string thumbprint = importedCert.Thumbprint;

Additionally, I can grab my subscription ID from the .publishsettings file – this we will also use later.

    string subscriptionId = xdoc.Descendants("Subscription").First().Attribute("Id").Value;

Now, we can take our X509Certificate2 and install it directly into our certificate store.

    X509Store store = new X509Store(StoreName.My);
    store.Open(OpenFlags.ReadWrite);
    store.Add(importedCert);
    store.Close();

After running this code, you can see that the certificate has been installed into my personal certificate store.

CertMgr

If you select the certificate you’ll see that it’s the same certificate with the same thumbprint.

certificate

Since the certificate is now loaded into the certificate store I can delete the .publishsettings file – I no longer need it. (It’s also a credential that I don’t want to let anyone else get their hands on.)

Now I have the following resources available to me:

  • My X509 certificate loaded in my personal certificate store.
  • The thumbprint for the certificate (which we’ll use to identify the right certificate).
  • My Windows Azure subscription ID.

With this information we can do the exact same thing Steve shows in his post except without the .publishsettings file.

    X509Store store = new X509Store(StoreName.My);
    store.Open(OpenFlags.ReadWrite);
    X509Certificate2 managementCert =
        store.Certificates.Find(X509FindType.FindByThumbprint, thumbrprint, false)[0];
    
    var req = (HttpWebRequest)WebRequest.Create(
        string.Format("https://management.core.windows.net/{0}/services/hostedservices",
        subscriptionId));
    
    req.Headers["x-ms-version"] = "2011-10-01";
    req.ClientCertificates.Add(managementCert);
    
    XNamespace xmlns = "http://schemas.microsoft.com/windowsazure";
    
    Console.WriteLine(string.Join("\n",
        XDocument.Load(req.GetResponse().GetResponseStream())
        .Descendants(xmlns + "ServiceName").Select(n => n.Value).ToArray()));

Essentially, we can grab the certificate out of the certificate store using the thumbprint and then make the exact same call to the service management API.

The console output below shows that I’m able to get a list of all my hosted services:

Console

It’s as simple as that!

I’m not sure that this post applies to everyone—in fact, most of you may find it boring or cryptic—but for those of you that are building content or tools you’ll probably find this a really simple way to automate a lot of the pieces. I know that my team plans to use these techniques in a lot of places to simply the experience of getting started with Windows Azure.

I hope this helps!