Introduction to Windows Azure Mobile Services

MobileServices

Today I would like to write about one of the feature on Windows Azure that was created by the team of Scott Guthrie. This new service, still tagged as a preview in the Azure management console, allows you to make easier your developments for Windows Phone, Windows 8 and even iPhone and Android devices with:

  • Structured storage. You can send and retrieve structured data between your client device and Azure using JSON messages or with the Windows Azure Mobile Services SDK. The backend of this storage is a SQL Server database but you don’t have to take care of it. Windows Store C#, Windows Phone 8, iOS.
  • User authentication. You will be able using a very simple line of code to get your mobile users to authenticate using for example their Microsoft Account or Facebook to access some restricted data or just to be identify by your system. Windows Store C#, Windows Phone 8, iOS.
  • Push notifications. Send a push notification to display a toast or change the tile on the client device has never been easier. With one line of JavaScript embedded on Azure, you can send push notification to all of your users. Windows Store C#, Windows Phone 8, iOS.

Microsoft did an amazing job by creating a lot of content to help developers creating applications using Windows Azure and I’ve linked, for each feature mentioned above, the corresponding tutorial for Windows 8 and Windows Phone 8 apps or even iOS.

Ok, now that we have the big picture of what is Windows Azure Mobile Services, let’s code a little bit. For one of my project I’m working on, I needed to connect Mobile Services, not from a mobile device but from a Worker Role also hosted on Azure. The main problem is that the Mobile Service SDK is not working for other projects than Windows 8, Windows Phone 8 (in the .NET world). Remember what I said about the Structured storage? You can exchange data using JSON messages. So I’ll use the REST APIs to communicate with my backend.

But first, let’s talk about the permissions. When you create a Table, you have to set the permission level against each operation on the table: Insert, Update, Delete and Read. You can choose between “Everyone”, “Anybody with the application key”, “Only Scripts and Admins”. The last category requires a Master key, to add in the headers of the HTTP request.

Permissions

We can start by creating a helper class named MobileServices.

public class MobileServices
{
    public string ServiceName { get; private set; }
    public string ApplicationId { get; private set; }
    public string MasterKey { get; private set; }

    public MobileServices(string serviceName, string applicationId)
        : this(serviceName, applicationId, string.Empty)
    {
    }

    ///Key used to send the request as Admin.
    public MobileServices(string serviceName, string applicationId, string masterKey)
    {
        ServiceName = serviceName;
        ApplicationId = applicationId;
        MasterKey = masterKey;
    }
}

Then, let’s create some basic operations like Insert:

public void Insert<T>(string tableName, T item)
    where T : class
{
    Uri address = new Uri(string.Format("https://{0}.azure-mobile.net/tables/{1}", ServiceName, tableName));

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);

    request.AllowWriteStreamBuffering = false;
    request.Method = "POST";
    request.Headers = new WebHeaderCollection
                                {
                                    {"X-ZUMO-APPLICATION", ApplicationId},
                                    {"X-ZUMO-MASTER", MasterKey},
                                };

    string serialization = item.Serialize();
    byte[] byteData = Encoding.UTF8.GetBytes(serialization);
    request.ContentLength = byteData.Length;

    using (Stream postStream = request.GetRequestStream())
    {
        postStream.Write(byteData, 0, byteData.Length);
    }

    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    response.Close();
}

Have a look at my previous post about JSON Serialization / Deserialization to get the snippet code for the method Serialize().

Now, how to delete a specific item in a table:

public void Delete(string tableName, string idToDelete)
{
    Uri address = new Uri(string.Format("https://{0}.azure-mobile.net/tables/{1}/{2}", ServiceName, tableName, idToDelete));

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);

    request.Method = "DELETE";
    request.Headers = new WebHeaderCollection
                            {
                                {"X-ZUMO-APPLICATION", ApplicationId},
                                {"X-ZUMO-MASTER", MasterKey},
                            };

    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    response.Close();
}

It is not possible (as I know) to clean up a table without deleting the table and re-creating it after. The problem with that is that when you ask to delete a table, it is queued in Microsoft system and will be deleted sometimes later so it prevents you to re-create a table with the same name right after. So you’ll have to retrieve all items then delete each of them.

Let’s try to retrieve items in a table:

public IEnumerable<T> Get<T>(string tableName, string filter = "")
    where T : class
{
    Uri address = new Uri(string.Format("https://{0}.azure-mobile.net/tables/{1}{2}", ServiceName, tableName, filter));

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);

    request.Method = "GET";
    request.Headers = new WebHeaderCollection
                            {
                                {"X-ZUMO-APPLICATION", ApplicationId},
                                {"X-ZUMO-MASTER", MasterKey},
                            };

    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {
        Stream stream = response.GetResponseStream();

        return stream.Deserialize<T[]>();
    }
}

I hope these methods can help you accessing your data in Azure Mobile Services. The code is far from perfect, you can still optimize it a lot more, but I think it is a good start.
The team Azure also introduced new features like the Job Scheduler, but I’ll come back on this part in another post.

2 thoughts on “Introduction to Windows Azure Mobile Services

Comments are closed.