November 2012

Volume 27 Number 11

Azure Insider - Microsoft Azure Mobile Services: A Robust Back End for Your Device Applications

By Bruno Terkaly, Ricardo Villalobos | November 2012

Bruno Terkaly / Ricardo VillalobosDuring the last few years, the developer’s landscape has been characterized by three main features: multiple devices and OSes to support; applications that rely on asynchronous Web services, typically hosted in the cloud; and variable traffic that complicates resource planning and provisioning. The new Microsoft Azure Mobile Services (WAMS) simplifies the implementation of software architectures that address this type of environment, as shown in Figure 1.

Typical Architecture to Support Multiple Devices with a Single Web Service
Figure 1 Typical Architecture to Support Multiple Devices with a Single Web Service

Even though it’s possible to manually create and deploy the required components for this approach to work, what mobile developers really want are endpoints that provide the needed functionality without having to worry about the underlying infrastructure. Having to spend cycles on maintaining structured or semi-structured storage, user authentication or push notifications is a distraction from developing mobile applications.

Keep in mind that we’re using the term “mobile application” very loosely here. This client-side (mobile application) technology can target almost anything: a Windows 8 phone or tablet; an iOS iPhone or iPad; or an Android phone or tablet. This is possible due to the fact that WAMS is based on open standards and regular HTTP requests.

Creating Your First Application Based on WAMS

WAMS is currently in preview mode and getting started is just a few clicks away. Simply sign up for a free trial, at bit.ly/azuretestdrive and log in to access the Azure Portal, then click on CREATE A NEW APP.

As you’ll see, a window will pop up that allows you to quickly accomplish several things. Here you’ll define a URL that will be used by your mobile application to interact with the available services and you’ll create a new relational database (though you could choose to use an existing Azure SQL Database). At the same time, a series of REST-based endpoints and services will be created and exposed for mobile clients.

Next, you’ll provide a database name, server, login name, password and region, as shown in Figure 2.

Specifying Database Settings
Figure 2 Specifying Database Settings

In just a few moments, you created a new mobile service in one of the reliable, secured, and globally distributed Microsoft datacenters, as shown in Figure 3.

The Mobile Service Account
Figure 3 The Mobile Service Account

Now click on the service name (“brunoterkaly” in Figure 3) to access the underlying management dashboard.

Using the Dashboard to Create a Windows 8 Application

Once you access the dashboard, you’ll be able to generate a simple Windows 8 application that demonstrates how all the pieces fit together. Notice the link in Figure 4 that reads “Create a new Windows 8 application.”

The Main Portal for Your New Mobile Service Project
Figure 4 The Main Portal for Your New Mobile Service Project

Click on that link to start the WAMS wizard. To create a basic solution for Windows 8 devices, you’ll have to accomplish three essential steps, as follows:

  1. Get the tools. If you haven’t yet installed Visual Studio Express 2012 for Windows 8, do so by clicking on the corresponding link. Also, install the Azure Mobile Services SDK by downloading the bits from bit.ly/TpWfxy. Keep in mind that this last component requires Visual Studio 2012 running on a Windows 8 machine.
  2. Create a relational table to store your data. When you click on the Create TodoItem Table button, the wizard will automatically create a table based on the Azure SQL Database you created (or re-used) previously.
    In case you’re not familiar with Azure SQL Database, this is a highly scalable service that provides SQL Server capabilities in the cloud. You won’t need to do it for this project, but it’s actually possible to connect to your newly created database using tools 
such as SQL Server Management Studio (version 2008 R2 is required), or even from different programming languages.
    The portal even provides a simple interface that allows you to manage your data and table structures. Because Azure SQL Database supports the traditional tabular data stream (TDS) protocol, you can use the exact same tooling as you would with the typical on-premises SQL Server database.
    All Azure SQL Database servers are automatically protected by an external firewall whose rules you can also manage from the portal. The important thing to remember is that the WAMS wizard takes care of all these steps for you.
  3. Generate and download the required code for your application. Now that the required data and endpoints for this project are in place, it’s time to look at some code. The final step at the portal allows you to generate a Visual Studio project that automatically takes advantage of the WAMS platform. Here’s how to accomplish this:
    1. Choose your programming language, either C# or JavaScript.
    2. When you click Download, you’ll be presented with a dialog box that will ask if you want to open or save the generated code. Save the zip file.
    3. After unzipping the code, open the project in Visual Studio 2012.
    4. Now run the code to see how it works. From the DEBUG menu, choose START DEBUGGING. Enter a TodoItem and hit Save, then Refresh, as shown in Figure 6.
    5. You can open the generated database using a tool such as SQL Server Management Studio (or the management tool in the portal) to review the data. You’ll notice that a new todo item has been added to the corresponding table.

The Database Dashboard
Figure 5 The Database Dashboard

Running the Application
Figure 6 Running the Application

Exploring the Code

Let’s take a look under the covers to see exactly how this works. The main location for all of this code is in MainPage.xaml.cs. Go to Solution Explorer and double-click on MainPage.xaml.cs to see the code shown in Figure 7.

Figure 7 The TodoItem Class

19  public class TodoItem
20  {
21    public int Id { get; set; }
22  
23    [DataMember(Name = "text")]
24    public string Text { get; set; }
25
26    [DataMember(Name = "complete")]
27    public bool Complete { get; set; }
28  }
29
30  public sealed partial class MainPage : Page
31  {
32    // MobileServiceCollectionView implements ICollectionView
33    // (useful for databinding to lists) and is integrated with your
34    // MobileService to make it easy to bind your data to the ListView
35    private MobileServiceCollectionView<TodoItem> items;
36
37    private IMobileServiceTable<TodoItem> todoTable =
38      App.MobileService.GetTable<TodoItem>();
42
43    public MainPage()...
50
51    private async void InsertTodoItem(TodoItem todoItem)...
60
61    private void RefreshTodoItems()…
68
69    private async void UpdateCheckedTodoItem(TodoItem item)...
73
74    private void ButtonRefresh_Click(object sender, RoutedEventArgs e)...
79
80    private void ButtonSave_Click(object sender, RoutedEventArgs e)...
86
87    private void CheckBoxComplete_Checked(object sender, RoutedEventArgs e)...
88
89    protected override void OnNavigatedTo(NavigationEventArgs e)...
91  }
=

Here’s what’s happening in the code:

  • Lines 19 to 28 create the TodoItem, an object that represents the data we want to save to Azure SQL Database. It represents the same data structure as the underlying 
table in the database, but they don’t need to be the same. The DataMember attributes affect how the item is serialized as well as the name of the actual columns in the Azure SQL Database. This allows you to have a column name in the database that’s different than the Property name in the Microsoft .NET Framework.
  • Line 35 creates a collection of items that get displayed in a list control in the main page of the application. The collection is bound to an underlying list control. It’s populated from the object on line 37.
  • Line 37 creates an IMobileServiceTable of TodoItems named todoTable. The todoTable object acts as a wrapper around the RESTful HTTP API exposed by WAMS and allows you to use client-side LINQ queries rather than manual REST API HTTP calls to query the data in the Azure SQL Database TodoItem table. The result of the LINQ 
queries are saved into the items collection created earlier, 
and later bound to the ListView for display. The same todoTable object also allows asynchronous insert, update and delete operations on the Azure SQL Database TodoItem table. This is all code that usually you’d have to write yourself. In short, the developer is saved from having to write a lot of plumbing code to perform typical create, read, update and delete operations.
  • Line 51 asynchronously inserts todo items into the table and updates the items collection.
  • Line 61 updates the items collection with the latest data from the todo table and binds that data to the list control.
  • Line 69 issues asynchronous updates to the underlying SQL database table and removes that item from the items collection.
  • Line 74 refreshes the list control with data from the database.
  • Line 80 inserts a new entry into the todo table.
  • Line 87 updates the underlying table to reflect the fact that a check box has been checked.

The App.xaml.cs file is also worth exploring, because it stores the startup code. The client object of type MobileServiceClient abstracts away the complexities of making a RESTful service call, which requires an application key (generated when the Azure Mobile Service is created). You can get the application key either at the Azure Mobile Services Portal or in the App.xaml.cs file:

 

sealed partial class App : Application
  {
    // This MobileServiceClient has been configured to
    // communicate with your Mobile Service URL and
    // application key; you're all set to start working with
    // your Mobile Service!
    public static MobileServiceClient MobileService =
      new MobileServiceClient(
      "https://brunoterkaly.azure-mobile.net/",
      "rsECynSsGJmPiHmydyTGEYOSlrbCgr27"
);

How Requests Get Executed

This is where things get interesting. It’s possible to analyze the HTTP requests generated by the Windows 8 client using a Web debugging proxy tool such as Fiddler (which can be downloaded for free at fiddler2.com). Before using Fiddler for this purpose, note that you need to allow Fiddler to capture and decrypt HTTP traffic. In Fiddler, go to Tools | Fiddler Options and then switch to the HTTPS tab and turn on the checkboxes for Capture HTTPS CONNECTs and Decrypt HTTPS traffic.

Analyzing the Generated HTTP Requests Using Fiddler
Figure 8 Analyzing the Generated HTTP Requests Using Fiddler

The JSON Code Returned from WAMS
Figure 9 The JSON Code Returned from WAMS

After starting the tool, navigate to the Composer tab, and 
follow these steps, as shown in Figure 8 and Figure 9:

  1. Select the verb, such as GET, and then enter the URL (for our project it’s https://brunoterkaly.azure-­mobile.net/tables/TodoItem), and the corresponding header; for example, https://brunoterkaly.azure-mobile.net/tables/TodoItem.
  2. Hit Execute.
  3. Right-click on the session in the left pane.
  4. Choose Inspect in New Window.
  5. The Web session pane will appear. Select the Response tab.
  6. Select the JSON tab. Now you’ll be able to see the data coming from the Azure Mobile Service you created previously. This is the same data you saw in the SQL Server database.

This essentially means that the Azure Mobile Service can be accessed from practically any environment, because HTTP requests and RESTful calls are widely supported by multiple platforms and programming languages. Note that the Azure Mobile Services SDK for Windows 8 makes this easier to use in Windows 8 apps. Also, client libraries will soon be available for iOS and Android.

Wrapping Up

Azure Mobile Services simplifies the life of mobile developers by automating the steps required to create a back end based on open standards, supporting multiple types of devices and OSes. Moreover, WAMS provides a reliable and secure infra­structure in the cloud that can be scaled based on traffic and demand, allowing programmers to concentrate on optimizing their apps and data.

There’s more to learn, of course, especially in the areas of push notification and authentication. Push notification makes it possible to easily send notifications to your Windows 8 app without writing, testing or managing back-end infrastructure code. In addition, WAMS eliminates the need to write, configure, and test custom authentication and user management solutions for your Windows 8 apps. We look forward to addressing these technologies in future columns.      

 

 


Bruno Terkaly* *is a developer evangelist for Microsoft. His depth of knowledge comes from years of experience in the field, writing code using a multitude of platforms, languages, frameworks, SDKs, libraries and APIs. He spends time writing code, blogging and giving live presentations on building cloud-based apps, specifically using the Azure platform and just wrote a a five-part series on iOS and Azure Mobile Services, available at bit.ly/UPXGdV.

Ricardo Villalobos* *is a seasoned software architect with more than 15 years of experience designing and creating applications for companies in the supply chain management industry. Holding different technical certifications, as well as a master’s degree in business administration from the University of Dallas, he works as a cloud architect in the Azure CSV incubation group for Microsoft.

Thanksto the following technical expert for reviewing this article:Bret Stateham