Start Developing with Windows Azure Mobile Services - Learning Windows Azure Mobile Services for Windows 8 and Windows Phone 8 (2014)

Learning Windows Azure Mobile Services for Windows 8 and Windows Phone 8 (2014)

Chapter 2. Start Developing with Windows Azure Mobile Services

So far, we've got everything ready in the Windows Azure portal, with an account setup and our first Windows Azure Mobile Service created. Next, we're going to look at the following topics:

· Preparing our development environment

· Creating starter apps from the portal

· Connecting existing apps to our service

Preparing our development environment

Chances are, you're already developing Windows Phone 8 or Windows Store apps so you'll have some of the tools you need, but there are a few extra bits of software you might need for certain features of Windows Azure Mobile Services. If you've not done Windows Phone development before and plan on doing so, definitely read all of this.

Requirement for hardware

For Windows Store app development, there is no special hardware requirement. However, to develop apps for Windows Phone 8, you need a machine which has specific requirements in order to run the Hyper-V phone emulators. The Windows Phone 8 SDK will do a prerequisite check before installation; however, you can read the exact requirements here: http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff626524(v=vs.105).aspx.

For phone development, it is always helpful to have a handset to test on. I would advise testing an app on a real device before publishing it, to make sure that everything works. The same goes for Windows 8; although Surface Pros and other tablets running full Windows 8 have exactly the same OS as PCs and laptops, it's helpful to test the touch gestures as well as keyboard as Surfaces (formerly called as Surface RTs) run on a different OS designed for ARM devices so that it is useful to have access to a tablet or machine with a touch screen.

Setting up the software

We will mainly use Visual Studio for developing Windows Store and Windows Phone 8 applications. Since I started writing this book, Windows 8.1 was made generally available; so, I'll be using Visual Studio Express 2013 for Windows (2012 version was labelled "for Windows 8") and Visual Studio Express 2012 for Windows Phone (when you are reading this, there may be a 2013 version so use that instead). Of course, you can use Professional and Ultimate versions of Visual Studio and you'll need to download SDKs for Windows 8 and Windows Phone 8 project types. All versions of Visual Studio can be downloaded here: http://www.microsoft.com/visualstudio/eng/downloads.

When we start looking at scripts, we'll cover how to manage them using Git version control. So, you'll need to install Git for doing this (http://git-scm.com/downloads). When I use Git, I prefer to use the GUI; so, if you want to do the same, make sure you select this option when you install. Also, I use the last option in the installer to prevent Git from changing the file line endings for cross-platform projects so that I don't get annoying warnings whenever I check something in.

We will also make use of NPM modules in scripts. So, we will need to install node.js from here: http://nodejs.org/.

Fiddle r is a really helpful HTTP debugging tool that we will mention when we look at security. This can be installed from here: http://fiddler2.com/.

Requirement for store accounts

To publish your apps, you need a store account. You'll also need an account to implement push notifications in Windows Store apps. Unlike Windows Azure Mobile Services, you actually need to pay for these and there is no free option. Previously, you needed separate accounts for Store and Phone apps; however, these have now been merged and only cost 19USD for an individual. You can sign up at: https://appdev.microsoft.com/StorePortals/en-us/Account/Signup/Start.

Creating apps from the portal

From the portal, we can download template solutions for Windows Store, Windows Phone 8, iOS, Android, HTML/JavaScript, and Xamarin, which have a working sample of creating a "To-do list"—complete with your app's URL and API key. We're going to take a look at Windows Store app now.

For a Windows Store app, select Windows Store and click on the CREATE A NEW WINDOWS STORE APP link:

Creating apps from the portal

If you haven't done so already, download Visual Studio. The boilerplate code in the app uses a TodoItem table, so click on the button to create it (you can delete it later if you like). We're going to discuss the C# app, but you can also download a JavaScript app. The downloaded app is in a ZIP folder. Make sure you go to the ZIP file properties and unblock it so we don't have security problems. Unzip the project and open it in Visual Studio. When we examine the solution, we see that it already has the NuGet packages installed for the Windows Azure Mobile Services API.

When we take a look at the App.xaml.cs class, we can see that there is a static variable for accessing an instance of MobileServiceClient from anywhere in the app. It has the service endpoint and API key configured:

namespace TileTapper

{

/// <summary>

/// Provides application-specific behavior to supplement the default Application class.

/// </summary>

sealed partial class App : Application

{

// This MobileServiceClient has been configured to communicate with your Mobile Service's url

// and application key. You're all set to start working with your Mobile Service!

public static MobileServiceClient MobileService = new MobileServiceClient(

"https://tiletapper.azure-mobile.net/",

"XXXXXXXXXXXXxxxxxxxxxxxxxxxxxxx"

);

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www. packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

MainPage.xaml and MainPage.xaml.cs contain the template code for exercising the TodoList table. Take a look round the code, then run the app, and have a quick play. The app should look something like this:

Creating apps from the portal

Once you've inserted a few items, go back to the portal and take a look at the TodoList table in the DATA tab:

Creating apps from the portal

You can use the TRUNCATE button to delete all the records you've created.

The Windows Phone 8 app is pretty much identical, so we won't go through it now; but have a look yourself or you may want to look at it instead of the Windows Store version.

The SDK implemented in these template apps exposes the mobile service REST API, which can be consumed by any platform capable of making HTTP requests, and not just ones listed in the portal.

Connecting existing apps to Windows Azure Mobile Services

Connecting existing apps is simple to do. We can add a Connected Service for Visual Studio 2013 solutions and we need to install the Windows Azure Mobile Services SDK NuGet package for Visual Studio 2012, or you can download the source from the following link: https://github.com/WindowsAzure/azure-mobile-services. As you can see, the SDK is open source and hosted on GitHub rather than CodePlex which is the usual place Microsoft host SDKs. So, it shows that they're really building a cross-platform service here.

Adding a Connected Service in Visual Studio 2013

To connect to a service, follow these instructions:

1. Right-click a project in the solution explorer, select Add | Connected Service:

Adding a Connected Service in Visual Studio 2013

Tip

If you have imported a subscription, skip to the last step.

2. Click on Import subscriptions and the Import Windows Azure Subscriptions dialog will appear.

3. Click on Download subscription file. Your default browser will be launched and the subscriptions file will be downloaded automatically. If you are logged into the portal, this will happen automatically; otherwise, you'll be prompted to log in.

4. Once downloaded, browse to the downloaded file in the Import Windows Azure Subscriptions dialog box and click on Import.

5. Select the subscription you want to use and click on OK.

The SDK NuGet package will be installed into our app and a static MobileServiceClient instance will be added to App.xaml.cs, in the same way as the app downloaded from the portal.

Manually installing the SDK in Visual Studio 2012 Express for Windows Phone

First, we're going to install the NuGet package into our solution. This can be done from the NuGet Package Manager dialog box by right-clicking on the project and selecting Manage NuGet Packages; or alternatively, from the Package Manager Console by typing the following command:

PM> Install-Package WindowsAzure.MobileServices

Install the package (accepting the licenses) and we're ready to go.

Note

If the install fails, check whether your NuGet Package Manager extension is up-to-date (by going to Tools | Extensions and Updates | Updates).

I prefer to implement MobileServiceClient in my own DataService class. So, I would install the package manually even in Visual Studio 2013 to save cleaning up code in App.xaml.cs.

Creating a table

We've got a database, but we need a table to interact with to get started. For the TileTapper game, we need a LeaderBoard table to keep track of player's high scores. So, we'll create that now. Click on the CREATE button on the toolbar in the DATA tab:

Creating a table

From the Create New Table dialog, enter the table name and for now, leave the default permissions (we'll look at these when we start talking about permissions in the next chapter). By default the database is set to have a dynamic schema. This means that the table adds new columns as it finds them in the inserted data.

Creating a table

We can see that we've got a table which already has an indexed id column and also _createdAt, _updatedAt, and _version columns for optimistic concurrency.

Writing a model of the table

We'll go back to Visual Studio and write a model for the LeaderBoard table that will be used to read and write records to the table. When the database first sees the model, it will create the table columns for us. Here's the code for the model:

using System;

using Newtonsoft.Json;

namespace TileTapper.Models

{

[JsonObject(Title="leaderboard")]

public class LeaderBoardItem

{

[JsonProperty(PropertyName = "id")]

public string Id { get; set; }

[JsonProperty(PropertyName = "timeStamp")]

public DateTime TimeStamp { get; set; }

[JsonProperty(PropertyName = "name")]

public string Name { get; set; }

[JsonProperty(PropertyName = "score")]

public int Score { get; set; }

}

}

You will notice that there are JsonObject and JsonProperty attributes on the class and properties. These attributes tell the JSON serializer to use these names instead of the property or class name when the object is serialized, so that we can have different names (I didn't want my item to be called LeaderBoard as this didn't make sense), our C# properties in Pascal case (PascalCase), and the JSON objects in Camel case (camelCase).

Interacting with the table

The next step is to write some code to interact with the LeaderBoard service that exposes the table. We're going to start a data service class to contain all the operations we want to perform on the LeaderBoard table. I'm steering us towards using an Model View View-Model (MVVM) pattern (you can read a bit about MVVM at http://en.wikipedia.org/wiki/Model_View_ViewModel), but we'll try and organise our code so that things are kept simple and our UI code is not littered with data access code. Here's the service with a GetAlland Insert method:

using System;

using System.Threading.Tasks;

using System.Collections.Generic;

using Microsoft.WindowsAzure.MobileServices;

using TileTapper.Models;

namespace TileTapper.Services

{

public class DataService

{

// Our MobileServiceClient instance with Url and application key set

private static readonly MobileServiceClient _mobileService = new MobileServiceClient(

"https://tiletapper.azure-mobile.net/",

"0000CZGhLgIKxkrBCFwxSGXKHzPLRq15"

);

public async Task<IEnumerable<LeaderBoardItem>> GetAll()

{

var table = _mobileService.GetTable<LeaderBoardItem>();

return await table.ToEnumerableAsync();

}

public async Task Insert(LeaderBoardItem item)

{

var table = _mobileService.GetTable<LeaderBoardItem>();

await table.InsertAsync(item);

}

}

}

The service contains its own instance of the MobileServiceClient object that allows us to access the service we created. You can find the URL on the dashboard in the portal and the key under Manage Keys on the portal's toolbar. We then interact with the table using the generic GetTable method. You'll notice the use of async and Task, these were introduced in C# 5 and feature heavily in Windows Store and Windows Phone 8 app development. If you're not familiar with asynchronous programming, it's worth having a quick read up on the Web. In C++ and JavaScript, async is handled differently.

To give the service a test drive, I created some temporary methods that are called in the app's MainPage.xaml.cs constructor to seed the table and examine the contents afterwards:

private async void Demo()

{

await this.Seed();

await this.GetAll();

}

private async Task Seed()

{

var service = new DataService();

// Seed a few items into the Leader Board

await service.Insert(new Models.LeaderBoardItem()

{

Name = "Tank Man",

Score = 885562,

TimeStamp = DateTime.Now

});

// A few others removed for brevity

}

private async Task GetAll()

{

var service = new DataService();

var task = await service.GetAll();

// Materialize leaders so we can have a look

var leaders = task.ToList();

}

You'll notice that I'm not setting the id field in the models as these will be set by the database. If we put a break point at the bottom of GetAll, we can see our four leaders have been created and the IDs are set by the database:

Interacting with the table

If we now have a look at the table in the portal, we can see the data and the columns that have been created for us:

Interacting with the table

Summary

We've now got all the development tools we need installed on our machine, had a look at the starter solutions which can be downloaded from the portal, installed the SDK into our own solution, and started laying down some foundations in code ready for adding some more interesting features.

In the next chapter, we'll look at the security features Windows Azure Mobile Services offers us to protect our data and users.