Introduction to Building Windows Store Apps with Windows Azure Mobile Services Overview In this HOL you will learn how you can leverage Visual Studio 2012 and Windows Azure Mobile Services to add structured storage, push notifications and integrated authentication to your Windows Store applications. Objectives Create a Windows Azure Mobile Service Use the Windows Azure Mobile Services SDK Learn how to Insert, Update, Read and Delete rows from a Mobile Service Add Push Notifications to your application Lock down your Mobile Service such that only authenticated users can consume it Prerequisites Windows Azure subscription with Mobile Services preview enabled - Create a Windows Azure account and enable preview features Visual Studio 2012 Exercises This hands- on lab includes the following exercises: 1. Creating your first Mobile Service 2. Adding Push Notifications to your app 3. Adding Auth to Your App and Services Exercise 1: Creating your first Mobile Service This exercise shows you how to add a cloud- based backend service to a Windows 8 app using Windows Azure Mobile Services. You will create both a new mobile service and a simple To do list app that stores app data in the new mobile service.
A screenshot from the completed app is below: Task 1- Create a new mobile service Follow these steps to create a new mobile service. 1. Log into the Windows Azure Management Portal and navigate to Mobile Services 2. Click the +New button then click Mobile Service, Create 3. Expand Mobile Service, then click Create This displays the New Mobile Service dialog. 4. In the Create a mobile service page, type a subdomain name for the new mobile service in the URL textbox and wait for name verification. Once name verification completes, click the right arrow button to go to the next page. This displays the Specify database settings page. Note: As part of this tutorial, you create a new SQL Database instance and server. You can reuse this new database and administer it as you would any other SQL Database instance. If you already have a database in the same region as the new mobile service, you can instead chooseuse existing Databaseand then select that database. The use of a database in a different region is not recommended because of additional bandwidth costs and higher latencies. 5. In Name, type the name of the new database, then type Login name, which is the administrator login name for the new SQL Database server, type and confirm the password, and click the check button to complete the process. Note: When the password that you supply does not meet the minimum requirements or when there is a mismatch, a warning is displayed. We recommend that you make a note of the administrator login name and password that you specify; you will need this information to reuse the SQL Database instance or the server in the future. You have now created a new mobile service that can be used by your mobile apps. You have now created a new mobile service that can be used by your mobile apps. Task 2 - Create a new app Once you have created your mobile service, you can follow an easy quick start in the Management Portal to either create a new Windows Store app or modify an existing app to connect to your mobile service.
1. In the Management Portal, click Mobile Services, and then click the mobile service that you just created. 2. In the quickstart tab, expand Create a new Windows 8 application. This displays the three easy steps to create a Windows 8 app connected to your mobile service. 3. If you haven't already done so, download and install Visual Studio 2012 Express for Windows 8 and the Mobile Services SDK on your local computer or virtual machine. This downloads the project for the sample To do list application that is connected to your mobile service. Save the compressed project file to your local computer, and make a note of where you save it. Task 3 - Run your app 1. Browse to the location where you saved the compressed project files, expand the files on your computer, and open the solution file in Visual Studio 2012 Express for Windows 8. 2. Press the F5 key to rebuild the project and start the app. 3. In the app, type meaningful text, such as Complete the demo, in the Insert a TodoItem textbox, and then click Save. This sends a POST request to the new mobile service hosted in Windows Azure. Data from the request is inserted into the TodoItem table. Items stored in the table are returned by the mobile service, and the data is displayed in the second column in the app. Note: You can review the code that accesses your mobile service to query and insert data, which is found in either the MainPage.xaml.cs file (/XAML project) or the default.js (JavaScript/HTML project) file. 4. Back in the Management Portal, click the Data tab and then click the TodoItems table and observe that the data as been successfully stored This lets you browse the data inserted by the app into the table. Task 4 - Explore your app code In this step we explore To do list application code and see how simple the Windows Azure Mobile Services Client SDK makes it to interact with Windows Azure Mobile Services. 1. Return to the downloaded To do list application Visual Studio 2012
2. In solution explorer expand the references folder and show the Windows Azure Mobile Services Client SDK reference. Note: You may also add references to the Windows Azure Mobile Services Client SDK from any Windows Store app. Using the Add reference dialog 3. Open App.xaml.cs and show the MobileServiceClient class. This is the key class provided by the Mobile Services client SDK that provides a way for your application to interact with Windows Azure Mobile Services. The first parameter in the constructor is the Mobile Service endpoint and the second parameter is the Application Key for your Mobile Service. public static MobileServiceClient MobileService = new MobileServiceClient( "https://cloudnick.azure-mobile.net/","viwepmcoxgpsycjqddcfbksnovxzlg52" ); 4. Open MainPage.xaml.cs to observe how the mobile service client is then used for Inserts, Updates, Reads and Deletes: The source creates a handle for operations on a table private IMobileServiceTable<TodoItem> todotable = App.MobileService.GetTable<TodoItem>(); Performs an Insert private async void InsertTodoItem(TodoItem todoitem) await todotable.insertasync(todoitem); items.add(todoitem); o Performs an Update
private async void UpdateCheckedTodoItem(TodoItem item) await todotable.updateasync(item); items.remove(item); o Performs a Read private void RefreshTodoItems() items = todotable.where(todoitem => todoitem.complete == false).tocollectionview(); ListItems.ItemsSource = items; 5. As an extension see if you can update the UpdateCheckedTodoItem method to perform a delete rather then update operation using the todotable.deleteasync(...) method Exercise 2: Register your apps for Facebook authentication with Mobile Services This topic shows you how to register your apps to be able to use Facebook to authenticate with Windows Azure Mobile Services. Note To complete the procedure in this topic, you must have a Facebook account that has a verified email address and a mobile phone number. To create a new Facebook account, go to facebook.com. Task 1 Create Facebook App 1. Navigate to the Facebook Developers web site and sign- in with your Facebook account credentials. 2. (Optional) If you have not already registered, click Register Now button, accept the policy, provide any and then click Done.
3. Click Apps, then click Create New App. 4. Choose a unique name for your app, select OK.
This registers the app with Facebook 5. Under Select how your app integrates with Facebook, expand Website with Facebook Login, type the URL of your mobile service in Site URL, and then click Save Changes. 6. Make a note of the values of App ID and App Secret. Task 2 - Add authentication 1. Modify Identity section of your mobile service, you must add App ID and App Secret in Facebook Section and save it. Task 3 - Add authentication 2. Download and install the Windows Azure Mobile SDK for Windows 3. Open the project file mainpage.xaml.cs and add the following using statements
using Windows.UI.Popups; 4. Add the following code snippet that creates a member variable for storing the current Facebook Connect session and a method to handle the authentication process: private MobileServiceUser user; private async System.Threading.Tasks.Task Authenticate() while (user == null) string message; try user = await App.MobileService.LoginAsync(MobileServiceAuthenticationProvider.Facebook); message = string.format("you are now logged in - 0", user.userid); catch (InvalidOperationException) message = "You must log in. Login Required"; var dialog = new MessageDialog(message); dialog.commands.add(new UICommand("OK")); await dialog.showasync(); 5. Update method OnNavigatedTo protected override async void OnNavigatedTo(NavigationEventArgs e) await Authenticate(); RefreshTodoItems(); Exercise 3: Adding Push Notifications to your app In demo, you add push notifications, using the Windows Push Notification service (WNS), to the quickstart project. When complete, an insert in the mobile service todolist table will generate a push notification back to your app.
Task 1 - Register your app for push notifications and configure Mobile Services 1. Navigate to the Windows Push Notifications & Live Connect page, login with your Microsoft account if needed, and then follow the instructions to register your app. Note: It's important to ensure the value supplied to the CN field is the same as the Publisher field in your applications package.appxmanifest Packaging tab 2. At the end of the registration process for your app you will be provided with WNS Credentials. Keep the page open or make a note of the Package Name, Client Secret and Package SID. You must provide these values to Mobile Services to be able to use WNS. Note: The client secret and package SID are important security credentials. Do not share these secrets with anyone or distribute them with your app. 3. Log on to the Windows Azure Management Portal, click Mobile Services, and then click your app. 4. Click the Push tab, enter the Client secret and Package SID values obtained for WNS above, and click Save. 5. In visual studio open package.appxmanifest, select the Packaging tab and update the package name field to match that provided in the Windows Push Notification and Live Connect Portal Task 2 - Add push notifications to the app 1. In Visual Studio open the package.appxmanifest, select the packaging tab and copy the Package Name from your WNS Credentials you recieved in the Windows Push Notifications & Live Connect portal and paste it into the Package name field in visual studio. 2. In the package.appxmanifest now select the Application UI tab and ensure toast capable is set to yes. Note: If you wish to send Wide Tiles then you must provide a default wide tile in the Wide Logo field. 3. Open the file App.xaml.cs 4. Add a Channel.cs class as follows. public class Channel
public int Id get; set; public string Uri get; set; 5. add the following using statement: using Windows.Networking.PushNotifications; 6. Find the OnLaunched method and mark it to be async as follows protected async override void OnLaunched(LaunchActivatedEventArgs args) 7. Add the following two lines of code to OnLaunched request a notification channel and register it with your Mobile Services app var ch = await PushNotificationChannelManager.CreatePushNotificationChannelForApplication Async(); await MobileService.GetTable<Channel>().InsertAsync(new Channel() Uri = ch.uri ); Now that we have the client wired up to request a channel and write it to our Mobile Service we now need to add a Channel table to our Mobile Service and add a server side script to send push notifications. Task 3 - Insert data to receive notifications In this section we add a Channel table and server side scripts to send push notifications everytime someone inserts into our todolist. 1. Return to the Windows Azure Management Portal, click Mobile Services, and then click your app. 2. Select the Data tab 3. Click + Create in the bottom toolbar 4. In Table name type Channel, then click the check button.
5. Click the new Channel table and verify that there are no data rows. 6. Click the Columns tab and verify that there is only a single id column, which is automatically created for you. This is the minimum requirement for a table in Mobile Services. Note: When dynamic schema is enabled on your mobile service, new columns are created automatically when JSON objects are sent to the mobile service by an insert or update operation. 7. Click the script tab and select the Insert Operation 8. Replace the existing script with the following script. JavaScript function insert(item, user, request) var channeltable = tables.gettable('channel'); channeltable.where( uri: item.uri ).read( success: insertchannelifnotfound); function insertchannelifnotfound(existingchannels) if(existingchannels.length > 0) request.respond(200, existingchannels[0]); else request.execute(); Note: The purpose of this script is to ensure that multiple channels with the same Uri are not submitted every time the OnLaunched handler executes in the sample application. This code is sufficient for a HOL scenario but in a real application you would use an Id rather then matching on uri: item.uri to identify the channel to be replaced. The reasoning is Channels expire and will be replaced by a new unique Channel Uri. 9. Click Save in the bottom toolbar 10. Now in the left navbar select the TodoItem table 11. Click the Script tab and select the Insert Operation and replace the existing script with the following and walk through the following code JavaScript function insert(item, user, request) request.execute( success: function()
request.respond(); sendnotifications(item);, error: function(err) request.respond(500, "Error"); ); function sendnotifications(item) var channeltable = tables.gettable('channel'); channeltable.read( success: function(channels) channels.foreach(function(channel) push.wns.sendtoasttext04(channel.uri, text1: item.text, text2: "Hello World 1", text3: "Hello World 2", success: function(response) console.log(response);, error: function(err) console.error(err); ); ); ); Note: This script executes as a each time a the insert operation is executed on the Todoitem table. The sendnotifications method we select all channels from the Channels table and iterate through them sending a push notification to each channel uri. While we have only demonstrated a single toast template the push.wns.* namespace provides simple to use methods required for sending toast, tile and badge updates. As you can see in this scenario we are sending a ToastText04 template which requires three lines of text. When you build your applications we would advise that you do not send toast notifications so frequently but rather only at times when there is a critical or important message to deliver the user of your application. Next we will move on to look at how you can secure your Mobile Service endpoints