It's ok. Be different.

Setting up push notifications for your SharePoint Windows Phone app is fairly straight-forward. Push notifications with SharePoint uses the same Microsoft Push Notification Service (MSPNS) to create a communications channel from the server to the device. The following code sets up an MSPNS channel:

If a channel hasn't yet been created, then we create it, add event handlers for events that we need to handle and then open the channel. The event handler ShellToastNotificationReceived is used so that we can handle the notification while the app is running. If the app is not running, the toast will be handled automatically by calling BindToShellToast().

When MSPNS has created a channel and assigned it a URI, we need to then create a notification subscription in SharePoint:

First we check to see if the notification subscriber already exists. Subscriptions are stored in a list in SharePoint called PushNotificationSubscriptionStore. This is a hidden list that you can't get to through the UI; however, it does show up in the ListData.svc OData service. To see what fields are in the list, review the service's metadata (ex/ http://mobile-apps.fabrikam.com/sites/Team%20Site/_vti_bin/listdata.svc/$metadata). This list contains PushNotificationSubscriptionStoreItem items. The DeviceIdentifier field is what you can use to store the GUID that was generated for the device/app and the ServiceToken field should be used to store the channel URI. Also note that you should probably come up with distinct SubscriberType values. Since all of these notification subscriptions are stored in a single list, this is the simplest way for you to distinguish which notification to send for each application notification. Once these fields are set, we use ClientContext.ExecuteQueryAsync() to save the values. One other thing to mention, don’t forget to activate the Push Notifications site feature on the site where you’ll be using push notifications (this should actually be the first thing you do).

To handle unregistering for the push notification, you need to unregister the notification subscription from SharePoint:

Once this is ready, then on the server, all you have to do is to find all the notification subscribers that you need to send a notification to and send the notification out using the same code you'd normally use to send push notifications out to other Windows Phone apps. For this app, I decided to handle this in an Event Receiver and send notifications out when an item is added or updated in the Products list:

Note that it's probably not a good idea to do a foreach loop over the SPPushNotificationSubscriberCollectionif there's going to be thousands of items in that list. I did this for the sake of simplicity. Also, LINQ to SharePoint won't work on this list. The only way you might be able to do a more efficient filtering is through a CAML query, though I didn't test this.

Once this feature is installed and the user has registered for push notifications in this app, the results look like this:

One thing to be aware of is that with Windows Phone apps, there's no event notification for when your app is uninstalled. Given this, you probably need some way to determine on the server if a notification subscription should be deleted (if it hasn't been used in a while). Otherwise, you might be flooding MPNS with attempts to send a notification to a channel that is no longer accessible.

If you want the full source code to this, please tweet a link to this post and then send me an email (bart.tubalinal at deviantpoint dot com). I will then email you the source code for both the phone app project and the event receiver project.

With SharePoint 2013, Microsoft has included a set of Windows Phone assemblies that will allow you to quickly build native Windows Phone applications that can communicate and interact with data in SharePoint. The two assemblies you need to reference in your WP application are Microsoft.SharePoint.Client.Phone and Microsoft.SharePoint.Client.Phone.Runtime. Both assemblies are located in C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\TEMPLATE\LAYOUTS\ClientBin.

Authentication to the SharePoint site is handled using the Authenticator class. Windows Phone apps with SharePoint supports four authentication modes: Windows Authentication (Default), Forms Authentication, Anonymous, and using Microsoft Online. I have not tested the Microsoft Online-based Authentication but I believe it's used in conjunction with the Microsoft.SharePoint.Client.BrowserLogin class (in the Runtime assembly), which is an application page that will load when using this type of authentication.

For Windows Authentication, note that either Forefront UAG must be used or the web application must be configured to use Basic Authentication.

The following is an example of retrieving data from a SharePoint list:

If you've done any coding with CSOM or the SharePoint Javascript object model, the above code should be very familiar. It uses the same classes like ClientContext, Site, Web, etc to interact with SharePoint. Like all Windows Phone apps, requests must be done asynchronously to prevent locking the UI thread – which means you need to use ExecuteQueryAsync instead of ExecuteQuery or you will get an Exception.

The important part of the code is that the ClientContext.Credentials is set to an instance of the Authenticator class.

Again, this handler is typical of what you would use with CSOM/JavaScript. When this handler executes, we need to move back to the UI thread to add these items and for it to display in our view. That's what the line currentDispatcher.BeginInvoke(() => {}) is for.

When the code executes, this is what the Phone app looks like:

This data is being pulled from a SharePoint list:

With Windows Phone apps, there is full support for CRUD operations on list data. This also includes external lists. There is also support for push notifications, which I'll cover in the next blog post. I’ll also be sharing the full source code for this little app in the next post.

Intro

This is the third post in a series that shows how to use Windows Azure as a platform that provides key services for native mobile applications. In the first two parts of the series, I walked through the process of creating my SpeakEasy app, a fictitious iPhone app that keeps track of speakers and their events.

In this post, I will walk through how to use the Azure AppFabric Access Control Service (ACS). ACS is a service that provides federated authentication using claims. ACS provides support for different identity providers, including Facebook, Windows Live, Google, Yahoo!, and ADFS 2.0 (and other WS-Federation identity providers). In this scenario, I will be using Facebook as an identity provider. Rather than force the user to log in using their Facebook account right away, I will only ask the user to log in when they want to share the details of an event on their Facebook wall. When they attempt to share the event, they will first have to log in using their Facebook account and then, by using the token received from Facebook (which will be provided as a claim), I will show how to post a message on the user's wall.

Facebook Application Setup

In the Create New App dialog, enter an appropriate name and the optional namespace. I have configured my application with the following settings:

App Name: SpeakEasy iPhone App from DeviantPoint

App Namespace: speakeasy-dp.

This is optional but if you want to use Facebook’s Open Graph to post different Actions and define custom Object Types, you’ll need a namespace (I presume to prevent naming collisions).

After you have agreed to the Facebook Platform Policies agreement and clicked the Continue button, you will be taken to your app’s settings page. On this page are two very important pieces of information: the App ID and App Secret. Make a copy of both values as this will be used later on in the ACS setup. The rest of the application configuration is as follows:

This is the URL that Facebook will redirect to after the user has successfully logged in. While you’re debugging your application, it’s ok to configure this section and set the URL to your Azure ACS service namespace URL (details in following section). However, when you’ve published your app to the App Store, you’ll want to delete this section and then configure the Native iOS App section correctly to point to your app in the app store.

ACS Setup

Configuring a Service Namespace

Log in to the Azure Management Portal and go to the Service Bus, Access Control & Caching section.

Select Services > Access Control from the left pane and click on the New menu item from the ribbon. My Service Namespace configuration looks like this:

The end result of this will be an ACS URL for my namespace: https://speakeasy.accesscontrol.windows.net.

Once the Service Namespace has been created, you will be redirected to the Access Control Service management portal for your new namespace.

Configuring Facebook as an Identity Provider

The next step is configuring your Identity Providers (idP). In this example, we’ll only be using Facebook as our idP. However, you can configure multiple idPs to allow your users to log in using different idP services, like Facebook, Google, Yahoo, Windows Live, and ADFS 2.0.

Click on the Identity Providers link under Trust Relationships in the left pane.

Application ID: this is one of the values that you should have copied from the Facebook Application Setup. Enter that value here.

Application secret: this is one of the values that you should have copied from the Facebook Application Setup. Enter that value here.

Application permissions:email, publish_stream

The application permissions field is used to tell Facebook what permissions your app will need. The email is given by default. The publish_stream permission will allow our app to post on the user’s behalf on his/her newsfeed. Here is a list of all application permissions you can request.

Click Save.

Configuring a Relying Party Application

The next step is to configure a relying party application. A relying party application is an application that trusts the identity provider and consumes the claims made by that identity provider about the user.

Click on the Relying party applications under Trust Relationships in the left pane.

Click on the Add link.

The following are the configuration settings I used for my relying party application:

Name: speakeasy.deviantpoint.com

Mode: manual

Realm: uri:speakeasy.deviantpoint.com

Return URL:empty

Normally, this is where ACS will redirect your application to after the user has successfully logged in. Since we’re building a native iPhone app, this setting isn’t needed. However, it is sometimes still a good idea to set this to a web page that you’ve built that can take the incoming claims and do something with them. I like to set this to a page on my site where I have some code to read the incoming claims so that I am able to look at them in case I need to debug something.

Error URL: empty

Token Format:SWT

This setting is important. Originally, I had this set to SAML 2.0 but I realized after some debugging efforts that the Windows Azure Toolkit for iOS is expecting the format to be SWT (Simple Web Token).

Token Encryption Policy: None

Token Lifetime: 600 (secs)

Identity Providers: Facebook

Rule Groups: Create New Rule Group

Token Signing: Use Service Namespace Certificate

Click Save.

Configuring Rule Groups

Rule Groups determine how incoming claims from the identity provider are mapped to output claims delivered to the relying party application.

Click on Rule groups under Trust Relationships in the left pane.

Click the Generate link and select the Facebook identity provider.

Clicking the Generate link will create a default set of rules for the identity provider. ACS is smart enough to tell a standard set of claims that most of the idPs provide. If the idP provided more claims than what was generated, then you can add those claims as well. Similarly, if there are claims that your relying party application doesn’t need, you can remove them as well.

Assuming you’ve set up the Facebook application and ACS (identity provider, relying party application, and rule groups) correctly, then you should be able to use the link to an ACS-hosted login page, found in the Application Integration section under Development in the left pane, to test the process. Note that unless you configured a Return URL for the Relying Party Application, you will get an ACS50011: The RP ReplyTo address is missing.’ error. It’s probably best to configure a Return URL at first for testing purposes to make sure your setup is correct.

Using ACS in the iPhone App

Modifying the Windows Azure iOS Toolkit

Now that the set up is complete, we can start to use ACS in the SpeakEasy app – except for one little detail: if you downloaded the iOS toolkit from the Master branch on Github, the toolkit currently filters out any claims that don’t start with a prefix of ‘http://schemas.xmlsoap.org/ws/2005/05/identity/claims/’. Fortunately, you have two options. The first option is to download the toolkit from the Develop branch. This branch removes the check for this prefix and just passes any claims through. The second option is to just modify the source code yourself. This is the option I took since I wasn’t sure exactly what other changes have been made to the Develop branch and I didn’t want to introduce any unknowns.

If you’re modifying the source code, find the file WACloudAccessToken.m. Around line 80, you will see the following code:

UI Changes

Now that the Toolkit is ready, we want to add the ability for the user to post an event’s details to his Facebook newsfeed. The easiest place to start is to make changes to the user interface,

Storyboard Changes

Open up the MainStoryboard.storyboard file and find the Event Details view.

From the Object library, drag a Bar Button Item to the navigation bar.

Select the Bar Button Item and change the Identifier to Action in the Attributes Inspector.

Add a View Controller from the Object library to the Storyboard.

Select the View Controller and change the Top Bar to Navigation Bar and the Bottom Bar to Tab Bar.

Change the Navigation Item’s title to Post to Facebook.

Add a Text View and a Round Rect Button from the Object library to the new view.

Resize the Text View to be about 1/3 of the height of the view and almost the full width.

Change the text of the button to Post!.

CTRL+Drag from the Event Details View Controller to the Post to Facebook View Controller.

Select Push for the Segue type.

Set the segue identifier to PostToFacebookSegue.

The new part of the storyboard should now look like this:

PostToFacebookViewController

Now we need a custom view controller that will interact with the new Post To Facebook view.

From the Project navigator, right-click the ViewControllers group and select New File.

Select the UIViewController subclass template and click Next.

Name the class PostToFacebookViewController as a subclass of UIViewController.

Click Next a few times until the .h and .m files are created.

Open the .h file and add #import statements for SEEvent.h and WACloudAccessToken.h.

Add the following code to the interface definition:

1: @property(nonatomic, retain) WACloudAccessToken *acsToken;

2: @property(nonatomic, retain) SEEvent *event;

3: @property(nonatomic, retain) IBOutlet UITextView *messageTextView;

4:

5: -(IBAction)postMessage:(id)sender;

The WACloudAccessToken is a class from the Windows Azure iOS Toolkit that represents an ACS access token.

The IBAction postMessage: is the action that will be called when the Post! button is pushed by the user. Synthesize the properties in the .m file and connect the two outlets to their interface counterparts in the storyboard. Add the postMessage: method to PostToFacebookViewController.m but just leave the implementation blank for now.

EventDetailsViewController

Now we need to add code to handle transitioning from the Event Details View to the Post To Facebook View. To do this, we need to modify the EventDetailsViewController.

Open EventDetailsViewController.hand add the following field:

WACloudAccessControlClient *_acsClient;

Add the following method:

-(IBAction)shareButtonPressed:(id)sender;

This method is the event handler for when the user clicks on the Action button we added in the storyboard for this view.

The above code is where we use the WACloudAccessControlClient class provided by the iOS Azure toolkit to create a client we can use to hit the ACS service. The namespace and realm passed in are the namespace/realm that was configured as part of the ACS setup.

Modify the prepareForSegue:sender: method so it looks like the following:

In the above code, we just add a new condition for the new segue we added. If the segue we’re trying to perform is the segue to move to the Facebook view, then we pass the event and the access token (which is available from the WACloudAccessControlClient after the user has successfully signed in) to that view.

Finally, to handle the Action button being clicked, add this method to the bottom of the file:

This method calls the showInViewController:allowsClose:withCompletionHandler method on the WACloudAccessControlClient instance. When the method runs after the button is clicked, the facebook login screen will be shown to the client:

After the user has successfully logged in, the completion handler code will run which basically checks to see if the user is logged in and if so, performs the segue to the Post To Facebook view.

Handling the segue to PostToFacebookViewController

In PostToFacebookViewController.m, add the following to viewDidLoad to add a default message to the Text View in the view:

In the first line of this method, I retrieve the Facebook access token that is returned to me as a claim from Facebook after a successful login. The claims property of the WACloudAccessToken is a collection of all the claims that were passed through from the idP to the relying party application.

The rest of the lines are just used to create a POST request to Facebook. Any requests made to Facebook needs to include the access token (passed in as the access_token parameter). The message parameter is the actual text that will be posted to the feed, which must be URL-escaped.

If the post is successful, then I just navigate back to the details view (I didn’t any any error-handling in this example). A successful post to Facebook looks like this:

Conclusion

That’s really all to using ACS from an iPhone app using the Windows Azure Toolkit for iOS. Like I mentioned earlier, you can use ACS for your app’s authorization and authentication needs with other, multiple idPs. This is an especially low barrier-of-entry for apps that need to use Active Directory by taking advantage of ADFS through ACS.

I hope you enjoyed this post. If you have any questions, ask them in the comments section and I’ll try to answer them as best as I can. For the next part of the series, I will cover using Azure to send push notifications.