Execute read query in Azure Mobile Services

Microsoft had their cloud services from past many years. Traditionally developers have to spend good amount of efforts in writing the service related code. With the advent of Windows 8, Microsoft is helping developers to focus more on client based application development. Their major intent is to give fewer burdens to the developer for Server side development and let him/her focus more on metro style app development. With these intentions in mind, they released a very light weighted product called Azure Mobile Service. I will recommend anyone who wants to explore Azure Mobile service to watch the video on the same by Josh Twist at Channel 9
Azure Mobile Service comes with easy installation and usage guide. Creating a new Windows 8 or Windows Store app and integrating it with Azure mobile service is pretty straightforward. Here in this blog we will focus on ways to read entities from Azure Mobile service and how to effectively use them.
To get started with Azure Mobile Service you can browse here. With every newly created service there are four functions namely – Insert, Read, Update and Delete. As already mentioned I want to discuss 2 approaches from where the data can be read through Azure Mobile Service. This blog is specifically dedicated to differentiate between these 2 read function approaches in order to bring forth the usage of them in real time. They are :
1.       Query executed at client side
2.       Query executed at server side

Query executed at client side


Scenario: Assume that there is an application where the developer fetches the overall data at one go and then filters and prunes the collected data at the client side to fulfill all the functionalities. So apparently there is only one service call to fulfill all the functionalities through the rest of the application. For such kind of scenario the query sent from the client should be to fetch all the data in a List or an array for further process.
Code Snippet:
/// <summary>
/// Fetch the user by UserId
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public async Task<UserDetails> GetUserByUserId(int userId)
{
        try
        {
           var myTab = await App.MobileService.GetTable<UserDetails>().ToListAsync();
           UserDetails userList = myTab.Where(user => user.UserId == userId).ToList<UserDetails>().FirstOrDefault();
           return userList;
        }
        catch (Exception)
        {
           //TODO
        }
}

Description: In the above code snippet the objective is to fetch user details specific to an userId. Here my Azure Mobile Service table has been named as UserDetails. The UserDetails table has id, first name, last name, Company and email as its entities.
Here the line
var myTab = await App.MobileService.GetTable<UserDetails>().ToListAsync();

fetches all the data that exists in the UserDetails table and stores it in a list. Remember, all these are asynchronous call and should be preceded by await command.
The next line which says
UserDetails userList = myTab.Where(user => user.UserId == userId).ToList<UserDetails>().FirstOrDefault();

does the comparison between the Column entity UserId value and the function parameter userId, so in this case we fetch the data once and then can reuse the same set of data again without making another server query request. For ex:  The same data can be used to fetch all the users of same company.

 

Query executed at server side


Scenario: Assume that our objective to find all the friends of the same userId. Now in this case, our user can have hundreds of friends and the whole friend database might have lakhs of entries. In this case it is not feasible to fetch all the records and do the selection at the client side. For such kind of scenarios we need a snippet that can select the response based on the query at the server side.
Code Snippet:
/// <summary>
/// to fetch the list of friends by user's unique Id
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public async Task<List<FriendsDetails>> GetFriendsListForUser(int userId)
{
     try
     {
        MobileServiceTableQuery<FriendsDetails> query = friendDetailsTable.Where(
                    user => user.UserId == userId).Take(1000);
         return await query.ToListAsync();
       }
       catch (Exception)
       {
                //TODO
       }
}

Description: In the above code snippet we are creating a MobileServiceTableQuery on the FriendDetails table. The query has a constraint that it has to fetch all the friend details which are pertaining to the user.
Remember, that Azure mobile service tend to send 50 data at a time. If you wish to fetch more data you need to explicitly mention it as I have done here by Take command. Now in comparison to the previous code snippet, here the query is first created and then sent to the server which processes the response on the same condition. Thus the filtering happens at the server side and the response is then sent to the client.

Both the approaches are equally useful and can help in optimization of code. It depends on what the objective is and the desired output. Hope this information is useful.

Comments

Popular posts from this blog

Firebase authentication with Ionic creator

Big Data - SWOT Analysis

LINKEDIN api call using NODE.JS OAUTH module