Tuesday, 13 March 2012

Streamlining Data for Delivery Over Web Services

Taking a subset of data from SQL to pass through a WCF web service is of utmost importance for mobile applications using cellular networks. I never thought I'd be helping write applications for cell phones, but my opportunity to help came recently when the architect in charge of the project read "web services" from my skills list. I have done some crazy things reading and writing data to SharePoint via the out-of-the-box web services, but I've never created a web service of my own. Time to grow, I said…

After a brief ramp up, I had a WCF returning data along an HTTPS pipeline. I was dealing with objectified data within the entity framework model. The "queryable" data was of an abstract type I call "message".  Imagine a not too complex system to store and retrieve email messages. The data was heavy, dripping with metadata and system-used fields. Some of the data went well with the web-based version of the program that I was helping to create the mobile version of, but most of it didn't need to be passed along the packetized cellular radio infrastructure.

What I needed was to pass my queried data into a method that would transform it into a private object class that would be more suited for transport.

First, I chose a subset of the fields I wanted to return. Then I created a transformer method that mapped fields from the data model into the structure of the subset. I returned a list of these new class objects, which are then serialized with the JavaScript Serializer which spit out objects in JSON format for delivery via web service.

Transformer method:

private static List<Message> CleanResults(IQueryable<Model.message_vw> matchedMessages)
   var MessagesTransformed = matchedMessages.Select(x => new Message
                message_id = x.message_id,
                message_subject = x.message_subject,
                message_body = x.message_body,
                is_urgent = x.is_urgent,
                sent_by_user_id = x.sent_by_user_id
   return MessagesTransformed;

Data Retriever:

using (Model.Wef_Entities myWefEntities = new Model.Wef_Entities())
   var matchedMessages = myWefEntities.message_vw
      .Where(m => m.recipient_user_id == this.UserGuid)
      .OrderByDescending(o => o.sent_dt);
   return SerializeData(CleanResults(matchedMessages));

JSON Serializer:

public string SerializeData(object obj)
   JavaScriptSerializer jss = new JavaScriptSerializer();
   return jss.Serialize(obj);