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.

Client

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.

Queries

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.

Filtering

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();
}

Sorting

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.

Paging

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.

CUD
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)
Float(53)
Boolean
Bit
DateTime
DateTimeOffset(3)
String
Nvarchar(max)

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.

Login
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);

92 comments:

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

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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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.
    Regards,
    Python Training in Chennai|Python training courses|Python training in velachery

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


    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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.

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

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

    UI UX Design Courses in Chennai

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete

  28. Very useful and informative content has been shared out here, Thanks for sharing it.
    Visit Learn Digital Academy for more information on Digital marketing course in Bangalore.

    ReplyDelete
  29. Your post is really awesome. Your blog is really helpful for me to develop my skills in a right way. Thanks for sharing this unique information with us.
    - Learn Digital Academy

    ReplyDelete
  30. Very useful and informative content has been shared out here, Thanks for sharing it.
    Visit Learn Digital Academy for more information on Digital marketing course in Bangalore https://www.learndigital.co/.

    ReplyDelete
  31. Wonderful bloggers like yourself who would positively reply encouraged me to be more open and engaging in commenting.So know it's helpful.
    python course institute in bangalore
    python Course in bangalore
    python training institute in bangalore

    ReplyDelete

  32. Thank you for sharing your article. Great efforts put it to find the list of articles which is very useful to know, Definitely will share the same to other forums.

    best openstack training in chennai | openstack course fees in chennai | openstack certification in chennai | redhat openstack training in chennai

    ReplyDelete
  33. In the beginning, I would like to thank you much about this great post. Its very useful and helpful for anyone looking for tips. I like your writing style and I hope you will keep doing this good working.
    Angularjs Training Institute in Bangalore
    Angularjs Classes in Bangalore
    Angularjs Coaching in Bangalore
    Best Institute For ccna Course in Bangalore
    Best ccna Training Institute in Bangalore
    ccna Coaching in Bangalore

    ReplyDelete
  34. Wonderful piece of work. Master stroke. I have become a fan of your words. Pls keep on writing.

    Guest posting sites
    Education

    ReplyDelete
  35. Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your blog.

    best rpa training in chennai
    rpa training in chennai
    rpa interview questions and answers
    automation anywhere interview questions and answers
    blueprism interview questions and answers
    uipath interview questions and answers
    rpa training in bangalore

    ReplyDelete
  36. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging

    UIPath Training in Chennai
    UIPath Training

    ReplyDelete
  37. When I initially commented, I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get several emails with the same comment. Is there any way you can remove people from that service? Thanks.
    AWS Training in Bangalore | Amazon Web Services Training in Bangalore
    Advanced Amazon Web Services Training in Pune | Best AWS Training in Pune
    AWS Online Training | Best Online AWS Certification Course - Gangboard
    Best Top 110 plus AWS Interview Question and Answers 2019

    ReplyDelete
  38. Outstanding blog thanks for sharing such wonderful blog with us ,after long time came across such knowlegeble blog. keep sharing such informative blog with us.
    Check out : machine learning with python course in Chennai

    machine learning course in Chennai

    ReplyDelete
  39. Thank you so much for your information,its very useful and helful to me.Keep updating and sharing. Thank you.
    RPA training in chennai | UiPath training in chennai

    ReplyDelete
  40. Such a Great Article!! I learned something new from your blog. Amazing stuff. I would like to follow your blog frequently. Keep Rocking!!
    Blue Prism training in chennai | Best Blue Prism Training Institute in Chennai

    ReplyDelete
  41. Thanks for such a great article here. I was searching for something like this for quite a long time and at last, I’ve found it on your blog. It was definitely interesting for me to read about their market situation nowadays.AngularJS Training in Chennai | Best AngularJS Training Institute in Chennai

    ReplyDelete
  42. Given so much info in it, The list of your blogs are very helpful for those who want to learn more interesting facts. Keeps the users interest in the website, and keep on sharing more, To know more about our service:
    Please free to call us @ +91 9884412301 / 9600112302

    Openstack course training in Chennai | best Openstack course in Chennai | best Openstack certification training in Chennai | Openstack certification course in Chennai | openstack training in chennai omr | openstack training in chennai velachery

    ReplyDelete
  43. 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.
    rpa training in bangalore
    best rpa training in bangalore
    RPA training in bangalore
    rpa course in bangalore
    rpa training in chennai
    rpa online training

    ReplyDelete
  44. Wow!! Really a nice Article. Thank you so much for your efforts. Definitely, it will be helpful for others. I would like to follow your blog. Share more like this. Thanks Again.
    iot training in Chennai | Best iot Training Institute in Chennai

    ReplyDelete
  45. Great post! I am actually getting ready to across this information, It's very helpful for this blog. Also great with all of the valuable information you have Keep up the good work you are doing well.DevOps Training in Chennai | Best DevOps Training Institute in Chennai

    ReplyDelete
  46. Nice blog..! I really loved reading through this article. Thanks for sharing such a
    amazing post with us and keep blogging... Best React js training near me | React js training online

    ReplyDelete
  47. Appreciating the persistence you put into your blog and detailed information you provide
    Python Online training
    python Training in Chennai
    Python training in Bangalore

    ReplyDelete
  48. My rather long internet look up has at the end of the day been compensated with pleasant insight to talk about with my family and friends.
    iosh course in chennai

    ReplyDelete
  49. Whoa! I’m enjoying the template/theme of this website. It’s simple, yet effective. A lot of times it’s very hard to get that “perfect balance” between superb usability and visual appeal. I must say you’ve done a very good job with this.

    AWS Training in Bangalore | Best AWS Amazon Web Services…
    Amazon Web Services (AWS) Training in Pune India
    AWS Training | AWS Training and Certification | AWS online training
    AWS Training in Bangalore cost| Aws training in Bangalore with placements

    ReplyDelete
  50. 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.
    online Python training
    python training in chennai

    ReplyDelete
  51. I think this is the best article today about the future technology. Thanks for taking your own time to discuss this topic, I feel happy about that curiosity has increased to learn more about this topic. Artificial Intelligence Training in Bangalore. Keep sharing your information regularly for my future reference.

    ReplyDelete
  52. Thanks for such a great article here. I was searching for something like this for quite a long time and at last, I’ve found it on your blog. It was definitely interesting for me to read about their market situation nowadays.iot certification chennai | iot training courses in chennai | iot training institutes in chennai | industrial iot training chennai

    ReplyDelete
  53. This is very good content you share on this blog. it's very informative and provide me future related information.
    AWS training in chennai

    AWS Training in Bangalore

    ReplyDelete
  54. I Read more blog with this same topic... But This blog is very clear and informative
    Regards,
    Best Devops Training in Chennai | Best Devops Training Institute in Chennai

    ReplyDelete
  55. Nice blog..! I really loved reading through this article. Thanks for sharing such a
    amazing post with us and keep blogging... best angularjs training institute in chennai | angularjs training in omr | angular 4 training in chennai | angularjs training in omr

    ReplyDelete
  56. This is a great inspiring article.I am pretty much pleased with your good work.You put really very helpful information. Keep it up. Keep blogging. Looking to reading your next post.
    Devops Training in Chennai | Devops Training Institute in Chennai

    ReplyDelete

  57. NICE for giving a chance to share ideas for your comuty i really thanks for that great post.
    Deer Hunting Tips Camping Trips Guide DEER HUNTING TIPS travel touring tips

    ReplyDelete

  58. Thanks for sharing the information. It is very useful for my future. keep sharing
    Still Hunting Method
    Hunting psych tips Survival Tips Travel Touring Tips


    ReplyDelete
  59. 1. many peoples want to join random whatsapp groups . On this website you can join unlimited groups . click and get unlimited whatsapp group links 18+

    ReplyDelete
  60. 2. if you are searching for free unlimted tricks then visit now on Uvoffer.com and get unlimited offers and informations.
    film ka naam whatsapp puzzle answer 🐵🐵🐵 +🐘+3+🏹+🏚+💔 =

    ReplyDelete
  61. 3. if you want girls mobile numbers then this website is best for you . you can visit on this website and get their information and you also can meet with thrm and go for a date . click here to use our website --- 100% free online dating website

    ReplyDelete
  62. Interesting information and attractive.This blog is really rocking... Yes, the post is very interesting and I really like it.I never seen articles like this. I meant it's so knowledgeable, informative, and good looking site. I appreciate your hard work. Good job.
    Kindly visit us @
    Sathya Online Shopping
    Online AC Price | Air Conditioner Online | AC Offers Online | AC Online Shopping
    Inverter AC | Best Inverter AC | Inverter Split AC
    Buy Split AC Online | Best Split AC | Split AC Online
    LED TV Sale | Buy LED TV Online | Smart LED TV | LED TV Price
    Laptop Price | Laptops for Sale | Buy Laptop | Buy Laptop Online
    Full HD TV Price | LED HD TV Price
    Buy Ultra HD TV | Buy Ultra HD TV Online
    Buy Mobile Online | Buy Smartphone Online in India

    ReplyDelete
  63. This is really great work. Thank you for sharing such a good and useful information here in the blog for students.
    Kindly visit us @
    SATHYA Technosoft (I) PVT LTD
    Social Media Marketing Company in India
    SEO Company India
    PPC Services in India

    ReplyDelete
  64. Just seen your Article, it amazed me and surpised me with god thoughts that eveyone will benefit from it. It is really a very informative post for all those budding entreprenuers planning to take advantage of post for business expansions. You always share such a wonderful articlewhich helps us to gain knowledge .Thanks for sharing such a wonderful article, It will be deinitely helpful and fruitful article.
    Thanks
    DedicatedHosting4u.com

    ReplyDelete
  65. This comment has been removed by the author.

    ReplyDelete
  66. Thanks for sharing this valuable information and we collected some information from this blog.
    VPS Hosting India

    ReplyDelete