Mobile Apps continue to flood the ecosystem with exciting real world scenarios that could be accomplished from the Devices, which couldn’t have been imagined, even a few years back. Native Mobile Apps install and run on client devices such as Windows 8, Windows Phone, iOS and Android. They however need to communicate with a server for fetching data and other operations. We introduced Windows Azure Mobile Services to make it easier for mobile app developers to abstract common backend functionality across all mobile platforms into a cloud-based service.

This post was authored by Harish Ranganathan in our Technical Evangelism team.

Traditionally, mobile apps use a web service or WCF service to accomplish this. However, there are a few trivial things when dealing with client apps.

1. Regular CRUD operations (Read, Update, Create & Delete) from Tables

2. Notify clients of changes made to the Server Data

3. Authentication from the client application before accessing the server data

4. Running scheduled jobs that can push updates to the client apps at periodic/specified intervals.

To accomplish the above common tasks, it is often required to write a lot of application code. The complexity involved in building a Service to accomplish basic CRUD operations is high.

Also, the Service needs to be able to cater to various platforms such that the client app can be abstracted from the backend service and data. It also helps in reusability of the service without having to write one, for each and every technology.

Enter Windows Azure Mobile Services

Windows Azure Mobile Services (WAMS) is one of the offerings in Azure that exposes relational database as an OData endpoint for consumption by Client Apps. In simplified terms, it provides a service URL that can be used to access data and make read/write operations from applications running on client devices such as Windows 8, Windows Phone, iOS and Android.

WAMS exposes OData endpoints from the server which can be consumed in the client apps through classes replicating the data model. Once this is accomplished, it becomes fairly straight forward to plug-in the other components such as authentication, push notifications & scheduled jobs.

Structured Data on the Cloud

Often when designing Mobile Apps, the requirements keep growing and over a period of time, the backend data and the schema needs significant modifications to suit the requirements. With WAMS, we can design and make changes to Database and Schema on the fly using the “Dynamic Schematization” built into the framework.

Let us take an example of a Windows Store App built for our scenario. We plan to store Restaurant Names, their cuisine and their ratings. Let’s go ahead and create a New Mobile Service. We will follow the steps outlined in Get started with Mobile Services and create the “restapp” mobile service.

clip_image002

If we create the “ToDoItem” sample table and download the starter project, we can straight away have an App pushing data into Cloud using Azure Mobile Service.

Here below is a sample code for INSERTing a record.

private async void InsertTodoItem(TodoItem todoItem) {

// This code inserts a new TodoItem into the database. When the operation completes

// and Mobile Services has assigned an Id, the item is added to the CollectionView

            await todoTable.InsertAsync(todoItem);

            items.Add(todoItem);                       

}

 

As you can see, the InsertAsync Method of the todoTable which accepts an instance of the class todoItem and makes an asynchronous push to save the record.

If you further delve into the InsertAsync Method, it is a part of IMobileServiceTable Interface as defined as

Task InsertAsync(T instance);

This Async Method is intercepted at the Server Level by Node.js which renders Serverside script to make the data insert into the SQL Azure Table.

Once we have the service up and running, we would like to authenticate users who have access to this service. In general Mobile Service Tables have CRUD access to anyone with the “Application Key” (The Application URL and Application Key is unique to every Mobile Service and can be acquired from the dashboard of the Mobile Services). We can modify and allow access to only Authenticated Users or Scripts & Admins to make INSERT, UPDATE & DELETE. This brings us to the interesting part. Authentication.

Authentication

A bit into what happens in the backend

When you create a Mobile service, the dashboard screen offers various options such as “Data”, “Scheduler”, “Push”, “Identity”, “Configure”, “Scale” and Logs.

The Identity Tab allows you to configure authentication for your Mobile Service. Here is a screen capture of the Identity Screen

clip_image004

As you can see, we can use Microsoft Account (Live) or Facebook or Twitter or even Google Account for enabling authentication for the Mobile Service. Again, the plumbing work of writing the APIs for authenticating with the above services is automated by WAMS. A typical Facebook Authentication enabling involves two steps.

1. Register in Facebook the App and grab the Client Id and Client Secret Key

2. Add the below code snippet to enable authentication as a first step in the service.

private async 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 login. Login Required";

}

var dialog = new MessageDialog(message);

dialog.Commands.Add(new UICommand("OK"));

await dialog.ShowAsync();

}

}

Then this method can be called in the OnNavigatedTo event of the Mobile Service, as below:-

protected override async void OnNavigatedTo(NavigationEventArgs e){

await Authenticate();

RefreshTodoItems();

}

In the Data tab you can find the tables listed. This screen offers the options to see the table schema, make permission changes to access the tables such as read, drop to various users.

The configure screen allows you to control “Dynamic Schematization”. This is ideal when you create database from scratch through the mobile service or at a later point want to add a column dynamically.

The scale screen allows you to choose between “Free” and “Reserved Mode” for your Mobile Service and also manage the instance count.

The Scheduler screen allows you to create a named schedule job. Once this is created, you can switch to the “Script” and write the required functionality.

The Logs allow you to debug mobile services. You can log requests using simple statement such as console.log(request) and thereafter each and every request for the table will log the details that can be used to analyze.

Push Notifications

Push Notifications generally allows client apps to receive notifications when server side data has modifications. To accomplish this, normally, one would have to invest in server infrastructure which keeps poling the data and sending notification back to the client devices. WAMS simplifies this by enabling Push Notification through simple configuration steps. A typical Push Notification code snippet is as below

function sendNotifications() {

    var channelTable = tables.getTable('Channel');

    channelTable.read({

        success: function(channels) {

            channels.forEach(function(channel) {

                push.wns.sendToastText04(channel.uri, {

                    text1: item.ProductName

                }, {

                    success: function(pushResponse) {

                        console.log("Sent push:", pushResponse);

                        }

                    });

                });

            }

        });

    }

 

Push Notification works for Windows, iOS as well as Android applications and the notification settings screen is as below

clip_image006

To enable push notifications, the Client App (in our case Windows 8 App) needs to have “Toast Notifications” enabled. Also, the app must have a Store Id (package manifest) which has Push Notifications enabled from the Live Services Portal.

Once these configuration steps are done, we can write scripts for particular table and enable notification for insert/update or any other operation that we need to receive notifications. I will reserve a detailed step by step instruction and point to Get started with push notifications in Mobile Services

Scheduled Jobs

Scheduled Jobs are general server side operations that are triggered at a specific interval or on an external trigger. Similar to Push Notifications, Scheduled Jobs can be configured in the WAMS configuration portal through simple steps instead of you having to set up server infrastructure for the same. A typical scheduld job configuration screen looks as below.

clip_image008

A bit deeper into what is WAMS

WAMS is a Node.js implementation running on IIS powered by Azure Virtual Machines. You can load the required node modules such as “events”, “util”, “crypto”, “dns” and few others in your database scripts. By default, tables have the “Insert”, “Update”, “Delete” & “Read” operations which make a request.execute() method. Any customizations to the operations can be accomplished in this space.

At the moment, the tables and classes in client app work on a 1:1 mapping. If you would like to use foreign key mapping and pull data from multiple tables, you can do joins in the scripts to retrieve from multiple tables.

Where Mobile Services doesn’t fit

Mobile Services are useful in scenarios where the Client Apps need to talk to a backend service for CRUD as well as other operations. It is also handy in setting up infrastructure for Authentication, Notification & Scheduled Jobs. However, Mobile Services will not replace traditional WCF Services suited for Enterprise Architecture. They don’t fit in Enterprise Service Bus scenarios for integration with Windows Server AppFabric and other scenarios.

Downloads

Mobile Service SDK can be downloaded from here

A complete walkthrough of creating a Mobile Service and configuring custom properties is available here