This topic has not yet been rated - Rate this topic

Step 3: Create a mobile app and register for push notifications

apps for SharePoint

Learn how to create a companion mobile app for an app for SharePoint by using the Windows Phone SharePoint List Application template.

Last modified: October 31, 2013

Applies to: SharePoint Server 2013 Enterprise

In this article
Prerequisites for creating a companion mobile app
Create a companion mobile app for an app for SharePoint
Add push notifications to a companion Windows Phone app for SharePoint
Additional resources

This is the third article in a three-part series that shows how to create a companion mobile app for SharePoint. For more information, see How to: Create a companion mobile app for an app for SharePoint.

In this step, you create a companion Windows Phone app by using the Windows Phone SharePoint List Application template (for the app for SharePoint created in Step 1: Create a list-based autohosted app in SharePoint 2013) and register your mobile app to receive push notifications.

You create a Windows Phone app from the Windows Phone SharePoint List Application template, specifying the appWebUrl for your app for SharePoint. In this procedure, you have a single list in your app for SharePoint (created in Step 1: Create a list-based autohosted app in SharePoint 2013). If you have multiple lists in your app, see How to: Use multiple SharePoint 2013 lists in a Windows Phone app for more information.

After you create the mobile app, you can develop a Notifications class for subscribing to push notifications, implementing handlers for notification events, and storing information related to notifications on the phone. You also add a XAML page to your app with controls to allow users to register or unregister for push notifications.

The appWebUrl is the URL of the app for SharePoint. The format of this URL is https://<name of your developer site>.GUID.sharepoint.com/<SharePoint app name>. In this procedure, we used an autohosted app for SharePoint and deployed it on Office 365.

To complete these steps, you need the following:

Core concepts to know for creating a companion mobile app

Before completing these steps, you should have a basic understanding of the concepts in Table 1.

Table 1. Core concepts for mobile apps

Article title

Description

Overview of Windows Phone SharePoint 2013 application templates in Visual Studio

Learn about the Visual Studio templates installed by the Windows Phone SharePoint Software Development Kit for mobile app development.

http://msdn.microsoft.com/en-us/library/office/jj163784.aspx#BKMK_NotificationPhoneApp

Learn how to develop a Windows Phone app for receiving the push notifications.

In this section, you create a mobile companion Windows Phone app by using the Windows Phone SharePoint List Application template. The mobile companion app is used by technicians to view and edit the tasks that are assigned to them and to get push notifications when new tasks are assigned to them. This app uses the list created in Step 1: Create a list-based autohosted app in SharePoint 2013 as the target list. This procedure is similar to creating a Windows Phone SharePoint list app. For more information, see How to: Create a Windows Phone SharePoint 2013 list app. The difference is the URL you provide in the SharePoint Phone Application wizard in Visual Studio. You need an appWebUrl to create your companion mobile app.

To create a mobile app

  1. Start Visual Studio by using the Run as Administrator option.

  2. Choose File, New, Project.

    The New Project dialog box appears.

  3. In the New Project dialog box, expand the Visual C# node, and then choose the Silverlight for Window Phone node. (Ensure that the target .NET Framework version is set to 4.)

    Note Note

    The templates installed by the Windows Phone SharePoint SDK work only in C# projects. The templates are not available for Visual Basic projects.

  4. In the Templates pane, choose the Windows Phone SharePoint List Application template, and give the project a name, such as SupportCenterCompanionPhoneApp.

  5. Choose the OK button. The SharePoint Phone Application Wizard appears. You use this wizard to choose a SharePoint list within your SharePoint app and configure properties of that list to determine how it appears in your Windows Phone app.

  6. Specify the appweburl URL of your SharePoint app created in Step 1: Create a list-based autohosted app in SharePoint 2013, as shown in Figure 1. The wizard prompts you to enter your SharePoint credentials for the target SharePoint site on your network (that is, an on-premises installation of SharePoint Server).

    Figure 1. SharePoint Phone Application wizard - Step 1

    SharePoint Phone Application Wizard Step1
  7. Choose Find Lists. If the account under which you are running Visual Studio has access to the specified target developer site and the SharePoint app, the SharePoint Phone Application Wizard displays the lists that are available in that app for SharePoint.

  8. Choose Cases from the list of available lists in the app for SharePoint created in Step 1: Create a list-based autohosted app in SharePoint 2013.

  9. Choose Next. The wizard displays the available views associated with the selected list. Here you can choose all the available views on the list.

  10. Select the check box next to each view you want to include in your Windows Phone app.

  11. Choose Next. The wizard displays the available operations for the selected list in your Windows Phone app.

  12. Choose Display and Edit operations at this step. The technicians are using the mobile companion Windows Phone app only to view and edit the cases assigned to them.

  13. Choose Next. The wizard gives you the opportunity to order the fields you selected in the previous step.

  14. Order the fields according to your needs by selecting individual fields and moving them higher or lower in the order by choosing the up or down arrows.

  15. Choose Finish. Visual Studio creates the necessary files for the project and opens the List.xaml file for editing.

    Note Note

    The Windows Phone list-based app can authenticate against SharePoint Online for the first time, but it may fail to authenticate for the second time and display a server error at run time. To overcome this error, enable cookie caching (at.CookieCachingEnabled = true;) before passing the Authenticator object to clientContext.Credentials, as shown in the following code, which appears in the ListDataProvider.cs file generated by Visual Studio.

    public override ClientContext Context
        {
            get
            {
                if (m_Context != null)
                    return m_Context;
    
                m_Context = new ClientContext(SiteUrl);
    
                Authenticator at = new Authenticator();
                // To avoid re-authentication error
                at.CookieCachingEnabled = true;
                // In case of Microsoft Online federated authentication, set ADFS authentication scheme preference for passive authentication
                // Example, to set client preference for SAML 2.0 username-password authentication scheme: 
                // at.FederationPassiveAuthUri = "urn:oasis:names:tc:SAML:2.0:ac:classes:Password"; 
                m_Context.Credentials = at;
    
                return m_Context;
            }
        }
    

The basic working version of your companion app is ready at this point. Visual Studio creates all the code that is needed to run the app. You can always enhance the app so that it can perform more complicated tasks. For more information, see Build mobile apps for SharePoint 2013.

In this section, you create the necessary .cs files to enable push notifications on your companion mobile app. You develop a Notifications class for subscribing to push notifications, implementing handlers for notification events, and storing information related to notifications on the phone. You also add a XAML page to your app with controls to allow users to register or unregister for push notifications.

To follow the procedures in this section, first perform the steps in Create a companion mobile app for an app for SharePoint to create a Visual Studio project from the Windows Phone SharePoint List Application template, using the Cases list created in the preceding section as the target SharePoint list for the project. The procedures in this section assume that the name of the project is SupportCenterCompanionPhoneApp.

To create the class for managing subscriptions and received notifications

  1. In Solution Explorer, choose the node that represents the project (named SupportCenterCompanionPhoneApp).

  2. On the Project menu, choose Add Class. The Add New Item dialog box appears with the C# Class template already selected.

  3. Specify Notifications.cs as the name of the file, and choose Add. The class file is added to the solution and opened for editing.

  4. Replace the contents of the file with the following code.

    using System;
    using System.Net;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Documents;
    using System.Windows.Ink;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Animation;
    using System.Windows.Shapes;
    using Microsoft.Phone.Notification;
    using Microsoft.SharePoint.Client;
    using System.Collections.Generic;
    using Microsoft.Phone.Shell;
    using System.IO;
    using System.Diagnostics;
    using System.IO.IsolatedStorage;
    
    namespace SupportCenterCompanionPhoneApp
    {
        public class Notification
        {
            #region Static properties and Fields
    
            private static HttpNotificationChannel HttpChannel
            {
                get;
                set;
            }
    
            private static ClientContext Context
            {
                get
                {
                    return App.DataProvider.Context;
                }
            }
    
            private static string DeviceAppIdKey = "DeviceAppIDKey";
    
            private static string ChannelName = "SupportCenterNotificationChannel";
    
            #endregion
    
            public static void SubscribeDeviceForNotification()
            {
                //Get Existing Channel
                HttpChannel = HttpNotificationChannel.Find(ChannelName);
    
                // If Channel is Found and is connected
                if (HttpChannel != null && HttpChannel.ConnectionStatus == ChannelConnectionStatus.Connected)
                {
    
                    HttpChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(OnChannelUriUpdated);
                    HttpChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(OnHttpChannelExceptionOccurred);
    
                    //Subscribe to SharePoint for receving Push Notification
                    SubscribeToSharePointNotificationService();
                }
                else
                {
                    //create a new channel
                    HttpChannel = new HttpNotificationChannel(ChannelName);
    
                    //Register for callback when Channel is opened
                    HttpChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(OnChannelUriUpdated);
                    HttpChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(OnHttpChannelExceptionOccurred);
    
                    try
                    {
                        //Open HttpChannel for Notification Service
                        HttpChannel.Open();
                    }
                    catch (Exception) { }
                }
            }
    
            /// <summary>
            /// Subscribes device for Receiving Push Notifications from SharePoint.
            /// </summary>
            private static void SubscribeToSharePointNotificationService()
            {
                Context.Load(Context.Web, w => w.Title, w => w.Description);
    
                //Ensure device ID is created and saved to IS
                Notification.SaveDeviceAppIdToIS();
                //Get device-app unique ID
                Guid deviceAppInstanceId = GetSettingValue<Guid>(DeviceAppIdKey);
    
                PushNotificationSubscriber Regsubscriber = Context.Web.RegisterPushNotificationSubscriber(deviceAppInstanceId, HttpChannel.ChannelUri.AbsoluteUri);
    
                Context.ExecuteQueryAsync(
                        (object sender, ClientRequestSucceededEventArgs args) =>
                        {
                            ShowMessage("Subscriber successfully Registered for Notifications");
                        },
                        (object sender, ClientRequestFailedEventArgs args) =>
                        {
                            ShowMessage("Subscriber failed to register");
                        });
            }
    
            /// <summary>
            /// On Channel Uri updation, subscribes to SharePoint for receiving Push Notifications
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private static void OnChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
            {
                try
                {
                    if (!HttpChannel.IsShellToastBound)
                        HttpChannel.BindToShellToast();
    
                    SubscribeToSharePointNotificationService();
                }
                catch (Exception)
                {
                    //Catch exception here
                }
            }
    
            private static void OnHttpChannelExceptionOccurred(object sender, NotificationChannelErrorEventArgs e)
            {
                Debugger.Break();
            }
    
    
            #region Utility methods
    
            /// <summary>
            /// Save Device ID to Phone Isolated Storage
            /// </summary>
            private static void SaveDeviceAppIdToIS()
            {
                if (!IsolatedStorageSettings.ApplicationSettings.Contains(DeviceAppIdKey))
                {
                    Guid DeviceAppId = Guid.NewGuid();
                    SetSettingValue<Guid>(DeviceAppIdKey, DeviceAppId);
                }
            }
    
            /// <summary>
            /// Show Error message on UI thread.
            /// </summary>
            /// <param name="message"></param>
            private static void ShowMessage(string message)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    //MessageBox.Show(message);
                });
            }
    
            private static void SetSettingValue<T>(string key, T value)
            {
                if (IsolatedStorageSettings.ApplicationSettings.Contains(key))
                    IsolatedStorageSettings.ApplicationSettings[key] = value;
                else
                    IsolatedStorageSettings.ApplicationSettings.Add(key, value);
    
                IsolatedStorageSettings.ApplicationSettings.Save();
            }
    
            private static T GetSettingValue<T>(string key)
            {
                if (IsolatedStorageSettings.ApplicationSettings.Contains(key))
                    return (T)IsolatedStorageSettings.ApplicationSettings[key];
                else
                    return default(T);
            }
    
            #endregion
        }
    }
    
  5. Save the file.

In this code, the OpenNotificationChannel creates a notification channel for receiving notifications from MPNS. Event handlers are attached to the channel object for dealing with notification events, and then the channel is opened. In this example, the HttpNotificationReceived event (for receiving raw notifications) is implemented. Raw notifications can be received only when the phone app is running. The handler for the ShellToastNotificationReceived event (for receiving toast notifications) is also implemented here to demonstrate its use. Tile notifications can be received only when the subscribing phone app is not running, so there's no need to implement an event handler in the app for receiving tile notifications.

The SubscribeToService method executes the RegisterPushNotificationSubscriber method of the SPWeb object asynchronously (passing a value to identify the phone app and a URI value associated with the notification channel) to register with the SharePoint server to receive push notifications. If the registration is successful, the Windows Phone shell is set to receive (and display) toast and tile notifications on the particular notification channel registered with the SharePoint server when the phone app itself is not running.

The UnSubscribe method in this code calls the UnregisterPushNotificationSubscriber method of the SPWeb object. The development guidelines for Windows Phone apps recommend that users be allowed to choose whether to subscribe to push notifications or not. In a later procedure, you will add a mechanism for the user to register or unregister for notifications. That registration state is preserved between sessions of the app, making it unnecessary to ask the user to register every time the app is started. The GetRegistrationStatus method is made available so that the phone app can determine whether the user has registered (in an earlier session) to receive push notifications and the notification channel is subsequently opened. The SaveDeviceAppIdToStorage saves the identifier (represented as a GUID) for the app instance on a given Windows Phone to isolated storage.

The ClearSubscriptionStore method is included here as a demonstration of one way of clearing the subscribers from the subscription store on the SharePoint Server. Subscribers to push notifications are stored in a SharePoint list named "Push Notification Subscription Store". A button for calling this method of the Notifications class is added to the notifications settings page and is added to the app in a later procedure.

The operations that involve accessing the SharePoint server to configure settings or prepare for notifications (such as the RegisterPushNotificationSubscriber method) can take time to complete, depending on the conditions of the network and the availability of the server. These operations are therefore executed asynchronously (specifically, by using the ExecuteQueryAsync method of a ClientContext object) to allow the app to continue other processes and to keep the UI responsive to the user.

To convert the customer address field to map with Bing Maps, add the following code at the end of the autogenerated code in the DisplayForm.xaml.cs file in the Views folder.

private void txtCustomerAddress_Click_1(object sender, RoutedEventArgs e)
        {
            BingMapsTask task = new BingMapsTask();
            task.SearchTerm = viewModel["CustomerAddress"].ToString();
            task.Show();
        }

When you add an item to the Cases list in your app for SharePoint list, the code in the event receiver associated with the list tries to send notifications using MPNS to subscribed phones. But, depending on network conditions and other factors, a given notification may not be received by a phone. You can look at the Notification list on the server, especially the values in the Status Code and Headers columns, to determine the status and results related to individual notifications.

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.