<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
  version="2.0">
  <channel>
    <title>Carlos Figueira MSDN blog</title>
    <atom:link
      href="https://docs.microsoft.com/archive/blogs/carlosfigueira/feed.xml"
      rel="self"
      type="application/rss+xml" />
    <link>https://docs.microsoft.com/archive/blogs/carlosfigueira/feed.xml</link>
    <description>General thoughts and usage examples about PowerApps, WCF, ASP.NET Web API, Windows Azure Mobile Services, testing and programming in general.</description>
    <lastBuildDate>Thu, 21 Dec 2017 18:30:27 GMT</lastBuildDate>
    <language>en-US</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <item>
      <title>Decoupling the browse gallery from the display / edit forms in PowerApps</title>
      <link>https://docs.microsoft.com/archive/blogs/carlosfigueira/decouplingbrowsegalleryfromforms</link>
      <pubDate>Wed, 04 Oct 2017 19:20:43 GMT</pubDate>
      <dc:creator><![CDATA[CarlosFigueira]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/carlosfigueira/?p=2525</guid>
      <description><![CDATA[One of my favorite features of PowerApps is the "Start with your data" way of creating apps. The...]]></description>
      <content:encoded><![CDATA[One of my favorite features of <a href="https://www.powerapps.com">PowerApps</a> is the "Start with your data" way of creating apps. The ability to start with a fully-functional app (a browse screen that lists the items from your data source, plus two screens with a details view and an edit view of individual items) that you can customize is a great way for people to start playing with the platform. The app that is generated has fairly simple formulas, to further help understanding how PowerApps works.

One of the characteristics of the app is that both the detail and the edit forms used in the app are bound to the selected item in the gallery: the Item property of the form controls is set as shown below:

<code>DetailForm1.Item: BrowseGallery1.Selected
EditForm1.Item: BrowseGallery1.Selected
</code>

This works well for most cases - but now all. A user in the forums wanted to have not one but two browse galleries, so it couldn't bind the item in the forms to only one of them. Another user wanted to go to the display/edit screens not by selecting an item in the gallery, but by <a href="https://powerusers.microsoft.com/t5/PowerApps-Forum/navigate-to-the-screen-which-screen-contain-the-number-in-the/m-p/56407">performing a lookup in the list based on some property (such as an id)</a>. I've also faced a problem while using that app, since it's possible possible that, after changing the item, it will not be part of the items shown in the gallery anymore (as shown in the example below):

<img src="https://msdnshared.blob.core.windows.net/media/2017/10/BlogPost20171004-All.png" alt="Disappearing item" width="1058" height="296" class="alignnone size-full wp-image-2786" />

One way to solve this problem - and some of the other problems I mentioned above - is to decouple the form item from the gallery selection, by passing the item that is selected to the screens in which the forms appear. I'll go over the changes needed below.
<h3>The browse screen</h3>
Let's start with the browse screen. Currently, the formula for the NextArrow1 icon in the gallery that navigates to the details page doesn't pass any information to that page, but we can change it using the third argument to the <a href="https://powerapps.microsoft.com/tutorials/function-navigate/">Navigate function</a>:

<code>NextArrow1.OnSelect: Navigate(DetailScreen1, ScreenTransition.None, {displayItem:ThisItem})</code>

When the screen 'DetailScreen1' is shown, it will contain a <a href="https://powerapps.microsoft.com/tutorials/working-with-variables/">context variable</a> that will have the item that was selected in the gallery (via the <a href="https://powerapps.microsoft.com/tutorials/operators/">ThisItem operator</a>).
<h3>The details screen</h3>
In the details screen, the places that reference the gallery's selected item will need to be changed, to reference the <code>item</code> variable that was passed to this screen:

<code>DetailForm1.Item: displayItem
IconDelete1.OnSelect: Remove(Contacts, displayItem); If (IsEmpty(Errors(Contacts)), Back())</code>

We also need to change the OnSelect property of the edit icon, to pass the item that is being viewed to the next screen to be edited:

<code>EditForm(EditForm1);Navigate(EditScreen1, ScreenTransition.None, {editItem:displayItem})</code>
<h3>The edit screen</h3>
As the item was passed from the details screen, we also need to update the reference in the edit form to use the item that was passed. In addition, when a form is submitted successfully, then we need to update the item to be displayed (to reflect the changes made by the user). We can use the <a href="https://powerapps.microsoft.com/tutorials/control-form-detail/#key-properties">LastSubmit property</a> of the form, which contains "the last successfully submitted record" - which is exactly what we want to display.

<code>EditForm1.Item: editItem
EditForm1.OnSuccess: Navigate(DetailScreen1, ScreenTransition.None, {displayItem:EditForm1.LastSubmit})</code>

And those are the main changes that need to be made. There is a small difference in behavior - when a new item is created, before the user would be sent back to the browse screen (via the <a href="https://powerapps.microsoft.com/tutorials/function-navigate/">Back function</a>), but with the change in the OnSuccess property of the edit form it now always navigates to the details page. That's something that <a href="https://powerusers.microsoft.com/t5/PowerApps-Forum/Updating-a-display-form-with-the-results-of-an-edit-form/m-p/60171">has been requested as well</a>, but if you prefer the old behavior, we can always pass another parameter when navigating to the edit screen (such as a true/false value that indicates whether to navigate to the browse or details screen) and use the <a href="https://powerapps.microsoft.com/tutorials/function-if/">If function</a> to decide where to send the user.]]></content:encoded>
    </item>
    <item>
      <title>Excluding weekends and holidays in date differences in PowerApps</title>
      <link>https://docs.microsoft.com/archive/blogs/carlosfigueira/excluding-weekends-and-holidays-in-date-differences-in-powerapps</link>
      <pubDate>Sat, 23 Sep 2017 16:22:46 GMT</pubDate>
      <dc:creator><![CDATA[CarlosFigueira]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/carlosfigueira/?p=2735</guid>
      <description><![CDATA[The DateDiff function allows an app to calculate the difference between two dates - a simple...]]></description>
      <content:encoded><![CDATA[The <a href="https://powerapps.microsoft.com/tutorials/function-dateadd-datediff/">DateDiff function</a> allows an app to calculate the difference between two dates - a simple calendar operation. However, in many business applications, one needs to remove weekends when getting the difference - the app needs to know how many <em>business days</em> are between two given dates. There are a <a href="https://powerusers.microsoft.com/t5/PowerApps-Forum/Excluding-weekends-using-DateDiff-and-Datepicker/m-p/38122">few</a> <a href="https://powerusers.microsoft.com/t5/PowerApps-Forum/Date-Difference-excluding-Weekends/m-p/2479">threads</a> in <a href="https://powerusers.microsoft.com/t5/PowerApps-Forum/Datediff-excluding-weekends-and-public-holidays/m-p/45629">the</a> <a href="https://powerusers.microsoft.com/t5/PowerApps-Forum/Hours-between-dates/m-p/58246">forums</a> with the same issue, so I decided to write a detailed post with a solution for this problem.
<h3>Excluding weekends</h3>
The first part of the problem to calculate the difference in business days is to exclude the weekends in the calculation. To start with that, we first need to calculate the number of <em>whole weeks</em> between the two dates, which we can get by taking the whole part of the division (using the <a href="https://powerapps.microsoft.com/tutorials/function-round/">RoundDown function</a>) of the "raw" date difference by 7:

<code>RoundDown(DateDiff(StartDate.SelectedDate, EndDate.SelectedDate, Days) / 7, 0)</code>

And then the difference of the days not in the whole weeks. For that we need to use the <a href="https://powerapps.microsoft.com/tutorials/function-datetime-parts/">Weekday function</a>. In the function below, if the start and end dates are between Monday and Friday (weekdays from 2 to 6), their difference will be in the -4 (start on Friday, end on Monday) to 4 (start on Monday, end on Friday) range; to get the number of days we use a modular operation to convert between that range to 0 to 4 which gets us the number of days in the "partial week" that we didn't count in the whole weeks:

<code>Mod(5 + Weekday(EndDate.SelectedDate) - Weekday(StartDate.SelectedDate), 5)</code>

Putting it all together, we have the number of days, excluding weekends, between two days as the number of weeks times 5 (days per week), plus the number of days in the partial week:

<code>RoundDown(DateDiff(StartDate.SelectedDate, EndDate.SelectedDate, Days) / 7, 0) * 5 +
Mod(5 + Weekday(EndDate.SelectedDate) - Weekday(StartDate.SelectedDate), 5)</code>

Notice that the partial week calculation given above will not work if the start or end dates fall on weekends; in this case we'd need to decide what to do (either use the previous Friday or the following Monday) in the calculations - and that will depend on the application.
<h3>Dealing with holidays</h3>
Holidays are not something for which we can find a universal formula - each country (or region within a country) has its own list of holidays. To account for that then, we need to have the information of holidays stored somewhere (e.g., in an Excel file, in a SQL database table, etc.) so that we can use that in our logic. In this example, I'll use an Excel table with the US holidays:

<img src="https://msdnshared.blob.core.windows.net/media/2017/09/BlogPost20170923-01.png" alt="US Holidays 2017" width="254" height="224" class="alignnone size-full wp-image-2745" />

Once that table is imported into the app (named Holidays2017 in my case), then we can use the <a href="https://powerapps.microsoft.com/tutorials/function-table-counts/">CountIf function</a> to determine how many of those holidays fall within our date range:

<code>CountIf(Holidays2017, Date &gt;= StartDate.SelectedDate, Date &lt;= EndDate.SelectedDate)</code>

And finally we can put everything together to get the difference in business days between two dates:

<code>RoundDown(DateDiff(StartDate.SelectedDate, EndDate.SelectedDate, Days) / 7, 0) * 5 +
Mod(5 + Weekday(EndDate.SelectedDate) - Weekday(StartDate.SelectedDate), 5) -
CountIf(Holidays2017, Date &gt;= StartDate.SelectedDate, Date &lt;= EndDate.SelectedDate)</code>

]]></content:encoded>
    </item>
    <item>
      <title>Supporting multi-valued "listboxes" in PowerApps</title>
      <link>https://docs.microsoft.com/archive/blogs/carlosfigueira/supporting-multi-valued-listboxes-in-powerapps</link>
      <pubDate>Fri, 15 Sep 2017 22:40:59 GMT</pubDate>
      <dc:creator><![CDATA[CarlosFigueira]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/carlosfigueira/?p=2685</guid>
      <description><![CDATA[One the current limitations of PowerApps is the lack of support for multi-valued fields - a column...]]></description>
      <content:encoded><![CDATA[One the current limitations of PowerApps is the <a href="https://powerusers.microsoft.com/t5/PowerApps-Ideas/Full-support-for-Sharepoint-Choice-fields/idi-p/16766">lack of support for multi-valued fields</a> - a column in a data source that can take zero or more of a predefined set of values. One example is a Choice column in SharePoint that allows multiple selections, which is <a href="https://powerusers.microsoft.com/t5/PowerApps-Forum/New-Split-function-table/m-p/56583">a required scenario for some users.</a> - if you add it to a form it currently doesn't allow you to see or edit the values. Even without the use of forms, if you want to use a listbox to display / select multiple items, it still doesn't work today as currently the <a href="https://powerusers.microsoft.com/t5/PowerApps-Ideas/Listbox-Pre-Selection-of-Listbox-from-Existing-records/idi-p/5549">listbox doesn't let you set multiple default selected values</a>.

In this post I'll give a workaround for this scenario, using a gallery in place of the listbox to support having multiple items selected by default. The gallery gives you some additional capability not present in the listbox, such as the ability to format items individually (which <a href="https://powerusers.microsoft.com/t5/PowerApps-Forum/Format-specific-items-in-ListBox-based-on-criteria/m-p/56305">has been requested in the forums as well</a>).
<h3>Scenario</h3>
To talk about something concrete, the scenario I'll be talking in this post is the following: in my app, the user can choose to show interest in one of the products of my company. I'll define an app that will be created in this post. I want to save a list of potential customers for my products, and I'll collect how they intend to use them, given a set of choices. To do that, I have the following SharePoint list:

<img src="https://msdnshared.blob.core.windows.net/media/2017/09/BlogPost20170915-01.png" alt="Sharepoint list" width="766" height="386" class="alignnone wp-image-2696 size-full" />

The list of usages (IntendedUses) is set as a Choice column, with multiple selection allowed. And here is where we hit the first block - as I mentioned before, those columns are not supported. But we can still make the scenario work, if we store the same information in a string column (Single line of text), and store the usages in a comma-separated value (if any of the values has a comma another separator would need to be used).

<img src="https://msdnshared.blob.core.windows.net/media/2017/09/BlogPost20170915-02.png" alt="New column with multiple values" width="964" height="340" class="alignnone size-full wp-image-2705" />
<h3>Creating the app</h3>
The app will show all the products that the current user has shown interest, and lets them register to be notified about new products - for simplicity I'll make it as a 2-screen phone app, with the first screen listing the existing registrations, and the next screen to view / add / update existing ones.

<img src="https://msdnshared.blob.core.windows.net/media/2017/09/BlogPost20170915-03.png" alt="Screen listing the products" width="355" height="271" class="alignnone size-full wp-image-2715" />

Those are the significant formulas that are used in this screen, shown in the <code>&lt;control name&gt;.&lt;property name&gt;: expression</code> format:

<code>BrowseGallery.Items: Filter(ProductResearch, UserEmail = User().Email)
(inside gallery) TitleLabel.Text: ThisItem.Title
(inside gallery) NextArrow.OnSelect: Navigate(DetailsScreen, ScreenTransition.Fade, {item: ThisItem})
NewItemIcon.OnSelect: Navigate(DetailsScreen, ScreenTransition.Fade, {item:Defaults(ProductResearch)})
RefreshIcon.OnSelect: Refresh(ProductResearch)</code>

In this example, when we navigate to the details screen, we're passing the item that needs to be edited as a parameter to it. When we're editing an item, we pass the selected item in the gallery; when we create a new item, we pass an empty record (using the <a href="https://powerapps.microsoft.com/tutorials/function-defaults/">Defaults function</a>).

Now on to the second screen, which will look something like this:

<img src="https://msdnshared.blob.core.windows.net/media/2017/09/BlogPost20170915-04.png" alt="Details screen" width="340" height="337" class="alignnone size-full wp-image-2716" />

And for the main formulas used in the screen:

<code>DetailsScreen.OnVisible: ClearCollect(coll, AddColumns(["Day-to-day use", "Formal dining", "Gifts", "Other"], "On", Value in Split(item.IntendedUses2, ",")))
ProductNameTextInput.Default: item.Title
IntendedUsesGallery.Items: coll
(inside gallery) IntendedUseLabel.Text: ThisItem.Value
(inside gallery) IntendedUseLabel.Color: If(ThisItem.On, Color.White, RGBA(47,41,43,1))
(inside gallery) IntendedUseLabel.Fill: If(ThisItem.On, RGBA(62,96,170,1), RGBA(0, 0, 0, 0))
(inside gallery) IntendedUseLabel.OnSelect: Patch(coll, ThisItem, {On: !ThisItem.On})
SubmitButton.OnSelect: Patch(ProductResearch, item, { Title: ProductNameTextInput.Text, UserName: User().FullName, UserEmail: User().Email, IntendedUses2: Concat(Filter(coll, On), Value, ",") }); Navigate(BrowseScreen, ScreenTransition.Fade)
BackButton.OnSelect: Navigate(BrowseScreen, ScreenTransition.Fade)</code>

Let's go through the formulas. When the screen is shown (via navigation from the previous screen), we create a collection ('coll') that holds all possible choices for the column; in addition, we add an additional column to the table, with a value <code>true</code> if the value is part of the existing choices for the record, or <code>false</code> otherwise. This is the source that will be used as the list of items for the gallery (our "fake" listbox).

In the gallery, we have one single child element - a label that shows one of the possible choices. To make it look like a list box, you'll need to stretch the label to fill the entire template cell, and possibly adjust padding options. The color of the text (which changes based on whether the choice is selected) we adjust based on the 'On' column of the collection that was created when the user navigated to the screen - if the choice is selected, then it will show with the background inverted, just like in the default listbox behavior. The last thing we need to define is how to "toggle" the value of the selection - and we do this by <a href="https://powerapps.microsoft.com/tutorials/function-patch/">Patching</a> the local collection, for the selected item, inverting the value of the 'On' column. At this point we have a listbox that supports multiple selection working.

The final part of the scenario is to get the choices selected by the user and save them back to the data source. This is where the Patch call in the SelectButton comes up. By using the <a href="https://powerapps.microsoft.com/tutorials/function-concatenate/">Concat function</a>, we can <a href="https://powerapps.microsoft.com/tutorials/function-filter-lookup/">Filter</a> the local collection and recreate the comma-separated list of values that we can write back to save the changes made by the user.

And this completes this scenario - support for multi-valued fields is possible in PowerApps, albeit not as simple as it should be (and in the future this support will certainly be made easier).

<h3>Limitations</h3>

It's worth to notice some limitations of this approach. First, it doesn't work natively with multi-valued choice columns in Sharepoint (or a similar column type in other data sources). We needed to create a column to store the value in a way that PowerApps can work with (in this case, a string column).

Also, galleries cannot be inserted inside forms. So if you are working with a form for all other columns of the data source, you will not be able to add this "fake listbox" inside one of the cards of the form. You may be able to add it outside of the form (and possibly make it look as if it was part of the same form), but if the form has too many cards that it needs to scroll, then the gallery will not be a part of the scrollable area (and will not look good in this case).

Again, this post is an attempt to unblock a scenario that currently isn't possible (at least not easily) to do in PowerApps, and I expect that it will be made easier in the future.

As usual, let us know of any comments / questions you have by <a href="https://powerusers.microsoft.com/t5/PowerApps-Forum/bd-p/PowerAppsForum1">posting in our forums</a>, we want to hear your feedback!]]></content:encoded>
    </item>
    <item>
      <title>Building multilingual apps in PowerApps</title>
      <link>https://docs.microsoft.com/archive/blogs/carlosfigueira/building-multilingual-apps-in-powerapps</link>
      <pubDate>Fri, 08 Sep 2017 06:00:53 GMT</pubDate>
      <dc:creator><![CDATA[CarlosFigueira]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/carlosfigueira/?p=2615</guid>
      <description><![CDATA[PowerApps is localized in many languages - depending on the language of your computer, you'll see...]]></description>
      <content:encoded><![CDATA[PowerApps is localized in many languages - depending on the language of your computer, you'll see the authoring experience in the appropriate language (if the language is supported). For example, if I set my browser (Chrome) language to French, I'll see the authoring Studio in that language.

<img src="https://msdnshared.blob.core.windows.net/media/2017/09/BlogPost20170908-01.png" alt="PowerApps Studio in French" width="733" height="254" class="alignnone size-full wp-image-2635" />

If we want to make an <em>app</em> that can be viewed by its user in multiple locales, however, the Studio currently doesn't provide any easy way to have the messages shown to the user in their own language. This is a request that comes often in the forums (like <a href="https://powerusers.microsoft.com/t5/PowerApps-Forum/Multilingual-app/m-p/55226">one this week</a>), so I'll show one way to accomplish that here.
<h3>Extracting strings</h3>
The first step in a multilingual app is to remove the "hardcoded" strings from it. That means that all text, messages, etc. that are shown to the user need to be taken out of the app.

<img src="https://msdnshared.blob.core.windows.net/media/2017/09/BlogPost20170908-02.png" alt="Hard-coded resource strings" width="694" height="226" class="alignnone size-full wp-image-2636" />

Notice that there are also strings that are not easily visible. Tooltips, hint texts, and others should also be considered. These are some of the places that have strings:

<img src="https://msdnshared.blob.core.windows.net/media/2017/09/BlogPost20170908-03.png" alt="Many places with strings" width="398" height="215" class="alignnone size-full wp-image-2645" />

One simple place to store those strings is in an Excel table - it's simple to edit, it can be imported directly into the app, and once in the app we can use functions to query it based on the user language. Here's an example of my translations (some of them came from an automated translation, so please forgive me if I'm butchering your language)

<img src="https://msdnshared.blob.core.windows.net/media/2017/09/BlogPost20170908-04.png" alt="" width="339" height="323" class="alignnone size-full wp-image-2646" />

Once the Excel table is created, you can import it to your app - go to the View tab in the ribbon, select "Data sources" and "Add data source"; select then the option to add static data from Excel:

<img src="https://msdnshared.blob.core.windows.net/media/2017/09/BlogPost20170908-05.png" alt="Add static Excel table" width="322" height="161" class="alignnone size-full wp-image-2655" />

Now your app has all the strings that it will use loaded in memory; in my case I called the table 'Strings'.
<h3>Detecting the user language and fallback</h3>
We can get the language of the user via the <a href="https://powerapps.microsoft.com/tutorials/function-language/">Language function</a>. That function can either simply return the language (e.g., "fr" for French) or it can also return additional information such as the region (such as "pt-BR" for Portuguese / Brazil) and the script (e.g., Serbian has two scripts: Cyrillic and Latin). For this post, I'll focus on the language only, and we need a formula to extract the language from whatever format the Language function can return.

But what you don't have translations for the user language? What is commonly done is to designate some of the languages to be the "fallback" language - one that will be used if the user's is not supported. And the formula to select the actual language to be used to lookup the translation from the table can start to get large, especially if it's going to be used in many places.

Since PowerApps currently doesn't support the concept of a macro (basically, an alias for a large expression), in those cases I use a hidden page, and store the result of the expression in a control, such as a label. For my app, I created
such a page and added a few labels to it as shown below (their names are shown in red):

<img src="https://msdnshared.blob.core.windows.net/media/2017/09/BlogPost20170908-06.png" alt="Labels with language codes" width="245" height="113" class="alignnone size-full wp-image-2656" />

Here are the formulas for those labels:
<code>lblLanguage.Text: Language()
lblLanguageOnly.Text: If("-" in lblLanguage.Text, Left(lblLanguage.Text, Find("-", lblLanguage.Text) - 1), lblLanguage.Text)
lblUsedLang.Text: Coalesce(LookUp(Strings, lblLanguageOnly.Text = Lang).Lang, "en")</code>

In the first label I store the language itself (mostly for my debugging purposes). The second label (lblLanguageOnly) looks at the value of the first label; if it has a '-' (meaning that it has more information that the language only) it strips down that part. The third label checks if the language of the user is supported. If it is, then the lookup will succeed and it will be returned by the <a href="https://powerapps.microsoft.com/en-us/tutorials/function-isblank-isempty/">Coalesce function</a>. Otherwise, the <a href="https://powerapps.microsoft.com/tutorials/function-filter-lookup/">LookUp function</a> will return a blank value, and in this case I'm using English ("en") as the fallback language.

<h3>Retrieving the strings for the user language</h3>

Now we have the language that will be used (in the lblUsedLang.Text property), and the strings have already been imported. It's then time to go to the controls that display those strings to the user, and update their properties to look up the appropriate translation. We can do it using the LookUp function again. Here are the expressions for the contacts app that I showed in the beginning of this post:

<code>LblAppName1.Text: LookUp(Strings, Key = "AppTitle" And Lang = lblUsedLang.Text, Value)
TextSearchBox1.HintText: LookUp(Strings, Key = "SearchItemsHint" And Lang = lblUsedLang.Text, Value)
NextArrow1.Tooltip: LookUp(Strings, Key = "ViewDetails" And Lang = lblUsedLang.Text, Value)
IconNewItem1.Tooltip: LookUp(Strings, Key = "NewContactTooltip" And Lang = lblUsedLang.Text, Value)</code>

And so on. The idea is that for all messages / strings that are shown to the user, a lookup will be made in the strings table. Here's my app when I run it in English:

<img src="https://msdnshared.blob.core.windows.net/media/2017/09/BlogPost20170908-07.png" alt="App in English" width="488" height="317" class="alignnone size-full wp-image-2665" />

And the same app in French:

<img src="https://msdnshared.blob.core.windows.net/media/2017/09/BlogPost20170908-08.png" alt="App in French" width="491" height="303" class="alignnone size-full wp-image-2675" />

<h3>Wrapping up</h3>

It's possible that in the future we'll add a native support for string / localization tables in PowerApps to make this process easier - and if you feel strongly about this feature, please create one / vote up an existing in the <a href="https://aka.ms/powerapps-ideas">PowerApps Ideas board</a>. This post shows one way to accomplish this scenario today, in case this is a mandatory requirement for the app that you're building.

As usual, let us know of any comments / questions you have by posting in <a href="https://powerusers.microsoft.com/t5/PowerApps-Forum/bd-p/PowerAppsForum1">our forums</a>, we want to hear your feedback!]]></content:encoded>
    </item>
    <item>
      <title>Formatting fields in PowerApps data tables</title>
      <link>https://docs.microsoft.com/archive/blogs/carlosfigueira/formatting-fields-in-data-tables</link>
      <pubDate>Fri, 01 Sep 2017 23:48:19 GMT</pubDate>
      <dc:creator><![CDATA[CarlosFigueira]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/carlosfigueira/?p=2545</guid>
      <description><![CDATA[The Data table control in PowerApps is an easy and quick way to display data in a tabular format on...]]></description>
      <content:encoded><![CDATA[The <a href="https://powerapps.microsoft.com/tutorials/control-data-table/">Data table</a> control in <a href="https://www.powerapps.com">PowerApps</a> is an easy and quick way to display data in a tabular format on an app created in the platform. It has been released a couple of months ago, and it still has many features coming up over the upcoming versions (<a href="https://powerapps.microsoft.com/tutorials/control-data-table/">listed in the control reference page</a>).

One of the missing features is the ability to choose the formatting of the data that is displayed on the table (as was noted by a <a href="https://powerusers.microsoft.com/t5/PowerApps-Forum/Format-values-from-Collection-Table-displayed-in-Data-Table/m-p/54173">question in the PowerApps forum</a>). For example, the image below shows a table with three columns with the (only) way that the data can be formatted at this point:

<img src="https://msdnshared.blob.core.windows.net/media/2017/09/BlogPost20170901-01.png" alt="Default data table control" />

While the data table control itself cannot do that, we can use the <a href="https://powerapps.microsoft.com/tutorials/function-table-shaping/">AddColumns function</a> to create "virtual" columns in our data source that look like we want, and then use them in the data table. Notice that the AddColumns function doesn't change the original data source - my SQL table that contains the data will still only have the columns that originally had. Instead, it will <em>return a new data source</em> with new columns added at runtime.

In my example, I want to format both the date and the number in a different way. To do that, select the data table and in the formula bar choose the Item property:

<img src="https://msdnshared.blob.core.windows.net/media/2017/09/BlogPost20170901-02.png" alt="Data table Items property" />

Now replace that formula with one that adds the two formatted columns:

<code>AddColumns(
'[blog20170901].[Accounts]',
"FormattedOpenedDate", Text(OpenedDate, "dd mmm yyyy"),
"FormattedBalance", Text(Balance, "$##,#"))</code>

And nothing happens... And even when we look at the customization table, we still don't see the new columns

<img src="https://msdnshared.blob.core.windows.net/media/2017/09/BlogPost20170901-03.png" alt="Data table customization - no new columns" />

That's a bug in the control that will be fixed in an upcoming release - apparently if you have a connected data source, the customization pane is only showing the original columns.

But there's a way to work around this issue: if you have a <em>disconnected</em> data source (i.e., a local collection), then the new columns do appear in the customization pane. So we can "cache" the data from the original data source in a local collection, and use that local collection as the source of the data table. One way to do that is to, on the <strong>OnVisible</strong> property of the screen, to load all the data locally:

<code>ClearCollect(localCollection,
AddColumns(
'[blog20170901].[Accounts]',
"FormattedOpenedDate", Text(OpenedDate, "dd mmm yyyy"),
"FormattedBalance", Text(Balance, "$##,#")))</code>

Now, if we choose the local collection as the source of the data table, we should see the new columns:

<img src="https://msdnshared.blob.core.windows.net/media/2017/09/BlogPost20170901-04.png" alt="Data table customization - local collection" />

After unchecking the original columns, and checking the formatted ones (and going to the advanced pane to change the title of the columns), we can finally see the formatted data in the data table:

<img src="https://msdnshared.blob.core.windows.net/media/2017/09/BlogPost20170901-05.png" alt="Formatted columns in data table" />

Notice that since the collection displayed in the data table is local, if there are updates to the original data source, you'll need to reload it. If the updates are all made on a screen other than the one that contains the data table, then using the OnVisible property of the screen already solves this problem. If you can modify the data source in the same screen, then you'll need to run the same <a href="https://powerapps.microsoft.com/tutorials/function-clear-collect-clearcollect/">ClearCollect</a> action to reload the collection.

<h3>Wrapping up</h3>
This is the first of a series of blog posts that I'll write on how to make some scenarios in PowerApps to work. Some of them are workarounds for existing bugs that will be fixed, some are missing features. For new feature requests (or even to make some existing features easier to use), please do go to the <a href="https://aka.ms/powerapps-ideas">PowerApps Ideas Board</a> and either vote up existing ideas or create new feature requests; that helps the team to prioritize the new features that are constantly being added to the platform. Send us your feedback!]]></content:encoded>
    </item>
    <item>
      <title>Using automatic format selection with a compression encoder in self-hosted scenarios</title>
      <link>https://docs.microsoft.com/archive/blogs/carlosfigueira/using-automatic-format-selection-with-a-compression-encoder-in-self-hosted-scenarios</link>
      <pubDate>Tue, 23 Feb 2016 23:15:36 GMT</pubDate>
      <dc:creator><![CDATA[CarlosFigueira]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/carlosfigueira/?p=2521</guid>
      <description><![CDATA[Although I haven't been working with WCF for over 4 years, every now and then I run into a question...]]></description>
      <content:encoded><![CDATA[Although I haven't been working with WCF for over 4 years, every now and then I run into a question from either the forums or someone directly contacting me that catches my attention and I try to see if I can help. Last week I got one of those and I think it was interesting enough for me to get back to writing about it.

Basically, a customer had a WCF REST service (I know, if you want to be pedantic you'd say that it's a WCF service with a Web endpoint, but let's not go there), and they were using the <a href="https://msdn.microsoft.com/en-us/library/ee476510.aspx">automatic formatting feature</a> for the response. This way, if the client wants a JSON response, they send the <code>Accept: application/json</code>, and receive that. If they want XML, they can send <code>Accept: text/xml</code>, and off they go to in the XML land. Things were working fine, until the moment when they decided to start compressing the data to save bandwidth. To do that, they went to the canonical example of compression in WCF, the <a href="https://msdn.microsoft.com/en-us/library/ms751458.aspx">"Custom Message Encoder: Compression Encoder" sample</a>, replaced the web encoder of their binding with it. And just like that, the auto format selection stopped working - all responses, regardless of the incoming Accept header, were coming back in XML.

So what's the story here? The story for using compression (most specifically, GZip) on a WCF service is to host the service in IIS, and let IIS itself handle the compression (which it does beautifully). On self-hosted scenarios, the story has been to use an encoder that implements the compression itself (one could also implement that using a custom transport, but that's <a href="https://blogs.msdn.microsoft.com/carlosfigueira/2012/01/03/wcf-extensibility-transport-channels-reply-channel/">so complicated</a> that it becomes a no-go for all but a handful of people). In most scenarios this works out fine, but in this case, there's an implementation detail on the <a href="https://msdn.microsoft.com/en-us/library/system.servicemodel.description.webhttpbehavior.aspx">WebHttpBehavior</a> that it will only apply the <a href="https://msdn.microsoft.com/en-us/library/system.servicemodel.description.webhttpbehavior.automaticformatselectionenabled.aspx">AutomaticFormatSelectionEnabled </a> property if the encoder that is being used is the one provided by the <a href="https://msdn.microsoft.com/en-us/library/system.servicemodel.channels.webmessageencodingbindingelement.aspx">WebMessageEncodingBindingElement</a>. Change the encoder (for example, to use the compression encoder), and the feature stops working (yes, it's a bug, but given the state of WCF in mostly maintenance mode, especially in the Web/REST functionalities, it's unlikely that it will be fixed anytime soon, so for all purposes, this is the behavior that we're stuck with).

In this post I'll show a workaround for this issue that one can use to have both ways - automatic format selection, and the compression encoder. As far as workarounds go, validate for your scenarios before deploying it into a production system: I tested it for a few scenarios and it worked, but I make no guarantees that it will work for all.

TL;DR: if all you want is the code, you can also find it on my <a href="https://github.com/carlosfigueira/WCFSamples">WCFSamples GitHub repository</a>, under <a href="https://github.com/carlosfigueira/WCFSamples/tree/master/MessageEncoder/GZipEncoderAndAutoFormatSelection">MessageEncoder/GZipEncoderAndAutoFormatSelection</a>.
<h3>Tweaking the compression encoder sample</h3>
First off, we'll need to change a little of the encoder sample so that it behaves better in a HTTP-centric world. The sample defines a new Content-Type for the encoder (application/x-gzip), which makes sense if we want to use the encoder in a transport-agnostic world (i.e., it can be used with the TCP or Named Pipes transport), but for HTTP, the compression is signalled by the Accept-Encoding and Content-Encoding headers, not by the content type itself (whether the content is compressed or not is orthogonal to the type of the content). Therefore we get rid of the new content type and delegate most of the calls to the inner encoder.
<pre>    public override string ContentType
    {
        get { return innerEncoder.ContentType; }
    }

    public override string MediaType
    {
        get { return innerEncoder.MediaType; }
    }

    public override bool IsContentTypeSupported(string contentType)
    {
        return innerEncoder.IsContentTypeSupported(contentType);
    }

    public override T GetProperty()
    {
        return innerEncoder.GetProperty();
    }

    public override MessageVersion MessageVersion
    {
        get { return innerEncoder.MessageVersion; }
    }
</pre>
Next, when reading a message, we need to pass the content-type along to the inner encoder, since the web encoder uses it to determine how to deserialize the message (using JSON or XML).
<pre>    public override Message ReadMessage(ArraySegment buffer, BufferManager bufferManager, string contentType)
    {
        //Decompress the buffer
        ArraySegment decompressedBuffer = DecompressBuffer(buffer, bufferManager);
        //Use the inner encoder to decode the decompressed buffer
        Message returnMessage = innerEncoder.ReadMessage(decompressedBuffer, bufferManager, contentType);
        returnMessage.Properties.Encoder = this;
        return returnMessage;
    }
</pre>
At this point, the encoder will work fine if you send compressed (via gzip) requests. But not all requests are compressed, so we must update the encoder so that it will only decompress the requests if necessary. The correct way to do that would be to check for the presence of the <code>Content-Encoding: gzip</code> header in the request. However, this information isn't available to the encoder in WCF - that's one of the pitfalls of a transport-agnostic framework, you cannot count on having information at the transport layer. We can work around this limitation, however, by checking for the GZip header in the bytes that indicate a GZipped content. From the <a href="http://www.gzip.org/zlib/rfc-gzip.html">GZip specification</a>, it must start with the following magic bytes: 0x1F, 0x8B, 0x08. Updating the ReadMessage method will enable the encoder to consume both compressed and uncompressed payloads:

<pre>
    public override Message ReadMessage(ArraySegment buffer, BufferManager bufferManager, string contentType)
    {
        ArraySegment decompressedBuffer = buffer;

        if (buffer.Count &gt;= 3 &amp;&amp; buffer.Array[buffer.Offset] == 0x1F &amp;&amp;
            buffer.Array[buffer.Offset + 1] == 0x8B &amp;&amp; buffer.Array[buffer.Offset + 2] == 0x08)
        {
            //Decompress the buffer
            decompressedBuffer = DecompressBuffer(buffer, bufferManager);
        }

        //Use the inner encoder to decode the decompressed buffer
        Message returnMessage = innerEncoder.ReadMessage(decompressedBuffer, bufferManager, contentType);
        returnMessage.Properties.Encoder = this;
        return returnMessage;
    }
</pre>

And we now have an encoder that can receive both compressed and uncompressed data, but always writes out compressed data. We still have the problem of the auto format selection not working, and we'll take a look at solving it next.

<h3>Adding an inspector to implement auto format selection and selective output compression</h3>

Now we need to change the encoder behavior depending on the client request, or more precisely the presence (and value) of the Accept and Accept-Encoding HTTP headers. The easiest way to implement this correlation is via a message inspector, which will look at the incoming request properties, and take some actions based on it.

The easiest part is to get the automatic format selection functionality back on. Although the property in the WebHttpBehavior doesn't work in the GZip encoder, setting the <a href="https://msdn.microsoft.com/en-us/library/system.servicemodel.web.outgoingwebresponsecontext.format.aspx">OutgoingResponse.Format</a> property in the <a href="https://msdn.microsoft.com/en-us/library/system.servicemodel.web.weboperationcontext.aspx">WebOperationContext</a> does, and we can use that in the inspector.

<pre>
    public class CompressionAndFormatSelectionMessageInspector : IDispatchMessageInspector
    {
        static readonly Regex jsonContentTypes = new Regex(@"[application|text]\/json");
        static readonly Regex xmlContentTypes = new Regex(@"[application|text]\/xml");

        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            object propObj;
            if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out propObj))
            {
                var prop = (HttpRequestMessageProperty)propObj;
                var accept = prop.Headers[HttpRequestHeader.Accept];
                if (accept != null)
                {
                    if (jsonContentTypes.IsMatch(accept))
                    {
                        WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Json;
                    }
                    else if (xmlContentTypes.IsMatch(accept))
                    {
                        WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Xml;
                    }
                }
            }

            return null;
        }

        public void BeforeSendReply(ref Message reply, object correlationState)
        {
        }
    }
</pre>

To handle the Accept-Encoding header, we'll need to use the correlation object that is passed between the AfterReceiveRequest and BeforeSendReply methods in the inspector. If the request contains an <code>Accept-Encoding: gzip</code> header, then we'll pass this information along to the reply.

<pre>
    public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
    {
        bool shouldCompressResponse = false;

        object propObj;
        if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out propObj))
        {
            var prop = (HttpRequestMessageProperty)propObj;
            var accept = prop.Headers[HttpRequestHeader.Accept];
            if (accept != null)
            {
                if (jsonContentTypes.IsMatch(accept))
                {
                    WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Json;
                }
                else if (xmlContentTypes.IsMatch(accept))
                {
                    WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Xml;
                }
            }

            var acceptEncoding = prop.Headers[HttpRequestHeader.AcceptEncoding];
            if (acceptEncoding != null &amp;&amp; acceptEncoding.Contains("gzip"))
            {
                shouldCompressResponse = true;
            }
        }

        return shouldCompressResponse;
    }
</pre>

On the BeforeSendReply, we will now use that information to add the appropriate header (<code>Content-Encoding: gzip</code>) to the reply.

<pre>
    public void BeforeSendReply(ref Message reply, object correlationState)
    {
        var useGzip = (bool)correlationState;
        if (useGzip)
        {
            // Add property to be used by encoder
            HttpResponseMessageProperty resp;
            object respObj;
            if (!reply.Properties.TryGetValue(HttpResponseMessageProperty.Name, out respObj))
            {
                resp = new HttpResponseMessageProperty();
                reply.Properties.Add(HttpResponseMessageProperty.Name, resp);
            }
            else
            {
                resp = (HttpResponseMessageProperty)respObj;
            }

            resp.Headers[HttpResponseHeader.ContentEncoding] = "gzip";
        }
    }
</pre>

Finally, at the encoder's WriteMessage method, we can look at the message properties to see if that header is present. Only if that is the case that the response is compressed.

<pre>
    public override ArraySegment WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset)
    {
        //Use the inner encoder to encode a Message into a buffered byte array
        ArraySegment buffer = innerEncoder.WriteMessage(message, maxMessageSize, bufferManager, 0);

        object respObj;
        if (message.Properties.TryGetValue(HttpResponseMessageProperty.Name, out respObj))
        {
            var resp = (HttpResponseMessageProperty)respObj;
            if (resp.Headers[HttpResponseHeader.ContentEncoding] == "gzip")
            {
                // Need to compress the message
                buffer = CompressBuffer(buffer, bufferManager, messageOffset);
            }
        }

        return buffer;
    }
</pre>

And that's it. With those changes, the encoder will now only compress the responses if the client asked them to be so.

<h3>Wrapping up</h3>

This scenario shows a limitation of the WCF architecture - by trying to be transport-agnostic, it loses the ability to take advantage of some of the transport features, especially at the encoder level (in other extensibility points one can find the HTTP headers via the message properties). So if your implementation is tied to a particular transport, especially HTTP, WCF will probably do what you want, but with other frameworks (such as ASP.NET Web API) it will likely be easier to do.
]]></content:encoded>
    </item>
    <item>
      <title>Logging with the .NET backend for Azure Mobile Services</title>
      <link>https://docs.microsoft.com/archive/blogs/carlosfigueira/logging-with-the-net-backend-for-azure-mobile-services</link>
      <pubDate>Thu, 24 Apr 2014 14:00:00 GMT</pubDate>
      <dc:creator><![CDATA[CarlosFigueira]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/carlosfigueira/2014/04/24/logging-with-the-net-backend-for-azure-mobile-services/</guid>
      <description><![CDATA[[This post originally appeared in...]]></description>
      <content:encoded><![CDATA[<p><em>[This post originally appeared in <a href="http://blogs.msdn.com/b/azuremobile/archive/2014/04/24/logging-with-the-net-backend-for-azure-mobile-services.aspx">http://blogs.msdn.com/b/azuremobile/archive/2014/04/24/logging-with-the-net-backend-for-azure-mobile-services.aspx</a></em><em></em><em>. I’ll be writing Azure Mobile Service related posts in the </em><a href="http://blogs.msdn.com/b/azuremobile"><em>Azure Mobile blog</em></a><em> primarily, and cross-posting them here for people who have feeds linked to this blog only]</em></p>  <p>On the node.js version of mobile services, logging was done mostly via the node’s console object. In any of the server scripts you could call console.[log|warn|error] and when that script was executed you could go to the “logs” tab in the portal to see them. In the .NET backend you still have the same capabilities, but there are some new features and quirks which one should be aware to get the best logging experience in that new backend. Let’s go over them here.</p>  <h3>Logging when running locally</h3>  <p>This is a very simple example of logging in the .NET backend. If we write this controller class, we can use the <code>Log</code> property in the <code>Services</code> member of the <code>TableController&lt;T&gt;</code> class to write to the Azure logs.</p>  <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:c18d628a-97d0-4dee-9567-d1c3595b873d" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #fff; overflow: auto"> <ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">class</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">TodoItemController</span><span style="background:#ffffff;color:#000000"> : </span><span style="background:#ffffff;color:#2b91af">TableController</span><span style="background:#ffffff;color:#000000">&lt;</span><span style="background:#ffffff;color:#2b91af">TodoItem</span><span style="background:#ffffff;color:#000000">&gt;</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">{</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">protected</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">override</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">void</span><span style="background:#ffffff;color:#000000"> Initialize(</span><span style="background:#ffffff;color:#2b91af">HttpControllerContext</span><span style="background:#ffffff;color:#000000"> controllerContext)</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">{</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">base</span><span style="background:#ffffff;color:#000000">.Initialize(controllerContext);</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> context = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">MyContext</span><span style="background:#ffffff;color:#000000">(</span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">.Services.Settings.Schema);</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">.DomainManager = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">EntityDomainManager</span><span style="background:#ffffff;color:#000000">&lt;</span><span style="background:#ffffff;color:#2b91af">TodoItem</span><span style="background:#ffffff;color:#000000">&gt;(context, </span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">.Request, </span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">.Services);</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">}</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">Task</span><span style="background:#ffffff;color:#000000">&lt;</span><span style="background:#ffffff;color:#2b91af">TodoItem</span><span style="background:#ffffff;color:#000000">&gt; PostItem(</span><span style="background:#ffffff;color:#2b91af">TodoItem</span><span style="background:#ffffff;color:#000000"> item)</span></li> <li>    <span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">.Services.Log.Info(</span><span style="background:#ffffff;color:#a31515">&quot;[PostItem] Inserting new item: &quot;</span><span style="background:#ffffff;color:#000000"> + item.Id ?? </span><span style="background:#ffffff;color:#a31515">&quot;&lt;&lt;no id&gt;&gt;&quot;</span><span style="background:#ffffff;color:#000000">);</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">return</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">base</span><span style="background:#ffffff;color:#000000">.InsertAsync(item);</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">}</span></li> <li><span style="background:#ffffff;color:#000000">}</span></li> </ol> </div> </div> </div>  <p>When we publish the application to Azure and insert an item, we can see the log in the “logs” tab in the azure portal.</p>  <p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/95/96/metablogapi/4380.001LogEntryOnPortal_5319BBBD.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-95-96-metablogapi/4380.001LogEntryOnPortal_5F00_5319BBBD.png"><img title="001-LogEntryOnPortal" style="border-width: 0px; display: inline;" border="0" alt="001-LogEntryOnPortal" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/95/96/metablogapi/4212.001LogEntryOnPortal_thumb_20B5E83E.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-95-96-metablogapi/4212.001LogEntryOnPortal_5F00_thumb_5F00_20B5E83E.png" width="705" height="60" /></a> </p>  <p>However, when we’re running the backend locally, there is no portal where we can see the logs, so where can we find them. As one <a href="http://stackoverflow.com/q/23148086/751090">user in Stack Overflow had this question</a>, I imagine that others may have the same problem. And there’s nothing really fancy here – the logging is implemented (by default, see more advanced topics later) using the standard System.Diagnostics tracing system, so we can add a new listener in the web.config and send the log output to some file where you can read:</p>  <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:74a44c15-20af-48dc-923d-e0e47b83105e" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #fff; overflow: auto"> <ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#0000ff">&lt;</span><span style="background:#ffffff;color:#a31515">system.diagnostics</span><span style="background:#ffffff;color:#0000ff">&gt;</span></li> <li style="background: #f3f3f3">  <span style="background:#ffffff;color:#0000ff">&lt;</span><span style="background:#ffffff;color:#a31515">trace</span><span style="background:#ffffff;color:#0000ff"> </span><span style="background:#ffffff;color:#ff0000">autoflush</span><span style="background:#ffffff;color:#0000ff">=</span><span style="background:#ffffff;color:#000000">&quot;</span><span style="background:#ffffff;color:#0000ff">true</span><span style="background:#ffffff;color:#000000">&quot;</span><span style="background:#ffffff;color:#0000ff">&gt;</span></li> <li>    <span style="background:#ffffff;color:#0000ff">&lt;</span><span style="background:#ffffff;color:#a31515">listeners</span><span style="background:#ffffff;color:#0000ff">&gt;</span></li> <li style="background: #f3f3f3">      <span style="background:#ffffff;color:#0000ff">&lt;</span><span style="background:#ffffff;color:#a31515">add</span><span style="background:#ffffff;color:#0000ff"> </span><span style="background:#ffffff;color:#ff0000">name</span><span style="background:#ffffff;color:#0000ff">=</span><span style="background:#ffffff;color:#000000">&quot;</span><span style="background:#ffffff;color:#0000ff">default</span><span style="background:#ffffff;color:#000000">&quot;</span></li> <li>           <span style="background:#ffffff;color:#0000ff"></span><span style="background:#ffffff;color:#ff0000">initializeData</span><span style="background:#ffffff;color:#0000ff">=</span><span style="background:#ffffff;color:#000000">&quot;</span><span style="background:#ffffff;color:#0000ff">c:&#92;temp&#92;mylog.txt</span><span style="background:#ffffff;color:#000000">&quot;</span></li> <li style="background: #f3f3f3">           <span style="background:#ffffff;color:#0000ff"></span><span style="background:#ffffff;color:#ff0000">type</span><span style="background:#ffffff;color:#0000ff">=</span><span style="background:#ffffff;color:#000000">&quot;</span><span style="background:#ffffff;color:#0000ff">System.Diagnostics.TextWriterTraceListener</span><span style="background:#ffffff;color:#000000">&quot;</span><span style="background:#ffffff;color:#0000ff"> /&gt;</span></li> <li>    <span style="background:#ffffff;color:#0000ff">&lt;/</span><span style="background:#ffffff;color:#a31515">listeners</span><span style="background:#ffffff;color:#0000ff">&gt;</span></li> <li style="background: #f3f3f3">  <span style="background:#ffffff;color:#0000ff">&lt;/</span><span style="background:#ffffff;color:#a31515">trace</span><span style="background:#ffffff;color:#0000ff">&gt;</span></li> <li><span style="background:#ffffff;color:#0000ff">&lt;/</span><span style="background:#ffffff;color:#a31515">system.diagnostics</span><span style="background:#ffffff;color:#0000ff">&gt;</span></li> </ol> </div> </div> </div>  <p>If we send the same request to the local service, we can now find it out the traces.</p>  <blockquote>   <p><font size="2" face="Consolas">iisexpress.exe Information: 0 : Message='[PostItem] Inserting new item: 01234567-89ab-cdef-0123-456789abcdef-1', Id=00000000-0000-0000-0000-000000000000, Category='PostItem'</font></p> </blockquote>  <p>Another alternative, if you’re running the local .NET backend under the debugger, you can look at the “Output” window, selecting “Show output from: Debug”, and the traces will be shown in the window. If that’s the case you don’t even need to add a trace listener, as when running under the debugger VS will add one listener by default that writes to its output/debug window. There will be some noise on other information which is traced to the debug window, but that may be an acceptable solution as well.</p>  <p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/95/96/metablogapi/4705.001bLogEntryOnVSDebug_009ADB81.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-95-96-metablogapi/4705.001bLogEntryOnVSDebug_5F00_009ADB81.png"><img title="001b-LogEntryOnVSDebug" style="border: 0px currentcolor; display: inline;" border="0" alt="001b-LogEntryOnVSDebug" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/95/96/metablogapi/5488.001bLogEntryOnVSDebug_thumb_074DE504.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-95-96-metablogapi/5488.001bLogEntryOnVSDebug_5F00_thumb_5F00_074DE504.png" width="776" height="164" /></a> </p>  <p>The traces does not have the same format as we find in the portal, but that’s a quick way to get the information you want.</p>  <h3>Customizing traces</h3>  <p>But what if you really want a better formatted traces? Not a problem. The .NET backend uses the same system as its underlying framework, ASP.NET Web API. All traces are written via the <code>ITraceWriter</code> interface, and you can supply your own implementation of that interface, like in the code below, which uses a format very similar to the one displayed in the portal. The “category” parameter by default has the name of the member (typically method or property) where the log method was called, but it can be customized for anything that makes sense for your application.</p>  <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:87162be9-7cfe-48ff-b5f0-be7a860db71e" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #fff; overflow: auto"> <ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">class</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">MyTraceWriter</span><span style="background:#ffffff;color:#000000"> : </span><span style="background:#ffffff;color:#2b91af">ITraceWriter</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">{</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">void</span><span style="background:#ffffff;color:#000000"> Trace(</span><span style="background:#ffffff;color:#2b91af">HttpRequestMessage</span><span style="background:#ffffff;color:#000000"> request, </span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> category, </span><span style="background:#ffffff;color:#2b91af">TraceLevel</span><span style="background:#ffffff;color:#000000"> level, </span><span style="background:#ffffff;color:#2b91af">Action</span><span style="background:#ffffff;color:#000000">&lt;</span><span style="background:#ffffff;color:#2b91af">TraceRecord</span><span style="background:#ffffff;color:#000000">&gt; traceAction)</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">{</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> record = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">TraceRecord</span><span style="background:#ffffff;color:#000000">(request, category, level);</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000">traceAction(record);</span></li> <li>        <span style="background:#ffffff;color:#000000">System.Diagnostics.</span><span style="background:#ffffff;color:#2b91af">Trace</span><span style="background:#ffffff;color:#000000">.WriteLine(</span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000">.Format(</span><span style="background:#ffffff;color:#a31515">&quot;{0} - {1} - {2} - {3}&quot;</span><span style="background:#ffffff;color:#000000">,</span></li> <li style="background: #f3f3f3">            <span style="background:#ffffff;color:#000000">record.Level, record.Message, record.Category, record.Timestamp.ToString(</span><span style="background:#ffffff;color:#a31515">&quot;ddd MMM dd yyyy, HH:mm:ss tt&quot;</span><span style="background:#ffffff;color:#000000">)));</span></li> <li>    <span style="background:#ffffff;color:#000000">}</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">}</span></li> </ol> </div> </div> </div>  <p>And to use it we can replace the trace writer service with our own implementation in the <code>HttpConfiguration</code> object returned by the <code>ServiceConfig.Initialize</code> method.</p>  <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:83ffcd54-668d-4bbe-8785-e26446d5e817" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #fff; overflow: auto"> <ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">static</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">class</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">WebApiConfig</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">{</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">static</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">void</span><span style="background:#ffffff;color:#000000"> Register()</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">{</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> configBuilder = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">ConfigBuilder</span><span style="background:#ffffff;color:#000000">(configOptions);</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> config = </span><span style="background:#ffffff;color:#2b91af">ServiceConfig</span><span style="background:#ffffff;color:#000000">.Initialize(</span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">ConfigBuilder</span><span style="background:#ffffff;color:#000000">());</span></li> <li>        <span style="background:#ffffff;color:#000000">config.Services.Replace(</span><span style="background:#ffffff;color:#0000ff">typeof</span><span style="background:#ffffff;color:#000000">(</span><span style="background:#ffffff;color:#2b91af">ITraceWriter</span><span style="background:#ffffff;color:#000000">), </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">MyTraceWriter</span><span style="background:#ffffff;color:#000000">());</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">}</span></li> <li><span style="background:#ffffff;color:#000000">}</span></li> </ol> </div> </div> </div>  <p>The document Tracing in <a href="http://www.asp.net/web-api/overview/testing-and-debugging/tracing-in-aspnet-web-api">ASP.NET Web API</a> has a good introduction on the tracing system used by Web API (and the .NET backend of the mobile service). Now, everything works fine when we run locally, but if we publish the service to Azure and invoke the operations in the controller again, we won’t see the traces in the portal anymore. The problem is that while we’re tracing to the System.Diagnostic subsystem, that is not hooked up to the tracing in the service running in Azure. We can fix that by passing the original trace writer (which can trace within Azure) to our trace writer implementation:</p>  <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:94d0e4f1-4fd3-425f-8e3f-aadad6143a52" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #fff; overflow: auto"> <ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">class</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">MyTraceWriter</span><span style="background:#ffffff;color:#000000"> : </span><span style="background:#ffffff;color:#2b91af">ITraceWriter</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">{</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">ITraceWriter</span><span style="background:#ffffff;color:#000000"> original;</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> MyTraceWriter(</span><span style="background:#ffffff;color:#2b91af">ITraceWriter</span><span style="background:#ffffff;color:#000000"> original)</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">{</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">.original = original;</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">}</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">void</span><span style="background:#ffffff;color:#000000"> Trace(</span><span style="background:#ffffff;color:#2b91af">HttpRequestMessage</span><span style="background:#ffffff;color:#000000"> request, </span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> category, </span><span style="background:#ffffff;color:#2b91af">TraceLevel</span><span style="background:#ffffff;color:#000000"> level, </span><span style="background:#ffffff;color:#2b91af">Action</span><span style="background:#ffffff;color:#000000">&lt;</span><span style="background:#ffffff;color:#2b91af">TraceRecord</span><span style="background:#ffffff;color:#000000">&gt; traceAction)</span></li> <li>    <span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">if</span><span style="background:#ffffff;color:#000000"> (</span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">.original != </span><span style="background:#ffffff;color:#0000ff">null</span><span style="background:#ffffff;color:#000000">)</span></li> <li>        <span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">            <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">.original.Trace(request, category, level, traceAction);</span></li> <li>        <span style="background:#ffffff;color:#000000">}</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> record = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">TraceRecord</span><span style="background:#ffffff;color:#000000">(request, category, level);</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000">traceAction(record);</span></li> <li>        <span style="background:#ffffff;color:#000000">System.Diagnostics.</span><span style="background:#ffffff;color:#2b91af">Trace</span><span style="background:#ffffff;color:#000000">.WriteLine(</span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000">.Format(</span><span style="background:#ffffff;color:#a31515">&quot;{0} - {1} - {2} - {3}&quot;</span><span style="background:#ffffff;color:#000000">,</span></li> <li style="background: #f3f3f3">            <span style="background:#ffffff;color:#000000">record.Level, record.Message, record.Category, record.Timestamp.ToString(</span><span style="background:#ffffff;color:#a31515">&quot;ddd MMM dd yyyy, HH:mm:ss tt&quot;</span><span style="background:#ffffff;color:#000000">)));</span></li> <li>    <span style="background:#ffffff;color:#000000">}</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">}</span></li> </ol> </div> </div> </div>  <p>And when creating our trace writer we can pass the original writer if the service is running in Azure (which you can access via the extension method <code>GetIsHosted</code> – you’ll need to add a <code>&quot;using System.Web.Http&quot;</code> statement if you don’t have already to see that method).</p>  <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:3c370b75-bf8a-42ec-a35b-2bee7ab60333" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #fff; overflow: auto"> <ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">static</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">class</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">WebApiConfig</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">{</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">static</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">void</span><span style="background:#ffffff;color:#000000"> Register()</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">{</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> config = </span><span style="background:#ffffff;color:#2b91af">ServiceConfig</span><span style="background:#ffffff;color:#000000">.Initialize(</span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">ConfigBuilder</span><span style="background:#ffffff;color:#000000">());</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">ITraceWriter</span><span style="background:#ffffff;color:#000000"> originalTraceWriter = </span><span style="background:#ffffff;color:#0000ff">null</span><span style="background:#ffffff;color:#000000">;</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">if</span><span style="background:#ffffff;color:#000000"> (config.GetIsHosted())</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000">{</span></li> <li>            <span style="background:#ffffff;color:#000000">originalTraceWriter = (</span><span style="background:#ffffff;color:#2b91af">ITraceWriter</span><span style="background:#ffffff;color:#000000">)config.Services.GetService(</span><span style="background:#ffffff;color:#0000ff">typeof</span><span style="background:#ffffff;color:#000000">(</span><span style="background:#ffffff;color:#2b91af">ITraceWriter</span><span style="background:#ffffff;color:#000000">));</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000">}</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000">config.Services.Replace(</span><span style="background:#ffffff;color:#0000ff">typeof</span><span style="background:#ffffff;color:#000000">(</span><span style="background:#ffffff;color:#2b91af">ITraceWriter</span><span style="background:#ffffff;color:#000000">), </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">MyTraceWriter</span><span style="background:#ffffff;color:#000000">(originalTraceWriter));</span></li> <li>    <span style="background:#ffffff;color:#000000">}</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">}</span></li> </ol> </div> </div> </div>  <p>Notice that for the case of a better local logging you could also only replace the trace writer if the service was running locally (i.e., if it was not hosted). But that organization will be useful in the next section.</p>  <h3>Changing logs destination</h3>  <p>Looking at the traces in the portal is fine during development, but as the service goes into production and if your mobile application is successful, you can expect thousands of traces being generated, and going through them via the portal isn’t the ideal way to analyze your logs. But since we can own completely the logging implementation, nothing prevents us from redirecting the logs to some external source – for example, table storage, where you can fetch and analyze them easier with several of the existing tools. Let’s change our trace listener implementation to send the logs to a table in Azure Storage if the service is running in the cloud.</p>  <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:80220ef9-3105-4ab1-8dd0-5736e235e688" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #fff; overflow: auto"> <ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">class</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">MyTraceWriter</span><span style="background:#ffffff;color:#000000"> : </span><span style="background:#ffffff;color:#2b91af">ITraceWriter</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">{</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">ITraceWriter</span><span style="background:#ffffff;color:#000000"> original;</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> mobileServiceName;</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> storageConnectionString;</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> MyTraceWriter(</span><span style="background:#ffffff;color:#2b91af">ITraceWriter</span><span style="background:#ffffff;color:#000000"> original, </span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> mobileServiceName, </span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> storageConnectionString)</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">{</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">.original = original;</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">.mobileServiceName = mobileServiceName;</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">.storageConnectionString = storageConnectionString;</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">}</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">void</span><span style="background:#ffffff;color:#000000"> Trace(</span><span style="background:#ffffff;color:#2b91af">HttpRequestMessage</span><span style="background:#ffffff;color:#000000"> request, </span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> category, </span><span style="background:#ffffff;color:#2b91af">TraceLevel</span><span style="background:#ffffff;color:#000000"> level, </span><span style="background:#ffffff;color:#2b91af">Action</span><span style="background:#ffffff;color:#000000">&lt;</span><span style="background:#ffffff;color:#2b91af">TraceRecord</span><span style="background:#ffffff;color:#000000">&gt; traceAction)</span></li> <li>    <span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> record = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">TraceRecord</span><span style="background:#ffffff;color:#000000">(request, category, level);</span></li> <li>        <span style="background:#ffffff;color:#000000">traceAction(record);</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">if</span><span style="background:#ffffff;color:#000000"> (</span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">.original == </span><span style="background:#ffffff;color:#0000ff">null</span><span style="background:#ffffff;color:#000000">)</span></li> <li>        <span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">            <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Running locally</span></li> <li>            <span style="background:#ffffff;color:#000000">System.Diagnostics.</span><span style="background:#ffffff;color:#2b91af">Trace</span><span style="background:#ffffff;color:#000000">.WriteLine(</span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000">.Format(</span><span style="background:#ffffff;color:#a31515">&quot;{0} - {1} - {2} - {3}&quot;</span><span style="background:#ffffff;color:#000000">,</span></li> <li style="background: #f3f3f3">                <span style="background:#ffffff;color:#000000">record.Level, record.Message, record.Category, record.Timestamp.ToString(</span><span style="background:#ffffff;color:#a31515">&quot;ddd MMM dd yyyy, HH:mm:ss tt&quot;</span><span style="background:#ffffff;color:#000000">)));</span></li> <li>            <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">return</span><span style="background:#ffffff;color:#000000">;</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000">}</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">.original.Trace(request, category, level, traceAction);</span></li> <li>        <span style="background:#ffffff;color:#000000">TraceToTableStorage(record);</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">}</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">private</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">void</span><span style="background:#ffffff;color:#000000"> TraceToTableStorage(</span><span style="background:#ffffff;color:#2b91af">TraceRecord</span><span style="background:#ffffff;color:#000000"> record)</span></li> <li>    <span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">CloudStorageAccount</span><span style="background:#ffffff;color:#000000"> storageAccount = </span><span style="background:#ffffff;color:#2b91af">CloudStorageAccount</span><span style="background:#ffffff;color:#000000">.Parse(</span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">.storageConnectionString);</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">CloudTableClient</span><span style="background:#ffffff;color:#000000"> tableClient = storageAccount.CreateCloudTableClient();</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">CloudTable</span><span style="background:#ffffff;color:#000000"> table = tableClient.GetTableReference(</span><span style="background:#ffffff;color:#a31515">&quot;mylogs&quot;</span><span style="background:#ffffff;color:#000000">);</span></li> <li>        <span style="background:#ffffff;color:#000000">table.CreateIfNotExists();</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">TableOperation</span><span style="background:#ffffff;color:#000000"> operation = </span><span style="background:#ffffff;color:#2b91af">TableOperation</span><span style="background:#ffffff;color:#000000">.Insert(</span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">TableTraceRecord</span><span style="background:#ffffff;color:#000000">(mobileServiceName, record));</span></li> <li>        <span style="background:#ffffff;color:#000000">table.Execute(operation);</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">}</span></li> <li><span style="background:#ffffff;color:#000000">}</span></li> </ol> </div> </div> </div>  <p>You’ll need to add a reference to the <a href="http://www.nuget.org/packages/WindowsAzure.Storage/">“Windows Azure Storage” package</a> if you haven’t done it yet to be able to use the classes shown in the code above. The <code>TableTraceRecord</code> class is defined as a subclass of <a href="http://msdn.microsoft.com/en-us/library/microsoft.windowsazure.storage.table.tableentity.aspx">TableEntity</a>, which is required to insert items into the tables. In this example I’m using the timestamp as the row key to make it easier to sort based on the trace order (and adding a random set of characters to disambiguate in case multiple trace requests come at the exact same instant).</p>  <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:c05ff083-3c61-4f78-a683-afa61d8bca58" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #fff; overflow: auto"> <ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">class</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">TableTraceRecord</span><span style="background:#ffffff;color:#000000"> : </span><span style="background:#ffffff;color:#2b91af">TableEntity</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">{</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">const</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> DateTimeFormat = </span><span style="background:#ffffff;color:#a31515">&quot;yyyy-MM-dd&#39;T&#39;HH:mm:ss.fffffff&#39;Z&#39;&quot;</span><span style="background:#ffffff;color:#000000">;</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> Message { </span><span style="background:#ffffff;color:#0000ff">get</span><span style="background:#ffffff;color:#000000">; </span><span style="background:#ffffff;color:#0000ff">set</span><span style="background:#ffffff;color:#000000">; }</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> Category { </span><span style="background:#ffffff;color:#0000ff">get</span><span style="background:#ffffff;color:#000000">; </span><span style="background:#ffffff;color:#0000ff">set</span><span style="background:#ffffff;color:#000000">; }</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> Level { </span><span style="background:#ffffff;color:#0000ff">get</span><span style="background:#ffffff;color:#000000">; </span><span style="background:#ffffff;color:#0000ff">set</span><span style="background:#ffffff;color:#000000">; }</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> TableTraceRecord(</span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> mobileServiceName, </span><span style="background:#ffffff;color:#2b91af">TraceRecord</span><span style="background:#ffffff;color:#000000"> traceRecord)</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000">: </span><span style="background:#ffffff;color:#0000ff">base</span><span style="background:#ffffff;color:#000000">(partitionKey: mobileServiceName, rowKey: CreateRowKey(traceRecord.Timestamp))</span></li> <li>    <span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">.Category = traceRecord.Category;</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">.Level = traceRecord.Level.ToString();</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">.Message = traceRecord.Message;</span></li> <li>    <span style="background:#ffffff;color:#000000">}</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">private</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">static</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> CreateRowKey(</span><span style="background:#ffffff;color:#2b91af">DateTime</span><span style="background:#ffffff;color:#000000"> dateTime)</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">{</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> disambiguator = </span><span style="background:#ffffff;color:#2b91af">Guid</span><span style="background:#ffffff;color:#000000">.NewGuid().ToString(</span><span style="background:#ffffff;color:#a31515">&quot;N&quot;</span><span style="background:#ffffff;color:#000000">).Substring(0, 8); </span><span style="background:#ffffff;color:#008000">// in case two entries have same timestamp</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">return</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000">.Format(</span><span style="background:#ffffff;color:#a31515">&quot;{0}-{1}&quot;</span><span style="background:#ffffff;color:#000000">,</span></li> <li>            <span style="background:#ffffff;color:#000000">dateTime.ToUniversalTime().ToString(DateTimeFormat, </span><span style="background:#ffffff;color:#2b91af">CultureInfo</span><span style="background:#ffffff;color:#000000">.InvariantCulture),</span></li> <li style="background: #f3f3f3">            <span style="background:#ffffff;color:#000000">disambiguator);</span></li> <li>    <span style="background:#ffffff;color:#000000">}</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">}</span></li> </ol> </div> </div> </div>  <p>We now need to pass the connection string and mobile service name to the trace writer class. The recommended way to store the connection string is via the app settings, so I’ll add the connection string fro my account there:</p>  <p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/95/96/metablogapi/6283.002TableStorageConnectionString_3BEE413F.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-95-96-metablogapi/6283.002TableStorageConnectionString_5F00_3BEE413F.png"><img title="002-TableStorageConnectionString" style="border-width: 0px; display: inline;" border="0" alt="002-TableStorageConnectionString" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/95/96/metablogapi/6787.002TableStorageConnectionString_thumb_1BD33482.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-95-96-metablogapi/6787.002TableStorageConnectionString_5F00_thumb_5F00_1BD33482.png" width="694" height="93" /></a> </p>  <p>And on the <code>Register</code> method we retrieve the values we need from the application settings.</p>  <p></p>  <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:bf440986-4ca4-467a-871a-15c1bbeb25fe" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #fff; overflow: auto"> <ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">static</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">class</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">WebApiConfig</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">{</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">static</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">void</span><span style="background:#ffffff;color:#000000"> Register()</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">{</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> config = </span><span style="background:#ffffff;color:#2b91af">ServiceConfig</span><span style="background:#ffffff;color:#000000">.Initialize(</span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">ConfigBuilder</span><span style="background:#ffffff;color:#000000">());</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">ITraceWriter</span><span style="background:#ffffff;color:#000000"> originalTraceWriter = </span><span style="background:#ffffff;color:#0000ff">null</span><span style="background:#ffffff;color:#000000">;</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">if</span><span style="background:#ffffff;color:#000000"> (config.GetIsHosted())</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000">{</span></li> <li>            <span style="background:#ffffff;color:#000000">originalTraceWriter = (</span><span style="background:#ffffff;color:#2b91af">ITraceWriter</span><span style="background:#ffffff;color:#000000">)config.Services.GetService(</span><span style="background:#ffffff;color:#0000ff">typeof</span><span style="background:#ffffff;color:#000000">(</span><span style="background:#ffffff;color:#2b91af">ITraceWriter</span><span style="background:#ffffff;color:#000000">));</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000">}</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> mobileServiceName = </span><span style="background:#ffffff;color:#2b91af">ConfigurationManager</span><span style="background:#ffffff;color:#000000">.AppSettings[</span><span style="background:#ffffff;color:#2b91af">ServiceSettingsKeys</span><span style="background:#ffffff;color:#000000">.ServiceName];</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> storageConnectionString = </span><span style="background:#ffffff;color:#2b91af">ConfigurationManager</span><span style="background:#ffffff;color:#000000">.AppSettings[</span><span style="background:#ffffff;color:#a31515">&quot;MyTableStorageConnString&quot;</span><span style="background:#ffffff;color:#000000">];</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> myTraceWriter = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">MyTraceWriter</span><span style="background:#ffffff;color:#000000">(originalTraceWriter, mobileServiceName, storageConnectionString);</span></li> <li>        <span style="background:#ffffff;color:#000000">config.Services.Replace(</span><span style="background:#ffffff;color:#0000ff">typeof</span><span style="background:#ffffff;color:#000000">(</span><span style="background:#ffffff;color:#2b91af">ITraceWriter</span><span style="background:#ffffff;color:#000000">), myTraceWriter);</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000">config.SetIsHosted(</span><span style="background:#ffffff;color:#0000ff">true</span><span style="background:#ffffff;color:#000000">);</span></li> <li>    <span style="background:#ffffff;color:#000000">}</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">}</span></li> </ol> </div> </div> </div>  <p>Now when the trace is executed, it will write to the table storage.</p>  <h3>More logging please!</h3>  <p>So far we’re looking at how to look at the logs which our application writes out. But the .NET backend also exposes other kinds of logs which you can see as well. When we’re initializing the service configuration, we can pass a set of configuration options. One of them is the list of trace categories which are excluded from the traces. By default, internal traces are excluded, but we can remove those by clearing the <code>ExcludedTraceCategories</code> list in the config options passed to the initializer, as shown below.</p>  <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:806aaa6a-347c-47ec-aebe-13853ceb58f3" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #fff; overflow: auto"> <ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">static</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">class</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">WebApiConfig</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">{</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">static</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">void</span><span style="background:#ffffff;color:#000000"> Register()</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">{</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> configOptions = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">ConfigOptions</span><span style="background:#ffffff;color:#000000">();</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000">configOptions.ExcludedTraceCategories.Clear();</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> configBuilder = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">ConfigBuilder</span><span style="background:#ffffff;color:#000000">(configOptions);</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> config = </span><span style="background:#ffffff;color:#2b91af">ServiceConfig</span><span style="background:#ffffff;color:#000000">.Initialize(configBuilder);</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// ...</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">}</span></li> <li><span style="background:#ffffff;color:#000000">}</span></li> </ol> </div> </div> </div>  <p>Try it out – you’ll see more information about the inner workings of the backend. Definitely some information that the majority of the users won’t need, but a good way to get a better view of what’s happening behind the scenes.</p>  <p></p>  <h3>Wrapping up</h3>  <p>I hope this post will help you understand how to better use the logging subsystems in the .NET backend for mobile services. As usual, feel free to submit questions or comments to this post, the <a href="http://social.msdn.microsoft.com/Forums/windowsazure/en-US/home?forum=azuremobile">MSDN forums</a> or contact us via Twitter <a href="https://twitter.com/azuremobile">@AzureMobile</a>.</p>]]></content:encoded>
    </item>
    <item>
      <title>Creating MongoDB-backed tables in Azure Mobile Services with .NET backend</title>
      <link>https://docs.microsoft.com/archive/blogs/carlosfigueira/creating-mongodb-backed-tables-in-azure-mobile-services-with-net-backend</link>
      <pubDate>Mon, 14 Apr 2014 13:07:55 GMT</pubDate>
      <dc:creator><![CDATA[CarlosFigueira]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/carlosfigueira/2014/04/14/creating-mongodb-backed-tables-in-azure-mobile-services-with-net-backend/</guid>
      <description><![CDATA[[This post originally appeared in...]]></description>
      <content:encoded><![CDATA[<p><em>[This post originally appeared in </em><a title="http://blogs.msdn.com/b/azuremobile/archive/2014/04/14/creating-mongodb-backed-tables-in-azure-mobile-services-with-net-backend.aspx" href="http://blogs.msdn.com/b/azuremobile/archive/2014/04/14/creating-mongodb-backed-tables-in-azure-mobile-services-with-net-backend.aspx"><em>http://blogs.msdn.com/b/azuremobile/archive/2014/04/14/creating-mongodb-backed-tables-in-azure-mobile-services-with-net-backend.aspx</em></a><em>. I’ll be writing Azure Mobile Service related posts in the </em><a href="http://blogs.msdn.com/b/azuremobile"><em>Azure Mobile blog</em></a><em> primarily, and cross-posting them here for people who have feeds linked to this blog only]</em></p>  <p>One of the advantages of the .NET backend for Azure Mobile Services is that it has out-of-the-box support for multiple data storages, not only SQL Azure. In the node.js runtime you could bypass the SQL operations and use some other storage option (as in <a href="http://chrisrisner.com/Mobile-Services-and-Windows-Azure-Storage">this post by Chris Risner</a> for Azure Table Storage), but it’s not a built-in functionality and you’d need to write a lot of code yourself. With the .NET runtime, a lot of the support is built-in, and there’s no need to create a “dummy” table just to have the requests to it redirected. In this post I’ll talk a little about the MongoDB support, and how we can create tables for which the CRUD operations are directed to a MongoDB collection.</p>  <h3>Database setup</h3>  <p>If you already have a MongoDB account with some collection created, feel free to skip this step (just make sure to take a note of your connection string, we’ll need it later). I’ll also use a collection named “orders” in this post – you don’t need to create one, the backend will create one if it doesn’t exist.</p>  <p>If you’re starting from scratch, for this post I’m using a Mongo Labs database, which we can get for free (for the sandboxed, developer edition) on the Azure portal. To create an account, you can go to the Azure portal, select “New” –&gt; “Store”, and select the MongoLab add-on, where you can sign up for an account.</p>  <p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/95/96/metablogapi/0755.001NewMongoLabAddOn_186DCDA3.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-95-96-metablogapi/0755.001NewMongoLabAddOn_5F00_186DCDA3.png"><img title="001-NewMongoLabAddOn" style="border-width: 0px; display: inline;" border="0" alt="001-NewMongoLabAddOn" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/95/96/metablogapi/7230.001NewMongoLabAddOn_thumb_4F4AB29A.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-95-96-metablogapi/7230.001NewMongoLabAddOn_5F00_thumb_5F00_4F4AB29A.png" width="699" height="462" /></a> </p>  <p>Once you have the account set up, click the “Connection info” button to copy the URI to connect to the database and save that value. The name you gave to the account is the name of the database, which we’ll also use later.</p>  <p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/95/96/metablogapi/5670.002ConnectionInfoAndManage_67DA4FEA.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-95-96-metablogapi/5670.002ConnectionInfoAndManage_5F00_67DA4FEA.png"><img title="002-ConnectionInfoAndManage" style="border-width: 0px; display: inline;" border="0" alt="002-ConnectionInfoAndManage" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/95/96/metablogapi/3835.002ConnectionInfoAndManage_thumb_35767C6B.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-95-96-metablogapi/3835.002ConnectionInfoAndManage_5F00_thumb_5F00_35767C6B.png" width="575" height="192" /></a> </p>  <p>Now the Mongo database is set; we don’t need to create a collection, it will be created when we first try to access it via the backend.</p>  <h3>Service setup</h3>  <p>Since we don’t have a complete Visual Studio tooling story for non-Entity Framework backend types, let’s begin with an empty web project. We’ll start as I did on my <a href="http://blogs.msdn.com/b/azuremobile/archive/2014/04/10/creating-an-azure-mobile-services-net-backend-from-scratch.aspx">previous post about creating a .NET backend from scratch</a>, but instead of adding the Azure Mobile Services .NET Backend Entity Framework Extension NuGet package, we’ll add the <a href="https://www.nuget.org/packages/WindowsAzure.MobileServices.Backend.Mongo">Azure Mobile Services .NET Backend Mongo Extension</a> package instead. Let’s also add the <a href="https://www.nuget.org/packages/Microsoft.Owin.Host.SystemWeb">Microsoft.Owin.Host.SystemWeb</a> package so that we’ll be able to run it locally for easier debugging.</p>  <p>With the two packages (and all of its dependencies) installed, let’s add the bootstrapper class by adding a WebApiConfig static class with a default Register method:</p>  <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:9fee8630-6c96-4335-916b-32133d364d48" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #fff; overflow: auto"> <ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">static</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">class</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">WebApiConfig</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">{</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">static</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">void</span><span style="background:#ffffff;color:#000000"> Register()</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">{</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">ServiceConfig</span><span style="background:#ffffff;color:#000000">.Initialize(</span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">ConfigBuilder</span><span style="background:#ffffff;color:#000000">());</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">}</span></li> <li><span style="background:#ffffff;color:#000000">}</span></li> </ol> </div> </div> </div>  <p>And also add a Global Application Class to invoke the bootstrapper when running locally:</p>  <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:304d52bf-b644-4f07-806b-a10fb29f07d8" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #fff; overflow: auto"> <ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">class</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">Global</span><span style="background:#ffffff;color:#000000"> : System.Web.</span><span style="background:#ffffff;color:#2b91af">HttpApplication</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">{</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">protected</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">void</span><span style="background:#ffffff;color:#000000"> Application_Start(</span><span style="background:#ffffff;color:#0000ff">object</span><span style="background:#ffffff;color:#000000"> sender, </span><span style="background:#ffffff;color:#2b91af">EventArgs</span><span style="background:#ffffff;color:#000000"> e)</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">{</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">WebApiConfig</span><span style="background:#ffffff;color:#000000">.Register();</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">}</span></li> <li><span style="background:#ffffff;color:#000000">}</span></li> </ol> </div> </div> </div>  <p>Next let’s define our object model which we’ll store in the database collection. For this example, let’s define the order which contains a series of items.</p>  <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:7bdd7c7c-8ff4-4650-98e3-c62bd4ea3b44" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #fff; overflow: auto"> <ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">class</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">Order</span><span style="background:#ffffff;color:#000000"> : </span><span style="background:#ffffff;color:#2b91af">DocumentData</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">{</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">DateTime</span><span style="background:#ffffff;color:#000000"> OrderDate { </span><span style="background:#ffffff;color:#0000ff">get</span><span style="background:#ffffff;color:#000000">; </span><span style="background:#ffffff;color:#0000ff">set</span><span style="background:#ffffff;color:#000000">; }</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> Client { </span><span style="background:#ffffff;color:#0000ff">get</span><span style="background:#ffffff;color:#000000">; </span><span style="background:#ffffff;color:#0000ff">set</span><span style="background:#ffffff;color:#000000">; }</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">List</span><span style="background:#ffffff;color:#000000">&lt;</span><span style="background:#ffffff;color:#2b91af">OrderItem</span><span style="background:#ffffff;color:#000000">&gt; Items { </span><span style="background:#ffffff;color:#0000ff">get</span><span style="background:#ffffff;color:#000000">; </span><span style="background:#ffffff;color:#0000ff">set</span><span style="background:#ffffff;color:#000000">; }</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">}</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">class</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">OrderItem</span></li> <li><span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> Name { </span><span style="background:#ffffff;color:#0000ff">get</span><span style="background:#ffffff;color:#000000">; </span><span style="background:#ffffff;color:#0000ff">set</span><span style="background:#ffffff;color:#000000">; }</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">double</span><span style="background:#ffffff;color:#000000"> Quantity { </span><span style="background:#ffffff;color:#0000ff">get</span><span style="background:#ffffff;color:#000000">; </span><span style="background:#ffffff;color:#0000ff">set</span><span style="background:#ffffff;color:#000000">; }</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">double</span><span style="background:#ffffff;color:#000000"> Price { </span><span style="background:#ffffff;color:#0000ff">get</span><span style="background:#ffffff;color:#000000">; </span><span style="background:#ffffff;color:#0000ff">set</span><span style="background:#ffffff;color:#000000">; }</span></li> <li><span style="background:#ffffff;color:#000000">}</span></li> </ol> </div> </div> </div>  <p>Notice that, like on EF-backed data the models to be used in tables need to implement the <code>ITableData</code> interface. For the EF scenario we provide the <code>EntityData</code> base class which can be used, and similarly for the MongoDB case we provide the <code>DocumentData</code> class which implements that interface, leaving the model class to define the domain-specific properties only.</p>  <h3>Defining the table</h3>  <p>Tables for MongoDB-backed data are really similar to the EF-based ones. The operations can be implemented exactly like in that scenario, except that we need a new domain manager implementation, for which we can use the <code>MongoDomainManager</code> class which comes with the <a href="https://www.nuget.org/packages/WindowsAzure.MobileServices.Backend.Mongo">Azure Mobile Services .NET Backend Mongo Extension</a> NuGet package. Notice that you can always use the types from the MongoDB driver (or any other Mongo client) directly to implement the operations, but for common scenarios, the base class <code>TableController&lt;T&gt;</code> provides the implementation necessary.</p>  <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:391dc38d-c7ab-4e48-87a9-7af29956b695" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #fff; overflow: auto"> <ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">class</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">OrderController</span><span style="background:#ffffff;color:#000000"> : </span><span style="background:#ffffff;color:#2b91af">TableController</span><span style="background:#ffffff;color:#000000">&lt;</span><span style="background:#ffffff;color:#2b91af">Order</span><span style="background:#ffffff;color:#000000">&gt;</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">{</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">protected</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">override</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">void</span><span style="background:#ffffff;color:#000000"> Initialize(</span><span style="background:#ffffff;color:#2b91af">HttpControllerContext</span><span style="background:#ffffff;color:#000000"> controllerContext)</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">{</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">base</span><span style="background:#ffffff;color:#000000">.Initialize(controllerContext);</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> connStringName = </span><span style="background:#ffffff;color:#a31515">&quot;mongodb&quot;</span><span style="background:#ffffff;color:#000000">;</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> dbName = </span><span style="background:#ffffff;color:#a31515">&quot;MyMongoLab&quot;</span><span style="background:#ffffff;color:#000000">;</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> collectionName = </span><span style="background:#ffffff;color:#a31515">&quot;orders&quot;</span><span style="background:#ffffff;color:#000000">;</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">.DomainManager = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">MongoDomainManager</span><span style="background:#ffffff;color:#000000">&lt;</span><span style="background:#ffffff;color:#2b91af">Order</span><span style="background:#ffffff;color:#000000">&gt;(connStringName, dbName, collectionName, </span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">.Request, </span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">.Services);</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">}</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">IQueryable</span><span style="background:#ffffff;color:#000000">&lt;</span><span style="background:#ffffff;color:#2b91af">Order</span><span style="background:#ffffff;color:#000000">&gt; GetAllOrders()</span></li> <li>    <span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">return</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">base</span><span style="background:#ffffff;color:#000000">.Query();</span></li> <li>    <span style="background:#ffffff;color:#000000">}</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">Order</span><span style="background:#ffffff;color:#000000"> GetOneOrder(</span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> id)</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">{</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> result = </span><span style="background:#ffffff;color:#0000ff">base</span><span style="background:#ffffff;color:#000000">.Lookup(id).Queryable.FirstOrDefault();</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">if</span><span style="background:#ffffff;color:#000000"> (result == </span><span style="background:#ffffff;color:#0000ff">null</span><span style="background:#ffffff;color:#000000">)</span></li> <li>        <span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">            <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">throw</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">HttpResponseException</span><span style="background:#ffffff;color:#000000">(</span><span style="background:#ffffff;color:#2b91af">HttpStatusCode</span><span style="background:#ffffff;color:#000000">.NotFound);</span></li> <li>        <span style="background:#ffffff;color:#000000">}</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">else</span></li> <li>        <span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">            <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">return</span><span style="background:#ffffff;color:#000000"> result;</span></li> <li>        <span style="background:#ffffff;color:#000000">}</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">}</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">Task</span><span style="background:#ffffff;color:#000000">&lt;</span><span style="background:#ffffff;color:#2b91af">Order</span><span style="background:#ffffff;color:#000000">&gt; PostOrder(</span><span style="background:#ffffff;color:#2b91af">Order</span><span style="background:#ffffff;color:#000000"> order)</span></li> <li>    <span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">return</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">base</span><span style="background:#ffffff;color:#000000">.InsertAsync(order);</span></li> <li>    <span style="background:#ffffff;color:#000000">}</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">Task</span><span style="background:#ffffff;color:#000000"> DeleteOrder(</span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> id)</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">{</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">return</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">base</span><span style="background:#ffffff;color:#000000">.DeleteAsync(id);</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">}</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">Task</span><span style="background:#ffffff;color:#000000">&lt;</span><span style="background:#ffffff;color:#2b91af">Order</span><span style="background:#ffffff;color:#000000">&gt; PatchOrder(</span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> id, </span><span style="background:#ffffff;color:#2b91af">Delta</span><span style="background:#ffffff;color:#000000">&lt;</span><span style="background:#ffffff;color:#2b91af">Order</span><span style="background:#ffffff;color:#000000">&gt; patch)</span></li> <li>    <span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">return</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">base</span><span style="background:#ffffff;color:#000000">.UpdateAsync(id, patch);</span></li> <li>    <span style="background:#ffffff;color:#000000">}</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">}</span></li> </ol> </div> </div> </div>  <p>The first parameter in the <code>MongoDomainManager</code> constructor is the name of an element in the &lt;connectionStrings&gt; section in the configuration which contains the actual connection string for the database (we may add an option to pass the actual connection string to the constructor later). If we add the appropriate section to the web.config file (use the connection string you got from the Azure portal):</p>  <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:6d1386f9-2445-4c78-ac82-3d88ff9c2082" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #fff; overflow: auto"> <ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#0000ff">&lt;</span><span style="background:#ffffff;color:#a31515">connectionStrings</span><span style="background:#ffffff;color:#0000ff">&gt;</span></li> <li style="background: #f3f3f3">  <span style="background:#ffffff;color:#0000ff">&lt;</span><span style="background:#ffffff;color:#a31515">add</span><span style="background:#ffffff;color:#0000ff"> </span><span style="background:#ffffff;color:#ff0000">name</span><span style="background:#ffffff;color:#0000ff">=</span><span style="background:#ffffff;color:#000000">&quot;</span><span style="background:#ffffff;color:#0000ff">mongodb</span><span style="background:#ffffff;color:#000000">&quot;</span><span style="background:#ffffff;color:#0000ff"> </span><span style="background:#ffffff;color:#ff0000">connectionString</span><span style="background:#ffffff;color:#0000ff">=</span><span style="background:#ffffff;color:#000000">&quot;</span><span style="background:#ffffff;color:#0000ff">mongodb://MyMongoLab:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX-@dsNNNNNN.mongolab.com:PPPPP/MyMongoLab</span><span style="background:#ffffff;color:#000000">&quot;</span><span style="background:#ffffff;color:#0000ff">/&gt;</span></li> <li><span style="background:#ffffff;color:#0000ff">&lt;/</span><span style="background:#ffffff;color:#a31515">connectionStrings</span><span style="background:#ffffff;color:#0000ff">&gt;</span></li> </ol> </div> </div> </div>  <p>We should be able to run the project now. If we press CTRL+F5 the service should start running.</p>  <h3>Testing the service</h3>  <p>To test the service, let’s fire up Fiddler to send some requests to the service. First, let’s see what we GET from it:</p>  <blockquote>   <pre>GET http://localhost:54524/tables/order HTTP/1.1 
User-Agent: Fiddler 
Host: localhost:54524 

=-=-=-=-=-=-=-=-=-

HTTP/1.1 200 OK 
Cache-Control: no-cache 
Pragma: no-cache 
Content-Length: 2 
Content-Type: application/json; charset=utf-8 
Expires: 0 
Server: Microsoft-IIS/8.0 
X-Powered-By: ASP.NET 
Date: Mon, 14 Apr 2014 15:43:31 GMT 

[]</pre>
</blockquote>

<p>Nothing unexpected here (unless you already had an “orders” collection in your database). Let’s add some orders to our collection:</p>

<blockquote>
  <pre>POST http://localhost:54524/tables/order HTTP/1.1
User-Agent: Fiddler
Host: localhost:54524
Content-Length: 211
Content-Type: application/json

{
    &quot;client&quot;:&quot;John Doe&quot;,
    &quot;orderDate&quot;:&quot;2014-04-13T00:00:00Z&quot;,
    &quot;items&quot;:[
        { &quot;name&quot;: &quot;bread&quot;, &quot;quantity&quot;: 1, &quot;price&quot;: 1.99 },
        { &quot;name&quot;: &quot;milk&quot;, &quot;quantity&quot;: 2, &quot;price&quot;: 2.99 }
    ]
}

=-=-=-=-=-=-=-=-=-

HTTP/1.1 200 OK
Content-Length: 383
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/8.0
X-Powered-By: ASP.NET
Date: Mon, 14 Apr 2014 15:53:13 GMT

{
  &quot;orderDate&quot;: &quot;2014-04-13T00:00:00Z&quot;,
  &quot;client&quot;: &quot;John Doe&quot;,
  &quot;items&quot;: [
    {
      &quot;name&quot;: &quot;bread&quot;,
      &quot;quantity&quot;: 1.0,
      &quot;price&quot;: 1.99
    },
    {
      &quot;name&quot;: &quot;milk&quot;,
      &quot;quantity&quot;: 2.0,
      &quot;price&quot;: 2.99
    }
  ],
  &quot;id&quot;: &quot;534c0469f76e1e10c4703c2b&quot;,
  &quot;__createdAt&quot;: &quot;2014-04-14T15:53:12.982Z&quot;,
  &quot;__updatedAt&quot;: &quot;2014-04-14T15:53:12.982Z&quot;
}</pre>
</blockquote>

<p>And one more</p>

<blockquote>
  <pre>POST http://localhost:54524/tables/order HTTP/1.1
User-Agent: Fiddler
Host: localhost:54524
Content-Length: 216
Content-Type: application/json

{
    &quot;client&quot;:&quot;Jane Roe&quot;,
    &quot;orderDate&quot;:&quot;2014-02-22T00:00:00Z&quot;,
    &quot;items&quot;:[
        { &quot;name&quot;: &quot;nails&quot;, &quot;quantity&quot;: 100, &quot;price&quot;: 3.50 },
        { &quot;name&quot;: &quot;hammer&quot;, &quot;quantity&quot;: 1, &quot;price&quot;: 12.34 }
    ]
}

=-=-=-=-=-=-=-=-=-

HTTP/1.1 200 OK
Content-Length: 387
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/8.0
X-Powered-By: ASP.NET
Date: Mon, 14 Apr 2014 15:53:21 GMT

{
  &quot;orderDate&quot;: &quot;2014-02-22T00:00:00Z&quot;,
  &quot;client&quot;: &quot;Jane Roe&quot;,
  &quot;items&quot;: [
    {
      &quot;name&quot;: &quot;nails&quot;,
      &quot;quantity&quot;: 100.0,
      &quot;price&quot;: 3.5
    },
    {
      &quot;name&quot;: &quot;hammer&quot;,
      &quot;quantity&quot;: 1.0,
      &quot;price&quot;: 12.34
    }
  ],
  &quot;id&quot;: &quot;534c0471f76e1e10c4703c2c&quot;,
  &quot;__createdAt&quot;: &quot;2014-04-14T15:53:21.557Z&quot;,
  &quot;__updatedAt&quot;: &quot;2014-04-14T15:53:21.557Z&quot;
}</pre>
</blockquote>

<p>Now we can try to resend the GET request to see what we've got:</p>

<blockquote>
  <pre>GET http://localhost:54524/tables/order HTTP/1.1 
User-Agent: Fiddler 
Host: localhost:54524 

=-=-=-=-=-=-=-=-=-

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Length: 239
Content-Type: application/json; charset=utf-8
Expires: 0
Server: Microsoft-IIS/8.0
X-Powered-By: ASP.NET
Date: Mon, 14 Apr 2014 15:55:12 GMT

[
  {
    &quot;id&quot;: &quot;534c0469f76e1e10c4703c2b&quot;,
    &quot;client&quot;: &quot;John Doe&quot;,
    &quot;orderDate&quot;: &quot;2014-04-13T00:00:00Z&quot;
  },
  {
    &quot;id&quot;: &quot;534c0471f76e1e10c4703c2c&quot;,
    &quot;client&quot;: &quot;Jane Roe&quot;,
    &quot;orderDate&quot;: &quot;2014-02-22T00:00:00Z&quot;
  }
]</pre>
</blockquote>

<p>We got the items which we added, but we don’t get the complex property (items) in the object. The issue we have here is that the return type of the operation (<code>IQueryable&lt;Order&gt;</code>) only returns complex properties if the client explicitly asks for it (by passing the <b>$expand=&lt;propertyName&gt;</b> query string parameter). Having the method return a queryable object is useful because it also adds the additional filtering and ordering capabilities (via $filter and $orderby parameters, respectively), so we must make a decision on whether to continue using the queryable and pass the $expand to retrieve the items, or move to another return type. For the latter, the change is fairly small:</p>

<div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:8481fb81-7767-4e5c-a18c-90af78eb4edc" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;">
<div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt">
<div style="background: #fff; overflow: auto">
<ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;">
<li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">List</span><span style="background:#ffffff;color:#000000">&lt;</span><span style="background:#ffffff;color:#2b91af">Order</span><span style="background:#ffffff;color:#000000">&gt; GetAllOrders()</span></li>
<li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">{</span></li>
<li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">return</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">base</span><span style="background:#ffffff;color:#000000">.Query().ToList();</span></li>
<li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">}</span></li>
</ol>
</div>
</div>
</div>

<p>For the former, there are some alternatives. The easier (on the server) is to make the client send the $expand header, and nothing needs to be changed in the server. In this case, we can send the request and get the full document back:</p>

<blockquote>
  <pre>GET http://localhost:54524/tables/order?$expand=items HTTP/1.1 
User-Agent: Fiddler 
Host: localhost:54524 

=-=-=-=-=-=-=-=-=-

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Length: 663
Content-Type: application/json; charset=utf-8
Expires: 0
Server: Microsoft-IIS/8.0
X-Powered-By: ASP.NET
Date: Mon, 14 Apr 2014 17:52:26 GMT

[
  {
    &quot;id&quot;: &quot;534c0469f76e1e10c4703c2b&quot;,
    &quot;client&quot;: &quot;John Doe&quot;,
    &quot;orderDate&quot;: &quot;2014-04-13T00:00:00Z&quot;,
    &quot;items&quot;: [
      {
        &quot;name&quot;: &quot;bread&quot;,
        &quot;quantity&quot;: 1.0,
        &quot;price&quot;: 1.99
      },
      {
        &quot;name&quot;: &quot;milk&quot;,
        &quot;quantity&quot;: 2.0,
        &quot;price&quot;: 2.99
      }
    ]
  },
  {
    &quot;id&quot;: &quot;534c0471f76e1e10c4703c2c&quot;,
    &quot;client&quot;: &quot;Jane Roe&quot;,
    &quot;orderDate&quot;: &quot;2014-02-22T00:00:00Z&quot;,
    &quot;items&quot;: [
      {
        &quot;name&quot;: &quot;nails&quot;,
        &quot;quantity&quot;: 100.0,
        &quot;price&quot;: 3.5
      },
      {
        &quot;name&quot;: &quot;hammer&quot;,
        &quot;quantity&quot;: 1.0,
        &quot;price&quot;: 12.34
      }
    ]
  }
]</pre>
</blockquote>

<p>Another alternative is to use an action filter which will change the incoming requests to always add the expand query parameter. One possible implementation is given below:</p>

<div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:db14a692-359e-423e-9a5d-90ab7bdac2b6" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;">
<div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt">
<div style="background: #fff; overflow: auto">
<ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;">
<li><span style="background:#ffffff;color:#000000">[</span><span style="background:#ffffff;color:#2b91af">AttributeUsage</span><span style="background:#ffffff;color:#000000">(</span><span style="background:#ffffff;color:#2b91af">AttributeTargets</span><span style="background:#ffffff;color:#000000">.Method, AllowMultiple = </span><span style="background:#ffffff;color:#0000ff">true</span><span style="background:#ffffff;color:#000000">)]</span></li>
<li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">class</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">ExpandPropertyAttribute</span><span style="background:#ffffff;color:#000000"> : </span><span style="background:#ffffff;color:#2b91af">ActionFilterAttribute</span></li>
<li><span style="background:#ffffff;color:#000000">{</span></li>
<li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> propertyName;</span></li>
<li>&nbsp;</li>
<li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> ExpandPropertyAttribute(</span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> propertyName)</span></li>
<li>    <span style="background:#ffffff;color:#000000">{</span></li>
<li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">.propertyName = propertyName;</span></li>
<li>    <span style="background:#ffffff;color:#000000">}</span></li>
<li style="background: #f3f3f3">&nbsp;</li>
<li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">override</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">void</span><span style="background:#ffffff;color:#000000"> OnActionExecuting(</span><span style="background:#ffffff;color:#2b91af">HttpActionContext</span><span style="background:#ffffff;color:#000000"> actionContext)</span></li>
<li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">{</span></li>
<li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">base</span><span style="background:#ffffff;color:#000000">.OnActionExecuting(actionContext);</span></li>
<li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> uriBuilder = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">UriBuilder</span><span style="background:#ffffff;color:#000000">(actionContext.Request.RequestUri);</span></li>
<li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> queryParams = uriBuilder.Query.TrimStart(</span><span style="background:#ffffff;color:#a31515">&#39;?&#39;</span><span style="background:#ffffff;color:#000000">).Split(</span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000">[] { </span><span style="background:#ffffff;color:#a31515">&#39;&amp;&#39;</span><span style="background:#ffffff;color:#000000"> }, </span><span style="background:#ffffff;color:#2b91af">StringSplitOptions</span><span style="background:#ffffff;color:#000000">.RemoveEmptyEntries).ToList();</span></li>
<li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">int</span><span style="background:#ffffff;color:#000000"> expandIndex = -1;</span></li>
<li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">for</span><span style="background:#ffffff;color:#000000"> (</span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> i = 0; i &lt; queryParams.Count; i++)</span></li>
<li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000">{</span></li>
<li>            <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">if</span><span style="background:#ffffff;color:#000000"> (queryParams[i].StartsWith(</span><span style="background:#ffffff;color:#a31515">&quot;$expand&quot;</span><span style="background:#ffffff;color:#000000">, </span><span style="background:#ffffff;color:#2b91af">StringComparison</span><span style="background:#ffffff;color:#000000">.Ordinal))</span></li>
<li style="background: #f3f3f3">            <span style="background:#ffffff;color:#000000">{</span></li>
<li>                <span style="background:#ffffff;color:#000000">expandIndex = i;</span></li>
<li style="background: #f3f3f3">                <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">break</span><span style="background:#ffffff;color:#000000">;</span></li>
<li>            <span style="background:#ffffff;color:#000000">}</span></li>
<li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000">}</span></li>
<li>&nbsp;</li>
<li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">if</span><span style="background:#ffffff;color:#000000"> (expandIndex &lt; 0)</span></li>
<li>        <span style="background:#ffffff;color:#000000">{</span></li>
<li style="background: #f3f3f3">            <span style="background:#ffffff;color:#000000">queryParams.Add(</span><span style="background:#ffffff;color:#a31515">&quot;$expand=&quot;</span><span style="background:#ffffff;color:#000000"> + </span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">.propertyName);</span></li>
<li>        <span style="background:#ffffff;color:#000000">}</span></li>
<li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">else</span></li>
<li>        <span style="background:#ffffff;color:#000000">{</span></li>
<li style="background: #f3f3f3">            <span style="background:#ffffff;color:#000000">queryParams[expandIndex] = queryParams[expandIndex] + </span><span style="background:#ffffff;color:#a31515">&quot;,&quot;</span><span style="background:#ffffff;color:#000000"> + propertyName;</span></li>
<li>        <span style="background:#ffffff;color:#000000">}</span></li>
<li style="background: #f3f3f3">&nbsp;</li>
<li>        <span style="background:#ffffff;color:#000000">uriBuilder.Query = </span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000">.Join(</span><span style="background:#ffffff;color:#a31515">&quot;&amp;&quot;</span><span style="background:#ffffff;color:#000000">, queryParams);</span></li>
<li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000">actionContext.Request.RequestUri = uriBuilder.Uri;</span></li>
<li>    <span style="background:#ffffff;color:#000000">}</span></li>
<li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">}</span></li>
</ol>
</div>
</div>
</div>

<p>And if we decorate our method with that attribute</p>

<div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:998814e5-22b1-4765-8c04-ca2b22816399" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;">
<div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt">
<div style="background: #fff; overflow: auto">
<ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;">
<li><span style="background:#ffffff;color:#000000">[</span><span style="background:#ffffff;color:#2b91af">ExpandProperty</span><span style="background:#ffffff;color:#000000">(</span><span style="background:#ffffff;color:#a31515">&quot;Items&quot;</span><span style="background:#ffffff;color:#000000">)]</span></li>
<li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">IQueryable</span><span style="background:#ffffff;color:#000000">&lt;</span><span style="background:#ffffff;color:#2b91af">Order</span><span style="background:#ffffff;color:#000000">&gt; GetAllOrders()</span></li>
<li><span style="background:#ffffff;color:#000000">{</span></li>
<li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">return</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">base</span><span style="background:#ffffff;color:#000000">.Query();</span></li>
<li><span style="background:#ffffff;color:#000000">}</span></li>
</ol>
</div>
</div>
</div>

<p>We can send requests which use other queryable attributes while still having the expanded items in our order</p>

<blockquote>
  <pre>GET http://localhost:54524/tables/order?$orderby=client HTTP/1.1 
User-Agent: Fiddler 
Host: localhost:54524 

=-=-=-=-=-=-=-=-=-
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Length: 663
Content-Type: application/json; charset=utf-8
Expires: 0
Server: Microsoft-IIS/8.0
X-Powered-By: ASP.NET
Date: Mon, 14 Apr 2014 18:37:27 GMT

[
  {
    &quot;id&quot;: &quot;534c0471f76e1e10c4703c2c&quot;,
    &quot;client&quot;: &quot;Jane Roe&quot;,
    &quot;orderDate&quot;: &quot;2014-02-22T00:00:00Z&quot;,
    &quot;items&quot;: [
      {
        &quot;name&quot;: &quot;nails&quot;,
        &quot;quantity&quot;: 100.0,
        &quot;price&quot;: 3.5
      },
      {
        &quot;name&quot;: &quot;hammer&quot;,
        &quot;quantity&quot;: 1.0,
        &quot;price&quot;: 12.34
      }
    ]
  },
  {
    &quot;id&quot;: &quot;534c0469f76e1e10c4703c2b&quot;,
    &quot;client&quot;: &quot;John Doe&quot;,
    &quot;orderDate&quot;: &quot;2014-04-13T00:00:00Z&quot;,
    &quot;items&quot;: [
      {
        &quot;name&quot;: &quot;bread&quot;,
        &quot;quantity&quot;: 1.0,
        &quot;price&quot;: 1.99
      },
      {
        &quot;name&quot;: &quot;milk&quot;,
        &quot;quantity&quot;: 2.0,
        &quot;price&quot;: 2.99
      }
    ]
  }
]</pre>
</blockquote>

<h3>Deployment</h3>

<p>Now that the service runs locally correctly, we’re ready to publish to Azure. After downloading the publishing profile from the portal, right-click the project in VS and select “publish”, the service will be live. And if we fire up Fiddler again, we should be able to retrieve our two orders straight from Azure:</p>

<blockquote>
  <pre>GET http://blog20140413.azure-mobile.net/tables/order HTTP/1.1
User-Agent: Fiddler
Host: blog20140413.azure-mobile.net

=-=-=-=-=-=-=-=-=-
HTTP/1.1 500 Internal Server Error
Cache-Control: no-cache
Pragma: no-cache
Content-Length: 43
Content-Type: application/json; charset=utf-8
Expires: 0
Server: Microsoft-IIS/8.0
X-Powered-By: ASP.NET
Date: Mon, 14 Apr 2014 18:50:22 GMT

{
  &quot;message&quot;: &quot;An error has occurred.&quot;
}</pre>
</blockquote>

<p>Something is wrong. By default the runtime doesn’t return any error details (for security purposes), so we can go to the portal, in the logs tab, to see what is going on, and the error is listed there:</p>

<blockquote>
  <pre>Exception=System.ArgumentException: No connection string named 'mongodb' could be found in the service configuration.
   at Microsoft.WindowsAzure.Mobile.Service.MongoDomainManager`1.GetMongoContext(String connectionStringName)
   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
   at Microsoft.WindowsAzure.Mobile.Service.MongoDomainManager`1..ctor(String connectionStringName, String databaseName, String collectionName, HttpRequestMessage request, ApiServices services)
   at MongoDbOnNetBackend.OrderController.Initialize(HttpControllerContext controllerContext)
   at System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)
   at System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<sendasync>d__0.MoveNext(), Id=6133b3eb-9851-41d1-9e17-38f196e41f6b, Category='App.Request'</sendasync></pre>
</blockquote>

<p>The problem is that the local web.config file which we were using when running the service locally is not used when the service is running in the cloud. We need to define the connection string some other way. Unfortunately due to a current bug we have there’s no easy way to define the connection string (it should be easily done in the portal, but this is not there yet), so we have to work around it for now.</p>

<p>To do that, first go to the “configure” tab of the mobile service in the portal, and add a new <em>app setting</em> whose value is the connection string which we had defined in the web.config file before:</p>

<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/95/96/metablogapi/8640.004AppSettingWithConnString_30FFFBA4.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-95-96-metablogapi/8640.004AppSettingWithConnString_5F00_30FFFBA4.png"><img title="004-AppSettingWithConnString" style="border-width: 0px; display: inline;" border="0" alt="004-AppSettingWithConnString" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/95/96/metablogapi/8750.004AppSettingWithConnString_thumb_5357911D.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-95-96-metablogapi/8750.004AppSettingWithConnString_5F00_thumb_5F00_5357911D.png" width="684" height="259" /></a> </p>

<p>And when initializing the table controller, we change the connection strings in the service settings based on that value which we can read from the app settings.</p>

<div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:6b2589de-3447-4c37-b2a1-791ade89b4f3" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;">
<div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt">
<div style="background: #fff; overflow: auto">
<ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;">
<li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">static</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">bool</span><span style="background:#ffffff;color:#000000"> connectionStringInitialized = </span><span style="background:#ffffff;color:#0000ff">false</span><span style="background:#ffffff;color:#000000">;</span></li>
<li style="background: #f3f3f3">&nbsp;</li>
<li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">private</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">void</span><span style="background:#ffffff;color:#000000"> InitializeConnectionString(</span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> connStringName, </span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> appSettingName)</span></li>
<li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">{</span></li>
<li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">if</span><span style="background:#ffffff;color:#000000"> (!connectionStringInitialized)</span></li>
<li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">{</span></li>
<li>        <span style="background:#ffffff;color:#000000">connectionStringInitialized = </span><span style="background:#ffffff;color:#0000ff">true</span><span style="background:#ffffff;color:#000000">;</span></li>
<li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">if</span><span style="background:#ffffff;color:#000000"> (!</span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">.Services.Settings.Connections.ContainsKey(connStringName))</span></li>
<li>        <span style="background:#ffffff;color:#000000">{</span></li>
<li style="background: #f3f3f3">            <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> connFromAppSetting = </span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">.Services.Settings[appSettingName];</span></li>
<li>            <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> connSetting = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">ConnectionSettings</span><span style="background:#ffffff;color:#000000">(connStringName, connFromAppSetting);</span></li>
<li style="background: #f3f3f3">            <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">.Services.Settings.Connections.Add(connStringName, connSetting);</span></li>
<li>        <span style="background:#ffffff;color:#000000">}</span></li>
<li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">}</span></li>
<li><span style="background:#ffffff;color:#000000">}</span></li>
<li style="background: #f3f3f3">&nbsp;</li>
<li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">protected</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">override</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">void</span><span style="background:#ffffff;color:#000000"> Initialize(</span><span style="background:#ffffff;color:#2b91af">HttpControllerContext</span><span style="background:#ffffff;color:#000000"> controllerContext)</span></li>
<li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">{</span></li>
<li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> connStringName = </span><span style="background:#ffffff;color:#a31515">&quot;mongodb&quot;</span><span style="background:#ffffff;color:#000000">;</span></li>
<li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> dbName = </span><span style="background:#ffffff;color:#a31515">&quot;MyMongoLab&quot;</span><span style="background:#ffffff;color:#000000">;</span></li>
<li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> collectionName = </span><span style="background:#ffffff;color:#a31515">&quot;orders&quot;</span><span style="background:#ffffff;color:#000000">;</span></li>
<li style="background: #f3f3f3">&nbsp;</li>
<li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Workaround for lack of connection strings in the portal</span></li>
<li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">InitializeConnectionString(connStringName, </span><span style="background:#ffffff;color:#a31515">&quot;mongoConnectionString&quot;</span><span style="background:#ffffff;color:#000000">);</span></li>
<li>&nbsp;</li>
<li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">base</span><span style="background:#ffffff;color:#000000">.Initialize(controllerContext);</span></li>
<li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">.DomainManager = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">MongoDomainManager</span><span style="background:#ffffff;color:#000000">&lt;</span><span style="background:#ffffff;color:#2b91af">Order</span><span style="background:#ffffff;color:#000000">&gt;(connStringName, dbName, collectionName, </span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">.Request, </span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">.Services);</span></li>
<li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">}</span></li>
</ol>
</div>
</div>
</div>

<p>And now when we publish it again we should be able to consume the table from Azure.</p>

<blockquote>
  <pre>GET http://blog20140413.azure-mobile.net/tables/order HTTP/1.1
User-Agent: Fiddler
Host: blog20140413.azure-mobile.net
x-zumo-application: cOFQkbaAmffuVRBJRpYDKHbNHbtDYG97

=-=-=-=-=-=-=-=-=-
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Length: 663
Content-Type: application/json; charset=utf-8
Expires: 0
Server: Microsoft-IIS/8.0
X-Powered-By: ASP.NET
Date: Mon, 14 Apr 2014 19:21:11 GMT

[
  {
    &quot;id&quot;: &quot;534c0469f76e1e10c4703c2b&quot;,
    &quot;client&quot;: &quot;John Doe&quot;,
    &quot;orderDate&quot;: &quot;2014-04-13T00:00:00Z&quot;,
    &quot;items&quot;: [
      {
        &quot;name&quot;: &quot;bread&quot;,
        &quot;quantity&quot;: 1.0,
        &quot;price&quot;: 1.99
      },
      {
        &quot;name&quot;: &quot;milk&quot;,
        &quot;quantity&quot;: 2.0,
        &quot;price&quot;: 2.99
      }
    ]
  },
  {
    &quot;id&quot;: &quot;534c0471f76e1e10c4703c2c&quot;,
    &quot;client&quot;: &quot;Jane Roe&quot;,
    &quot;orderDate&quot;: &quot;2014-02-22T00:00:00Z&quot;,
    &quot;items&quot;: [
      {
        &quot;name&quot;: &quot;nails&quot;,
        &quot;quantity&quot;: 100.0,
        &quot;price&quot;: 3.5
      },
      {
        &quot;name&quot;: &quot;hammer&quot;,
        &quot;quantity&quot;: 1.0,
        &quot;price&quot;: 12.34
      }
    ]
  }
]</pre>
</blockquote>

<p>Just a final note on this request – when the service is running locally, there’s no authentication by default so our request didn’t need to send any keys. To send the request to the server running on Azure, we need to specify the application key (the default authentication level) in the “x-zumo-application” header.</p>

<h3>Wrapping up</h3>

<p>The .NET backend for Azure Mobile Services offers a selection of storage providers for the “table” abstraction. Since most examples out there deal with the Entity Framework (SQL Server) based option, hopefully this post will give you some information on how to use our MongoDB provider for storing data. And as usual, we welcome comments and suggestions in this blog, in our <a href="http://social.msdn.microsoft.com/Forums/windowsazure/en-US/home?forum=azuremobile">MSDN forums</a> or via twitter <a href="https://twitter.com/AzureMobile">@AzureMobile</a>.</p>]]></content:encoded>
    </item>
    <item>
      <title>Creating an Azure Mobile Services .NET backend from scratch</title>
      <link>https://docs.microsoft.com/archive/blogs/carlosfigueira/creating-an-azure-mobile-services-net-backend-from-scratch</link>
      <pubDate>Thu, 10 Apr 2014 15:12:15 GMT</pubDate>
      <dc:creator><![CDATA[CarlosFigueira]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/carlosfigueira/2014/04/10/creating-an-azure-mobile-services-net-backend-from-scratch/</guid>
      <description><![CDATA[[This post originally appeared in...]]></description>
      <content:encoded><![CDATA[<p><em>[This post originally appeared in <a href="http://blogs.msdn.com/b/azuremobile/archive/2014/04/10/creating-an-azure-mobile-services-net-backend-from-scratch.aspx">http://blogs.msdn.com/b/azuremobile/archive/2014/04/10/creating-an-azure-mobile-services-net-backend-from-scratch.aspx</a>. </em><em>I’ll be writing Azure Mobile Service related posts in the <a href="http://blogs.msdn.com/b/azuremobile">Azure Mobile blog</a> primarily, and cross-posting them here for people who have feeds linked to this blog only]</em></p>  <p>When learning a new feature I often like to understand the minimum pieces necessary to get it running. In the case of the .NET backend of azure mobile services, that would mean the smallest number steps required to go from an empty project to a running mobile service – no additional tooling required. Currently the item and project templates required for the mobile services backend require the VS 2013 Update 2 Release Candidate, and many people (myself included) are wary of installing non-RTM versions of VS updates, so here’s a guide on how to create a .NET backend project without those.</p>  <h3>Set up</h3>  <p>The minimum project which we can create for a service backend is an empty ASP.NET application (on VS 2013, select the New Project –&gt; Web –&gt; ASP.NET Web Application, then select Empty). At that point we’ll won’t have anything at all (except for an empty web.config file).</p>  <p>Now it’s time to add the reference to the .NET backend binaries. Right-click the project, select “Manage NuGet Packages…”, and search for “MobileServices”. There will be (as of today) 5 packages related to the backend, with three of them (<a href="http://www.nuget.org/packages/WindowsAzure.MobileServices.Backend.Entity/">Entity Framework Extension</a>, <a href="http://www.nuget.org/packages/WindowsAzure.MobileServices.Backend.Storage/">Azure Storage Extension</a>, <a href="http://www.nuget.org/packages/WindowsAzure.MobileServices.Backend.Mongo/">Mongo Extension</a>) defining extensions for specific storage providers. Let’s choose the entity framework one (Windows Azure Mobile Services .NET Backend Entity Framework Extension), and click “Install”. After being prompted to accept licenses, NuGet will install the necessary packages (there is currently a bug that a “conflict file” dialog is shown; you can safely ignore that dialog). And now we still have an empty project, with the difference that the web.config has a few more entries which we can ignore.</p>  <h3>Defining the model</h3>  <p>Now let’s add a class to represent the model (entity) we’ll want to expose. For simplicity sake, I’ll use the old TodoItem class. To expose a class as a table in the .NET backend, it needs to implement the <code>ITableData</code> interface, but the entity framework extension NuGet package defines the <code>EntityData</code> class which we can use as a base type.</p>  <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:d27ba1de-f641-42f7-914d-331863784bca" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #fff; overflow: auto"> <ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">class</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">TodoItem</span><span style="background:#ffffff;color:#000000"> : </span><span style="background:#ffffff;color:#2b91af">EntityData</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">{</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> Text { </span><span style="background:#ffffff;color:#0000ff">get</span><span style="background:#ffffff;color:#000000">; </span><span style="background:#ffffff;color:#0000ff">set</span><span style="background:#ffffff;color:#000000">; }</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">bool</span><span style="background:#ffffff;color:#000000"> Complete { </span><span style="background:#ffffff;color:#0000ff">get</span><span style="background:#ffffff;color:#000000">; </span><span style="background:#ffffff;color:#0000ff">set</span><span style="background:#ffffff;color:#000000">; }</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">}</span></li> </ol> </div> </div> </div>  <p>Now we need a context to hook up Entity Framework with our model types (or single type in this case). When you create a new mobile service, a new schema is defined in the associated database, and the service is granted access to that schema. In our implementation of the context we need to tell it that we use that schema (you can also use databases on different schemas, or even a completely different database, and that is a topic for another post). Normally we’d override the <code>OnModelCreating</code> method on the DbContext class:</p>  <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:4c24f38b-cede-4bc1-8018-d5e693597e2d" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #fff; overflow: auto"> <ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">protected</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">override</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">void</span><span style="background:#ffffff;color:#000000"> OnModelCreating(</span><span style="background:#ffffff;color:#2b91af">DbModelBuilder</span><span style="background:#ffffff;color:#000000"> modelBuilder)</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">{</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">if</span><span style="background:#ffffff;color:#000000"> (modelBuilder == </span><span style="background:#ffffff;color:#0000ff">null</span><span style="background:#ffffff;color:#000000">)</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">{</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">throw</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">ArgumentNullException</span><span style="background:#ffffff;color:#000000">(</span><span style="background:#ffffff;color:#a31515">&quot;modelBuilder&quot;</span><span style="background:#ffffff;color:#000000">);</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">}</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">if</span><span style="background:#ffffff;color:#000000"> (!</span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000">.IsNullOrEmpty(</span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">.Schema))</span></li> <li>    <span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000">modelBuilder.HasDefaultSchema(</span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">.Schema);</span></li> <li>    <span style="background:#ffffff;color:#000000">}</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">}</span></li> </ol> </div> </div> </div>  <p>But since this would be done many times, we provide one class derived from DbContext – <code>EntityContext</code> – which does that automatically, so we can implement our context fairly concisely:</p>  <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:e21c178c-5f26-4b0d-95ce-eb73cf05d0f0" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #fff; overflow: auto"> <ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">class</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">MyContext</span><span style="background:#ffffff;color:#000000"> : </span><span style="background:#ffffff;color:#2b91af">EntityContext</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">{</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> MyContext()</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000">: </span><span style="background:#ffffff;color:#0000ff">base</span><span style="background:#ffffff;color:#000000">()</span></li> <li>    <span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">}</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> MyContext(</span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> schema)</span></li> <li>        <span style="background:#ffffff;color:#000000">: </span><span style="background:#ffffff;color:#0000ff">base</span><span style="background:#ffffff;color:#000000">(schema)</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">{</span></li> <li>    <span style="background:#ffffff;color:#000000">}</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">DbSet</span><span style="background:#ffffff;color:#000000">&lt;</span><span style="background:#ffffff;color:#2b91af">TodoItem</span><span style="background:#ffffff;color:#000000">&gt; TodoItems { </span><span style="background:#ffffff;color:#0000ff">get</span><span style="background:#ffffff;color:#000000">; </span><span style="background:#ffffff;color:#0000ff">set</span><span style="background:#ffffff;color:#000000">; }</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">}</span></li> </ol> </div> </div> </div>  <p>The <code>EntityContext</code> class also “teaches” EF how to use the <code>TableColumnAttribute</code> attribute, which you can use to customize the type of the columns created in your tables. And now that the context is created, we can define the table controller. This code is pretty much boilerplate for exposing entities as tables, and if you have the latest tooling (currently with the VS 2013 Update 2 RC) you can do that by using the item template.</p>  <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:1938d5cf-0d95-4fd4-99b6-18fad4cb5245" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #fff; overflow: auto"> <ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">class</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">TodoItemController</span><span style="background:#ffffff;color:#000000"> : </span><span style="background:#ffffff;color:#2b91af">TableController</span><span style="background:#ffffff;color:#000000">&lt;</span><span style="background:#ffffff;color:#2b91af">TodoItem</span><span style="background:#ffffff;color:#000000">&gt;</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">{</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">protected</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">override</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">void</span><span style="background:#ffffff;color:#000000"> Initialize(</span><span style="background:#ffffff;color:#2b91af">HttpControllerContext</span><span style="background:#ffffff;color:#000000"> controllerContext)</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">{</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">base</span><span style="background:#ffffff;color:#000000">.Initialize(controllerContext);</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> context = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">MyContext</span><span style="background:#ffffff;color:#000000">(</span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">.Services.Settings.Schema);</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">.DomainManager = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">EntityDomainManager</span><span style="background:#ffffff;color:#000000">&lt;</span><span style="background:#ffffff;color:#2b91af">TodoItem</span><span style="background:#ffffff;color:#000000">&gt;(context, </span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">.Request, </span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">.Services);</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">}</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">IQueryable</span><span style="background:#ffffff;color:#000000">&lt;</span><span style="background:#ffffff;color:#2b91af">TodoItem</span><span style="background:#ffffff;color:#000000">&gt; GetAll()</span></li> <li>    <span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">return</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">base</span><span style="background:#ffffff;color:#000000">.Query();</span></li> <li>    <span style="background:#ffffff;color:#000000">}</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">SingleResult</span><span style="background:#ffffff;color:#000000">&lt;</span><span style="background:#ffffff;color:#2b91af">TodoItem</span><span style="background:#ffffff;color:#000000">&gt; GetOne(</span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> id)</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">{</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">return</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">base</span><span style="background:#ffffff;color:#000000">.Lookup(id);</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">}</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">[</span><span style="background:#ffffff;color:#2b91af">HttpPost</span><span style="background:#ffffff;color:#000000">]</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">Task</span><span style="background:#ffffff;color:#000000">&lt;</span><span style="background:#ffffff;color:#2b91af">TodoItem</span><span style="background:#ffffff;color:#000000">&gt; InsertItem(</span><span style="background:#ffffff;color:#2b91af">TodoItem</span><span style="background:#ffffff;color:#000000"> item)</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">{</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">return</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">base</span><span style="background:#ffffff;color:#000000">.InsertAsync(item);</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">}</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">[</span><span style="background:#ffffff;color:#2b91af">HttpPatch</span><span style="background:#ffffff;color:#000000">]</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">Task</span><span style="background:#ffffff;color:#000000">&lt;</span><span style="background:#ffffff;color:#2b91af">TodoItem</span><span style="background:#ffffff;color:#000000">&gt; UpdateItem(</span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> id, </span><span style="background:#ffffff;color:#2b91af">Delta</span><span style="background:#ffffff;color:#000000">&lt;</span><span style="background:#ffffff;color:#2b91af">TodoItem</span><span style="background:#ffffff;color:#000000">&gt; patch)</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">{</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">return</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">base</span><span style="background:#ffffff;color:#000000">.UpdateAsync(id, patch);</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">}</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">Task</span><span style="background:#ffffff;color:#000000"> DeleteItem(</span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> id)</span></li> <li>    <span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">return</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">base</span><span style="background:#ffffff;color:#000000">.DeleteAsync(id);</span></li> <li>    <span style="background:#ffffff;color:#000000">}</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">}</span></li> </ol> </div> </div> </div>  <p>That’s it, the service is ready to be built and deployed. If you publish it to the mobile service (after downloading the publishing profile from the portal), you should be able to send requests to the table.</p>  <h3>Configuring the service</h3>  <p>The mobile service is now running, but we haven’t configured anything on how we want it to run – so the mobile service used a default bootstrapper, which initializes the service configuration with default options. If you want to change any configuration settings, define additional routes, access other extensibility points, define mapping between entity objects and DTOs, among other initialization tasks, you need to define a method to be called on startup. My colleague Henrik described the configuration in details on <a href="http://blogs.msdn.com/b/azuremobile/archive/2014/03/28/making-it-yours-configuring-mobile-services-net-backend.aspx">this blog post</a> so I won’t cover it here, and let’s just define a WebApiConfig class to change something in our project, which calls the <code>Initialize</code> method on the <code>ServiceConfig</code> class, and changes a setting in the JSON.NET serializer.</p>  <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:0cbfb40a-ae46-4708-8c70-a3441a7d30f7" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #fff; overflow: auto"> <ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">static</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">class</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">WebApiConfig</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">{</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">static</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">void</span><span style="background:#ffffff;color:#000000"> Register()</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">{</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> config = </span><span style="background:#ffffff;color:#2b91af">ServiceConfig</span><span style="background:#ffffff;color:#000000">.Initialize(</span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">ConfigBuilder</span><span style="background:#ffffff;color:#000000">());</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000">config.Formatters.JsonFormatter.SerializerSettings.Formatting = </span><span style="background:#ffffff;color:#2b91af">Formatting</span><span style="background:#ffffff;color:#000000">.Indented;</span></li> <li>    <span style="background:#ffffff;color:#000000">}</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">}</span></li> </ol> </div> </div> </div>  <p>If you now publish the project to the server again and send a request to the server, you’ll see that the JSON responses are now indented.</p>  <h3>Running locally</h3>  <p>One of the great features of the .NET backend for Azure Mobile Services is the ability to test the service locally prior to deploying. But at this point, while your service can be run in the cloud, if you try to run it locally it won’t do anything (it will show an error page). There are two things which we still need to do: hook up the .NET backend to the ASP.NET pipeline running in IIS Express, and call the bootstrapper code needs to be called.</p>  <p>For the first part can be done by installing another NuGet package, <a href="https://www.nuget.org/packages/Microsoft.Owin.Host.SystemWeb">Microsoft.Owin.Host.SystemWeb</a>, to the project. The .NET backend is implemented using the OWIN framework, and that NuGet adds a bridge between the OWIN adapter and System.Web, which is used in IIS. No code is needed in this step.</p>  <p>For the second part, we need to tell the application to invoke the WebApiConfig.Register method. To do that, add a new Global Application Class (global.asax). You can remove all methods except <code>Application_Start</code> from the generated class. In the app start, call that method, as shown below.</p>  <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:af6c2487-bd56-4592-9fac-42612baaef3c" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #fff; overflow: auto"> <ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">class</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">Global</span><span style="background:#ffffff;color:#000000"> : System.Web.</span><span style="background:#ffffff;color:#2b91af">HttpApplication</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">{</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">protected</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">void</span><span style="background:#ffffff;color:#000000"> Application_Start(</span><span style="background:#ffffff;color:#0000ff">object</span><span style="background:#ffffff;color:#000000"> sender, </span><span style="background:#ffffff;color:#2b91af">EventArgs</span><span style="background:#ffffff;color:#000000"> e)</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">{</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">WebApiConfig</span><span style="background:#ffffff;color:#000000">.Register();</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">}</span></li> <li><span style="background:#ffffff;color:#000000">}</span></li> </ol> </div> </div> </div>  <p>If you now press F5, the project will run (i.e., the “This mobile service is up and running” page will appear on your browser). But when you try to invoke any operation in the table controller, you’ll get an internal server error. Looking at the response body it will show the following error:</p>  <blockquote>   <pre>System.ArgumentNullException: Value cannot be null. Parameter name: schema
   at Microsoft.WindowsAzure.Mobile.Service.EntityContext..ctor(String schema)
   at WebApplication9.MyContext..ctor(String schema) in c:\…\WebApplication9\WebApplication9\MyContext.cs:line 17
   at WebApplication9.TodoItemController.Initialize(HttpControllerContext controllerContext) in c:\…\WebApplication9\WebApplication9\TodoItemController.cs:line 18
   at System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)
   at System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__0.MoveNext()&quot;  </pre>
</blockquote>

<p>The parameter which we passed to the context constructor (<code>this.Services.Settings.Schema</code>) is null, which is causing this error. What is missing are configuration settings which the service adds when the backend is running on the cloud, but for local running they need to be defined in web.config. The schema can be defined with the MS_TableSchema app setting, but if that value is not defined it will default to the mobile service name (defined by the MS_MobileServiceName app setting). Another thing which we need to define is the connection string for the database used by the Entity Framework context. The <code>EntityContext</code> class which we used to define our DB context uses the connection setting named MS_TableConnectionString by default, so we need to define it as well.</p>

<div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:80416e90-f185-4671-b918-2b11a5c4b403" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;">
<div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt">
<div style="background: #fff; overflow: auto">
<ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;">
<li><span style="background:#ffffff;color:#0000ff">&lt;</span><span style="background:#ffffff;color:#a31515">appSettings</span><span style="background:#ffffff;color:#0000ff">&gt;</span></li>
<li style="background: #f3f3f3">  <span style="background:#ffffff;color:#0000ff">&lt;</span><span style="background:#ffffff;color:#a31515">add</span><span style="background:#ffffff;color:#0000ff"> </span><span style="background:#ffffff;color:#ff0000">key</span><span style="background:#ffffff;color:#0000ff">=</span><span style="background:#ffffff;color:#000000">&quot;</span><span style="background:#ffffff;color:#0000ff">MS_MobileServiceName</span><span style="background:#ffffff;color:#000000">&quot;</span><span style="background:#ffffff;color:#0000ff"> </span><span style="background:#ffffff;color:#ff0000">value</span><span style="background:#ffffff;color:#0000ff">=</span><span style="background:#ffffff;color:#000000">&quot;</span><span style="background:#ffffff;color:#0000ff">myMobileServiceName</span><span style="background:#ffffff;color:#000000">&quot;</span><span style="background:#ffffff;color:#0000ff"> /&gt;</span></li>
<li><span style="background:#ffffff;color:#0000ff">&lt;/</span><span style="background:#ffffff;color:#a31515">appSettings</span><span style="background:#ffffff;color:#0000ff">&gt;</span></li>
<li style="background: #f3f3f3"><span style="background:#ffffff;color:#0000ff">&lt;</span><span style="background:#ffffff;color:#a31515">connectionStrings</span><span style="background:#ffffff;color:#0000ff">&gt;</span></li>
<li>  <span style="background:#ffffff;color:#0000ff">&lt;</span><span style="background:#ffffff;color:#a31515">add</span><span style="background:#ffffff;color:#0000ff"> </span><span style="background:#ffffff;color:#ff0000">name</span><span style="background:#ffffff;color:#0000ff">=</span><span style="background:#ffffff;color:#000000">&quot;</span><span style="background:#ffffff;color:#0000ff">MS_TableConnectionString</span><span style="background:#ffffff;color:#000000">&quot;</span></li>
<li style="background: #f3f3f3">       <span style="background:#ffffff;color:#0000ff"></span><span style="background:#ffffff;color:#ff0000">connectionString</span><span style="background:#ffffff;color:#0000ff">=</span><span style="background:#ffffff;color:#000000">&quot;</span><span style="background:#ffffff;color:#0000ff">Data Source=(localdb)&#92;v11.0;Initial Catalog=mylocaldatabasename;Integrated Security=True;MultipleActiveResultSets=True</span><span style="background:#ffffff;color:#000000">&quot;</span></li>
<li>       <span style="background:#ffffff;color:#0000ff"></span><span style="background:#ffffff;color:#ff0000">providerName</span><span style="background:#ffffff;color:#0000ff">=</span><span style="background:#ffffff;color:#000000">&quot;</span><span style="background:#ffffff;color:#0000ff">System.Data.SqlClient</span><span style="background:#ffffff;color:#000000">&quot;</span><span style="background:#ffffff;color:#0000ff"> /&gt;</span></li>
<li style="background: #f3f3f3"><span style="background:#ffffff;color:#0000ff">&lt;/</span><span style="background:#ffffff;color:#a31515">connectionStrings</span><span style="background:#ffffff;color:#0000ff">&gt;</span></li>
</ol>
</div>
</div>
</div>

<p>There are many other values which you can add to the app settings – you can check them out in the ServiceSettingsKeys class.</p>

<h3>Wrapping up</h3>

<p>I hope this post will give you not only a recipe for starting from scratch to create a mobile service backend (but if it does, great) but also explain a little more about how the .NET backend is hosted in the Azure Mobile Service. If you have any comments or questions, feel free to leave as comments in this post, ask a new question in <a href="http://social.msdn.microsoft.com/Forums/windowsazure/en-US/home?forum=azuremobile">our MSDN forums</a> or contact us via twitter <a href="https://twitter.com/AzureMobile">@AzureMobile</a>.</p>]]></content:encoded>
    </item>
    <item>
      <title>Deep dive on the offline support in the Azure Mobile Service managed client SDK</title>
      <link>https://docs.microsoft.com/archive/blogs/carlosfigueira/deep-dive-on-the-offline-support-in-the-azure-mobile-service-managed-client-sdk</link>
      <pubDate>Mon, 07 Apr 2014 12:41:44 GMT</pubDate>
      <dc:creator><![CDATA[CarlosFigueira]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/carlosfigueira/2014/04/07/deep-dive-on-the-offline-support-in-the-azure-mobile-service-managed-client-sdk/</guid>
      <description><![CDATA[[This post originally appeared in...]]></description>
      <content:encoded><![CDATA[<em>[This post originally appeared in <a title="http://blogs.msdn.com/b/azuremobile/archive/2014/04/07/deep-dive-on-the-offline-support-in-the-managed-client-sdk.aspx" href="http://blogs.msdn.com/b/azuremobile/archive/2014/04/07/deep-dive-on-the-offline-support-in-the-managed-client-sdk.aspx">http://blogs.msdn.com/b/azuremobile/archive/2014/04/07/deep-dive-on-the-offline-support-in-the-managed-client-sdk.aspx</a>. </em><em>I&rsquo;ll be writing Azure Mobile Service related posts in the <a href="http://blogs.msdn.com/b/azuremobile">Azure Mobile blog</a> primarily, and cross-posting them here for people who have feeds linked to this blog only]</em>

Last week we announced a new feature in the Azure Mobile Service SDK (managed code only for now): support for offline handling of data. While before all table operations required an active internet connection, with this new support the application can store table operations in a local data store, and later when connected push the changes to the mobile service (and also pull changes from the service into the local table). The local data store is defined by an interface, so you can use whatever implementation you want, but we also released a new NuGet package with a SQLite-based implementation of the store to help you get started quickly.

<h3>New table types: IMobileServiceSyncTable and IMobileServiceSyncTable&lt;T&gt;</h3>

One thing which we decided to do when implementing the offline support is that we wanted the developers to be aware of what kind of data would be offline and which data would be online. We thought about implementing the support in a transparent way and data would be synchronized to the server whenever a connection could be established, but almost always the &ldquo;magic&rdquo; that we would implement would be wrong. Instead, we released an alpha version of the SDK with offline capabilities (meaning that when managing the NuGet packages you&rsquo;ll need to select the &ldquo;Include prerelease&rdquo; option in the combo box on top of the package names), and based on the feedback we get from all of you we&rsquo;ll decide the direction to go next (which can be implementing a full &ldquo;auto-sync&rdquo; framework).

In practice, that means that to use the offline feature, you&rsquo;ll need to use a different kind of table. There are two new methods in the <a href="http://msdn.microsoft.com/library/azure/microsoft.windowsazure.mobileservices.mobileserviceclient.aspx">MobileServiceClient class</a>: <code>GetSyncTable(string tableName)</code> and <code>GetSyncTable&lt;T&gt;()</code>, which return instances of the <code>IMobileServiceSyncTable</code> and <code>IMobileServiceSyncTable&lt;T&gt;</code> interfaces, respectively. They&rsquo;re in most ways very similar to the <a href="http://msdn.microsoft.com/en-US/library/azure/microsoft.windowsazure.mobileservices.imobileservicetable.aspx">IMobileServiceTable</a> and <a href="http://msdn.microsoft.com/en-US/library/azure/jj554297.aspx">IMobileServiceTable&lt;T&gt;</a> interfaces, exposing similar methods. The biggest difference is that for the local (sync) tables, there are no overloads for the CRUD operations with additional query string parameters (there&rsquo;s no HTTP request going on the operation on those tables). Other differences include the fact that sync tables only work with entities with string ids (those with integer ids are not supported locally) and the shape of the response for insert and update operations (on regular tables, the responses can be any JSON value, including arrays and primitives; for sync tables they need to be objects).

One more thing which I think is important &ndash; a few people have asked me why the interface was named <em>sync</em> table &ndash; why not name it <em>local </em>table, which is : the interface name tells us something about its behavior. We&rsquo;re not talking simply about a <em>local</em> table. It&rsquo;s an object which can synchronize the state of the <em>remote</em> table (on Azure) with the table in the local store. We&rsquo;ll get to more details on the synchronization later.

Let&rsquo;s get coding. To start, let&rsquo;s try to insert an item into a sync table to see what happens&hellip;

<div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:54b4917a-44d4-470b-a12e-a4fef3c56804" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #fff; overflow: auto"> <ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> client = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">MobileServiceClient</span><span style="background:#ffffff;color:#000000">(ApplicationUri, ApplicationKey);</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> table = client.GetSyncTable&lt;</span><span style="background:#ffffff;color:#2b91af">TodoItem</span><span style="background:#ffffff;color:#000000">&gt;();</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">AddToDebug(</span><span style="background:#ffffff;color:#a31515">"Table: {0}"</span><span style="background:#ffffff;color:#000000">, table.TableName);</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> item = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">TodoItem</span><span style="background:#ffffff;color:#000000"> { Text = </span><span style="background:#ffffff;color:#a31515">"Buy bread"</span><span style="background:#ffffff;color:#000000">, Complete = </span><span style="background:#ffffff;color:#0000ff">false</span><span style="background:#ffffff;color:#000000"> };</span></li> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">await</span><span style="background:#ffffff;color:#000000"> table.InsertAsync(item);</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">AddToDebug(</span><span style="background:#ffffff;color:#a31515">"Inserted into local store: {0}"</span><span style="background:#ffffff;color:#000000">, item.Id);</span></li> </ol> </div> </div> </div>

When we run that, it doesn&rsquo;t work. Instead, we get the following exception:

<blockquote>   <code>System.InvalidOperationException: SyncContext is not yet initialized.</code></p> </blockquote>

<p>The problem is that the SDK has no idea about where to store the local data. Before using any of the sync operations, we first need to initialize the <em>synchronization context</em> of the client so that those operations can start working.

<h3>The synchronization context</h3>

In addition to the two new methods to get sync table instances from the client, there&rsquo;s a new property, <code>SyncContext</code>, which needs to be initialized with an instance of the actual local store where the data will be saved. Before you can use any of the local operations, the sync context in the client needs to be initialized with an <code>IMobileServiceLocalStore</code> object. That means that you can define whatever mechanism to store the local data, but the large majority of developers doesn&rsquo;t need to go into that level of details, so we&rsquo;ve also released an implementation of that interface based on a SQLite database. To access that store implementation (in the class <code>MobileServiceSQLiteStore</code>) you&rsquo;ll need a new NuGet package, <a href="http://www.nuget.org/packages/WindowsAzure.MobileServices.SQLiteStore">Azure Mobile Services SQLiteStore</a>. On to fixing the code above. When we instantiate the store, we need to define the tables which will be used to store data locally. There are two ways to define the tables that the SDK will use: you can either pass a <a href="http://james.newtonking.com/json/help/index.html?topic=html/T_Newtonsoft_Json_Linq_JObject.htm">JObject</a> instance containing the properties which will be stored to the <code>DefineTable</code> method, or even easier, you can also use the <code>DefineTable&lt;T&gt;</code> method where you just pass the type which will be used as the generic parameter, and the SDK will deal with it.

<div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:f9bde91e-1a30-45c5-a3d7-f034bd18b73b" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #fff; overflow: auto"> <ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> client = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">MobileServiceClient</span><span style="background:#ffffff;color:#000000">(ApplicationUri, ApplicationKey);</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> store = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">MobileServiceSQLiteStore</span><span style="background:#ffffff;color:#000000">(StoreFileName);</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">store.DefineTable&lt;</span><span style="background:#ffffff;color:#2b91af">TodoItem</span><span style="background:#ffffff;color:#000000">&gt;();</span></li> <li><span style="background:#ffffff;color:#000000">AddToDebug(</span><span style="background:#ffffff;color:#a31515">"Defined table in the store"</span><span style="background:#ffffff;color:#000000">);</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">await</span><span style="background:#ffffff;color:#000000"> client.SyncContext.InitializeAsync(store);</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">AddToDebug(</span><span style="background:#ffffff;color:#a31515">"Initialized the sync context"</span><span style="background:#ffffff;color:#000000">);</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> table = client.GetSyncTable&lt;</span><span style="background:#ffffff;color:#2b91af">TodoItem</span><span style="background:#ffffff;color:#000000">&gt;();</span></li> <li><span style="background:#ffffff;color:#000000">AddToDebug(</span><span style="background:#ffffff;color:#a31515">"Table: {0}"</span><span style="background:#ffffff;color:#000000">, table.TableName);</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> item = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">TodoItem</span><span style="background:#ffffff;color:#000000"> { Text = </span><span style="background:#ffffff;color:#a31515">"Buy bread"</span><span style="background:#ffffff;color:#000000">, Complete = </span><span style="background:#ffffff;color:#0000ff">false</span><span style="background:#ffffff;color:#000000"> };</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">await</span><span style="background:#ffffff;color:#000000"> table.InsertAsync(item);</span></li> <li><span style="background:#ffffff;color:#000000">AddToDebug(</span><span style="background:#ffffff;color:#a31515">"Inserted into local store: {0}"</span><span style="background:#ffffff;color:#000000">, item.Id);</span></li> </ol> </div> </div> </div>

Now, if you run the code above it will work &ndash; a <code>TodoItem</code> table will be created in the local store and an item will be added to it.

The synchronization context is mainly responsible for, well, synchronizing the data between the local database (represented by the local store) and the remote database (accessed via the Azure Mobile Service). This synchronization is done via an explicit push / pull mechanism which must be invoked by the developer &ndash; at this point we don&rsquo;t have any &ldquo;auto-sync&rdquo; framework which will handle those calls automatically, but this feature may be implemented in a future version of the SDK.

So back to the synchronization context. Once we start calling operations on the local tables, those operations start getting queued up by the sync context. Those operations become &ldquo;pending&rdquo; and are persisted locally, so that even if the application is closed and reopened, the list of pending operations is returned. You can check the number of operations which are pending by looking at the <code>PendingOperations</code> property in the synchronization context. As more operations are executed in the local tables, the queue will grow, until there is a synchronization event (which we&rsquo;ll talk more in the next section). Let&rsquo;s look at that property a little closer, by expanding the example above and performing additional operations in the local table.

<div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:9ebee620-83c2-4e93-bdd0-6f98fbd245e9" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #fff; overflow: auto"> <ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> client = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">MobileServiceClient</span><span style="background:#ffffff;color:#000000">(ApplicationUri, ApplicationKey);</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> store = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">MobileServiceSQLiteStore</span><span style="background:#ffffff;color:#000000">(StoreFileName);</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">store.DefineTable&lt;</span><span style="background:#ffffff;color:#2b91af">TodoItem</span><span style="background:#ffffff;color:#000000">&gt;();</span></li> <li><span style="background:#ffffff;color:#000000">AddToDebug(</span><span style="background:#ffffff;color:#a31515">"Defined table in the store"</span><span style="background:#ffffff;color:#000000">);</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">await</span><span style="background:#ffffff;color:#000000"> client.SyncContext.InitializeAsync(store);</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">AddToDebug(</span><span style="background:#ffffff;color:#a31515">"Initialized the sync context"</span><span style="background:#ffffff;color:#000000">);</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">AddToDebug(</span><span style="background:#ffffff;color:#a31515">"Pending operations in the sync context queue: {0}"</span><span style="background:#ffffff;color:#000000">, client.SyncContext.PendingOperations);</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> table = client.GetSyncTable&lt;</span><span style="background:#ffffff;color:#2b91af">TodoItem</span><span style="background:#ffffff;color:#000000">&gt;();</span></li> <li><span style="background:#ffffff;color:#000000">AddToDebug(</span><span style="background:#ffffff;color:#a31515">"Table: {0}"</span><span style="background:#ffffff;color:#000000">, table.TableName);</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> item = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">TodoItem</span><span style="background:#ffffff;color:#000000"> { Text = </span><span style="background:#ffffff;color:#a31515">"Buy bread"</span><span style="background:#ffffff;color:#000000">, Complete = </span><span style="background:#ffffff;color:#0000ff">false</span><span style="background:#ffffff;color:#000000"> };</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">await</span><span style="background:#ffffff;color:#000000"> table.InsertAsync(item);</span></li> <li><span style="background:#ffffff;color:#000000">AddToDebug(</span><span style="background:#ffffff;color:#a31515">"Inserted into local store: {0}"</span><span style="background:#ffffff;color:#000000">, item.Id);</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li><span style="background:#ffffff;color:#000000">AddToDebug(</span><span style="background:#ffffff;color:#a31515">"Pending operations in the sync context queue: {0}"</span><span style="background:#ffffff;color:#000000">, client.SyncContext.PendingOperations);</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li><span style="background:#ffffff;color:#000000">item = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">TodoItem</span><span style="background:#ffffff;color:#000000"> { Text = </span><span style="background:#ffffff;color:#a31515">"Buy milk"</span><span style="background:#ffffff;color:#000000">, Complete = </span><span style="background:#ffffff;color:#0000ff">false</span><span style="background:#ffffff;color:#000000"> };</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">await</span><span style="background:#ffffff;color:#000000"> table.InsertAsync(item);</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">AddToDebug(</span><span style="background:#ffffff;color:#a31515">"Pending operations in the sync context queue: {0}"</span><span style="background:#ffffff;color:#000000">, client.SyncContext.PendingOperations);</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> thingsToDo = </span><span style="background:#ffffff;color:#0000ff">await</span><span style="background:#ffffff;color:#000000"> table.Where(t =&gt; !t.Complete).Select(t =&gt; t.Text).ToListAsync();</span></li> <li><span style="background:#ffffff;color:#000000">AddToDebug(</span><span style="background:#ffffff;color:#a31515">"Things to do {0}"</span><span style="background:#ffffff;color:#000000">, </span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000">.Join(</span><span style="background:#ffffff;color:#a31515">", "</span><span style="background:#ffffff;color:#000000">, thingsToDo));</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li><span style="background:#ffffff;color:#000000">AddToDebug(</span><span style="background:#ffffff;color:#a31515">"Pending operations in the sync context queue: {0}"</span><span style="background:#ffffff;color:#000000">, client.SyncContext.PendingOperations);</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li><span style="background:#ffffff;color:#000000">item.Complete = </span><span style="background:#ffffff;color:#0000ff">true</span><span style="background:#ffffff;color:#000000">;</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">await</span><span style="background:#ffffff;color:#000000"> table.UpdateAsync(item);</span></li> <li><span style="background:#ffffff;color:#000000">AddToDebug(</span><span style="background:#ffffff;color:#a31515">"Updated item: {0}"</span><span style="background:#ffffff;color:#000000">, item.Id);</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li><span style="background:#ffffff;color:#000000">AddToDebug(</span><span style="background:#ffffff;color:#a31515">"Pending operations in the sync context queue: {0}"</span><span style="background:#ffffff;color:#000000">, client.SyncContext.PendingOperations);</span></li> </ol> </div> </div> </div>

As I mentioned before, the sync tables have basically the same API as &ldquo;regular&rdquo; (remote) tables, so queries, updates and inserts (as well as deletes, not shown above) look just like methods on regular tables. As we run the code below (assuming that the local store was empty) we&rsquo;ll get an output similar to the one shown below. It looks expected &ndash; when we insert the first item the pending operation count goes to one; when we insert another item the count is incremented once more; when we read from the local table the count is not incremented &ndash; read operations are not synchronized. But there&rsquo;s one interesting aspect which happens when we update one of the items which we had just inserted: the number of operations in the queue is not changed. What the current implementation of the synchronization context does is to &ldquo;merge&rdquo; pending operations <em>for the same item</em>, so that during synchronization only one operation (in this case, insert) is sent to the server (where the value of the item is the most recent one).

<blockquote>   <font size="2" face="Consolas">Defined table in the store        <br>Initialized the sync context         <br>Pending operations in the sync context queue: 0         <br>Table: TodoItem         <br>Inserted into local store: 9e61196d-55df-4869-8b30-4a4a6eb792f2         <br>Pending operations in the sync context queue: 1         <br>Inserted another item into the local store: c349b30d-d603-48db-8509-b2fd170f4499         <br>Pending operations in the sync context queue: 2         <br>Things to do Buy bread, Buy milk         <br>Pending operations in the sync context queue: 2         <br>Updated item: c349b30d-d603-48db-8509-b2fd170f4499         <br>Pending operations in the sync context queue: 2</font></p> </blockquote>

<p>I talked about synchronization operations without introducing them. Let&rsquo;s look at them now.

<h3>Push / pull / purge</h3>

There are three basic operations which can trigger synchronization. The simplest of all is the <code>PushAsync</code> method in the synchronization context. Once that method is called, the changes which were performed in the local table are sent over to the server. In the example below, there will be one more item in the server once the call to <code>PushAsync</code> is completed (or maybe more, if there were other insert operations pending in the synchronization queue).

<div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:6cc7482b-6864-4b87-b42f-19a219a7f1d4" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #fff; overflow: auto"> <ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> localTable = client.GetSyncTable&lt;</span><span style="background:#ffffff;color:#2b91af">TodoItem</span><span style="background:#ffffff;color:#000000">&gt;();</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> remoteTable = client.GetTable&lt;</span><span style="background:#ffffff;color:#2b91af">TodoItem</span><span style="background:#ffffff;color:#000000">&gt;();</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> remoteItems = </span><span style="background:#ffffff;color:#0000ff">await</span><span style="background:#ffffff;color:#000000"> remoteTable</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">.Select(i =&gt; i.Text)</span></li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">.ToListAsync();</span></li> <li><span style="background:#ffffff;color:#000000">AddToDebug(</span><span style="background:#ffffff;color:#a31515">"Items from the server: {0}"</span><span style="background:#ffffff;color:#000000">, </span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000">.Join(</span><span style="background:#ffffff;color:#a31515">", "</span><span style="background:#ffffff;color:#000000">, remoteItems));</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> item = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">TodoItem</span><span style="background:#ffffff;color:#000000"> { Text = </span><span style="background:#ffffff;color:#a31515">"Buy bread"</span><span style="background:#ffffff;color:#000000">, Complete = </span><span style="background:#ffffff;color:#0000ff">false</span><span style="background:#ffffff;color:#000000"> };</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">await</span><span style="background:#ffffff;color:#000000"> localTable.InsertAsync(item);</span></li> <li><span style="background:#ffffff;color:#000000">AddToDebug(</span><span style="background:#ffffff;color:#a31515">"Inserted into local store: {0}"</span><span style="background:#ffffff;color:#000000">, item.Id);</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">await</span><span style="background:#ffffff;color:#000000"> client.SyncContext.PushAsync();</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">AddToDebug(</span><span style="background:#ffffff;color:#a31515">"Pushed the local changes to the server"</span><span style="background:#ffffff;color:#000000">);</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">remoteItems = </span><span style="background:#ffffff;color:#0000ff">await</span><span style="background:#ffffff;color:#000000"> remoteTable</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">.Select(i =&gt; i.Text)</span></li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">.ToListAsync();</span></li> <li><span style="background:#ffffff;color:#000000">AddToDebug(</span><span style="background:#ffffff;color:#a31515">"Items from the server: {0}"</span><span style="background:#ffffff;color:#000000">, </span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000">.Join(</span><span style="background:#ffffff;color:#a31515">", "</span><span style="background:#ffffff;color:#000000">, remoteItems));</span></li> </ol> </div> </div> </div>

Push is executed on the whole context, not on specific tables. It&rsquo;s implemented this way to support relationships between entities on the client side. For example, if you have an &ldquo;Order&rdquo; and an &ldquo;OrderItem&rdquo; table, you can insert an item in the first table, and having the id of that entity, insert the children items with the appropriate foreign key. And when the operations are sent to the server, they will be sent in order so that any FK relationships in the database will be satisfied.

The other operation which triggers a synchronization is a call to <code>PullAsync</code> on the local table. That call can either pull all items from the remote table, or just pull a subset of the items. Only pulling some items from the table is often advisable, as stuffing everything from the (potentially large) remote database table into the (restricted by the device memory) local table may have some bad performance implications. You can pass an OData-formatted query to select which items to pull from the server, or you can also use the (more friendly) Linq expressions to determine the query of items to be pulled.

<div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:79963ae9-713e-4ecc-b5b7-fc0e5e3e769d" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #fff; overflow: auto"> <ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> localTable = client.GetSyncTable&lt;</span><span style="background:#ffffff;color:#2b91af">TodoItem</span><span style="background:#ffffff;color:#000000">&gt;();</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> query = localTable.Where(t =&gt; !t.Complete);</span></li> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">await</span><span style="background:#ffffff;color:#000000"> localTable.PullAsync(query);</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> localItems = </span><span style="background:#ffffff;color:#0000ff">await</span><span style="background:#ffffff;color:#000000"> localTable</span></li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">.Select(i =&gt; i.Text)</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">.ToListAsync();</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">AddToDebug(</span><span style="background:#ffffff;color:#a31515">"Items from the server (in the local table): {0}"</span><span style="background:#ffffff;color:#000000">, </span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000">.Join(</span><span style="background:#ffffff;color:#a31515">", "</span><span style="background:#ffffff;color:#000000">, localItems));</span></li> </ol> </div> </div> </div>

One important thing to notice regarding pull operations &ndash; if there are items in the pending synchronization queue, those items are first pushed over to the server, then the pull operation takes place. That prevents a scenario where an update is done to a local item, but a pull operation would overwrite the changes locally and potentially leave the data in an inconsistent state. That&rsquo;s one the first synchronization rule: a pull triggers a push. In the example below, the insert operation for the &ldquo;Buy milk&rdquo; item will first be pushed to the server, then the items will be pulled into the local table.

<div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:152528e6-ee75-4d65-be65-88e80b37eb25" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #fff; overflow: auto"> <ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">await</span><span style="background:#ffffff;color:#000000"> client.SyncContext.InitializeAsync(store);</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">AddToDebug(</span><span style="background:#ffffff;color:#a31515">"Initialized the sync context"</span><span style="background:#ffffff;color:#000000">);</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> localTable = client.GetSyncTable&lt;</span><span style="background:#ffffff;color:#2b91af">TodoItem</span><span style="background:#ffffff;color:#000000">&gt;();</span></li> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> item = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">TodoItem</span><span style="background:#ffffff;color:#000000"> { Text = </span><span style="background:#ffffff;color:#a31515">"Buy milk"</span><span style="background:#ffffff;color:#000000">, Complete = </span><span style="background:#ffffff;color:#0000ff">false</span><span style="background:#ffffff;color:#000000"> };</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">await</span><span style="background:#ffffff;color:#000000"> localTable.InsertAsync(item);</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> query = localTable.Where(t =&gt; !t.Complete);</span></li> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">await</span><span style="background:#ffffff;color:#000000"> localTable.PullAsync(query);</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> localItems = </span><span style="background:#ffffff;color:#0000ff">await</span><span style="background:#ffffff;color:#000000"> localTable</span></li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">.Select(i =&gt; i.Text)</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">.ToListAsync();</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">AddToDebug(</span><span style="background:#ffffff;color:#a31515">"Items from the server (in the local table): {0}"</span><span style="background:#ffffff;color:#000000">, </span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000">.Join(</span><span style="background:#ffffff;color:#a31515">", "</span><span style="background:#ffffff;color:#000000">, localItems));</span></li> </ol> </div> </div> </div>

Another operation which triggers a synchronization event is a call to <code>PurgeAsync</code> on the local table. Often we want to clear the local cache to update the data which the application doesn&rsquo;t need anymore. For example, the canonical TODO app, we only display the items in the client which are not complete. In this case, there&rsquo;s no need to store locally any items which have already been complete. A call to purge such items can be done as shown below.

<div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:c8cf55a4-890b-4975-ad7f-ba7ddff7f1fa" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #fff; overflow: auto"> <ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> localTable = client.GetSyncTable&lt;</span><span style="background:#ffffff;color:#2b91af">TodoItem</span><span style="background:#ffffff;color:#000000">&gt;();</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">await</span><span style="background:#ffffff;color:#000000"> localTable.PurgeAsync(localTable.Where(t =&gt; t.Complete));</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> query = localTable.Where(t =&gt; !t.Complete);</span></li> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">await</span><span style="background:#ffffff;color:#000000"> localTable.PullAsync(query);</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> localItems = </span><span style="background:#ffffff;color:#0000ff">await</span><span style="background:#ffffff;color:#000000"> localTable</span></li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">.Select(i =&gt; i.Text)</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">.ToListAsync();</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">AddToDebug(</span><span style="background:#ffffff;color:#a31515">"Items from the server (in the local table): {0}"</span><span style="background:#ffffff;color:#000000">, </span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000">.Join(</span><span style="background:#ffffff;color:#a31515">", "</span><span style="background:#ffffff;color:#000000">, localItems));</span></li> </ol> </div> </div> </div>

Notice that, just like in the pull case, a call to purge will first send any pending operations to the server (the second synchronization rule: purge also triggers a push). This way, if we had marked an item as complete locally, we want to make sure that this information is in the server before we remove the item from the local store.

<h3>Handling conflict errors</h3>

Until now we&rsquo;ve looked at many synchronization scenarios where everything works fine. There are cases, however, where errors happen. If there are multiple sources changing a single entity (such as a row in the database), you may have conflicts when a second update is attempted (since the version of the item will have change &ndash; for more information see <a href="http://azure.microsoft.com/en-us/documentation/articles/mobile-services-windows-store-dotnet-handle-database-conflicts/">this document</a> on optimistic concurrency implementation on the server). In this case, a push operation would fail. Take the code below: the item is updated in the remote table, but when we try to push the update to the local item, since the version of the items will not match, the push operation will fail, and a <code>MobileServicePushFailedException</code> will be thrown. The exception has a list of all errors which happened for the individual elements from the synchronization queue.

<div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:5c583ed5-793a-4017-97d2-d6832243a0b0" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #fff; overflow: auto"> <ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> localTable = client.GetSyncTable&lt;</span><span style="background:#ffffff;color:#2b91af">TodoItem</span><span style="background:#ffffff;color:#000000">&gt;();</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> remoteTable = client.GetTable&lt;</span><span style="background:#ffffff;color:#2b91af">TodoItem</span><span style="background:#ffffff;color:#000000">&gt;();</span></li> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">await</span><span style="background:#ffffff;color:#000000"> localTable.PullAsync();</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> firstItem = (</span><span style="background:#ffffff;color:#0000ff">await</span><span style="background:#ffffff;color:#000000"> localTable.Take(1).ToEnumerableAsync()).FirstOrDefault();</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> firstItemCopy = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">TodoItem</span></li> <li><span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">Id = firstItem.Id,</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">Version = firstItem.Version,</span></li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">Text = firstItem.Text,</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">Complete = firstItem.Complete</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">};</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">firstItemCopy.Text = </span><span style="background:#ffffff;color:#a31515">"Modified"</span><span style="background:#ffffff;color:#000000">;</span></li> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">await</span><span style="background:#ffffff;color:#000000"> remoteTable.UpdateAsync(firstItemCopy);</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">AddToDebug(</span><span style="background:#ffffff;color:#a31515">"Updated the item on the server"</span><span style="background:#ffffff;color:#000000">);</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">firstItem.Text = </span><span style="background:#ffffff;color:#a31515">"Modified locally"</span><span style="background:#ffffff;color:#000000">;</span></li> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">await</span><span style="background:#ffffff;color:#000000"> localTable.UpdateAsync(firstItem);</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">AddToDebug(</span><span style="background:#ffffff;color:#a31515">"Updated the same item in the local table"</span><span style="background:#ffffff;color:#000000">);</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">AddToDebug(</span><span style="background:#ffffff;color:#a31515">"Number of pending operations: {0}"</span><span style="background:#ffffff;color:#000000">, client.SyncContext.PendingOperations);</span></li> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">await</span><span style="background:#ffffff;color:#000000"> client.SyncContext.PushAsync();</span></li> </ol> </div> </div> </div>

There are scenarios where you want to catch and deal with the synchronization conflicts in the client. You can control all the synchronization operations by implementing the <code>IMobileServiceSyncHandler</code> interface and passing it when initializing the context. For example, this is an implementation of a sync handler which traces all the operations which are happening.

<div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:aa3ee1e1-da64-4799-87ab-aa8efb424428" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #fff; overflow: auto"> <ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">class</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">MySyncHandler</span><span style="background:#ffffff;color:#000000"> : </span><span style="background:#ffffff;color:#2b91af">IMobileServiceSyncHandler</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">{</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">MainPage</span><span style="background:#ffffff;color:#000000"> page;</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> MySyncHandler(</span><span style="background:#ffffff;color:#2b91af">MainPage</span><span style="background:#ffffff;color:#000000"> page)</span></li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">{</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">.page = page;</span></li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">}</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">Task</span><span style="background:#ffffff;color:#000000">&lt;</span><span style="background:#ffffff;color:#2b91af">JObject</span><span style="background:#ffffff;color:#000000">&gt; ExecuteTableOperationAsync(</span><span style="background:#ffffff;color:#2b91af">IMobileServiceTableOperation</span><span style="background:#ffffff;color:#000000"> operation)</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">page.AddToDebug(</span><span style="background:#ffffff;color:#a31515">"Executing operation '{0}' for table '{1}'"</span><span style="background:#ffffff;color:#000000">, operation.Kind, operation.TableName);</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">return</span><span style="background:#ffffff;color:#000000"> operation.ExecuteAsync();</span></li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">}</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">Task</span><span style="background:#ffffff;color:#000000"> OnPushCompleteAsync(</span><span style="background:#ffffff;color:#2b91af">MobileServicePushCompletionResult</span><span style="background:#ffffff;color:#000000"> result)</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">page.AddToDebug(</span><span style="background:#ffffff;color:#a31515">"Push result: {0}"</span><span style="background:#ffffff;color:#000000">, result.Status);</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">foreach</span><span style="background:#ffffff;color:#000000"> (</span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> error </span><span style="background:#ffffff;color:#0000ff">in</span><span style="background:#ffffff;color:#000000"> result.Errors)</span></li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">{</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">page.AddToDebug(</span><span style="background:#ffffff;color:#a31515">"&nbsp;&nbsp;Push error: {0}"</span><span style="background:#ffffff;color:#000000">, error.Status);</span></li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">}</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">return</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">Task</span><span style="background:#ffffff;color:#000000">.FromResult(0);</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">}</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">}</span></li> </ol> </div> </div> </div>

And we can use this synchronization handler by passing it to the overload of <code>InitializeAsync</code> in the sync context, as shown below:

<div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:8beaaa2b-e66d-4857-a709-bee9d0ea0284" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #fff; overflow: auto"> <ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> store = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">MobileServiceSQLiteStore</span><span style="background:#ffffff;color:#000000">(StoreFileName);</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">store.DefineTable&lt;</span><span style="background:#ffffff;color:#2b91af">TodoItem</span><span style="background:#ffffff;color:#000000">&gt;();</span></li> <li><span style="background:#ffffff;color:#000000">AddToDebug(</span><span style="background:#ffffff;color:#a31515">"Defined table in the store"</span><span style="background:#ffffff;color:#000000">);</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> syncHandler = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">MySyncHandler</span><span style="background:#ffffff;color:#000000">(</span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">);</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">await</span><span style="background:#ffffff;color:#000000"> client.SyncContext.InitializeAsync(store, syncHandler);</span></li> <li><span style="background:#ffffff;color:#000000">AddToDebug(</span><span style="background:#ffffff;color:#a31515">"Initialized the sync context"</span><span style="background:#ffffff;color:#000000">);</span></li> </ol> </div> </div> </div>

This context implementation doesn&rsquo;t do much, but we can catch the exception which is thrown by the client when the server returns a Precondition Failed (HTTP status code 412) and retry the call again after updating the version on the client.

<div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:c8637352-a7e0-4ffc-be77-1f94702459f4" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #fff; overflow: auto"> <ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">class</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">MySyncHandler</span><span style="background:#ffffff;color:#000000"> : </span><span style="background:#ffffff;color:#2b91af">IMobileServiceSyncHandler</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">{</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">MainPage</span><span style="background:#ffffff;color:#000000"> page;</span></li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">IMobileServiceClient</span><span style="background:#ffffff;color:#000000"> client;</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> MySyncHandler(</span><span style="background:#ffffff;color:#2b91af">IMobileServiceClient</span><span style="background:#ffffff;color:#000000"> client, </span><span style="background:#ffffff;color:#2b91af">MainPage</span><span style="background:#ffffff;color:#000000"> page)</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">.client = client;</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">.page = page;</span></li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">}</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">async</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">Task</span><span style="background:#ffffff;color:#000000">&lt;</span><span style="background:#ffffff;color:#2b91af">JObject</span><span style="background:#ffffff;color:#000000">&gt; ExecuteTableOperationAsync(</span><span style="background:#ffffff;color:#2b91af">IMobileServiceTableOperation</span><span style="background:#ffffff;color:#000000"> operation)</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">JObject</span><span style="background:#ffffff;color:#000000"> result = </span><span style="background:#ffffff;color:#0000ff">null</span><span style="background:#ffffff;color:#000000">;</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">MobileServicePreconditionFailedException</span><span style="background:#ffffff;color:#000000"> conflictError = </span><span style="background:#ffffff;color:#0000ff">null</span><span style="background:#ffffff;color:#000000">;</span></li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">do</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">try</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">result = </span><span style="background:#ffffff;color:#0000ff">await</span><span style="background:#ffffff;color:#000000"> operation.ExecuteAsync();</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">}</span></li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">catch</span><span style="background:#ffffff;color:#000000"> (</span><span style="background:#ffffff;color:#2b91af">MobileServicePreconditionFailedException</span><span style="background:#ffffff;color:#000000"> e)</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">conflictError = e;</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">}</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">if</span><span style="background:#ffffff;color:#000000"> (conflictError != </span><span style="background:#ffffff;color:#0000ff">null</span><span style="background:#ffffff;color:#000000">)</span></li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">{</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// There was a conflict on the server. Let's "fix" it by</span></li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// forcing the client entity</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">JObject</span><span style="background:#ffffff;color:#000000"> serverItem = conflictError.Value;</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// In most cases, the server will return the server item in the request body</span></li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// when a Precondition Failed is returned, but it's not guaranteed for all</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// backend types.</span></li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">if</span><span style="background:#ffffff;color:#000000"> (serverItem == </span><span style="background:#ffffff;color:#0000ff">null</span><span style="background:#ffffff;color:#000000">)</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// If this is the case, let's retrieve it. First get a table instance</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> table = client.GetTable(operation.TableName);</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Force it to request the __version property</span></li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">table.SystemProperties = </span><span style="background:#ffffff;color:#2b91af">MobileServiceSystemProperties</span><span style="background:#ffffff;color:#000000">.Version;</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">serverItem = (</span><span style="background:#ffffff;color:#2b91af">JObject</span><span style="background:#ffffff;color:#000000">)(</span><span style="background:#ffffff;color:#0000ff">await</span><span style="background:#ffffff;color:#000000"> table.LookupAsync((</span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000">)operation.Item[</span><span style="background:#ffffff;color:#2b91af">MobileServiceSystemColumns</span><span style="background:#ffffff;color:#000000">.Id]));</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">}</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Now update the local item with the server version</span></li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">operation.Item[</span><span style="background:#ffffff;color:#2b91af">MobileServiceSystemColumns</span><span style="background:#ffffff;color:#000000">.Version] = serverItem[</span><span style="background:#ffffff;color:#2b91af">MobileServiceSystemColumns</span><span style="background:#ffffff;color:#000000">.Version];</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">}</span></li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">} </span><span style="background:#ffffff;color:#0000ff">while</span><span style="background:#ffffff;color:#000000"> (conflictError != </span><span style="background:#ffffff;color:#0000ff">null</span><span style="background:#ffffff;color:#000000">);</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">return</span><span style="background:#ffffff;color:#000000"> result;</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">}</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">Task</span><span style="background:#ffffff;color:#000000"> OnPushCompleteAsync(</span><span style="background:#ffffff;color:#2b91af">MobileServicePushCompletionResult</span><span style="background:#ffffff;color:#000000"> result)</span></li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">{</span></li> <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">return</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">Task</span><span style="background:#ffffff;color:#000000">.FromResult(0);</span></li> <li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#ffffff;color:#000000">}</span></li> <li><span style="background:#ffffff;color:#000000">}</span></li> </ol> </div> </div> </div>

And this is how we can resolve conflicts on the client. <a href="http://code.msdn.microsoft.com/Azure-Mobile-Handling-6e8538a0">This sample</a> shows another conflict handling policy (letting the user choose which version to keep), but the structure is similar to the one above. And a final note about resolving synchronization conflicts: to use the optimistic concurrency feature (which prevents two clients from overriding modifications in the same row), you&rsquo;ll need to define a version column in the class used in the client.

<h3>Advanced features</h3>

Some additional information about this release which I think is interesting. Unlike on remote tables, local tables can store arbitrary types, including complex ones (for example, a &ldquo;Person&rdquo; class can have an &ldquo;Address&rdquo; property), and when stored in the local table the complex property will be stored as a JSON-ified version of its value. You won&rsquo;t be able to query on those types (for example, list all people whose &ldquo;Address.City&rdquo; property is &ldquo;Springfield&rdquo;), but it can be stored and retrieved without any extra code.

When writing a sync handler (like the one used in the previous section to resolve conflicts) you can also abort the whole push operation if you find an error for which you don&rsquo;t want to continue. If this is the case, you can call the <code>AbortPush</code> method on the <code>IMobileServiceTableOperation</code> instance passed to the <code>ExecuteTableOperationAsync</code> method.

<p>One more thing: the implementation of the local store uses the SQLite database, which is a x86/arm only binary. The project cannot be configured to &ldquo;AnyCPU&rdquo;, it needs to be configured to a specific architecture.</p><h3>Wrapping up</h3><p>In this release we introduced offline capabilities in the .NET SDK for Mobile Services. We released it as an alpha NuGet package so you can try and give us feedback on what works, what doesn&rsquo;t and what we can improve. Please let us know in the comments, in <a href="http://social.msdn.microsoft.com/Forums/windowsazure/en-US/home?forum=azuremobile">our forum</a> or via twitter <a href="https://twitter.com/AzureMobile">@AzureMobile</a>.</p>]]></content:encoded>
    </item>
  </channel>
</rss>