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

168 comments:

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

    ReplyDelete
  2. 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
  3. 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
  4. 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
  5. nice information well done your information is helping alot thanks for valuable windows azure training in hyderabad


    ReplyDelete
  6. 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
  7. 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
  8. 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
  9. 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
  10. 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
  11. 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
  12. Thanks for sharing this article with us.powerful technology..Keep sharing

    UI UX Design Courses in Chennai

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

  14. 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
  15. 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
  16. 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

  17. 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
  18. 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
  19. Wonderful piece of work. Master stroke. I have become a fan of your words. Pls keep on writing.

    Guest posting sites
    Education

    ReplyDelete
  20. 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
  21. 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
  22. 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
  23. 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
  24. 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
  25. 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
  26. 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
  27. 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

  28. 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
  29. This comment has been removed by the author.

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

    ReplyDelete
  31. I Got Job in my dream company with decent 12 Lacks Per Annum salary, I have learned this world most demanding course out there in the current IT Market from the Data science courses in Bangalore Providers who helped me a lot to achieve my dreams comes true. Really worth trying.freelance SEO expert in bangalore

    ReplyDelete
  32. For Devops Training in Bangalore visit:Devops Training in Bangalore

    ReplyDelete
  33. amazing post written ... It shows your effort and dedication. Thanks for share such a nice post. Please check sandeep maheshwari quotes and harry potter wifi names

    ReplyDelete
  34. Its really nice post. Thank you. Ethical Hacking training in Chennai by Indian Cyber Security Solutions is a great opportunity for the people of Chennai. A computer hacker is any skilled computer expert that uses their technical knowledge to overcome a problem. Ethical Hacking Course done by ICSS. Indian Cyber Security Solutions is the Best Ethical Hacking Institute in Chennai.

    ReplyDelete
  35. Nice information, you write very nice articles, I visit your website for regular updates.
    Lucent GK

    ReplyDelete
  36. very nice amazing website your website is wonderfull thank you very much sir 먹튀 검증사이트

    ReplyDelete
  37. Nice information, you write very nice articles, I visit your website for regular updates.
    haircut for girls

    ReplyDelete
  38. Very good post, keep sending us such informative articles I visit your website on a regular basis.
    school management software

    ReplyDelete
  39. Wonderful thanks for sharing an amazing idea. keep it...

    Get SAP HANA Training in Bangalore from Real Time Industry Experts with 100% Placement Assistance in MNC Companies. Book your Free Demo with Softgen Infotech.

    ReplyDelete
  40. nic I Like It
    Today I am telling about make money online how from home and Best Earning apps or Best Way to make money online. Here you can Learn Every day Real Earning Apps or Mobile to earn money online using whatsapp.

    Visit - online earn money and Make Money Online Using Mobile

    ReplyDelete
  41. Thank you for sharing valuable information. Thanks for providing a great informatic blog, really nice required information & the things I never imagined. Thanks you once again Snapchat App Download

    ReplyDelete
  42. Thanks for your contribution in sharing such a useful information...
    AWS Course in Bangalore

    ReplyDelete
  43. Very useful and informative content has been shared out here, Thanks for sharing it...
    Devops Training in Bangalore

    ReplyDelete
  44. I just got to this amazing site not long ago. I was actually captured with the piece of resources you have got here. Big thumbs up for making such wonderful blog page!

    business analytics course

    data analytics courses in mumbai

    data science interview questions

    data science course in mumbai

    ReplyDelete
  45. Effective blog with a lot of information. I just Shared you the link below for Courses .They really provide good level of training and Placement,I just Had Data Science Classes in this institute , Just Check This Link You can get it more information about the Data Science course.


    Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery

    ReplyDelete
  46. Excellent Blog!!! The blog which you have shared here is more informative, This is really too useful and have more ideas and keep sharing many techniques about java. Thanks for giving a such a wonderful blog.
    Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery

    ReplyDelete
  47. Thank you for such a nice article keep posting, I am a RegularVisitor of your website.
    indiapostgdsonline phase 4 reg combinednew

    ReplyDelete
  48. Pretty article! I found some useful information in your blog....

    so here we provide,

    We provide you with flexible services and complete hybrid network solutions. It can provide your organisation with exceptional data speeds, advanced external security protection, and high-resilience by leveraging the latest SD-WAN and networking technologies to monitor, manage and strengthening your organisation’s existing network devices.

    https://www.quadsel.in/networking/>
    https://twitter.com/quadsel/
    https://www.linkedin.com/company/quadsel-systems-private-limited/
    https://www.facebook.com/quadselsystems/

    #quadsel #network #security #technologies #managedservices #Infrastructure #Networking #OnsiteResources #ServiceDeskSupport #StorageServices #WarrantyAMCServices #datacentersolutions #DataCenterBuild #EWaste #InfraConsolidation #DisasterRecovery #NetworkingServices #ImagingServices #MPS #Consulting #WANOptimisation #enduserservices

    ReplyDelete
  49. Nice information, you write very nice articles, I visit your website for regular updates.
    rakesh yadav maths

    ReplyDelete
  50. Nice information, you write very nice articles, I visit your website for regular updates.
    cm of goa

    ReplyDelete
  51. Nice information, you write very nice articles, I visit your website for regular updates.
    delhi pin code

    ReplyDelete
  52. I recently came across your blog and have been reading along. I thought I would leave my first comment. I don't know what to say except that I have enjoyed reading. Nice blog. I will keep visiting this blog very often keep it up
    Ai & Artificial Intelligence Course in Chennai
    PHP Training in Chennai
    Ethical Hacking Course in Chennai Blue Prism Training in Chennai
    UiPath Training in Chennai

    ReplyDelete
  53. Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot.

    SAP SD Online Training

    SAP SD Classes Online

    SAP SD Training Online

    Online SAP SD Course

    SAP SD Course Online


    ReplyDelete
  54. Thanks for sharing information awesome blog post Online Education Quiz website For Exam Follow this website Gk in Hindi

    ReplyDelete
  55. Wonderful narration great keep updating thanks for share
    GMAT classes chennai

    ReplyDelete
  56. introduced as Great Plains Software Makeup development environment, development language (Sanscript) and modification it services los angeles

    ReplyDelete
  57. The postings on your site are always excellent. i really loved the content in it Thanks for the share and keep up this great work! All the best to you. please keep updating.
    DevOps Training in Chennai

    DevOps Course in Chennai

    ReplyDelete
  58. I've been searching for 한국야동 hours on this topic 무료야동사이트, and finally I found your post 무료성인야동, and I've read your post 일본야동 and I'm very impressed 무료야동. We prefer your opinion 성인사진 and will visit this site frequently to refer to your opinion 성인야동. When would you like to visit my site? 조개모아

    ReplyDelete
  59. Awesome blog you have here 온라인카지노 but I was wondering if you knew of any forums 스포츠토토 that cover the same topics talked about here 먹튀검증사이트? I’d really like to be a part of group where I can get suggestions 안전놀이터 from other experienced people 추천픽 that share the same interest 먹튀사이트. If you have any recommendations 검증사이트, please let me know 먹중소. Bless you! 먹튀중개소

    ReplyDelete
  60. I've been searching for 토렌트사이트 hours on this topic 야동사이트, and finally I found your post 먹튀검증사이트, and I've read your post 웹툰사이트 and I'm very impressed 성인용품. We prefer your opinion 스포츠중계 and will visit this site frequently to refer to your opinion 드라마다시보기. When would you like to visit my site? 한인사이트 무료야동

    ReplyDelete
  61. I've been searching for 한국야동 hours on this topic 무료야동사이트, and finally I found your post 무료성인야동, and I've read your post 일본야동 and I'm very impressed 무료야동. We prefer your opinion 성인사진 and will visit this site frequently to refer to your opinion 성인야동. When would you like to visit my site? 조개모아

    ReplyDelete
  62. It's been our pleasure to inform you that our institution is offering a great deal by giving CS executive classes and a free CSEET class only for those who are interested in gaining knowledge. So what are you waiting for contact us or visit our website at https://uniqueacademyforcommerce.com/

    ReplyDelete
  63. Have you been bored during this lockdown! Don't worry our institution is here to conduct CS executive classes and free of cost CSEET classes . So stop wasting your time and hurry up. Contact us or visit our website at

    cs executive
    freecseetvideolectures/
    UNIQUE ACADEMY

    ReplyDelete
  64. Excellent article and with lots of information. I really learned a lot here. Do share more like this.
    UiPath Automation
    Robotic Process Automation UiPath

    ReplyDelete
  65. Don't Waste Your Time Checking Dollar To Real Every Day! Get The Most Accurate Exchange Rate For The Dollar To Real With Our Original Universal Currency Converter.

    ReplyDelete
  66. Do You Now AximTrade Login Is A Secure, Multi-channel, Multi-factor Authentication System, Enabling Customers To Securely Access Their Accounts To Fund/deposit, Request Withdrawal, Update Or Manage Their Profile And More.

    ReplyDelete
  67. If You Are Looking For A Reliable Fx Broker, Don't Rush And Read This XM REVIEW Review First. This Is A Serious Warning Against The Broker's Illegal Activities.

    ReplyDelete
  68. AVATRADE REVIEW Review - Find Out Everything About This Forex Broker. Read Our Detailed Fx Choice Review And Make Sure If This Broker Is For You. We Scrutinized The Broker And The Trading Conditions Thoroughly.

    ReplyDelete
  69. It is extremely nice to see the greatest details presented in an easy and understanding manner.
    data science training institute in hyderabad

    ReplyDelete
  70. Your blog provided us with valuable information to work with. Each & every tips of your post are awesome. Thanks a lot for sharing. Keep blogging,
    data scientist training in hyderabad

    ReplyDelete
  71. Nice information, you write very nice articles
    Jewellery ERP Software Dubai
    Jewellery ERP Software Dubai

    ReplyDelete
  72. As one of SAP’s most essential modules, SAP Material Management (MM) is a critical component. Almost every industry uses SAP, therefore the need for competent individuals is rather high. As part of daily company activities, the SAP MM application assists with inventory and procurement. In addition to purchasing and product receiving, inventory and material storage are also included in this process.

    best-sap-mm-training-in-hyderabad/

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

    ReplyDelete
  74. fantastic article It was really helpful to read your thorough description of how Windows Azure Mobile Services (WAMS) integration with Windows 8 Managed Applications using C# works. The knowledge gained about the MobileServicesClient and its many features, including CRUD operations, filtering, sorting, and paging, is priceless. I appreciate you sharing this useful manual.

    Data Analytics Courses in India

    ReplyDelete
  75. This comprehensive guide to Windows Azure Mobile Services (WAMS) showcases its capabilities for Windows 8 applications. The breakdown of client interactions and operations is valuable for developers. Great resource! Thank you.
    Data Analytics Courses in Nashik

    ReplyDelete
  76. https://ibuzzlog.blogspot.com/2013/11/install-mahout-on-virtualbox-ubuntu.html?sc=1695776692315#c7643235788897956484

    ReplyDelete
  77. Hello! Your guide is a valuable asset for developers seeking to utilize mobile services to enhance their applications. Thanks for sharing.
    Data Analytics Courses In Chennai

    ReplyDelete
  78. For developers looking to use mobile services to improve their applications, your handbook is an invaluable resource. I appreciate you sharing.
    Data Analytics Courses in Agra

    ReplyDelete
  79. good blog
    Data Analytics Courses In Vadodara

    ReplyDelete
  80. This blog post is a fantastic guide for developers looking to harness the power of mobile services in their Windows 8 managed applications.
    Digital marketing courses in illinois

    ReplyDelete
  81. The blog post effectively highlights the steps using mobile services in Windows 8 managed applications.
    Digital Marketing Courses in Italy

    ReplyDelete
  82. Thanks for sharing excellent and comprehensive tutorial on Using Mobile Services in Windows 8 Managed Application.
    data analyst courses in limerick

    ReplyDelete
  83. Useful material. Thank you for sharing a resourceful content.
    Investment banking courses in the world

    ReplyDelete
  84. The insights shared in the blog provide a valuable resource for developers looking at their applications. The mobile services add a dynamic layer to Windows 8 development, and this blog makes the process clear and accessible.
    Data analytics framework

    ReplyDelete