April 2013

Volume 28 Number 04

Modern Apps - Power Your Modern Apps with Microsoft Azure Mobile Services

By Rachel Appel | April 2013

Rachel AppelRegardless of the platform you’ve targeted for app publishing, Azure Mobile Services (WAMS) is one back end to rule them all. It’s a key component of the Azure platform and it’s the back end for cross-platform modern app and Web development. In this article I’ll cover setting up WAMS to work in Visual Studio, provide an overview of the WAMS API and explain the coding necessary to build a modern app with WAMS.  

The Cross-Platform Architecture of WAMS

There are many Azure services you can use for managing data and powering an app’s back end, and it isn’t uncommon for apps to consume more than one Azure service. Here are some of the available services:

  • WAMS: A cross-platform, full-featured set of back-end services and resources geared specifically for fast app building.
  • SQL Azure: This is the same popular SQL Server, but in the cloud, with an easy-to-use Web admin interface. It’s cost-effective for smaller startups, companies and ISVs.
  • Azure Table Storage: A NoSQL way to work with tabular and sometimes-not-so-tabular data.
  • Azure Binary Large Object (BLOB) Storage: A highly scalable way to contain data in key/value pairs in the cloud without the worries and restrictions of structured data.
  • Azure Web Sites: In addition to Web site hosting, Azure Web Sites can run ASP.NET and ASP.NET Web APIs. This is a great way to power legacy Web sites, programs and apps over HTTP without having to do much architectural rework.

An app’s architecture will depend on its requirements. If the app needs to store large amounts (for example, tens or hundreds of gigabytes of data) of media or binary content, using Azure BLOB Storage is likely a better fit. For most apps that just read and write textual data with some accompanying pictures, WAMS is a straightforward and easy solution. Many apps must deal with legacy data, so migrating from SQL Server, SQL Server Compact (SQL CE) or any of the Microsoft SQL family of databases straight to SQL Azure might be the best route if you need a DBA to administer the data.

For most apps, WAMS is quite suitable because not only does it have data storage, but also a full set of back-end services on top of the database created for the express purposes of supporting common app infrastructure scenarios like push notifications and authentication.

WAMS Core Services

The following features are core WAMS services:

  • Data: Of course, housing and manipulating data is essential to every app, so WAMS supports it. For each mobile service, there’s a SQL Azure database behind it.
  • Messaging: Push notifications are increasingly important because users want to stay up-to-date. As apps get progressively more complex, intuitive and user-friendly—in other words, more modern—features such as push messaging and real-time communication become commonplace. Fortunately, using push notifications in WAMS is as easy as a call to send a toast (a small pop-up message in the top- or bottom-right of the OS) notification like so:
push.wns.sendToastText04(channel, { text1: item.text });
  • Authentication: Securing data, especially user data, is as important as the data itself. A cornerstone of modern apps is authenticating via widely popular Web sites—such as Facebook or Twitter—so WAMS allows you to authenticate with any of the following identity providers:
  1. Microsoft Account (the authentication provider formerly known as Windows Live ID)
  2. Facebook login
  3. Twitter login
  4. Google login

WAMS sports several libraries for the Windows family of app development, including the Windows Runtime (WinRT) library for managed clients, the Windows Library for JavaScript (WinJS) client library and Representational State Transfer (REST) APIs for everything—core services, authentication and messaging. There are even iOS and Android client libraries for cross-platform parity.

Use the WAMS API in Windows Store or Windows Phone Projects

Whether you’re building a Windows Store or Windows Phone app, the code will be almost identical, and the JavaScript code is remarkably similar on the WinJS side. Once you have the proper development tools and WAMS set up and configured (see bit.ly/NAAQz8 for more on this), writing the code to access objects and data in a mobile service is easy, but different from traditional client/server or n-tier app development. This is because WAMS integrates with the app in such a way that certain changes in the app’s model can cause changes in the underlying data structures. In other words, you can throw out many of the traditional SQL data definition statements and simply modify a class’s member, recompile, run the app and verify the changes at the database level. In addition to this, JavaScript takes the place of SQL as the syntax du jour for database maintenance such as validation scripts or creating constraints on the data. Being able to easily script database changes from the app, command prompt and Web administration tool shortens the app-building process.

The Microsoft.WindowsAzure.MobileServices namespace provides standard-issue access to objects in the mobile service or its underlying SQL Azure database. The following code sample creates an instance of MobileServiceClient:

public static MobileServiceClient MobileService = new MobileServiceClient(

As you can see, your WAMS app URL and key are parameters of the MobileServiceClient constructor. To find your URL and key, log in to the Azure portal and navigate to your mobile service, then click the cloud icon to the left of the dashboard menu item.

In the preceding code sample, the MobileServiceClient class behaves somewhat like a connection object, but without those pesky open and close methods from the era of the SqlConnection object. The MobileServiceClient class manages the connectivity for you. If your data is set for public consumption, then you don’t need to call the MobileServiceClient.login method, yet you can access tables, run queries and sort data. Of course, more complex or security-conscious operations may require credentials.

Once you have a valid instance of a MobileServiceClient class, you can then use GetTable<T> to interact with an underlying WAMS table:

private IMobileServiceTable<Person> personsTable =
  MobileService.GetTable< Person>();

The type parameter T in IMobileServiceTable<T> causes the compiler to inspect the properties and information about the parameter—in this case the Person class in Figure 1—by mapping it to the underlying table at the database level. This allows you to add or modify properties during development and see the schema changes reflected in the cloud at run time, resulting in a more symbiotic alliance between the code and the database. However, schema changes at the database level don’t happen automatically for every change in code. For example, adding a property to the code in Figure 1 creates a new column in the table, but deleting an existing property doesn’t cause a deletion.

Figure 1 The Person Class

// Data model/class code.
public class Person
  public int Id { get; set; }
  public string Name { get; set; }
  [DataMember(Name = "Birthday")] 
  public DateTime Date { get; set; }
  public string Picture { get; set; }
  public string Notes { get; set; }

GetTable<T> returns an IMobileServiceTable object that represents the actual underlying table in WAMS and contains methods for inserting, updating, deleting and sorting services, as shown here:

// Perform delete asynchronously where item is of type Person, see Figure 1.
await itemsTable.DeleteAsync(item);
// Select specific records with LINQ query
var people =
  personsTable.Select(p => p.Birthday > DateTime.Now.AddDays(14));

You can build your data layer in the code by creating a custom class that matches the table and member names. This technique is known as convention over configuration, which is a way to cut down on bloated XML configuration code in favor of continuity and consistency in naming, resulting in less code that’s more maintainable. For example, the class and schema in Figure 1 demonstrate that the client class code maps to a WAMS table and its members.

The code in Figure 1 creates the database schema shown in Figure 2.

Figure 2 Convention over Configuration Matches Class Code and Database Schema Names

Column Type
Id SQL Bigint
Name String
Date DateTime
Picture String
Notes String

WAMS infers data types from the property’s data type in code. Some types, however, can’t be represented with data attributes, specifically image and binary data. This means that when you want to store an image, you should use Azure BLOB storage because it’s more scalable, cheaper and performs much better than the alternative, which is Base64 encoding to a string and then storing it in a WAMS table. Azure BLOB storage has a REST API and managed API so developers can easily access the services across platforms and preferences.

To perform insert, update or delete operations, just make an instance of your custom object and call the corresponding method from your IMobileServiceTable object:

Person person = new Person {
  Name = "Alan Turing",
  Birthday = DateTime dte = new DateTime(1912,6,23),
  Picture = base64string, // Image encoding done elsewhere in code. 
  Notes = "A father of modern computer science. There is a test " +
    "named after him that I fail regularly"};
await personsTable.InsertAsync(person);

Because the call to InsertAsync is clearly asynchronous, the call doesn’t block UI code from running, and you can manage data in the background without interfering with the user’s activities. Windows Store and Windows Phone apps work in an asynchronous fashion by default, as you can’t always count on reliable connectivity.

If you’re working in XAML, you can data bind the table by calling the IMobileServiceTable object’s ToListAsync method. This method preps the data and returns it into an object that binds WAMS tables easily to XAML ListView elements, as the following code sample demonstrates:

var results = await todoTable.ToListAsync();
items = new ObservableCollection<TodoItem>(results);
ListItems.ItemsSource = items;

The preceding code is similar to traditional data-binding code in the Microsoft .NET Framework. You can also call methods on the IMobileServiceTable object to return an IList<T> or IEnumerable<T> if you wish to manually loop through the data, rather than data bind.

Managing Advanced WAMS Features

You will, of course, need to administer and maintain the mobile service, its data, security and all the usual tasks that go with back-end maintenance, as not all of that kind of work should be done in the app. Fortunately, WAMS gives you a few choices in regard to back-end administrative tasks:

  • Command-line tool: This is great no matter what platform you use for development; you can use any command prompt once you’ve downloaded and installed the command-line libraries (see bit.ly/14Q49bi for more on this).    
  • Web administration: Great for cross-platform back-end development, and also known as the Azure portal, this tool lets you do all the basics online—create databases, run server-side scripts, manage services, manage security and so on (the portal is accessed from the main Azure site at bit.ly/4yqVhP).
  • SQL Server Management Studio: A classic Microsoft database administration tool that you can use to connect and manage the databases behind a mobile service (see bit.ly/VdqpZH for more on this).

WAMS contains a succinct yet complete WAMS server-side script reference (bit.ly/XvsVec). You can launch commands from the command-line tool or from the Azure portal online. At the command prompt, simply enter the command “azure mobile” to see a list of all available commands and “azure mobile list” to list all your mobile services.

Just like your app code, server-side script functions are “registered” to a table via naming conventions, so the scripts must match method signatures for insert, read, update and delete operations. Here are the data-manipulation script signatures in JavaScript:

  • Insert function: insert (item, user, request) { ... }
  • Read function: read (query, user, request) { ... }
  • Update function: update (item, user, request) { ... }
  • Delete function: del (id, user, request) { ... }

Notice that everything you need is included as method parameters, that is, the data row, the user identity and the request itself. This allows you to perform row-level security as well as run any type of server-side rules such as data validation when these activities occur.

As an example, you might want to perform validation to limit the incoming string’s length for insertions. You can do so by using this code:

function insert(item, user, request) {
  if (item.text.length > 20) {
    'The length of the input text must be less than 20');
  } else {

While you can modify these scripts at the Azure portal, you can also do so in your favorite text editor and save the file with a .js extension, for example, person.insert.js. You can then upload the prepared script via the command line with a command with this syntax and signature:

azure mobile script upload <service-name> table/<table-name>.<operation>.js

A command to upload the previous sample script would look something like this (where “Notable” is the service name and “person” is the table name):

azure mobile script upload NotablePeople table/person.insert.js

As you might expect, the results of a validation error can be caught by a try/catch statement in any client-side language.

Alas, SQL developers might be feeling out of touch at this point, with all the server-side JavaScript trends lately, but they can feel more at home by using SQL inside an mssql script object, even if it’s mixed with JavaScript:

mssql.query('select * from people', {
  success: function(results) {

This is especially helpful if you come from an enterprise development background that’s full of SQL, as it’s much different than the dynamic nature of JavaScript.

To review, WAMS is a complete set of back-end services for rapid, cross-platform app building. All of the Azure services except SQL Azure automatically implement REST-friendly URLs, and because REST is cross-platform, there’s no need to worry about ensuring your app architecture will support new client devices or user agents in the future. In the meantime, working with WAMS requires no hefty software installs on the client because of its powerful Web administration and command-line tools, as well as easy-to-use APIs for everything from basic data storage to bulk e-mailing and push notifications.

Rachel Appel is a developer evangelist at Microsoft New York City. Reach her via her Web site at rachelappel.com or by e-mail at rachel.appel@microsoft.com. You can also follow her latest updates on Twitter at twitter.com/rachelappel.

Thanks to the following technical expert for reviewing this article: Paul Batum (Microsoft)
Paul Batum is a program manager at Microsoft and works on Azure Mobile Services. His focus is on making it easy for mobile developers to add cloud capabilities to their applications. He can be reached at pbatum@microsoft.com