Hands-On Lab

Integrating SharePoint and Windows Phone 7 Notifications

Lab version:1.0.0

Last updated:12/11/2018

Contents

Overview

Exercise 1: Creating a SharePoint List Data Source

Task 1 – Creating the Maintenance Training Calendar List

Exercise 2: Verifying the Notification Registration WCF Service

Task 1 – Beginning the Exercise

Task 2 – Running the Service in Visual Studio 2010

Exercise 3: Creating the List Event Receiver to Send Notifications

Task 1 – Adding the EventNotification Project to the Solution

Task 2 – Completing the Notification.cs Class to Send Toast Notifications

Task 3 – Completing the EventListNotification.cs Class to Send Toast Notifications

Task 4 – Adding a Reference to the NotificationRegistration WCF Service

Task 5 – Verifying the Event Receiver Builds and Deploys Correctly.

Exercise 4: Creating the Windows Phone 7 Application

Task 1 – Adding the WP7.Notification.Events.PhoneApp Project to the Solution

Task 2 – Configuring Constants in the Windows Phone 7 Application

Task 3 – Completing the SettingsViewModel.cs Class

Task 4 – Completing the MainPage.xaml.cs File

Task 5 – Adding a Reference to the SharePoint Lists.asmx Web Service

Task 6 – Adding a Reference to the NotificationRegistration WCF Service

Task 7 – Modifying the ServiceReferences.ClientConfig File to Support the Cookie Container Used with Forms Based Authentication

Exercise 5: Testing the Windows Phone 7 Application

Task 1 – Testing the Application’ View Functionality in Windows Phone 7 Emulator

Task 2 -Testing the Toast Notification in Windows Phone 7 Emulator

Summary

Overview

Windows Phone 7 applications can use Windows Push Notification Services to notify users of custom events. Windows Phone 7 applications integrating with SharePoint can use notifications to alert users about changes in SharePoint data sources.

Objectives

In this hands-on lab, you will learn how to create a list event handler that will send Push Notifications to a Windows Phone 7 application. You will alow learn how to register for notifications and bind the phone and application to a toast notification.

  • Learn how to use a SharePoint list event reciever to create notifications for registered devices.
  • Learn how register a device with a custom WCF service to subscribe to notifications.
  • Learn how to subscribe to and bind to notifictions in a Windows Phone 7 application.

Prerequisites

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

Note: See Setting Up A SharePoint and Windows Phone 7 Development Environment Modulefor instructions that describe how to set up the SharePoint and Windows Phone 7 developer machine.

  • Windows 7 x64 installed with all Windows Updates installed, in one of the following scenarios.

◦Installed on a physical machine

◦Installed on a bootable VHD

  • SharePoint 2010 installed on the Windows 7 x64 developer machine configured with a site collection that uses Forms Based Authentication (FBA).
  • Windows Phone 7 Developer Tools

  • Windows Phone 7 Developer Tools - January 2011 Update

  • Windows Phone Developer Tools Fix

Note: The following prerequisites are not included in the Setting Up A SharePoint and Windows Phone 7 Development Environment Module installation instructions. If you are using a development machine built according to the Setting Up A SharePoint and Windows Phone 7 Development Environment Module instructions you must install these components.

  • KB981002- WCF: Hotfix rollup in .NET 3.5 SP1 for Win 7 and Win 2k8 R2

  • Internet connectivity

Note: This lab requires the firewall be turned off to enable connection to the Push Notification Service.

Exercise 1: Creating a SharePoint List Data Source

In this exercise, you will create a new calendar list that will contain training events. In this scenario, the Windows Phone 7 application will read the calender list and display the events it contains. The Windows Phone 7 applicationallows users to receive Toast notifications when items in the calendar list are added, modified or deleted. Users with write permissions will be able to add events to the calendar list to test the applciation.

Task 1 – Creating the Maintenance Training Calendar List

In this task, you willuse the calendar list template to create the maintenance training schedule list.

  1. Open Internet Explorer and navigate to the SharePoint Team Site configured for Forms Based Authentication.

example:

  1. Log into the site using site collection administrator credentials.
  2. Click Site Actions and select More Options.
  3. In the Filter By section, select List.
  4. Select the Calendar list.

Figure 1

Selecting a Calendar list template.

  1. In the Name textbox, enter Maintenance Training Schedule.
  1. Click Create.

Exercise 2: Verifying the Notification Registration WCF Service

In this exercise, you will verify an existing registration WCF service builds and runs in your development environment. The WCF service manages the notification registrations. It uses a static collection to maintain the notification registrations.

Task 1 – Beginning the Exercise

In this task, you will open the lab solution in Visual Studio 2010.

  1. Make sure that you have downloaded and installed the items listed in System Requirements above prior to beginning this exercise.
  2. Launch Visual Studio 2010 as administrator and open the lab project by selecting File » Open » Project.
  3. Browse to the WP7.Notification.Events.sln file located at %TrainingKitPath%\Labs\IntegratingNotifications\Source\Before and select it.
  4. Click Open to open the solution.

Task 2– Running the Service in Visual Studio 2010

In this task, you will run the NotificationRegistration service to verify it starts correctly.

  1. In the Solution Explorer, in the NotificationRegistration project, right click ListNotificationChannels.svc and select Set as Start Page.
  2. Press F5 to run the service.The service should start in the WCF Test Harness or display the Service page in the web browser.

Figure 2

NotificationRegistration WCF Test Client

Figure 3

NotificationRegistration WCF Services in Internet Explorer

  1. In Visual Studio, press Shift + F5 to stop debugging.

Exercise 3: Creating the List Event Receiver to Send Notifications

In this exercise, you will create a list event receiver to send toast notifications to registered devices. The list event receiver will be associated with calendar lists.

Task 1 – Adding the EventNotification Project to the Solution

In this task, you add the existing EventNotification project to the solution.

  1. In the Solution Explorer, right-click WP7.Notification.Events and select Add | Existing Project.
  2. Browse to EventNotification.csproj located in the EventNotification folder.
  3. Click Open.

Figure 4

Solution Explorer with WCF Service project and Event Receiver project

Task 2 – Completing the Notification.cs Class to Send Toast Notifications

In this task, you will complete the existing Notification class to send toast notification to any devices registered for notification.

  1. In the EventNotification project, open the Notification.cs file.
  1. Add the following code under the //TODO: 7.1.1 comment to define the SendNotificationmethod:

C#

public static void SendNotification(string channelUri, string text1, string text2)

{

string ToastPushXML = "<?xml version='1.0' encoding='utf-8'?>" +

"<wp:Notification xmlns:wp='WPNotification'>" +

"<wp:Toast>" +

"<wp:Text1>{0}</wp:Text1>" +

"<wp:Text2>{1}</wp:Text2>" +

"</wp:Toast>" +

"</wp:Notification>";

string str = string.Format(ToastPushXML, text1, text2);

HttpWebRequest sendNotificationRequest =

(HttpWebRequest)WebRequest.Create(channelUri);

sendNotificationRequest.Method = "POST";

sendNotificationRequest.Headers = new WebHeaderCollection();

sendNotificationRequest.ContentType = "text/xml";

sendNotificationRequest.Headers.Add("X-NotificationClass", "2");

sendNotificationRequest.Headers.Add("X-WindowsPhone-Target", "toast");

byte[] strBytes = new UTF8Encoding().GetBytes(str);

sendNotificationRequest.ContentLength = strBytes.Length;

using (Stream requestStream = sendNotificationRequest.GetRequestStream())

{

requestStream.Write(strBytes, 0, strBytes.Length);

}

try

{

var response = (HttpWebResponse)sendNotificationRequest.GetResponse();

var notiticationStatus = response.Headers["X-NotificationStatus"];

var notitificationChannelStatus = response.Headers["X-SubscriptionStatus"];

var deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];

}

catch

{

// Ignoring the response.

// In a production application you should review the response and

// code appropriate for the specific response.

//

}

}

The above code creates a HttpWebRequest object and posts XML to the channel Uri provided to the method. This method is called once for each channel (device) that is registered for notification with a matching list id.l The XMLpayload defines the type of notification (Toast) as well as the details of the notification ( text1 and text 2). A Toast notification accepts two text fields. Push Notification Services requires the additional header values included in the above code.

  1. Add the following code under the //TODO: 7.1.2 comment to define the Notify method:

C#

public static void Notify(string listId, string text1, string text2)

{

NotificationRegistration.ListNotificationChannels svc = new

NotificationRegistration.ListNotificationChannels();

string[] channelUris = svc.RetrieveChannelURIsForListId(listId);

foreach (var channel in channelUris)

{

SendNotification(channel, text1, text2);

}

}

The above code uses the proxy class Visual Studio 2010 generated for the NotificationRegistration WCF service to retrieve an array of channel URIs for any device registered for notifications for this specific list id. There will be one entry for each channel (device) registered for notifications for the list. This method will call the SendNotification method for each channel returned from the registration service.

  1. Save and close the Notification.cs file.

Task 3 – Completing the EventListNotification.cs Class to Send Toast Notifications

In this task, you will complete the existing EventListNotification class to send a Toast notification to any devices registered for notification.

  1. In the EventNotification project, open the EventListNotification.cs file located in the EventListNotification SharePoint Project Item.
  1. Add the following code under the //TODO: 7.1.3 comment to define the Notify method:

C#

private void Notify(SPItemEventProperties properties, string eventName)

{

string listId = properties.ListId.ToString();

string listTitle = properties.List.Title;

Notification.Notify(listId, string.Format("{0}: ", listTitle),

string.Format("Item: {0}", eventName)); }

The above code is called by the specific events in the receiver class. The code will call the static Notify method of the Notification class passing in the list id and the values for the notification’s text message. For each notified event of the event receiver, the receiver code will send notifications to devices registered for notifications for this list.

  1. Save and close the EventListNotification.cs file.

Task 4 – Adding a Reference to the NotificationRegistration WCF Service

In this task, you will add a reference to the NotificationRegistration WCF service.

  1. In the Solution Explorer, in the EventNotification project, right click Service References and select Add Service Reference.
  2. Click Advanced…
  3. Click Add Web Reference…
  4. Click Web services in this solution

Figure 5

Selecting Web Services in this solution

  1. Click ListNotificationChannels

Figure 6

Selecting the ListNotificationChannels service

  1. In the Web reference name textbox enter NotificationRegistration.

Figure 7

Entering the Web reference name for the service

  1. Click Add Reference.

Task 5 – Verifying the Event Receiver Builds and Deploys Correctly.

In this task, you verify the event receiver and WCF service builds and deploys correctly.

  1. In the Solution Explorer, right click the WP7.Notification.Eventssolution and select Properties.
  2. Select Multiple startup projects.
  3. Set the action for EventNotification to Start.
  1. Set the action for NotificationRegistration to Start.

Figure 8

Selecting multiple startup objects in Visual Studio 2010

  1. Click OK.
  1. In the Solution Explorer, select the EventNotification project.
  2. Set the Site URL property to the site containing the Maintenance Training Schedule list.

Figure 9

Setting the Site URL for the event receiver project

  1. In the WP7.Notification.Eventssolution, press F5.
  2. Verify the solution builds and deploys without error.
  3. In the WP7.Notification.Eventssolution, press Shift +F5 to stop debugging.

Exercise 4: Creating the Windows Phone 7 Application

In this exercise, you will create a Windows Phone 7 application to read from the list created in Exercise 1. The application will allow users to opt in for notifications. The application will enable and disable toast notifications based on the setting.

Task 1 – Adding the WP7.Notification.Events.PhoneAppProject to the Solution

In this task, you add the existing WP7.Notification.Events.PhoneApp project to the solution.

  1. In the Solution Explorer, right-click the WP7.Notification.Events solution, and select Add | Existing Project.
  2. Browse to WP7.Notification.Events.PhoneApp.csproj located in the PhoneApp folder.
  3. Click Open.

Figure 10

Solution Explorer with three projects displayed

Task 2 – ConfiguringConstants in the Windows Phone 7 Application

In this task, you will configure the constants used in the Windows Phone 7 application to work with your development environment.

  1. In the WP7.Notification.Events.PhoneAppproject, in the Utilities folder, open the Constants.cs file.
  2. Change the value for the USER_NAME and USER_PASSWORD constants to represent a Forms Based Authentication user specific to your development environment. For this lab, the user requires read and write permissions.
  3. Change the value for the AUTHENTICATION_SERVICE_URL constant to the URL specific to your development environment.

The following code example demonstrates the value for a SharePoint server named fbawp7.

C#

public const string AUTHENTICATION_SERVICE_URL ="

  1. Change theLIST_TITLE constant to Maintenance Training Schedule.
  2. Change theLIST_ID constant to the list id of the Maintenance Training Schedule.
  3. Open the Maintenance Training Schedulelist in Internet Explorer.
  4. Select the Calendar Ribbon tab.
  5. Click List Settings Ribbon button.
  6. Select the value of the List URL parameter from the browser’s address bar.
  7. The value of the list id in the address bar is URL encoded. Remove the %7B and %7D values at the beginning and end of the parameter. Replace %2D with the dash character.

For example:

%7B618FD6BA%2DE587%2D4C93%2D9143%2DD21B2C01E8AD%7D

Is converted to:

618FD6BA-E587-4C93-9143-D21B2C01E8AD

  1. Copy the unencoded list id to the LIST_ID constant value.

C#

public const string LIST_ID = "618FD6BA-E587-4C93-9143-D21B2C01E8AD";

Note: If the list id constant is not correct, the event handler will not receive the channel Uri (device) from the registration service.

Note: The above code is an example. You must use your unique list id.

Task 3 – Completing the SettingsViewModel.cs Class

In this task, you will complete the existing SettingsViewModel class. This class manages the application’s connection and bindings for notification.

  1. In the Solution Explorer, open the SettingsViewModel.cs file located in the ViewModels folder.
  1. Add the following code under the //TODO: 7.1.4 comment to define the Current property:

C#

private static SettingsViewModel current;

public static SettingsViewModel Current

{

get { return current; }

}

The above code creates a singleton-type property. This allows the code to have only one instance of this class at a time. This view model class contains the code to manage notifications. Creating a singleton of this class allows the code to be available at all times.

  1. Add the following code under the //TODO: 7.1.5 comment to define the IsNotificationEnabled property.

C#

public bool IsNotificationEnabled

{

get

{

if (settings.Contains(Constants.IS_NOTIFICATION_ENABLED))

{

return (bool)settings[Constants.IS_NOTIFICATION_ENABLED];

}

else

{

settings.Add(Constants.IS_NOTIFICATION_ENABLED, false);

return false;

}

}

set

{

if (settings.Contains(Constants.IS_NOTIFICATION_ENABLED))

{

settings[Constants.IS_NOTIFICATION_ENABLED] = value;

}

else

{

settings.Add(Constants.IS_NOTIFICATION_ENABLED, value);

}

if (value == true)

{

EnableNotifications();

}

else

{

DisableNotifications();

}

UpdateNotificationBindings();

RaisePropertyChanged("IsNotificationEnabled", this, PropertyChanged);

}

}

The IsNotificationEnabled property is persisted in isolated storage. This value is bound to the Settings.xaml view. When the user enables or disables notifications in the user interface or when the application starts the IsNotification value is set and the code will set the correct bindings. When the end user opts to enable notifications,the property configures the notifications on the phone..

  1. Add the following code under the //TODO: 7.1.6 comment to define the SettingsViewModelcontstructor.

C#

public SettingsViewModel()

{

if (current != null)

{

throw new InvalidOperationException("Only 1 SettingsViewModel Allowed");

}

settings = IsolatedStorageSettings.ApplicationSettings;

current = this;

}

The above code creates the view model and sets the current variable to the newly created object. This creates our singleton object.

  1. Add the following code under the //TODO: 7.1.7 comment to define the EnableNotifications method.

C#

public void EnableNotifications()

{

Channel = HttpNotificationChannel.Find(Constants.CHANNEL_NAME);

if (Channel == null)

{

Channel = new HttpNotificationChannel(Constants.CHANNEL_NAME);

Channel.ChannelUriUpdated += new

EventHandler<NotificationChannelUriEventArgs>(Channel_ChannelUriUpdated);

Channel.Open();

}

else

{

Channel.ChannelUriUpdated += new

EventHandler<NotificationChannelUriEventArgs>(Channel_ChannelUriUpdated);

ChannelUri = Channel.ChannelUri;

UpdateNotificationBindings();

}

}

The above code will attempt to find an existing HTTPNotificationChannel. The HTTPNotificationChannel object contains information about the persistant channel between the application, the phone OS and the Microsoft Push Notification service. Channels are defined using a channel name. The application will create a new channel if an existing channel is not found. Once there is a channel available, the code will update the notification bindings by calling UpdateNotificationBindings.

  1. Add the following code under the //TODO: 7.1.8 comment to define the RegisterWithNotificationSource method.

C#

internal void RegisterWithNotificationSource(Uri channelUri)

{

var svc = new NotificationRegistration.ListNotificationChannelsClient();

svc.RegisterAsync(channelUri.ToString(), Constants.LIST_ID);

}

The above code will use the service proxy created by Visual Studio to register the device’s channel URI with the NotificationRegistration WCF service after the application has a channel. The registration service tracks which notification channels (device) are listening to notifications. In this application, the registration service tracks the channel Uri and an associated list id.

  1. Add the following code under the //TODO: 7.1.9 comment to define the UpdateNotificationBindings method.

C#

private void UpdateNotificationBindings()

{

if (IsNotificationEnabled)

{

if (Channel != null & !Channel.IsShellToastBound)

{

Channel.BindToShellToast();

}

}

else

{

if (Channel.IsShellToastBound)

{

Channel.UnbindToShellToast();

}

}

}

The above code will bind or unbind the device to the toast notifications. When bound, this code alerts the phone that it is listening for toast notifications. When not bound to the toast notifications the phone will not display a toast notification sent from the Push Notification Service. Developers do not have access to modify the toast displayed by the phone. When bound to the toast notification the user interface will display a toast with the text sent in the Xml payload.