weather service push notificationsaz12722.vo.msecnd.net/.../pushnotifications.docx · web viewthe...

77
Hands-On Lab Using Push Notifications Lab version: 1.0.0 Last updated: 7/7/2022 Page | 1 ©2011 Microsoft Corporation. All rights reserved.

Upload: others

Post on 04-Jun-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

Hands-On LabUsing Push NotificationsLab version: 1.0.0

Last updated: 5/20/2023

Page | 1

©2011 Microsoft Corporation. All rights reserved.

Page 2: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

CONTENTS

Overview.....................................................................................................................................................3

Exercise 1: Introduction to the Windows Phone RAW Notifications Messages...........................................6

Task 1 – Creating the Weather Service Solution..................................................................................6

Task 2 – Creating the Windows® Phone 7 Client Application.............................................................21

Task 3 – Creating the Notification Channel........................................................................................22

Task 4 – Receiving and Processing Events from Push Notification Service........................................27

Exercise 2: Introduction to the Toast and Tile Notifications for Alerts......................................................30

Task 1 – Implementing Server Side of Sending Tiles & Toasts...........................................................31

Task 2 – Processing Tile & Toast Notifications on the Phone.............................................................33

Task 3 – Processing Scheduled Tile Notifications on the Phone.........................................................40

Exercise 3: Using sub-tiles and deep toast notifications............................................................................43

Task 1 – Making MSPN Registration Screen Independent.................................................................43

Task 2 – Updating the Client’s Main Page..........................................................................................54

Task 3 – Adding a Specific Location Page and Updating the Server...................................................61

Summary...................................................................................................................................................67

Page | 2

©2011 Microsoft Corporation. All rights reserved.

Page 3: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

Overview

The Microsoft Push Notification Service in Windows® Phone offers third party developers a resilient, dedicated, and persistent channel to send information and updates to a Windows® Phone application from their web sites (web services).

In the past, a mobile application would need to frequently poll its corresponding web service to know if there are any pending notifications. While effective, polling results in the device radio being frequently turned on, impacting battery life in a negative way. By using push notifications instead of polling, a web service can notify an application of important updates on an as-needed basis.

Figure 1Push Notifications

When a web service has information to send to an application, it sends a push notification to the Push Notification Service, which in turn routes the push notification to the application. Depending on the format of the push notification and the payload attached to it, the information is delivered as raw data to the application, the application's tile is visually updated, or a toast notification is displayed. The application can then contact the web service using its own protocol, if needed.

The Push Notification Service sends a response code to your web service after a push notification is sent. However, the Push Notification Service does not provide an end-to-end confirmation that your push notification was delivered from your web service to your application. For more information, see Push Notification Service Response Codes for Windows® Phone.

This lab covers push notifications and also introduces the usage of http services in Silverlight. During this lab you will create server side logic needed to send messages through the Push Notification Service. You will create a simple Windows® Phone 7 Codenamed Mango application which serves as a client to receive said notifications. The client application will receive weather updates. The server side business application (a simple WPF application) will send weather alerts to registered client applications through Push Notification Services. Once a client Windows® Phone 7 application receives such alert it will display the information received.

Page | 3

©2011 Microsoft Corporation. All rights reserved.

Page 4: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

Note: The server side Weather application uses the WindowsPhone.Recipes.Push.Messasges.dll which encapsulates all the logic and functionality for sending and receiving responses from Microsoft Push Notification Services. For more information, see http://windowsteamblog.com/windows_phone/b/wpdev/archive/2011/01/14/windows-push-notification-server-side-helper-library.aspx.

Objectives

During the course of this lab you will:

Familiarize yourself with the communication capabilities of Windows® Phone 7 applications

Familiarize yourself with the push notification concepts and the behaviors they enable on the phone

Understand how push notifications work on the phone and in the cloud

Use the phone push notification services to create a subscription for Tokens (tiles), Toasts, and raw push notifications

Use a web client to register for Push Notifications

Use the network status to display the current status of the phone network

Create a SL application that registers with the push notification services (both token and toast)

◦ Handle push events (token, toast, and raw) during run time

◦ Show token and toast information on the shell

Manage application sub-tiles which update independently and link to specific locations in the application (only available on Windows® Phone 7.1)

Prerequisites

The following is required to complete this hands-on lab:

Microsoft Visual Studio 2010 Express for Windows® Phone or Microsoft Visual Studio 2010

Windows® Phone Developer Tools

Note: All of these Tools can be downloaded together from http://go.microsoft.com/?linkid=9772716

Page | 4

©2011 Microsoft Corporation. All rights reserved.

Page 5: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

Exercises

This hands-on lab comprises of the following exercises:

1. Introduction to the Windows® Phone RAW notifications for Updates

2. Introduction to the Toast and Tile Notifications for Alerts

3. Introduction to sub-tiles and deep toast messages (only available on Windows® Phone 7.1)

Estimated time to complete this lab: 110 minutes.

Page | 5

©2011 Microsoft Corporation. All rights reserved.

Page 6: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

Exercise 1: Introduction to the Windows Phone RAW Notifications Messages

In this section we will open the starter solution and:

Implement server side notification and registration services

Create a Windows® Phone 7 client application

Create a notification channel and subscribe to channel events

Receive and process RAW Push Notification messages from the Push Notification Services

You’ll use Microsoft Visual Studio 2010 Express for Windows® Phone as your development environment, and will deploy to the Windows® Phone Emulator for debugging. The solution you’ll be working with is based upon the Silverlight for Windows® Phone Application template.

Note: The steps in this hands-on lab illustrate procedures using Microsoft Visual Studio 2010 Express for Windows® Phone, but they are equally applicable to Microsoft Visual Studio 2010 with the Windows® Phone Developer Tools. Instructions that refer generically to Visual Studio apply to both products.

Task 1 – Creating the Weather Service Solution

In this task, you use a provided starter solution for Microsoft Visual Studio 2010 Express for Windows® Phone or Microsoft Visual Studio 2010. This solution includes a simple WPF client application which we will use to send messages to the Windows® Phone 7 application via the Microsoft Push Notification Service. The WPF application will also host a WCF registration service. This service will be created during this task. The provided WPF application will self-host the REST WCF service. For this purpose the project already has all required configurations.

1. Navigate and open to the starter project located at the Source\Ex1-RawNotifications\Begin

Important note: In order to run self-hosted WCF services within Visual Phone 2010 Express for Windows® Phone or Microsoft Visual Studio 2010 it should be opened in Administrative Mode. For reference about creating and hosting self-hosted WCF services see MSDN article (http://msdn.microsoft.com/en-us/library/ms731758.aspx).

2. Examine the opened project, which is a standard WPF application:

Page | 6

©2011 Microsoft Corporation. All rights reserved.

Page 7: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

Note: This application targets .NET 4 Framework and not .NET 4 Framework Client Profile in order to support self-hosted RESTful WCF services.

a. The WPF application consists of the MainWindow screen, PushNotificationsLogViewer user control and StatusToBrush value converter.

b. The “Service” project folder contains an interface definition for the WCF RESTfull service.

c. Other than the standard WPF application references, this application references the System.ServiceModel and System.ServiceModel.Web assemblies to support RESTful WCF services.

d. In addition, this application references the WindowsPhone.Recipes.Push.Messasges assembly, which wraps push notification operations with convenience classes. This assembly is located in the folder Assets\Lib.

3. We will use the following classes from the WindowsPhone.Recipes.Push.Messasges assembly: RawPushNotificationMessage, ToastPushNotificationMessage and TilePushNotificationMessage to send raw, toast and tile messages correspondingly. All these classes inherit from the abstract class PushNotificationMessage, which implements the function SendAsync that asynchronously sends a push notification to the specified URI. The derived classes provide message specific properties.

a. This is the specification of SendAsync function:

C#

/// <summary>/// Asynchronously send this messasge to the destination address./// </summary>/// <remarks>/// This method uses the .NET Thread Pool. Use this method to /// send one or few messages asynchronously. If you have many /// messages to send, please consider using the synchronous /// method with a custom (external) queue-thread solution./// /// Note that properties of this instance may be changed by /// different threads while sending, but once the payload is /// created, it will not be changed until the next send./// </remarks>/// <param name="uri">Destination address uri.</param>/// <param name="messageSent">Message sent callback.</param>/// <param name="messageError">Message send error callback./// </param>/// <exception cref="ArgumentNullException">One of the arguments/// is null.</exception>

Page | 7

©2011 Microsoft Corporation. All rights reserved.

Page 8: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

/// <exception cref="ArgumentOutOfRangeException">Payload size /// is out of range. For maximum allowed message size see/// <see cref="PushNotificationMessage.MaxPayloadSize"/>/// </exception> public void SendAsync(Uri uri, Action<MessageSendResult> messageSent = null, Action<MessageSendResult> messageError = null){...}

b. Callback methods arguments are defined in the same library and have the following specifications:

C#

/// <summary>/// Push notification message send operation result./// </summary>public class MessageSendResult{ /// <summary> /// Gets the response time offset. /// </summary> public DateTimeOffset Timestamp { get; } /// <summary> /// Gets the associated message. /// </summary> public PushNotificationMessage AssociatedMessage { get; } /// <summary> /// Gets the channel URI. /// </summary> public Uri ChannelUri { get; } /// <summary> /// Gets the web request status. /// </summary> public HttpStatusCode StatusCode { get; } /// <summary> /// Gets the push notification status. /// </summary> public NotificationStatus NotificationStatus { get; } /// <summary> /// Gets the device connection status. /// </summary> public DeviceConnectionStatus DeviceConnectionStatus { get; }

Page | 8

©2011 Microsoft Corporation. All rights reserved.

Page 9: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

/// <summary> /// Gets the subscription status. /// </summary> public SubscriptionStatus SubscriptionStatus { get; }}

/// <summary>/// Represents errors that occur during push notification message send operation./// </summary>public class MessageSendException : Exception{ /// <summary> /// Gets the message send result. /// </summary> public MessageSendResult Result { get; }}

c. RawPushNotificationMessage has the following specification:

C#

/// <summary>/// Represents a raw push notification message./// </summary>/// <remarks>/// If you do not wish to update the tile or send a toast /// notification, you can instead send raw information /// to your application. /// If your application is not currently running, /// the raw notification is discarded on the Microsoft Push/// Notification Service and is not delivered to the device./// /// This class members are thread safe./// </remarks>public sealed class RawPushNotificationMessage : PushNotificationMessage{ #region Properties

/// <summary> /// Gets or sets the message raw data bytes. /// </summary> public byte[] RawData { get; set; } #endregion

Page | 9

©2011 Microsoft Corporation. All rights reserved.

Page 10: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

#region Ctor /// <summary> /// Initializes a new instance of this type. /// </summary> /// <param name="sendPriority"> /// The send priority of this message in the MPNS.</param> public RawPushNotificationMessage( MessageSendPriority sendPriority = MessageSendPriority.High) { ... } #endregion}

d. TilePushNotificationMessage has the following specification:

C#

/// <summary>/// Represents a tile push notification message./// </summary>/// <remarks>/// Every phone application has one assigned 'tile' – /// a visual, dynamic representation of the application /// or its content. /// A tile displays in the Start screen /// if the end user has pinned it./// /// This class members are thread safe./// </remarks>public sealed class TilePushNotificationMessage : PushNotificationMessage{ #region Properties /// <summary> /// Gets or sets the phone's local path, /// or a remote path for the background image. /// </summary> /// <remarks> /// If the uri references a remote resource, /// the maximum allowed size of the tile /// image is 80 KB, with a maximum /// download time of 15 seconds. /// </remarks> public Uri BackgroundImageUri { get; set; } /// <summary> /// Gets or sets an integer value from 1 to 99

Page | 10

©2011 Microsoft Corporation. All rights reserved.

Page 11: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

/// to be displayed in the tile, or 0 to clear count. /// </summary> public int Count { get; set; } /// <summary> /// Gets or sets the title text should be displayed in the tile. /// Null keeps the existing title. /// </summary> /// <remarks> /// The Title must fit a single line of text and should not /// be wider than the actual tile. /// Imperatively a good number of letters /// would be 18-20 characters long. /// </remarks> public string Title { get; set; } /// <summary> /// Gets or sets the URI and query string of the secondary /// tile as specified by the Windows Phone client. /// <example>/GameList.xaml</example> /// <example>/GameList.xaml?sort=byName</example> /// </summary> /// <remarks> /// Null or empty string refers to the main tile. /// Only supported when communicating with Windows Phone 7.1 /// applications. /// </remarks> public string SecondaryTile { get; set; }

#endregion #region Ctor /// <summary> /// Initializes a new instance of this type. /// </summary> /// <param name="sendPriority"> /// The send priority of this message in the MPNS.</param> public TilePushNotificationMessage( MessageSendPriority sendPriority = MessageSendPriority.Normal) : base(sendPriority) {...} #endregion}

e. ToastPushNotificationMessage has the following specification:

Page | 11

©2011 Microsoft Corporation. All rights reserved.

Page 12: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

C#

/// <summary>/// Represents a toast push notification message./// </summary>/// <remarks>/// Toast notifications are system-wide notifications/// that do not disrupt the user workflow or require/// intervention to resolve. /// They are displayed at the top of the screen for /// ten seconds before disappearing. /// If the toast notification is tapped, /// the application that sent the toast notification/// will launch. /// A toast notification can be dismissed with a flick./// /// This class’s members are thread safe./// </remarks> public sealed class ToastPushNotificationMessage : PushNotificationMessage{ #region Properties /// <summary> /// Gets or sets a bolded string that should be displayed /// immediately after the application icon. /// </summary> public string Title { get; set; } /// <summary> /// Gets or sets a non-bolded string /// that should be displayed /// immediately after the Title. /// </summary> public string SubTitle { get; set; } /// <summary> /// Gets or sets the URI and query string of the target page /// should be navigated when clicking on the toast /// notification at client side. /// </summary> /// <example>/AppSettings.xaml</example> /// <example>/AppSettings.xaml?tab=push</example> /// <remarks> /// Null or empty string refers the main page. /// Only supported when communicating with Windows Phone 7.1 /// applications. /// </remarks> public string TargetPage { get; set; }

Page | 12

©2011 Microsoft Corporation. All rights reserved.

Page 13: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

#endregion

#region Ctor /// <summary> /// Initializes a new instance of this type. /// </summary> /// <param name="sendPriority"> /// The send priority of this message in the MPNS.</param> public ToastPushNotificationMessage( MessageSendPriority sendPriority = MessageSendPriority.Normal) : base(sendPriority) { } #endregion}

With this we conclude our explanation of the helper library and get back to our exercise.

4. Press F5 to compile and run the application. Familiarize yourself with it and then close the application and get back to the Visual Studio. The application allows you to send Tile, Toast and Raw HTTP notifications.

Figure 2Push Notifications Server Application

5. During the following few steps you will create a WCF service instance and initialize it. In order to communicate with the Push Notification Service the Windows® Phone application should provide a URI of the channel registered with MSPN (Microsoft Push Notifications)

Page | 13

©2011 Microsoft Corporation. All rights reserved.

Page 14: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

services to the WPF application. You will set up such a channel from the phone application to the WPF application and use it for registering the phone’s URI with the WPF application in next tasks of this lab.

6. Open the file named RegistrationService.cs located at Service folder.

7. Implement the IRegistrationService interface. This interface defines a set of methods that allow phone applications to register their MSPN URI.

C#

public class RegistrationService : IRegistrationService{

}

8. Implement this interface opening context menu and selecting Implement interface IRegistrationService to implement the interface the default way.

9. The registration service holds all the registered Windows® Phone client application URIs in an internal list. The service checks that clients requesting registration are not already registered in order to avoid double registration of the same URI. To support this functionality add following class variables:

C#

public static event EventHandler<SubscriptionEventArgs> Subscribed;

private static List<Uri> subscribers = new List<Uri>();private static object obj = new object();

10. Replace the Register function body with the following code:

C#

Uri channelUri = new Uri(uri, UriKind.Absolute);Subscribe(channelUri);

11. Replace the Unregister function body with the following code:

C#

Uri channelUri = new Uri(uri, UriKind.Absolute);Unsubscribe(channelUri);

12. Create a new region containing two additional helper functions, Subscribe and Unsubscribe, according to the following code:

Page | 14

©2011 Microsoft Corporation. All rights reserved.

Page 15: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

C#

#region Subscription/Unsubscribing logicprivate void Subscribe(Uri channelUri){ lock (obj) { if (!subscribers.Exists((u) => u == channelUri)) { subscribers.Add(channelUri); } } OnSubscribed(channelUri, true);}

public static void Unsubscribe(Uri channelUri){ lock (obj) { subscribers.Remove(channelUri); } OnSubscribed(channelUri, false);}#endregion

13. Create a helper OnSubscribed function according to the following code:

C#

#region Helper private functionalityprivate static void OnSubscribed(Uri channelUri, bool isActive){ EventHandler<SubscriptionEventArgs> handler = Subscribed; if (handler != null) { handler(null, new SubscriptionEventArgs(channelUri, isActive)); }}#endregion

14. To hold Subscribed event arguments, create the SubscriptionEventArgs internal class (inside the RegistrationService class) according to the following code:

C#

#region Internal SubscriptionEventArgs class definitionpublic class SubscriptionEventArgs : EventArgs

Page | 15

©2011 Microsoft Corporation. All rights reserved.

Page 16: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

{ public SubscriptionEventArgs(Uri channelUri, bool isActive) { this.ChannelUri = channelUri; this.IsActive = isActive; }

public Uri ChannelUri { get; private set; } public bool IsActive { get; private set; }}#endregion

15. Lastly, create a public function in the class that returns the list of all subscribers – it will be used later by the WPF client application.

C#

#region Helper public functionalitypublic static List<Uri> GetSubscribers(){ return subscribers;}#endregion

16. Open App.xaml.cs file.

17. Locate the code line with “//TODO - remove remark after creating registration service” and uncomment the WCF service host initialization (as shown below):

C#

//TODO - remove remark after creating registration servicehost = new ServiceHost(typeof(RegistrationService));host.Open();

18. Compile and run the application. Once application starts, check that the RESTful WCF service works. To do this, add a break point to the Register and/or Unregister functions in RegistrationService.cs.

Page | 16

©2011 Microsoft Corporation. All rights reserved.

Page 17: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

Figure 3Breakpoint to check RESTful WCF service

19. Launch Internet Explorer and navigate to the following address:

http://localhost:8000/RegirstatorService/Register?uri=http://www.microsoft.com

20. When breakpoint hit occurs, check that received URI address is http://www.microsoft.com.

Figure 4Checking RESTful WCF service

21. Stop debugging, remove the break points and close Internet Explorer.

22. Open PushNotificationsLogMsg.cs file.

23. Define the class constructor that creates the log message from the notification sending result and the type:

C#

#region Ctorpublic PushNotificationsLogMsg( NotificationType notificationType, MessageSendResult messageSendResult){ this.Timestamp = messageSendResult.Timestamp; this.MessageId = messageSendResult.AssociatedMessage.Id.ToString();

Page | 17

©2011 Microsoft Corporation. All rights reserved.

Page 18: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

this.ChannelUri = messageSendResult.ChannelUri.ToString(); this.NotificationType = notificationType; this.StatusCode = messageSendResult.StatusCode; this.NotificationStatus = messageSendResult.NotificationStatus.ToString(); this.DeviceConnectionStatus = messageSendResult.DeviceConnectionStatus.ToString(); this.SubscriptionStatus = messageSendResult.DeviceConnectionStatus.ToString();}#endregion

24. Open MainWindow.xaml.cs located under the WPPushNotification.ServerSideWeatherSimulator project.

25. Locate the Private variables region and replace the “TODO” comment with the following code:

C#

private ObservableCollection<PushNotificationsLogMsg> trace = new ObservableCollection<PushNotificationsLogMsg>();private RawPushNotificationMessage rawPushNotificationMessage = new RawPushNotificationMessage(MessageSendPriority.High);

26. Our Windows® Phone 7 Codenamed Mango client application will soon have the logic to subscribe with the Weather Server Registration Service you just created. The WPF application mimics real-world web site solution by pushing Weather information to the connected clients, thus it should know about client Windows® Phone 7 Codenamed Mango applications and receive events upon their registrations. In addition, our WPF client shows a Push notification Service communication log. Locate the MainWindow class constructor and add the following code after the “TODO” comment:

C#

Log.ItemsSource = trace;RegistrationService.Subscribed += new EventHandler<RegistrationService.SubscriptionEventArgs>(RegistrationService_Subscribed);

27. Locate the Event Handlers regions and add the following function:

C#

Page | 18

©2011 Microsoft Corporation. All rights reserved.

Page 19: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

void RegistrationService_Subscribed(object sender, RegistrationService.SubscriptionEventArgs e){ Dispatcher.BeginInvoke((Action)(() => { UpdateStatus(); }) );}

28. After the previous function, add the following function which serves as a callback function for the push notification calls:

C#

private void OnMessageSent(NotificationType type, MessageSendResult result){ PushNotificationsLogMsg msg = new PushNotificationsLogMsg(type, result); Dispatcher.BeginInvoke((Action)(() => { trace.Add(msg); }));}

29. Locate the Private functionality region and add the following function (this function updates the WPF client application’s UI):

C#

private void UpdateStatus(){ int activeSubscribers = RegistrationService.GetSubscribers().Count; bool isReady = (activeSubscribers > 0); txtActiveConnections.Text = activeSubscribers.ToString(); txtStatus.Text = isReady ? "Ready" : "Waiting for connection...";}

30. Locate the sendHttp function and add the following code. This function will get the list of connected clients, prepare the payload from UI inputs and send it asynchronously using a rawPushNotificationMessage field:

C#

//Get the list of subscribed WP7 clientsList<Uri> subscribers = RegistrationService.GetSubscribers();//Prepare payloadbyte[] payload = prepareRAWPayload( cmbLocation.SelectedValue as string,

Page | 19

©2011 Microsoft Corporation. All rights reserved.

Page 20: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

sld.Value.ToString("F1"), cmbWeather.SelectedValue as string); rawPushNotificationMessage.RawData = payload;subscribers.ForEach(uri => rawPushNotificationMessage.SendAsync(uri, (result) => OnMessageSent(NotificationType.Raw, result), (result) => { }));

31. Locate the Private functionality region and add the prepareRAWPayload function. This function creates an XML document in-memory and returns it as a byte array (ready to be sent to the Windows® Phone Push Notification Services and from there to the Windows® Phone application clients). Later during this exercise you will add the functionality to parse this XML back on the device. Add the following code:

C#

private static byte[] prepareRAWPayload(string location, string temperature, string weatherType){ MemoryStream stream = new MemoryStream();

XmlWriterSettings settings = new XmlWriterSettings() { Indent = true, Encoding = Encoding.UTF8 }; XmlWriter writer = XmlTextWriter.Create(stream, settings);

writer.WriteStartDocument(); writer.WriteStartElement("WeatherUpdate");

writer.WriteStartElement("Location"); writer.WriteValue(location); writer.WriteEndElement();

writer.WriteStartElement("Temperature"); writer.WriteValue(temperature); writer.WriteEndElement();

writer.WriteStartElement("WeatherType"); writer.WriteValue(weatherType); writer.WriteEndElement();

writer.WriteStartElement("LastUpdated"); writer.WriteValue(DateTime.Now.ToString()); writer.WriteEndElement();

Page | 20

©2011 Microsoft Corporation. All rights reserved.

Page 21: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

writer.WriteEndElement(); writer.WriteEndDocument(); writer.Close();

byte[] payload = stream.ToArray(); return payload;}

32. Compile the application and fix compilation errors (if any). This step concludes the task.

Task 2 – Creating the Windows® Phone 7 Client Application

1. Open the project on the solution named WPPushNotification.TestClient.

2. Open MainPage.xaml.cs.

3. Add the following code snippet with private variables and constants to the beginning of the class:

C#

private HttpNotificationChannel httpChannel;const string channelName = "WeatherUpdatesChannel";const string fileName = "PushNotificationsSettings.dat";const int pushConnectTimeout = 30;

4. Compile and run the application.

5. At this stage application looks like the following:

Page | 21

©2011 Microsoft Corporation. All rights reserved.

Page 22: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

Figure 5Running the Weather client

6. Stop the debugging and return to the code. This step concludes the current task.

Task 3 – Creating the Notification Channel

During the next couple of steps you will create the functionality that is required to create a new push notification channel through which Microsoft Corporation Push Notification services can send messages. The HttpNotificationChannel class creates a notification channel between the Push Notification service and the Windows® Phone Push Client and creates a new subscription for raw, tile, and toast notifications. The channel creation flow is as follows: if the channel already exists, then the client application should try to re-open it. Trying to re-create an existing channel will lead to an exception. If the channel is still not opened, subscribe to the channel events and try to open the channel. Once the channel opens it fires the ChannelUriUpdated event. This event signals the Windows® Phone application, that channel was successfully created. Existing channel can be search by the channel’s name. In case of successfully finding a channel by name, you should open it to reactivated and used in the application. The entire process is asynchronous.

1. Open MainPage.xaml.cs from the WPPushNotification.TestClient.

2. Locate the Try/Catch blocks in the ConnectToMSPN function body.Page | 22

©2011 Microsoft Corporation. All rights reserved.

Page 23: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

3. Next, initialize a channel variable, subscribe to the channel events and try to open the channel. Create the try block body according to the following code:

C#

//First, try to pick up existing channelhttpChannel = HttpNotificationChannel.Find(channelName);

if (null != httpChannel){ Trace("Channel Exists - no need to create a new one"); SubscribeToChannelEvents();

Trace("Register the URI with 3rd party web service"); SubscribeToService();

//TODO: Place Notification

Dispatcher.BeginInvoke(() => UpdateStatus("Channel recovered"));}else{ Trace("Trying to create a new channel..."); //Create the channel httpChannel = new HttpNotificationChannel(channelName, "HOLWeatherService"); Trace("New Push Notification channel created successfully");

SubscribeToChannelEvents();

Trace("Trying to open the channel"); httpChannel.Open(); Dispatcher.BeginInvoke(() => UpdateStatus("Channel open requested"));}

4. Create a helper function, which will do the subscription to the channel events:

C#

#region Subscriptionsprivate void SubscribeToChannelEvents(){ //Register to UriUpdated event - occurs when channel successfully opens httpChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(httpChannel_ChannelUriUpdated); //Subscribed to Raw Notification

Page | 23

©2011 Microsoft Corporation. All rights reserved.

Page 24: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

httpChannel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(httpChannel_HttpNotificationReceived);

//general error handling for push channel httpChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(httpChannel_ExceptionOccurred);}#endregion

5. Add a helper function that subscribes the Channel URI to the server side Weather application. The subscription will be done via registering the PN channel’s URI to the registration service of the server side Weather application that you created in previous tasks. This function uses WebClient and hardcoded RESTful WCF service URL (http://localhost) to register the client’s URI (received from the push server). Add the following code snippet to the Subscriptions region inserted previously:

C#

private void SubscribeToService(){ //Hardcode for solution - need to be updated in case the REST WCF service address change string baseUri = "http://localhost:8000/RegirstatorService/Register?uri={0}"; string theUri = String.Format(baseUri, httpChannel.ChannelUri.ToString()); WebClient client = new WebClient(); client.DownloadStringCompleted += (s, e) => { if (null == e.Error) Dispatcher.BeginInvoke(() =>UpdateStatus("Registration succeeded")); else Dispatcher.BeginInvoke(() =>UpdateStatus("Registration failed: " + e.Error.Message)); }; client.DownloadStringAsync(new Uri(theUri));}

6. Localize the Channel event handlers region and create the event handler function inside to handle ChannelUriUpdate event:

C#

Page | 24

©2011 Microsoft Corporation. All rights reserved.

Page 25: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

void httpChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e){ Trace("Channel opened. Got Uri:\n" +httpChannel.ChannelUri.ToString()); Trace("Subscribing to channel events"); SubscribeToService(); Dispatcher.BeginInvoke(() => UpdateStatus("Channel created successfully"));}

7. Add the ExceptionOccured event handler function to the region:

C#

void httpChannel_ExceptionOccurred(object sender, NotificationChannelErrorEventArgs e){ Dispatcher.BeginInvoke(() => UpdateStatus(e.ErrorType + " occurred: " + e.Message));}

8. Press F5 to compile and run the application.

9. Make sure the Windows® Phone 7 client application successfully registers with the Registration Service:

Figure 6Checking client application registration

Page | 25

©2011 Microsoft Corporation. All rights reserved.

Page 26: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

10. Put the breakpoint at httpChannel_HttpNotificationReceived function.

11. Change some parameters on the WPF Push Notification Client, select RAW Data, and click the Send button. When the breakpoint is hit and execution of the code is suspended, examine information received.

Figure 7Breakpoint hit when notification arrives

Figure 8Notification payload received by Windows® Phone 7 client application

12. Press F5 to continue with program execution. Observe the new log entry in WPF Push Notification Client.

Page | 26

©2011 Microsoft Corporation. All rights reserved.

Page 27: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

Figure 9WPF Push Notification Client with updated log

13. Stop the debugging and return to the Visual Studio (do not close Windows® Phone 7 emulator!). This step concludes the task.

Task 4 – Receiving and Processing Events from Push Notification Service

1. During this task you will create a function to parse XML arrived in the payload and update Windows® Phone 7 application’s UI.

2. Add the following function to the Misc logic region of MainPage.xaml.cs:

C#

private void ParseRAWPayload(Stream e, out string weather, out string location, out string temperature){ XDocument document;

using (var reader = new StreamReader(e)) { string payload = reader.ReadToEnd().Replace('\0',' '); document = XDocument.Parse(payload); }

location = (from c in document.Descendants("WeatherUpdate") select c.Element("Location").Value).FirstOrDefault(); Trace("Got location: " + location);

Page | 27

©2011 Microsoft Corporation. All rights reserved.

Page 28: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

temperature = (from c in document.Descendants("WeatherUpdate") select c.Element("Temperature").Value).FirstOrDefault(); Trace("Got temperature: " + temperature);

weather = (from c in document.Descendants("WeatherUpdate") select c.Element("WeatherType").Value).FirstOrDefault();}

3. Recall the last function you created in previous task (httpChannel_HttpNotificationReceived, in MainPage.xaml.cs). This function will call to the parsing functionality created before and will update the UI. Add the following yellow-highlighted code after the “//TODO - add parsing and UI updating logic here” comment:

C#

void httpChannel_HttpNotificationReceived(object sender, HttpNotificationEventArgs e){ Trace("==============================================="); Trace("RAW notification arrived:"); string weather, location, temperature; ParseRAWPayload(e.Notification.Body, out weather, out location, out temperature); Dispatcher.BeginInvoke(() => this.textBlockListTitle.Text = location); Dispatcher.BeginInvoke(() => this.txtTemperature.Text = temperature); Dispatcher.BeginInvoke(() => this.imgWeatherConditions.Source = new BitmapImage(new Uri(@"Images/" + weather + ".png", UriKind.Relative))); Trace(string.Format("Got weather: {0} with {1}F at location {2}", weather, temperature, location)); Trace("===============================================");}

4. Compile and run the application. After both applications start, change some values in WPF Push Notification Client, select RAW Data and click the Send button. Observe the notification arrives to the Windows® Phone 7 client and UI changes. Observe trace information in Visual Studio 2010 Output window.

Page | 28

©2011 Microsoft Corporation. All rights reserved.

Page 29: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

Figure 10Trace information in Output window

5. Send the different notifications and observe the UI changes.

Figure 11Http Notification arrived and parsed. Trace log updated

6. In Visual Studio, Press SHIFT+F5 to stop the debugging.

7. Compile and run the applications twice. Use debugging to check that first time application does the channel opening and saves the channel info and the second time finds the channel by name.

This step concludes the exercise. During this exercise you learned how to communicate with Microsoft Push Notification Services, how to prepare and send the message to client Windows® Phone 7 application and how to receive those messages on the Windows® Phone 7.

Note: The complete solution for this exercise is provided at the following location: Source\Ex1-RawNotifications\End.

Page | 29

©2011 Microsoft Corporation. All rights reserved.

Page 30: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

Page | 30

©2011 Microsoft Corporation. All rights reserved.

Page 31: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

Exercise 2: Introduction to the Toast and Tile Notifications for Alerts

In this section you will learn about two additional notification types – Toast and Tile notifications. This lab covers the backend server that posts data to MSPNS, as well as how to register and handle these events on your Windows® Phone 7 Codenamed Mango Application.

Tiles and toast notifications are two mechanisms that enable a cloud service to deliver relevant, actionable feedback to users outside an application’s own user interface. Additionally, a cloud service can send a raw notification request. Depending on the type of notification sent, the notification will be routed either to the application or the shell.

Tile Notifications

A tile is a visual, dynamic representation of an application or its content within the Quick Launch area of the phone’s Start experience. For example, a weather application may choose to display the user’s local time and climate conditions in a tile. Because a cloud service can alter its tile’s appearance at any time, this mechanism can be used to communicate information to the user on an ongoing basis. Each application that the user can launch on the phone is associated with a single tile, but only the user can control which of these tiles are pinned to the Quick Launch area (Windows® Phone 7.1 changes this by allowing applications to have multiple tiles, each launching the application in a specific way. Each tile can be updated individually).

A cloud service can control a tile's background image, counter (or 'badge'), and title properties. These properties are configured using the Windows® Phone Developer Tools. Animation and sound properties are controlled by how the platform is configured, not by the application. For example, if the platform is configured to animate and beep upon any tile update, that is what will occur for any tile.

A tile's background image can reference either a local resource, which is part of the application deployment, or a cloud resource. By referencing a resource in the cloud, applications are enabled to dynamically update a tile's background image. This enables scenarios which require processing of the background image before it is displayed. In most scenarios, the application package should include all needed background images for the tile, since this is the best solution for performance and battery life.

Toast Notifications

A cloud service can generate a special kind of push notification known as a toast notification, which displays as an overlay onto the user’s current screen. For example, a weather application may wish to display a toast notification if a severe weather alert is in effect. If the user decides to click the toast notification, the application can launch and perform other actions.

A cloud service can control a toast notification’s title and sub-title. The toast notification will also display the application’s icon that is included in the application’s deployment package (In Windows® Phone 7.1,

Page | 31

©2011 Microsoft Corporation. All rights reserved.

Page 32: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

a toast message can also supply a custom URI to use when launching the application, causing it to navigate to a specific page).

Best Practices

Toast notifications should be personally relevant and time critical.

Task 1 – Implementing Server Side of Sending Tiles & Toasts

1. Open the Begin.sln starter solution from the Source\Ex2-TileToastNotifications\Begin folder of this lab. Alternatively, you can continue working on the solution created in previous exercise.

2. Open MainWindow.xaml.cs from the WPPushNotification.ServerSideWeatherSimulator project.

3. Add the following fields to the MainWindow class. These fields will be used for sending tile and toast notifications:

C#

private TilePushNotificationMessage tilePushNotificationMessage = new TilePushNotificationMessage(MessageSendPriority.High);private ToastPushNotificationMessage toastPushNotificationMessage = new ToastPushNotificationMessage(MessageSendPriority.High);

4. Locate the sendToast function. This function should get the Toast message from the Push Notification Client UI and send it to all the subscribers. Add the following code in the function body:

C#

string msg = txtToastMessage.Text;txtToastMessage.Text = "";List<Uri> subscribers = RegistrationService.GetSubscribers(); toastPushNotificationMessage.Title = "WEATHER ALERT";toastPushNotificationMessage.SubTitle = msg; subscribers.ForEach(uri => toastPushNotificationMessage.SendAsync(uri, (result) => OnMessageSent(NotificationType.Toast, result), (result) => { }));

5. Locate the sendTile function. This function should get the parameters from Push Notification Client UI and send it to all the subscribers. Add the following code in the function body:

C#

Page | 32

©2011 Microsoft Corporation. All rights reserved.

Page 33: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

string weatherType = cmbWeather.SelectedValue as string;int temperature = (int)(sld.Value + 0.5);string location = cmbLocation.SelectedValue as string;List<Uri> subscribers = RegistrationService.GetSubscribers(); tilePushNotificationMessage.BackgroundImageUri = new Uri("/Images/" + weatherType + ".png", UriKind.Relative);tilePushNotificationMessage.Count = temperature;tilePushNotificationMessage.Title = location; subscribers.ForEach(uri => tilePushNotificationMessage.SendAsync(uri, (result) => OnMessageSent(NotificationType.Token, result), (result) => { }));

6. Locate the sendRemoteTile function. This function should send a tile notification using an image located on a remote server. Add the following code in the function body:

C#

List<Uri> subscribers = RegistrationService.GetSubscribers(); tilePushNotificationMessage.BackgroundImageUri = new Uri("http://www.larvalabs.com/user_images/screens_thumbs/12555452181.jpg"); subscribers.ForEach(uri => tilePushNotificationMessage.SendAsync(uri, (result) => OnMessageSent(NotificationType.Token, result), (result) => { }));

Page | 33

©2011 Microsoft Corporation. All rights reserved.

Page 34: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

7. Compile and run the applications. Check that messages are dispatched to the Push Notification Service.

Figure 12WPF Push Notifications Client log

8. This step concludes the task.

Task 2 – Processing Tile & Toast Notifications on the Phone

1. Open MainPage.xaml.cs in the WPPushNotification.TestClient project.

2. In the next few steps you will subscribe to Tile and Toast notification events and will handle those events. Locate the Subscriptions region and add the following code:

C#

private void SubscribeToNotifications(){ ////////////////////////////////////////// // Bind to Toast Notification ////////////////////////////////////////// try { if (httpChannel.IsShellToastBound == true) { Trace("Already bounded (register) to Toast notification"); }

Page | 34

©2011 Microsoft Corporation. All rights reserved.

Page 35: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

else { Trace("Registering to Toast Notifications"); httpChannel.BindToShellToast(); } } catch (Exception ex) { // handle error here }

////////////////////////////////////////// // Bind to Tile Notification ////////////////////////////////////////// try { if (httpChannel.IsShellTileBound == true) { Trace("Already bounded (register) to Tile Notifications"); } else { Trace("Registering to Tile Notifications");

// you can register the phone application to receive tile images from remote servers [this is optional] Collection<Uri> uris = new Collection<Uri>(); uris.Add(new Uri("http://www.larvalabs.com"));

httpChannel.BindToShellTile(uris); } } catch (Exception ex) { //handle error here }}

3. Now locate the SubscribeToChannelEvents function and add the following blue-highlighted code to the function body:

C#

private void SubscribeToChannelEvents(){ //Register to UriUpdated event - occurs when channel successfully opens

Page | 35

©2011 Microsoft Corporation. All rights reserved.

Page 36: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

httpChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(httpChannel_ChannelUriUpdated);

//Subscribed to Raw Notification httpChannel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(httpChannel_HttpNotificationReceived);

//general error handling for push channel httpChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(httpChannel_ExceptionOccurred); //subscrive to toast notification when running apphttpChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(httpChannel_ShellToastNotificationReceived);}

4. Locate the Channel event handlers region and add the following function to handle the events:

C#

void httpChannel_ShellToastNotificationReceived(object sender, NotificationEventArgs e){ Trace("==============================================="); Trace("Toast/Tile notification arrived:"); foreach (var key in e.Collection.Keys) { string msg = e.Collection[key];

Trace(msg); Dispatcher.BeginInvoke(() => UpdateStatus("Toast/Tile message: " + msg)); } Trace("===============================================");}

Note: In our simple case the functions just trace the message payload, but in a real-world application you could use it to perform any business logic.

5. Lastly, add the following code to the following number of locations:

C#Page | 36

©2011 Microsoft Corporation. All rights reserved.

Page 37: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

SubscribeToNotifications();

The locations to add this code are the following:

6. In the ConnectToMSPN function, in the try block, between “SubscribeToService();” and “Dispatcher.BeginInvoke();”

C#

if (null != httpChannel){ Trace("Channel Exists - no need to create a new one"); SubscribeToChannelEvents();

Trace("Register the URI with 3rd party web service"); SubscribeToService();

Trace("Subscribe to the channel to Tile and Toast notifications"); SubscribeToNotifications();

Dispatcher.BeginInvoke(() => UpdateStatus("Channel recovered"));}

7. In the httpChannel_ChannelUriUpdated function, between “SubscribeToService();” and “Dispatcher.BeginInvoke(…);”

C#

void httpChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e){ Trace("Channel opened. Got Uri:\n" + httpChannel.ChannelUri.ToString()); Dispatcher.BeginInvoke(() => SaveChannelInfo()); Trace("Subscribing to channel events"); SubscribeToService(); SubscribeToNotifications(); Dispatcher.BeginInvoke(() => UpdateStatus("Channel created successfully"));}

8. Press F5 to compile and run the applications. On the phone emulator, click the Back button () to exit the Push Notification application and go to the Quick Launch area.

Page | 37

©2011 Microsoft Corporation. All rights reserved.

Page 38: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

9. In the Quick Launch area, click the Right Arrow button to get to the “All Applications” screen.

Figure 13Opening the installed applications screen

10. Locate the WPPushNotification.TestClient item, push it down and hold until context menu pops-up. Click Pin to Start.

Figure 14Pinning tile to Start screen

Page | 38

©2011 Microsoft Corporation. All rights reserved.

Page 39: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

11. The emulator will automatically go back to the Quick Launch area where you’ll notice the WPPushNotification.TestClient tile pinned.

12. On WPF Push Notification Client, change some notifications parameters, ensure that the Tile is checked and click the Send button. Observe the Tile change in emulator.

Figure 15Tile Notification arrived on emulator

Page | 39

©2011 Microsoft Corporation. All rights reserved.

Page 40: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

13. On WPF Push Notification Client, ensure that the Remote Tile is checked and click the Send button. Observe the Tile change in emulator.

Figure 16Remote Tile Notification arrived on emulator

Page | 40

©2011 Microsoft Corporation. All rights reserved.

Page 41: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

14. On the WPF Push Notification Client enter some message and click the Send Toast button. Observe how the Toast message arrives to the phone. Click the Toast message to switch back to the application.

Figure 17Toast message on phone emulator

Note: While a real world application would make sure to synchronize between the information displayed by its tile and the information displayed by the application itself, this sample application does not do so. This is because the phone client does not actively request data from the WPF server, and RAW messages are lost while the application is not in the foreground.

Additionally, a real world server would always send RAW messages along with Tile messages as it has no way of knowing whether the client application is currently active. The server we created only sends a specific type of message as per the user’s selection.

15. This step concludes the task.

Task 3 – Processing Scheduled Tile Notifications on the Phone

Page | 41

©2011 Microsoft Corporation. All rights reserved.

Page 42: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

You can also update the application’s tile by using a shell tile schedule represented by the Microsoft.Phone.Shell.ShellTileSchedule class. This special class allows an application to schedule updates of its tile's background image by setting the background image fully qualified URI and its related scheduler recurrence and interval attributes. When the phone starts the tile schedule instance, it automatically sends a tile notification to the application that then fetches the image based on the qualified URI, and updates the tile.

In the next few steps you will create an instance of a ShellTileSchedule class that performs updates of the application tile under the hood.

1. Open App.xaml.cs in the WPPushNotification.TestClient project.

2. Locate the application’s constructor - App method, and insert the following code fragment right after it:

C#

// To store the instance for the application lifetimeprivate ShellTileSchedule shellTileSchedule;

/// <summary> /// Create the application shell tile schedule instance /// </summary> private void CreateShellTileSchedule() { shellTileSchedule = new ShellTileSchedule(); shellTileSchedule.Recurrence = UpdateRecurrence.Interval; shellTileSchedule.Interval = UpdateInterval.EveryHour; shellTileSchedule.StartTime = DateTime.Now; shellTileSchedule.RemoteImageUri = new Uri(@"http://cdn3.afterdawn.fi/news/small/windows-phone-7-series.png"); shellTileSchedule.Start(); }

Note: Note that you can only provide a RemoteImageUri. Therefore you must provide an online and available URI that represents an image to download and display. You can’t reference URI from your local application. The image size can NOT exceed 80KB, and download time can NOT exceed 60 sec.

3. Now, locate the App() function and call the CreateShellTileSchedule function from it (see the highlighted line):

C#

// Constructorpublic App(){ ...

Page | 42

©2011 Microsoft Corporation. All rights reserved.

Page 43: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

// Phone-specific initialization InitializePhoneApplication();

// Create the shell tile schedule instance CreateShellTileSchedule();}

You just provided the application with the object that will update the application tile according to the schedule properties.

You have set the property:

◦ Recurrent to the value Interval, which causes the tile to be periodically updated. The other possible value for this property is OneTime, which causes the tile to update only once.

◦ Interval to the value EveryHour, which causes the tile to be updated every 60 minutes. It is worth mentioning that an hour is the minimum possible value for the update interval. This restriction is in place to save phone resources.

◦ RemoteImageUri to the address where you want to get tile image updates from.

And after all that, you have called the Start method to start updating the tile. Be aware that the first update may delay for an hour because this class invokes updates on full hours. The tile update schedule is kind of funky. Even if you set StartTime to now, you’ll need to wait for the phone update, which occurs up to every 60 minutes. Unfortunately, this is a system limitation, so if you want to debug this code, you have to wait that one hour. I usually debug this code overnight.

1. Press F5 to compile and run the applications. On the phone emulator, click the Back button () to exit the Push Notification application and go to the Quick Launch area.

2. Verify that your application tile is pinned in the Quick Launch area, else pin it according to the procedure defined in steps 8-10 of Task 2.

3. The PushNotifications tile image now will be updated according to the ShellTileSchedule definitions. So when the first schedule interval expires sometime in the next hour, the application tile will display the image located at the address stored in RemoteImageUri property, http://cdn3.afterdawn.fi/news/small/windows-phone-7-series.png.

This concludes the exercise.

Note: The complete solution for this exercise is provided at the following location: Source\Ex2-TileToastNotifications\End.

Page | 43

©2011 Microsoft Corporation. All rights reserved.

Page 44: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

Exercise 3: Using sub-tiles and deep toast notifications

This exercise focuses on features that are new to Windows® Phone 7.1. We have mentioned both this features at the beginning of the previous exercise – sub-tiles and deep toast notifications.

The most noticeable change we will perform during this exercise is changing the Windows® Phone client application to allow it to retain weather information received from the server for each location individually. The client application will have a new main screen allowing the user to choose a location for which to display weather information. This new main page will also allow the user to pin sub-tiles for any of the locations to the start area.

We will use sub-tiles to display information about a specific location in the start area. Clicking the sub-tile will open the application and have it display that location’s weather information.

We will also change the way toast notifications sent from the server work. The new toast notifications, when clicked, will lead to the information page belonging to the location that they relate to.

Task 1 – Making MSPN Registration Screen Independent

The Windows® Phone client application is currently written under the assumption that entire application consists of a single screen. Since we intend to add an additional screen to the client, we must make sure that all application level functionality is independent of any specific screen. All MSPN logic is currently contained in the application’s main screen and in the course of this task we will correct this.

1. Open the Begin.sln starter solution from the Source\Ex3-SecondaryTilesToastInput\Begin folder of this lab.

2. Open the file LocationInformation.cs

3. Change the class to implement the INotifyPropertyChanged interface.

C#

public class LocationInformation : INotifyPropertyChanged{ ...}

This class encapsulates all the data about a location associated with a sub-tile: whether or not the location’s tile is pinned to the start area, the location’s name and the temperature at it. We add this class now as MSPN state now needs to contain information about sub-tiles.

4. Open the file Status.cs.

5. Change the class to implement the INotifyPropertyChanged interface and to contain the following fields and properties:

Page | 44

©2011 Microsoft Corporation. All rights reserved.

Page 45: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

C#

public class Status : INotifyPropertyChanged{ private string message; /// <summary> /// A message representing some status. /// </summary> public string Message { get { return message; } set { if (value != message) { message = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Message")); } } } }

#region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; #endregion}

This class simply supports a text field that fires change notifications and we will use it in the next steps to represent changing status messages.

6. Open the file PushHandler.cs.

The already added fields and properties are used to establish and keep track of the connection to MSPN and we will see how they are to be used in the following steps. Note the “Locations” property in particular. We will use the “Locations” property to map each location name to information about that location.

7. Add the following constructor to the class:

C#

/// <summary>/// Creates a new instance of the class.

Page | 45

©2011 Microsoft Corporation. All rights reserved.

Page 46: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

/// </summary>/// <param name="pushStatus">Status object to update with push /// related status messages.</param>/// <param name="locationsInformation">Dictionary containing /// information about the locations tracked by the /// application</param>/// <param name="uiDispatcher">A dispatcher to use when updating /// the user interface.</param>public PushHandler (Status pushStatus, Dictionary<string, LocationInformation> locationsInformation, Dispatcher uiDispatcher){ PushStatus = pushStatus; Locations = locationsInformation; Dispatcher = uiDispatcher;}

This constructor is simply used to initialize some of the class’s properties.

8. Add the following method to the class:

C#

/// <summary>/// Connects to the Microsoft Push Service and registers the /// received channel with the application server./// </summary>public void EstablishConnections(){ connectedToMSPN = false; connectedToServer = false; notificationsBound = false; try { //First, try to pick up existing channel httpChannel = HttpNotificationChannel.Find(channelName); if (null != httpChannel) { connectedToMSPN = true; App.Trace("Channel Exists – no need to create a new one"); SubscribeToChannelEvents(); App.Trace("Register the URI with 3rd party web service"); SubscribeToService(); App.Trace("Subscribe to the channel to Tile and Toast notifications");

Page | 46

©2011 Microsoft Corporation. All rights reserved.

Page 47: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

SubscribeToNotifications(); UpdateStatus("Channel recovered"); } else { App.Trace("Trying to create a new channel..."); //Create the channel httpChannel = new HttpNotificationChannel(channelName, "HOLWeatherService"); App.Trace("New Push Notification channel created successfully"); SubscribeToChannelEvents(); App.Trace("Trying to open the channel"); httpChannel.Open(); UpdateStatus("Channel open requested"); } } catch (Exception ex) { UpdateStatus("Channel error: " + ex.Message); }}

This method establishes all necessary connections with the MSPN and WPF server application and greatly resembles the “ConnectToMSPN” method created in Exercise 1, Task 3, Step 2.

9. Add the following method to the class:

C#

private void SubscribeToChannelEvents(){ //Register to UriUpdated event - occurs when channel //successfully opens httpChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>( httpChannel_ChannelUriUpdated); //Subscribed to Raw Notification httpChannel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>( httpChannel_HttpNotificationReceived); //general error handling for push channel httpChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(

Page | 47

©2011 Microsoft Corporation. All rights reserved.

Page 48: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

httpChannel_ExceptionOccurred); //subscribe to toast notification when running app httpChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>( httpChannel_ShellToastNotificationReceived);}

The above method simply registers for events related to the MSPN’s notification channel.

10. Add the following method to the class:

C#

private void SubscribeToService(){ //Hardcode for solution - need to be updated in case the REST //WCF service address change string baseUri = "http://localhost:8000/RegirstatorService/Register?uri={0}"; string theUri = String.Format(baseUri, httpChannel.ChannelUri.ToString()); WebClient client = new WebClient(); client.DownloadStringCompleted += (s, e) => { if (null == e.Error) { connectedToServer = true; UpdateStatus("Registration succeeded"); } else { UpdateStatus("Registration failed: " + e.Error.Message); } }; client.DownloadStringAsync(new Uri(theUri));}

This method registers with the WPF server as we have previously seen in this lab.

11. Add the following method to the class:

C#

private void SubscribeToNotifications(){ ////////////////////////////////////////// // Bind to Toast Notification ////////////////////////////////////////// try

Page | 48

©2011 Microsoft Corporation. All rights reserved.

Page 49: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

{ if (httpChannel.IsShellToastBound == true) { App.Trace("Already bound to Toast notification"); } else { App.Trace("Registering to Toast Notifications"); httpChannel.BindToShellToast(); } } catch (Exception ex) { // handle error here } ////////////////////////////////////////// // Bind to Tile Notification ////////////////////////////////////////// try { if (httpChannel.IsShellTileBound == true) { App.Trace("Already bound to Tile Notifications"); } else { App.Trace("Registering to Tile Notifications"); // you can register the phone application to receive // tile images from remote servers [this is optional] Collection<Uri> uris = new Collection<Uri>(); uris.Add(new Uri("http://www.larvalabs.com")); httpChannel.BindToShellTile(uris); } } catch (Exception ex) { //handle error here } notificationsBound = true;}

This method registers to toast and tile notifications as we have previously seen in the lab.

12. Add the following methods to the class to serve as the event handlers defined in step 11:

Page | 49

©2011 Microsoft Corporation. All rights reserved.

Page 50: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

C#

void httpChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e){ connectedToMSPN = true; App.Trace("Channel opened. Got Uri:\n" + httpChannel.ChannelUri.ToString()); App.Trace("Subscribing to channel events"); SubscribeToService(); SubscribeToNotifications(); UpdateStatus("Channel created successfully");} void httpChannel_ExceptionOccurred(object sender,NotificationChannelErrorEventArgs e){ UpdateStatus(e.ErrorType + " occurred: " + e.Message);} void httpChannel_HttpNotificationReceived(object sender,HttpNotificationEventArgs e){ App.Trace("==============================================="); App.Trace("RAW notification arrived"); Dispatcher.BeginInvoke(() => ParseRAWPayload(e.Notification.Body)); App.Trace("===============================================");} void httpChannel_ShellToastNotificationReceived(object sender,NotificationEventArgs e){ App.Trace("==============================================="); App.Trace("Toast/Tile notification arrived:"); string msg = e.Collection["wp:Text2"]; App.Trace(msg); UpdateStatus("Toast/Tile message: " + msg); App.Trace("===============================================");}

Page | 50

©2011 Microsoft Corporation. All rights reserved.

Page 51: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

These handlers are analogue to the ones we have defined in the MainPage class earlier in the lab.

13. Add two additional helper methods to the class:

C#

private void UpdateStatus(string message){ Dispatcher.BeginInvoke(() => PushStatus.Message = message);} private void ParseRAWPayload(Stream e){ XDocument document; using (var reader = new StreamReader(e)) { string payload = reader.ReadToEnd().Replace('\0', ' '); document = XDocument.Parse(payload); } XElement updateElement = document.Root; string locationName = updateElement.Element("Location"). Value; LocationInformation locationInfo = Locations[locationName]; App.Trace("Got location: " + locationName); string temperature = updateElement.Element("Temperature"). Value; locationInfo.Temperature = temperature; App.Trace("Got temperature: " + temperature); string weather = updateElement.Element("WeatherType").Value; locationInfo.ImageName = weather; App.Trace("Got weather type: " + weather); }

The first method simply updates the message that describes the client’s connection status, and the second parses the raw push notifications sent by the WPF server in order to extract weather information about a location.

14. Open App.xaml.

15. Add a new element as a child of the Application.Resources tag:

XAML

<!--Application Resources--><Application.Resources>

Page | 51

©2011 Microsoft Corporation. All rights reserved.

Page 52: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

<local:Status x:Key="PushStatus"> <local:Status.Message>Not connected</local:Status.Message> </local:Status>...

We have referenced this new resource from code in previous step and use it to display the client’s connection status across the application.

16. Open App.xaml.cs.

17. Add the following properties to the App class:

C#

/// <summary>/// Whether or not it is necessary to refresh the pin status of /// the secondary tiles./// </summary>public bool TileRefreshNeeded { get; set; } /// <summary>/// Contains information about the locations displayed by the /// application./// </summary>public Dictionary<string, LocationInformation> Locations { get; set; } /// <summary>/// Returns the application's dispatcher./// </summary>public Dispatcher Dispatcher{ get { return Deployment.Current.Dispatcher; }} private PushHandler PushHandler { get; set; }

18. Locate the Application_Launching method and change it to the following:

C#

private void Application_Launching(object sender, LaunchingEventArgs e){ TileRefreshNeeded = true; InitializeLocations(); RefreshTilesPinState();

Page | 52

©2011 Microsoft Corporation. All rights reserved.

Page 53: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

PushHandler = new PushHandler(Resources["PushStatus"] as Status, Locations, Dispatcher); PushHandler.EstablishConnections();}

The code above will cause the application to initialize location information upon startup, making sure to check which location has a sub-tile present in the start area and to connect to MSPN and the WPF server using the PushHandler class we have created at the beginning of this task.

19. Locate the Application_Activated method and change it to the following:

C#

private void Application_Activated(object sender, ActivatedEventArgs e){ if (!e.IsApplicationInstancePreserved) { // The application was tombstoned, so restore its state foreach (var keyValue in PhoneApplicationService.Current.State) { Locations[keyValue.Key] = keyValue.Value as LocationInformation; } // Reconnect to the MSPN PushHandler = new PushHandler(Resources["PushStatus"] as Status, Locations, Dispatcher); PushHandler.EstablishConnections(); } else if (!PushHandler.ConnectionEstablished) { // Connection was not fully established before fast app // switching occurred PushHandler.EstablishConnections(); } RefreshTilesPinState();}

The code above will cause the application to restore location information from the application’s state object to reestablish its connections in case it has been tombstoned. If the application’s instance was preserved but before properly establishing all connections then another attempt to establish them will be made. Finally, as the user may have removed some of the application’s sub-tiles while it was in the background, the application checks which of its tiles are present in the start area.

20. Locate the Application_Deactivated method and change it to the following:

C#

Page | 53

©2011 Microsoft Corporation. All rights reserved.

Page 54: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

private void Application_Deactivated(object sender, DeactivatedEventArgs e){ foreach (var keyValue in Locations) { PhoneApplicationService.Current.State[keyValue.Key] = keyValue.Value; }}

The code above simply stores all location information in the application’s state object in case the application is tombstoned.

21. Add the following helper methods to the App class:

C#

/// <summary>/// Writes debug output in debug mode./// </summary>/// <param name="message">The message to write to debug output./// </param>internal static void Trace(string message){#if DEBUG Debug.WriteLine(message);#endif} /// <summary>/// Initializes the contents of the location dictionary./// </summary>private void InitializeLocations(){ List<LocationInformation> locationList = new List<LocationInformation>(new[] { new LocationInformation { Name = "Redmond", TilePinned = false }, new LocationInformation { Name = "Moscow", TilePinned = false }, new LocationInformation { Name = "Paris", TilePinned = false }, new LocationInformation { Name = "London", TilePinned = false }, new LocationInformation { Name = "New York", TilePinned = false } }); Locations = locationList.ToDictionary(l => l.Name);}

Page | 54

©2011 Microsoft Corporation. All rights reserved.

Page 55: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

/// <summary>/// Sees which of the application's sub-tiles are pinned and /// updates the location information accordingly./// </summary>private void RefreshTilesPinState(){ Dictionary<string, LocationInformation> updateDictionary = Locations.Values.ToDictionary(li => li.Name); foreach (ShellTile tile in ShellTile.ActiveTiles) { string[] querySplit = tile.NavigationUri.ToString().Split('='); if (querySplit.Count() != 2) { continue; } string locationName = Uri.UnescapeDataString(querySplit[1]); updateDictionary[locationName].TilePinned = true; updateDictionary.Remove(locationName); } foreach (LocationInformation locationInformation in updateDictionary.Values) { locationInformation.TilePinned = false; }}

The “Trace” method above simply writes debug information. “InitializeLocations” fills the location information dictionary with the application’s five locations. “RefreshTilesPinState” goes over all of the application’s active tiles (using the new Windows® Phone 7.1 ShellTile class) and updates all locations according to whether or not their sub-tiles is one of the active tiles.

Note: ShellTile.ActiveTiles returns all of the application’s sub-tiles pinned to the start area in addition to the application’s primary tile, whether or not it is pinned to the start area.

Task 2 – Updating the Client’s Main Page

In the previous task we re-implemented application-wide functionality that was only present in the main page. In this task, we will change the main page so that it allows us to view any of the available locations, to see which locations have sub-tiles in the start area and to directly manipulate the application’s main tile.

Page | 55

©2011 Microsoft Corporation. All rights reserved.

Page 56: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

1. Under the folder named Converters open the file BoolToVisibilityConverter.cs

2. Change the BoolToVisibilityConverter class using the following code:

C#

public class BoolToVisibilityConverter : IValueConverter{ #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return ((bool)value) ? Visibility.Visible : Visibility.Collapsed; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } #endregion}

This class serves as a value converter which turns Boolean values into element visibility values.

3. There is another converter to pay attention to: BoolToInverseVisibilityConverter.

This class serves as a value converter which turns Boolean values into element visibility values, where true values represent collapsed elements.

4. Open MainPage.xaml from the WPPushNotification.TestClient project.

5. We now need to make changes in the main page’s code to match the new visual changes, and to remove the MSPN related functionality. Open MainPage.xaml.cs and change the OnNavigatedTo function into MainPage class to the following:

C#

#region Navigation protected override void OnNavigatedTo( System.Windows.Navigation.NavigationEventArgs e) { Locations = (App.Current as App).Locations; base.OnNavigatedTo(e); } #endregion

Page | 56

©2011 Microsoft Corporation. All rights reserved.

Page 57: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

The new version of the main page seen above simply retrieves the location information dictionary from the application object when the page is navigated to.

6. Replace the following methods in the main page class, to be used as UI handlers:

C#

private void UnpinItem_Click(object sender, RoutedEventArgs e){ LocationInformation locationInformation = (sender as MenuItem).DataContext as LocationInformation; ShellTile tile = ShellTile.ActiveTiles.FirstOrDefault( t => t.NavigationUri.ToString().EndsWith( locationInformation.Name)); if (tile == null) { MessageBox.Show("Tile inconsistency detected. It is suggested that you restart the application."); return; } try { tile.Delete(); locationInformation.TilePinned = false; } catch (Exception ex) { MessageBox.Show(ex.Message, "Error deleting tile", MessageBoxButton.OK); return; }} private void PinItem_Click(object sender, RoutedEventArgs e){ LocationInformation locationInformation = (sender as MenuItem).DataContext as LocationInformation; Uri tileUri = MakeTileUri(locationInformation); StandardTileData initialData = new StandardTileData() { BackgroundImage = new Uri("Images/Clear.png", UriKind.Relative), Title = locationInformation.Name };

Page | 57

©2011 Microsoft Corporation. All rights reserved.

Page 58: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

((sender as MenuItem).Parent as ContextMenu).IsOpen = false; try { ShellTile.Create(tileUri, initialData); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error creating tile", MessageBoxButton.OK); return; }} private void ListBox_SelectionChanged(object sender,SelectionChangedEventArgs e){ if (e.AddedItems.Count != 0) { (sender as ListBox).SelectedIndex = -1; NavigationService.Navigate(MakeTileUri(e.AddedItems[0] as LocationInformation)); }} private void ChangeMainTile_Click(object sender,RoutedEventArgs e){ // Get the main tile (it will always be available, even if // not pinned) ShellTile mainTile = ShellTile.ActiveTiles.FirstOrDefault( t => t.NavigationUri.ToString() == "/"); StandardTileData newData = new StandardTileData() { BackgroundImage = new Uri(String.Format("Images/MainTile/{0}.png",(listMainTileImage.SelectedItem as ListPickerItem).Content), UriKind.Relative), Title = txtMainTileTitle.Text }; mainTile.Update(newData);}

The first two methods are handlers for the context menu associated with the location entries we have added to the new main page. These allow to pin and un-pin locations to the start area according to their current state. The “ListBox_SelectionChanged” method navigates to a specific location’s page after the user selects it from the main page and the “ChangeMainTile_Click”

Page | 58

©2011 Microsoft Corporation. All rights reserved.

Page 59: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

method changes the application’s main tile according to selections made through the main page.

7. Press F5 to compile and run the client application and the WPF server.

8. Pressing and holding over an unpinned location (one without a tick in the checkbox to its left) will open up a menu that will allow pinning it to the start area. This will immediately move the focus to the start area where the new tile can be displayed. These tiles also lead to the “CityPage” page which does not yet exist:

Figure 18Opening a location’s context menu

Page | 59

©2011 Microsoft Corporation. All rights reserved.

Page 60: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

Figure 19A sub-tile pinned to the start area

9. Press the back button () to navigate back to the application and use the new controls at the bottom of the screen to alter the application’s main tile:

Page | 60

©2011 Microsoft Corporation. All rights reserved.

Page 61: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

Figure 20Updating the main tile

Page | 61

©2011 Microsoft Corporation. All rights reserved.

Page 62: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

Figure 21The start area after updating the application’s main tile

Note: To see the main tile changing, you must first pin it to the start area by pressing and holding this sample application in the installed application list.

10. Stop running the client application and the server.

Task 3 – Adding a Specific Location Page and Updating the Server

We now need to add a new page to view information about a specific location (much like the old main page) and to update the server and have it send enhanced tile and toast notifications.

1. Open CityPage.xaml.cs and add the following function to CityPage class:

C#

public partial class CityPage : PhoneApplicationPage{ ...

Page | 62

©2011 Microsoft Corporation. All rights reserved.

Page 63: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

protected override void OnNavigatedTo( System.Windows.Navigation.NavigationEventArgs e) { DataContext = (App.Current as App).Locations[ NavigationContext.QueryString["location"]]; base.OnNavigatedTo(e); }}

This will set the page’s data source to the location specified as a query parameter in the navigation URI.

2. We have finished altering the client application and will now alter the server. Open MainWindow.xaml.cs under the WPPushNotification.ServerSideWeatherSimulator project, locate the sendToast method and change it to the following (altered code yellow-highlighted):

C#

private void sendToast(){ string msg = txtToastMessage.Text; txtToastMessage.Text = ""; List<Uri> subscribers = RegistrationService.GetSubscribers(); toastPushNotificationMessage.Title = String.Format("WEATHER ALERT ({0})", cmbLocation.SelectedValue); toastPushNotificationMessage.SubTitle = msg; toastPushNotificationMessage.TargetPage = MakeTileUri(cmbLocation.SelectedValue.ToString()).ToString(); subscribers.ForEach(uri => toastPushNotificationMessage. SendAsync(uri, (result) => OnMessageSent(NotificationType.Toast, result), (result) => { }));}

This altered method will cause toast messages to lead to the page of the location selected when the message was sent from the server.

3. Find the sendTile method and change it using the following code (altered code yellow-highlighted):

C#

private void sendTile(){ string weatherType = cmbWeather.SelectedValue as string; int temperature = (int)(sld.Value + 0.5); string location = cmbLocation.SelectedValue as string;

Page | 63

©2011 Microsoft Corporation. All rights reserved.

Page 64: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

List<Uri> subscribers = RegistrationService.GetSubscribers(); tilePushNotificationMessage.BackgroundImageUri = new Uri("/Images/" + weatherType + ".png", UriKind.Relative); tilePushNotificationMessage.Count = temperature; tilePushNotificationMessage.Title = location; tilePushNotificationMessage.SecondaryTile = MakeTileUri(location).ToString(); subscribers.ForEach(uri => tilePushNotificationMessage. SendAsync(uri, (result) => OnMessageSent(NotificationType.Token, result), (result) => { }));}

This new version of the method will send the tile notification to the sub-tile matching the notification’s associated location.

4. Locate the sendRemoteTile method and change it to the following (modified code yellow-highlighted):

C#

private void sendRemoteTile(){ List<Uri> subscribers = RegistrationService.GetSubscribers(); tilePushNotificationMessage.BackgroundImageUri = new Uri("http://www.larvalabs.com/user_images/screens_thumbs/12555452181.jpg"); tilePushNotificationMessage.SecondaryTile = null; tilePushNotificationMessage.Title = null; tilePushNotificationMessage.Count = 0; subscribers.ForEach(uri => tilePushNotificationMessage.SendAsync(uri, (result) => OnMessageSent(NotificationType.Token, result), (result) => { }));}

While this method still functions in the same way, there are now more fields that need to be reset when sending a tile message.

5. Finally, add the following method to the server:

C#

private static Uri MakeTileUri(string locationName){

Page | 64

©2011 Microsoft Corporation. All rights reserved.

Page 65: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

return new Uri(Uri.EscapeUriString(String.Format( "/CityPage.xaml?location={0}", locationName)), UriKind.Relative);}

This method is a counterpart for the identically named one we have added to the client application and is used to construct URIs in the same manner.

6. Press F5 to compile and run the client application and the WPF server. In the windows phone emulator, press the Windows key to show the start area, and then try sending tile notifications from the WPF server. When you send a tile notification for a location pinned to the start area its tile will be updated with the relevant information

7. Try sending a toast notification and pressing it:

Figure 22A toast notification

Page | 65

©2011 Microsoft Corporation. All rights reserved.

Page 66: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

Figure 23Clicking the toast notification

8. Send some raw data regarding the displayed location:

Page | 66

©2011 Microsoft Corporation. All rights reserved.

Page 67: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

Figure 24The specific location page displaying information

Note: You may have expected the specific location page to already show the information displayed by the location’s sub-tile. This is indeed how a real world application should work. However, for simplicity’s sake, this feature was omitted from the client and server created during this lab. In order to support such a feature, the client application must be able to actively request the most up-to-date data from the server upon activation. The lab installation folder contains a folder named Source\Bonus which contains an implementation of this feature, but we will not cover the changes necessary to perform it.

Page | 67

©2011 Microsoft Corporation. All rights reserved.

Page 68: Weather Service Push notificationsaz12722.vo.msecnd.net/.../PushNotifications.docx · Web viewThe Microsoft Push Notification Service in Windows Phone offers third-party developers

Summary

During this lab you learned about the notification services for the Windows® Phone 7 platform. You learned about notification types, and how to prepare and send them through Microsoft Push Notification Service. You created the business client application to prepare and send such messages and Windows® Phone 7 client application. The Windows® Phone 7 client application subscribes to the notifications and updates the UI according to the information received in the messages. You also utilized new Windows® Phone 7.1 features to manipulate application sub-tiles and send deep-toast notifications.

Page | 68

©2011 Microsoft Corporation. All rights reserved.