Monday, October 1, 2012

Using Mobile Services in Windows 8 Managed Application (C# code)

Windows Azure Mobiles Services (WAMS) targets Windows 8 Applications in its first preview - a great starting point on the way to supporting multiple mobile platforms down the road. This post covers a few basics of using WAMS in managed code (C# or VB.NET) using C# examples. You could use VB.NET just as well. Some of this is already covered in tutorials but you might find this useful as a cheat sheet.

A Mobile Service created using WAMS has an http REST endpoint that can be used directly if you like. But  we  also ship an SDK (currently in MSI form) that elevates the experience quite a bit and bring it closer to the host language and platform. This post is about the SDK experience. If you haven't already completed the quick start and related tutorials, I strongly recommend you do those first. This post is intended to be complementary though I do repeat a few things to make the post a bit more self-contained.


The main class is the MobileServicesClient - the go to class for all your needs. It takes two parameters:
  1. URL for the Mobile Service. This is globally unique (hence you need to pick a unique service name when you create one)
  2. App key: this identifies the app (since this is distributed with the app and viewable in fiddler or other browser dev tools, you could call it an "open secret"; i.e. it has identification value and no real security value)

public static MobileServiceClient client = new MobileServiceClient(appURL, appKey);

You start by getting a table proxy so that subsequent code can be strongly typed.

IMobileServiceTable<TodoItem> TodoTable = App.client.GetTable<TodoItem>();

Don't worry, just as in other LINQ incarnations, this table is just a proxy that knows how to perform CRUD type operations. The following statement does NOT retrieve the entire table down to the client. (In fact, for the app's good, we don't allow that even otherwise but more about it later).

The client also supports login in addition to CRUD (Create, Read, Update and Delete) operations.


In managed code, the query support is quite straightforward. It is basically the LINQ experience with support for a subset that roughly covers filtering, sorting and paging against a single collection (i.e. no joins, no groupby etc.).

Getting Results

There are a few options to get the results of a query that is executed asynchronously (hint: you can't just use regular ToList here; you need an awaitable task or something that can handle async ops)

// If you just want and IEnumerable. Returns an awaitable Task
var items0 = todoTable.ToEnumerableAsync();
// Friendly collection to iterate through
var items1 = todoTable.ToListAsync();
// More fancy data binding.
// ICollectionView, INotifyCollectionChanged, INotifyPropertyChanged and a bunch of other interfaces are implemented
MobileServiceCollectionView<TodoItem> items2 = todoTable.ToCollectionView();

For quick and dirty prototyping, I prefer to use MobileServiceCollectionView (MSCV). For more specific use; it is better to have your own custom implementation of ICV etc.


MobileServiceTableQuery<TodoItem> query = todoTable.Where(todoItem => todoItem.Complete == false);
You could use the comprehension syntax if you prefer. It is just LINQ, though within limits of supported operators and member functions.
Lookup helps you get a single object.
// Singleton or null
var item0 = await todoTable.LookupAsync(id);
if (item0 != null)
    // For illustrative purposes only
    MessageDialog md = new MessageDialog(item0.Text);
    var ignoreAsyncResult = md.ShowAsync();


As in case of filtering, you can use the standard LINQ operators with lambda or comprehension syntax:
var query = todoTable.OrderBy(t => t.Text);

In addition, you can also use other operators like ThenBy, OrderByDescending etc.


For mobile apps, data is often bound to a UI so it is often best retrieved a page at a time. On slower networks, even data retrieved for other purposes (i.e. not for directly displaying in a UI) should be limited through paging. Paging relies on LINQ Skip and Take operators.
// First page
var query = todoTable.OrderBy(t => t.Text).Take(page_size);
// For (n+1)th page
var query = todoTable.OrderBy(t => t.Text).Skip(n*page_size).Take(page_size);

Mobile Services runtime (server-side) provides paging by default by restricting the results to 50 objects. This is usually appropriate for most UI binding scenarios. You can override that by applying Take(n) where n can be any number from 1 to 1000.

There is also a way to get the total count of all objects matching your query (not just the first page). I will cover that in a separate post later.

Create, Update and Delete operations are quite straightforward.

    // Insert a new record
    TodoItem newItem = new TodoItem { Text = "Complete C# Client blog post", Complete = false };
    await todoTable.InsertAsync(newItem);

    // Update a record
    newItem.Complete = true;
    await todoTable.UpdateAsync(newItem);

    // Delete a record
    await todoTable.DeleteAsync(newItem);

Insert operation performs dynamic schematization. You don't need to go through the ceremony of creating a table with typed columns etc. Mobile Services run-time looks at the properties in the JSON payload and adds eponymous column(s) if they are not already present. It looks at the value of the property to infer the type. Of course, because the base types in JavaScript (which is what is used for server scripts and underlies JSON) are fairly simple, the list of types is much smaller than that in .NET or SQL. Here is a quick table that describes the types currently used.

JSON Value
T-SQL Type
Numeric values (integer, decimal, floating point)

Likewise, update operation can also perform dynamic schematization if necessary.

Typically you want dynamic schematization when you are developing your app for rapid turnaround and changes. When you deploy, it is usually a good idea to "lock down" the schema by turning off dynamic schematization so users of your app can't accidentally or maliciously expand the schema. Mobile Service developers can turn off dynamic schematization in the portal ("CONFIGURE" tab).

For the delete operation, the only property on newItem object that matters is the ID assigned by Mobile Service when the object was created in the table.

Untyped Usage
The C# client is primarily designed for strongly typed scenarios. However, sometimes a more loosely typed experience is convenient (e.g. objects with open schema). That is enabled as follows. In queries, you lose LINQ and you have to dropped down to effectively the wire-format.

    // Get an untyped table reference
    IMobileServiceTable untypedTodoTable = App.MobileService.GetTable("TodoItems");

    // Lookup untyped data using odata
    IJsonValue untypedItems = await untypedTodoTable.ReadAsync("$filter=complete eq 0&$orderby=text");

You get back JSON value that you can use like a property bag.

I strongly recommend going through the tutorial on our dev center to understand authentication and users. This is just for completing the cheat sheet:
    // Log in
    MobileServiceUser user = await App.MobileService.LoginAsync(windowsLiveToken);


  1. Excellent post! Like this..Thanks for sharing!

  2. Excellent information. This site definitely explains essential concepts to its readers. Thanks for continuing to write such wonderful articles
    Establishing Business Value

  3. Superb data. This site without a doubt demonstrates key ideas to its followers and the concept of developing windows application is getting common day by day.

    For more details please visit
    windows mobile app // Android application development // mobile application development

  4. Your information about c# is really interesting and innovative. Also I want you to share latest updates about c#. Can you update it in your website? Thanks for sharing
    Dot net training institute in Chennai

  5. Nice article i was really impressed by seeing this article, it was very interesting and it is very useful for Learners.I get a lot of great information from this blog. Thank you for your sharing this informative blog.Android Training in chennai | Android Training chennai | Android course in chennai | Android course chennai

  6. Excellent Post, I welcome your interest about to post blogs. It will help many of them to update their skills in their interesting field.
    Python Training in Chennai|Python training courses|Python training in velachery

  7. nice information well done your information is helping alot thanks for valuable windows azure training in hyderabad

  8. Phone calls can be composed so that the calling party calls alternate members and adds them to the call; be that as it may, members are generally ready to call into the telephone call themselves by dialing a phone number that interfaces with a "meeting extension" (a specific sort of hardware that connections phone lines).
    Conference Calling Plugins

  9. it is really a new technology and thus it is very much useful for me to understand more things and it is very useful too.

    Salesforce Training institute in Chennai

  10. This idea is mind blowing. I think everyone should know such information like you have described on this post. Thank you for sharing this explanation.Your final conclusion was good. We are sowing seeds and need to be patiently wait till it blossoms.

    Best App store optimization services in Chennai

  11. Superb. I really enjoyed very much with this article here. Really it is an amazing article I had ever read. I hope it will help a lot for all. Thank you so much for this amazing posts and please keep update like this excellent article.thank you for sharing such a great blog with us. expecting for your.
    Digital Marketing Company in India

  12. Great post! I am see the great contents and step by step read really nice information.I am gather this concepts and more information. It's helpful for me my friend. Also great blog here with all of the valuable information you have.
    Germany Education Consultants in Chennai

  13. Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end.

    Digital marketing Course in Chennai

  14. This blog is having the general information. Got a creative work and this is very different one.We have to develop our creativity mind.This blog helps for this. Thank you for this blog. This is very interesting and useful.

    Fresher Jobs in Mumbai
    Fresher Jobs in Pune
    Fresher Jobs in Noida
    Fresher Jobs in Hyderabad

  15. Excellent and very cool idea and the subject at the top of magnificence and I am happy to this post..Interesting post! Thanks for writing it. What's wrong with this kind of post exactly? It follows your previous guideline for post length as well as clarity..
    Digital Marketing Company in Chennai

  16. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
    Android Training in Chennai
    Ios Training in Chennai

  17. Its a wonderful post and very helpful, thanks for all this information. You are including better information regarding this topic in an effective way.Thank you so much

    Installment loans in alabama
    Payday loans in alabama
    Title loans in alabama
    Cash Advances in alabama

  18. These provided information was really so nice,thanks for giving that post and the more skills to develop after refer that post. Your articles really impressed for me,because of all information so nice.

    Digital Marketing Company in India
    Web Development Company in India
    Web Design Company in Chennai

  19. Thanks for sharing informative article. Download Windows 7 ultimate for free from getintopc. It helps you to explore full functionality of windows operating system.

  20. What a fantabulous post this has been. Never seen this kind of useful post. I am grateful to you and expect more number of posts like these. Thank you very much. Managed IT Services Provider

  21. Hello, this weekend is good for me, since this time i am reading this enormous informative article here at my home. Managed IT services Calgary

  22. As you have now understood the usage of ‘Record and Playback’ tool, the following are the different posts using which you can explore the functioning of ‘Selenium IDE’
    selenium Training in chennai

  23. I am really happy with your blog because your article is very unique and powerful for new reader.
    selenium training in chennai
    selenium training in bangalore

  24. SQream Technologies provides you with a state of the art software which combines modern GPU technology (Graphic Processing Units) with the best practices in today’s Big Data platforms, providing up to 100x faster insights from data.
    Bigdata Training in Chennai OMR

  25. Thanks for sharing this article with us.powerful technology..Keep sharing

    UI UX Design Courses in Chennai

  26. I like it and help me to development very well. Thank you for this brief explanation and very nice information. Well, got a good knowledge.
    industrial course in chennai

  27. Nice tutorial. Thanks for sharing the valuable information. it’s really helpful. Who want to learn this blog most helpful. Keep sharing on updated tutorials…
    Devops Training courses
    Devops Training in Bangalore
    Best Devops Training in pune
    Devops interview questions and answers