Consuming Windows Azure Mobile Services REST API from ASP.NET Web API App

Windows Azure Mobile Services lets the developers to use structured storage, user authentication and push notifications to Android, iOS, HTML, Windows Store, or Windows Phone 8 apps  by leveraging the Windows Azure Cloud platform. Using with Windows Azure Mobile Services, you can enjoy the scalability power of Cloud to your Mobile apps. In this blog post, I will demonstrate how to persist data on Windows Azure Mobile Services Table from a ASP.NET Web API app by leveraging the Windows Azure Mobile Services REST API, and finally provides a generic type helper class for performing CRUD operations on the Windows Azure Mobile Services Table.

Consuming Windows Azure Mobile Services REST API from a ASP.NET Web API App

Windows Azure Mobile Services provides native API for Android, iOS, HTML, Windows Store, or Windows Phone 8 apps  so that you can directly consume the Windows Azure Mobile Services from your native Mobile apps. In this post, we will be consume the Windows Azure Mobile Services from a  ASP.NET Web API app. Windows Azure Mobile Services provides REST API so that we can easily consume it form our ASP.NET Web API app. This use case is based on a real world app I have recently worked, where iOS clients are consuming a REST API written in ASP.NET Web API and for some persistence over the REST API, we need to send push notifications to the iOS clients. So we are consuming the Windows Azure Mobile Services REST API from ASP.NET Web API app where we need to send push notifications. In this post, I am directly consuming the REST API from my app instead of using any REST API wrapper for .Net clients so that we can explore the Windows Azure Mobile Services REST API.

A Generic CRUD Helper Class for Windows Azure Mobile Services Table

Let’s create a generic type class for CRUD operations on the Windows Azure Mobile Services Table by consuming the REST API of Windows Azure Mobile Services. This generic type helper class can work with any type of Model object.

  1. public class MobileServiceRequestHelper<T> where T : class
  2.     {
  3.         private string tableEndpoint;
  4.         private string applicationKey;
  5.         private HttpClient client;
  6.         public MobileServiceRequestHelper(string tableName)
  7.         {
  8.             tableEndpoint = ConfigurationManager
  9.                 .AppSettings["TableEndpoint"] + tableName ;
  10.             applicationKey = ConfigurationManager
  11.                 .AppSettings["X-ZUMO-APPLICATION"];
  12.             client = new HttpClient();
  13.             client.DefaultRequestHeaders.
  14.                 Add("X-ZUMO-APPLICATION", applicationKey);
  15.             client.DefaultRequestHeaders.Accept
  16.                 .Add(new MediaTypeWithQualityHeaderValue("application/json"));
  17.         }
  18.     }

We are taking the application key and Mobile Services URI from the web.config table and we will pass the Windows Azure Table name in the constructor method of our generic type helper class.

Insert Operation

The API documentation for Insert record operation available from here. The code block below provides the implementation of HTTP Post for inserting a new record onto Windows Azure Mobile Services Table. We are serializing the model object as JSON format and executing the HTTP request by calling the SendAsync method of HTTPClient class.

  1. public bool Post(T requestData)
  2. {
  3.     var obj = JsonConvert.SerializeObject(requestData,
  4.         new JsonSerializerSettings()
  5.         {
  6.             NullValueHandling = NullValueHandling.Ignore
  7.         });
  8.     var request = new HttpRequestMessage(HttpMethod.Post,
  9.         tableEndpoint);
  10.     request.Content = new StringContent(obj, Encoding.UTF8,
  11.         "application/json");
  12.     var data = client.SendAsync(request).Result;
  13.     if (data.IsSuccessStatusCode)
  14.         return true;
  15.     else
  16.         throw new HttpResponseException(data.StatusCode);
  17. }

Update Operation

The API documentation for Update record operation available from here. The code block below provides the implementation of HTTP Put for updating an existing record onto Windows Azure Mobile Services Table.

  1. public bool Put(T requestData, int id)
  2. {
  3.             
  4.         var request = new HttpRequestMessage(new HttpMethod("PATCH"),
  5.             tableEndpoint + id);
  6.         var obj = JsonConvert.SerializeObject(requestData);
  7.         request.Content = new StringContent(obj, Encoding.UTF8,
  8.             "application/json");
  9.         var data = client.SendAsync(request).Result;
  10.         if (data.IsSuccessStatusCode)
  11.             return true;
  12.         else
  13.             throw new HttpResponseException(data.StatusCode);     
  14. }

Please note that Windows Azure Mobile Services used HTTP Verb “PATCH” for updating an existing record.

Delete Operation

The API documentation for Delete record operation available from here. The code block below provides the implementation of HTTP Delete for deleting an existing record from the Windows Azure Mobile Services Table.

  1. public void Delete(int id)
  2. {
  3.     var request = new HttpRequestMessage(HttpMethod.Delete,
  4.         tableEndpoint + id.ToString());
  5.     var data = client.SendAsync(request).Result;
  6.     if (!data.IsSuccessStatusCode)
  7.         throw new HttpResponseException(data.StatusCode);
  8. }

Query Operation

The API documentation for Query record operation available from here. The code block below provides the implementation of querying all records and filtering with id value from the Windows Azure Mobile Services Table.

  1. public IEnumerable<T> GetAll()
  2. {
  3.     var result = client.GetStringAsync(tableEndpoint).Result;
  4.     var data = JsonConvert.DeserializeObject<IEnumerable<T>>(result);
  5.     return data;
  6. }
  7. public T Get(int id)
  8. {
  9.     var result = client.GetStringAsync(tableEndpoint +
  10.         "?$filter=Id eq " + id).Result;
  11.     var data = JsonConvert.DeserializeObject<IEnumerable<T>>(result);
  12.     return data.FirstOrDefault();
  13. }

Windows Azure Mobile Services supports the Open Data Protocol (OData) so that you can query the data from Windows Azure Mobile Services Table by using the query option parameters provided by the OData.

The complete implementation of the MobileServiceRequestHelper class is available on Gist at https://gist.github.com/shijuvar/5562928

Consuming the REST API from ASP.NET Web API App

In the previous steps, we have created a generic type helper class for executing requests against Windows Azure Mobile Services REST API. The code block below provides the HTTP Post operation of our ASP.NET Web API where we inserting a new record onto Windows Azure Mobile Services table named “tokens”

  1. public HttpResponseMessage Post(Token token)
  2. {
  3.     if (ModelState.IsValid)
  4.     {
  5.         var req = new MobileServiceRequestHelper<Token>("tokens");
  6.         var isSuccess = req.Post(token);
  7.         if (isSuccess)
  8.         {
  9.             HttpResponseMessage response = Request.CreateResponse(
  10.                 HttpStatusCode.Created, token);
  11.             return response;
  12.         }
  13.         throw new HttpResponseException(HttpStatusCode.BadRequest);
  14.     }
  15.     else
  16.     {
  17.         return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
  18.     }
  19. }

In the above code block, we are creating an object of MobileServiceRequestHelper with generic type Token and inserting a new record on Windows Azure Mobile Services table “tokens”.

2 Comments

Comments have been disabled for this content.