Creating Live Tiles for Your Windows Phone Applications

Introduction

One of the things admired about Windows Phone, the new mobile operating system from Microsoft, is the concept of tiles. A tile is a link to an application, which is displayed on the home page.

Types of Tiles

There are two types of tiles a Windows Phone application supports.

  • Application Tile - An application tile is created when the user taps the application name in the application list and selects "pin to start". An application tile cannot be deleted.
  • Secondary tile - A secondary tile can be deleted by unpinning the tile from Start.

To see live tiles in action, let us create an application. To enable notifications, we will need to set up a client application, which will send notifications to the Windows Phone application.

Let us start off with creating a very simple windows phone application that will create an HTTP notification channel on which we will register for events of interest. In our case, we are interested in the Channel URI updated event.

To start off, create a new Silverlight for Windows Phone application called WPApplicationTileDemo.

In MainPage.xaml.cs, add an HTTPNotificationChannel as a member of the MainPage class. Also, add a button, and on its click event, add code create to instantiate the HTTPNotificationChannel. Once you have the notification channel, register for events we mentioned above. After registering for events, open the channel and bind the channel to tile events.

Here is how our button's click event handler code looks.

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            pushChannel = HttpNotificationChannel.Find(channelName);

            // If the channel was not found, then create a new connection to the push service.
            if (pushChannel == null)
            {
                pushChannel = new HttpNotificationChannel(channelName);

                // Register for all the events before attempting to open the channel.
                pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);

                pushChannel.Open();

                // Bind this new channel for Tile events.
                pushChannel.BindToShellTile();


            }
            else
            {
                // The channel was already open, so just register for all the events.
                pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);

                // Display the URI for testing purposes. Normally, the URI would be passed back to your web service at this point.
                System.Diagnostics.Debug.WriteLine(pushChannel.ChannelUri.ToString());
                MessageBox.Show(String.Format("Channel Uri is {0}",
                    pushChannel.ChannelUri.ToString()));

            }

        }
 

Here is how the event handler for the Channel URI updated event looks. Here, we seek to print the Channel URI so that we can use this in our client application to send the update notification back to the application.

        void PushChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
        {

            Dispatcher.BeginInvoke(() =>
            {
                System.Diagnostics.Debug.WriteLine(e.ChannelUri.ToString());
            });
        }

Now that we have our Windows Phone application done, we can work on our Client application.

Add a new Windows Form project to the solution. Let us call it WinformTileClient.

Add a couple of textboxes and a button to the form. We will paste the Channel URI on one text box and have an HTTP update response printed out in the second textbox. Here I show the code for the button we create in our WinformTileClient application.

        private void buttonUpdateTile_Click(object sender, EventArgs e)
{
            try
            {
                string subscriptionUri = textBox1.Text;

                HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest.Create(subscriptionUri);

                // Create an HTTPWebRequest POST Message.
                sendNotificationRequest.Method = "POST";

                // Create an XML Tile message.
                string tileMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                "<wp:Notification xmlns:wp=\"WPNotification\">" +
                    "<wp:Tile>" +
                      "<wp:Count>" + "1" + "</wp:Count>" +
                      "<wp:Title>" + "Test Message" + "</wp:Title>" +
                "</wp:Tile> " +
                "</wp:Notification>";

                // Set the notification payload to send.
                byte[] notificationMessage = Encoding.Default.GetBytes(tileMessage);

                // Set the web request content length.
                sendNotificationRequest.ContentLength = notificationMessage.Length;
                sendNotificationRequest.ContentType = "text/xml";
                sendNotificationRequest.Headers.Add("X-WindowsPhone-Target", "token");
                sendNotificationRequest.Headers.Add("X-NotificationClass", "1");


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

                // Send the notification and get the response.
                HttpWebResponse response = (HttpWebResponse)sendNotificationRequest.GetResponse();
                string notificationStatus = response.Headers["X-NotificationStatus"];
                string notificationChannelStatus = response.Headers["X-SubscriptionStatus"];
                string deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];

                // Display the response from the Microsoft Push Notification Service.
                textBox2.Text = notificationStatus + " | " + deviceConnectionStatus + " | " + notificationChannelStatus;
            }
            catch (Exception ex)
            {
                textBox2.Text = "We got an Exception : " + ex.ToString();
            }

        }

We see that in our action button, we create a WebRequest of the type "POST". We then send a XML message with the following content

<?xml version="1.0" encoding="utf-8"?>
	<wp:Notification xmlns:wp="WPNotification">
		<wp:Tile>
			<wp:Count>"somenumber" </wp:Count>
          <wp:Title>"Test Message"</wp:Title>
      </wp:Tile>
</wp:Notification>

This is what we intend to send.

We will display some number on the tile. We will also display some text "Test message" in the application tile.

We send the notification via sendNotificationRequest.GetResponse() API. We then process the response to update the textbox for response.

Now that our client is also coded, let us fire up the Windows Phone application and click on the button to get started.

Once we click on the button on the Windows Phone application, we notice that the Channel URI is printed in the Debug window inside Visual Studio.

'taskhost.exe' (Managed): Loaded 'mscorlib.dll'
'taskhost.exe' (Managed): Loaded 'System.Windows.RuntimeHost.dll'
'taskhost.exe' (Managed): Loaded 'System.dll'
'taskhost.exe' (Managed): Loaded 'System.Windows.dll'
'taskhost.exe' (Managed): Loaded 'System.Core.dll'
'taskhost.exe' (Managed): Loaded 'System.Xml.dll'
'taskhost.exe' (Managed): Loaded '\Applications\Install\56762ED3-65B8-45CC-9BF1-86DA84522B82\Install\WPApplicationTileDemo.dll', Symbols loaded.
'taskhost.exe' (Managed): Loaded 'Microsoft.Phone.dll'
'taskhost.exe' (Managed): Loaded 'Microsoft.Phone.Interop.dll'
http://sn1.notify.live.net/throttledthirdparty/01.00/AAHPFUssIu_VRK5mKzLx3ILfAgAAAAADAQAAAAQUZm52OjIzOEQ2NDJDRkI5MEVFMEQ
 

Copy paste the URI to clipboard.

Next navigate to the application list and right click on WPApplicationTileDemo and select "Pin to start".

Right click on WPApplicationTileDemo
Figure 1: Right click on WPApplicationTileDemo

You will notice that the application tile is created.

The application tile is created
Figure 2: The application tile is created

Now, start the Windows Forms application, and paste the contents of the URI to the textbox for the URI and click "Send Notification"

The Windows Forms application
Figure 3: The Windows Forms application

As soon as we receive a response in our Windows Form application, switch over to the Windows Phone emulator and you will notice that we get an update in the application tile.

The Windows Phone emulator
Figure 4: The Windows Phone emulator

This is how Windows Live tiles can be created.

If you are having trouble following along, you can download the attached source code which has this already.

Summary

In this article, we learned how to create live tiles for your Windows Phone application.

I hope you have found this information useful.



About the Author

Vipul Vipul Patel

Vipul Patel is a Software Engineer currently working at Microsoft Corporation, working in the Office Communications Group and has worked in the .NET team earlier in the Base Class libraries and the Debugging and Profiling team. He can be reached at vipul_d_patel@hotmail.com

Downloads

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: May 11, 2015 @ 1:00 p.m. ET / 10:00 a.m. PT One of the languages that have always been supported with the Intel® RealSense™ SDK (Software Developer Kit) is JavaScript, specifically so that web-enabled apps could be created. Come hear from Intel Expert Bob Duffy as he reviews his own little "space shooting" game where the orientation of your face controls the aiming reticle to help teach developers how to write apps and games in JavaScript that can use facial and gesture …

  • There has been growing buzz about DevOps. DevOps is a methodology that unites the often separate functions of software development (Dev) and production and operations (Ops) into a single, integrated, and continuous process. DevOps is about breaking down the barriers between Dev and Ops. It leverages people, processes, and technology to stimulate collaboration and innovation across the entire software development and release process. Dev and Ops should always be part of an integrated process, but that's not …

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date