# Friday, 07 November 2014

In my last article, I described how to use the Azure Mobile Services wizard to create a sample client application. In this article, we will look at the code created by this wizard.

I'll focus on the C#/XAML version of the sample app but all the principles apply for the HTML5/WinJS version as well.

Figure 1 shows the solution, which includes a Windows 8.1 project, a Windows Phone 8.1 project, and a project with files that are shared by the other two projects.

Zumo4-Figure 01 - Client App
Figure 1

I always compile this app before running it, because that ensures that all NuGet packages are updated.

Because this is a Universal app, it contains both a Windows 8.1 and a Windows Phone 8.1 project. The two projects do pretty much the same thing but each has a user interface appropriate to its own platform.

A screen shot of each running app is shown in Figure 2 (Windows 8.1) and Figure 3 (Windows Phone 8.1). As you can see, this app keeps track of a  user's To Do List. The list of "To Do Items" is stored in an Azure SQL Database, which is exposed via Azure Mobile Services.

Zumo4-Figure 02 - Running Win81 App
Figure 2

Zumo4-Figure 03 - Running Win81 App
Figure 3

Most of the interesting stuff happens in the Shared project.

TodoItem.cs

Let's look first at the Model. It is in the Shared project because both apps use the same model. You can find it in the TodoItem.cs file in the DataModel folder (Listing 1).

   1: public class TodoItem
   2: {
   3:     public string Id { get; set; }
   4:  
   5:     [JsonProperty(PropertyName = "text")]
   6:     public string Text { get; set; }
   7:  
   8:     [JsonProperty(PropertyName = "complete")]
   9:     public bool Complete { get; set; }
  10: }

Listing 1

The three properties (Id, Text, and Complete) will map to columns in the SQL Server table.  Text and Complete are decorated with the JsonProperty attribute, which is found in the Newtonsoft.Json library and tells .NET how to name these properties when an object is transformed into the JSON format. Strictly speaking, this is unnecessary, but JSON objects tend to follow the
JavaScript convention of Camel casing.

App.xaml.cs

The shared App.xaml.cs takes care of some basic processing when an app starts up, suspends, or has a problem.

As far as Azure Mobile Services is concerned, the important line is the MobileService field declaration (Listing 2)

   1: public static MobileServiceClient MobileService = new MobileServiceClient(
   2:     "https://giard.azure-mobile.net/",
   3:     "MqJSWTabZlOTRHeFXPRBADoQcVtqvE41"
   4: );
Listing 2

The second parameter of the constructor is the application key generated by your Mobile Service. Passing the Application Key to the constructor of our MobileServiceClient is necessary if we set permissions to only allow calls to the mobile service by clients that provide the Application Key. Whenever we call the REST service with this object, the Application Key will be passed in the header of HTTP calls to the mobile services endpoints.

This static class is available throughout the application and contains methods to communicate with your mobile service. Its main use is to create an IMobileServiceTable by calling the static object's GetTable() method, which is done in the MainPage.

MainPage.cs

Notice that all three projects contain the MainPage class, which derives from the Page object. In both the Windows project and in the Windows Phone project, this class is in the MainPage.xaml.cs file, while the class is in the MainPage.cs file in the shared project. Notice also that these are all "partial" classes and that each is in the same namespace. At compile time, both the Windows and Windows Phone projects will pull in the class from the Shared Project and use its code.

At the top of the MainPage class is the creation of two sets of our model (Listing 3).

   1: private MobileServiceCollection<TodoItem, TodoItem> items;
   2: private IMobileServiceTable<TodoItem> todoTable = App.MobileService.GetTable<TodoItem>();

Listing 3

MobileServiceCollection items is simply a collection on the client that is used to bind to a ListView control in our XAML named ListItems. 

The IMobileServiceTable interface has methods to interact with the REST API specified when the MobileService was created (which is our Azure Mobile Service API). So, the todoTable object has implementations of these methods specific to our service.

For example, the InsertTodoItem method makes a call to todoTable.InsertAsync() and passes an instance of the TodoItem. This calls our Azure Mobile Service REST endpoint (in this case, that endpoint is https://giard.azure-mobile.net/Tables/todoitem), using the POST Verb and passing

We can use Lync extension methods of todoTable to retrieve specific data into the todoTable object as in Listing 4 (from the RefreshTodoItems() method), which retrieves only todoItems for which the Boolean field Complete is false.  

   1: items = await todoTable
   2:     .Where(todoItem => todoItem.Complete == false)
   3:     .ToCollectionAsync();

Listing 4

The shared code takes advantage of the fact that the events fired in Windows and in Windows Phone are very similar and that the similar objects with similar names and events are created in the MainPage.xaml of each project. Because of this, the shared project can even contain event handlers that are appropriate for either project.  For example, Listing 5 is the event handler when you click a checkbox next to an item on either the phone or your Windows PC/Tablet to mark that item as "Complete".

   1: private async void CheckBoxComplete_Checked(object sender, RoutedEventArgs e)
   2: {
   3:     CheckBox cb = (CheckBox)sender;
   4:     TodoItem item = cb.DataContext as TodoItem;
   5:     await UpdateCheckedTodoItem(item);
   6: }

Listing 5

This event handler passes the checked item to the UpdateCheckedTodoItem method, which uses the todoTable object to call the REST endpoint (Listing 6).

   1: private async Task UpdateCheckedTodoItem(TodoItem item)
   2: {
   3:     // This code takes a freshly completed TodoItem and updates the database. When the MobileService 
   4:     // responds, the item is removed from the list 
   5:     await todoTable.UpdateAsync(item);
   6:     items.Remove(item);
   7:     ListItems.Focus(Windows.UI.Xaml.FocusState.Unfocused);
   8: }

Listing 6

The entire MainPage class is shown in Listing 7.

   1: sealed partial class MainPage: Page
   2: {
   3:     private MobileServiceCollection<TodoItem, TodoItem> items;
   4:     private IMobileServiceTable<TodoItem> todoTable = App.MobileService.GetTable<TodoItem>();
   5:  
   6:     public MainPage()
   7:     {
   8:         this.InitializeComponent();
   9:     }
  10:  
  11:     private async Task InsertTodoItem(TodoItem todoItem)
  12:     {
  13:         // This code inserts a new TodoItem into the database. When the operation completes
  14:         // and Mobile Services has assigned an Id, the item is added to the CollectionView
  15:         await todoTable.InsertAsync(todoItem);
  16:         items.Add(todoItem);
  17:     }
  18:  
  19:     private async Task RefreshTodoItems()
  20:     {
  21:         MobileServiceInvalidOperationException exception = null;
  22:         try
  23:         {
  24:             // This code refreshes the entries in the list view by querying the TodoItems table.
  25:             // The query excludes completed TodoItems
  26:             items = await todoTable
  27:                 .Where(todoItem => todoItem.Complete == false)
  28:                 .ToCollectionAsync();
  29:         }
  30:         catch (MobileServiceInvalidOperationException e)
  31:         {
  32:             exception = e;
  33:         }
  34:  
  35:         if (exception != null)
  36:         {
  37:             await new MessageDialog(exception.Message, "Error loading items").ShowAsync();
  38:         }
  39:         else
  40:         {
  41:             ListItems.ItemsSource = items;
  42:             this.ButtonSave.IsEnabled = true;
  43:         }
  44:     }
  45:  
  46:     private async Task UpdateCheckedTodoItem(TodoItem item)
  47:     {
  48:         // This code takes a freshly completed TodoItem and updates the database. When the MobileService 
  49:         // responds, the item is removed from the list 
  50:         await todoTable.UpdateAsync(item);
  51:         items.Remove(item);
  52:         ListItems.Focus(Windows.UI.Xaml.FocusState.Unfocused);
  53:     }
  54:  
  55:     private async void ButtonRefresh_Click(object sender, RoutedEventArgs e)
  56:     {
  57:         await RefreshTodoItems();
  58:     }
  59:  
  60:     private async void ButtonSave_Click(object sender, RoutedEventArgs e)
  61:     {
  62:         var todoItem = new TodoItem { Text = TextInput.Text };
  63:         await InsertTodoItem(todoItem);
  64:     }
  65:  
  66:     private async void CheckBoxComplete_Checked(object sender, RoutedEventArgs e)
  67:     {
  68:         CheckBox cb = (CheckBox)sender;
  69:         TodoItem item = cb.DataContext as TodoItem;
  70:         await UpdateCheckedTodoItem(item);
  71:     }
  72:  
  73:     protected override async void OnNavigatedTo(NavigationEventArgs e)
  74:     {
  75:         await RefreshTodoItems();
  76:     }
  77: }

Listing 7

Conclusion

Notice how much of the application logic was moved into the Shared project. This isn't surprising because both the Phone app and the Windows app do the same thing - but with different user interfaces. It should be your goal to push as much of our app as you can into the Shared project.

When you build your own app, you will almost certainly use a different model and a different user interface. However, the samples code in this generated application should provide you a template for how to do basic operations on your mobile service, such as Read, Write, Update, and Delete. Make sure you understand the sample; then copy the appropriate code into your application and modify it to fit your model.

Friday, 07 November 2014 10:00:00 (GMT Standard Time, UTC+00:00)
# Thursday, 06 November 2014

In the last article, I showed how to create a new Azure Mobile Service in the portal. In this article, I will show you how to use the wizard to create an application, consisting of a new table, an HTTP endpoint to access that table, and a sample client application to access the data through that endpoint.

Log onto the Azure Portal and select the MOBILE SERVICES icon in the left menu. Figure 1 shows the Mobile Service we created last time.

Zumo2-Figure 01 - List Service
Figure 1

Click the arrow next to the service name to display details about the service (Figure 2).

Zumo2-Figure 02 - GET STARTED
Figure 2

Notice the choices you have next to "CHOOSE A PLATFORM". The Platforms listed are the various client platforms explicitly supported by Mobile Services. Remember that Mobile Services exposes data via standard interfaces such as HTTP and JSON which can be used by a wide variety of platforms and languages. For this demo, click the "Windows" button; then expand the "CREATE A NEW WINDOWS APP" link. This will reveal the 3 steps to get you started building an application around Azure Mobile Services (Figure 3).

Zumo2-Figure 03 - GET STARTED
Figure 3

Get the tools (Figure 4) allows you to download a free version of Visual Studio. If you already have any version of Visual Studio 2013 installed, you can skip this step.

Zumo2-Figure 04 - Get the Tools
Figure 4

The "Create a table" step (Figure 5) allows you to create a sample SQL Server table. Click the green button to create a new table named "TodoItem" in your database with columns to keep track if the tasks you need to do today and whether you have completed each task.

Zumo2-Figure 05 - Create Table
Figure 5

The “Download and run your app” step (Figure 6) will generate client code that will connect to your application.

Zumo2-Figure 06 - Download App
Figure 6

Select a language (C# or JavaScript) and click the Download button to download a ZIP file containing a Universal App that includes a Windows 8.1 project, a Windows Phone 8.1 project, and a Shared Code project. Depending on your language selection, these projects will either contain a user interface written in XAML and C# code-behind or an HTML5 front-end with a WinJS code-behind. Figure 7 shows the results of C#/XAML project generated by Azure Mobile Services.

Zumo2-Figure 07 - Client App
Figure 7

Compile and run this app to see it in action. Figure 8 shows a screen shot of the Windows 8 app. You can enter a new task in the textbox and click Save to send data to the mobile service telling it to insert a row in the todoitem table. A list on the right displays all tasks that are not yet completed. Click the checkbox next to an item to send data to the mobile service telling it to update the todoitem table, setting the Complete column to FALSE.

Zumo2-Figure 08 - Running App
Figure 8

Figure 9 shows the Windows Phone project running.

Zumo2-Figure 09 - Running App
Figure 9

You can see that the apps look similar because they have the same functionality. The differences are related to the size, layout, and other considerations of the specific platform on which they run. Play with each app and you will see that they function about the same, thanks to the large percentage of shared code.

In this article, we saw how to run the Azure Mobile Services wizard to generate a sample table and client application.

Thursday, 06 November 2014 10:00:00 (GMT Standard Time, UTC+00:00)
# Wednesday, 05 November 2014

With Azure Mobile Services, developers can quickly create a REST interface to read and write their backend database.

The Azure portal provides a wizard for creating a sample solution built around mobile services in just a few minutes. In this article, I will walk you through the steps to create a new Azure Mobile Service.

Log onto the Azure Portal and select the MOBILE SERVICES icon (Figure 1) in the left menu.

Zumo2-Figure 01
Figure 1

Click the NEW button at the bottom of the screen (Figure 2).

Zumo2-Figure 02 - New Button 
Figure 2

This exposes a menu (Figure 3).

Zumo2-Figure 03 - Create
Figure 3

With COMPUTE and MOBILE SERVICES selected (which should already be the case) click the CREATE button.

The "Create a Mobile Service" dialog (Figure 4) displays.

Zumo2-Figure 04 - Create
Figure 4

Give a name for the service. The full name will be whatever you type in the URL textbox, followed by ".azure-mobile.net" and it must be unique. The portal will let you know if someone else has chosen the same name. Select an existing database or create a new one; then select the Region where the Mobile Service will live. It makes sense to create the service in the same region where the database resides.

Finally, select the language in which to build the backend service. If you select JavaScript, the server-side solution will be hosted in Node.js. If you select .NET, you can create a solution in Visual Studio and deploy it to Azure, where it will be hosted in IIS.

Click the arrow (Figure 5) at the bottom right of the dialog to advance to the next page, where you can specify database information.

Zumo2-Figure 05 - Next
Figure 5

Figure 6 show the page if you elect to connect to an existing database. Select the database connection string; then enter the login name and password with which you will connect to this database.

Zumo2-Figure 06 - DB
Figure 6

Click the check button to create the Mobile Service. After a few seconds, the service will show up in the portal as in Figure 7.

Zumo2-Figure 07 - New Service
Figure 7

In this article, we saw how to create a new Azure Mobile Service. In the next article, we will add a table and allow clients to retrieve and update data in that table, using this service.

Wednesday, 05 November 2014 10:00:00 (GMT Standard Time, UTC+00:00)
# Tuesday, 04 November 2014

Storing data in the cloud allows your application to remember information between launches and to share data among other users, applications, and devices.

Exposing that data via a REST interface makes this data accessible to applications running on a variety of platforms and written in a variety of languages. REST is an architectural pattern for allowing clients to read and update server data through a consistent API. The current implementations of REST uses an HTTP endpoint (a URL) to expose functionality and the features of HTTP (verbs, response codes, and header data) to exchange data between the client and the server.

Azure Mobile Services (ZuMo) makes it easier to expose your data as a REST endpoint by handling the "plumbing" code for you so that you can focus on your data model and your business logic.

With just a few clicks, you can create a service and map it to a database table. ZuMo will create an HTTP endpoint; map HTTP verbs to Create, Read, Update, and Delete methods; create those methods for you; and handle the transformation from JSON data into objects that map to rows in your database table. This isn't impossible code for you to write, but it can be a lot of code. And wouldn't your time be better spent writing the code that makes your application unique?

Azure Mobile Services will even generate a client application to call your new REST service and pass data to and from it. You can use this application as a starting point or you can copy and paste code from this app into your own client app. ZuMo is capable of generating a sample client application for Windows 8, Windows Phone, HTML and JavaScript, Xamarin, PhoneGap, Android, or iOS.

Azure Mobile Services is a true cross-platform solution that is simple to implement because it handles much of the plumbing code for you.

Tuesday, 04 November 2014 10:00:00 (GMT Standard Time, UTC+00:00)
# Monday, 03 November 2014
Monday, 03 November 2014 10:00:00 (GMT Standard Time, UTC+00:00)
# Sunday, 02 November 2014

11/2
Today I am grateful for the friends I have kept for decades. They've known me at my best and at my worst.

11/1
Today I am grateful I finally caught up editing all my videos and photos.

10/31
Today I am grateful for dinner with my niece Amanda last night.

10/30
Today I am grateful for a home-cooked meal last night.

10/29
Today I am grateful for a chance to speak at the Motor City Software Testers last night & to all who came to hear me.

10/28
Today I am grateful I attended an exciting Monday Night Football game in Dallas last night.

10/27
Today I am grateful for some authentic Texas BBQ last night.

10/26
Today I am grateful for the students at TAMUHack who show energy, imagination, and passion and built so many great projects this weekend. I'm also grateful for the Michigan State Spartans, who drove through the michigan wolverines like a spike through grass yesterday!

10/25
Today I am grateful for my first trip to College Station, TX.

10/24
Today I am grateful I was invited to speak at the inaugural meeting of the Local Variables user group in South Bend, IN yesterday.

10/23
Today I am grateful for a long hot shower on a chilly morning.

10/22
Today I am grateful to God, who helped me through the difficult times in my life.

10/21
Today I am grateful for a day with few responsibilities.

10/20
Today I am grateful for a weekend in Indiana watching football with Tim Giard

10/18
Today I am grateful for lunch yesterday with Corey Haines

10/17
Today I am grateful for an unexpected gift from the Madison Mobile .NET Developers Group .

10/16
Today I am grateful for a successfully completed trip to Minnesota and Wisconsin.

10/15
Today I am grateful I completed 1 year at the best job I've ever had.

10/14
Today I am grateful for dinner last night with Brent Stineman

10/13
Today I am grateful for the open Wi-Fi that suddenly showed up when I'm in my apartment. I'm not sure if the apartment complex added a repeater or if I have a new neighbor, but I appreciate it.

10/12
The Hitchhiker's Guide to the Galaxy was published 35 years ago today! I am fortunate to have met the book's author before his passing.

10/11
Today I am grateful for dinner and drinks last night with Patricia and Gary.

10/10
Today I am grateful to the folks a the Schaumburg Microsoft .NET Technologies Meetup for inviting me to speak last night

10/9
Today I am grateful for a great audience yesterday at the first Azure Dev Camp in St. Louis.

10/8
Today I am grateful that my son called me yesterday just to say "Hi".

10/7
Today I am grateful to Velichka, who brought me chicken soup when I was sick.

10/6
Today I am grateful for 12+ hours sleep last night that I desperately needed.

10/5
Today I am grateful for dinner with friends, a ticket to the Nebraska game, and a Spartan victory!

Sunday, 02 November 2014 15:03:28 (GMT Standard Time, UTC+00:00)
# Saturday, 01 November 2014

A few months ago, I migrated this blog to Azure Web Sites.

I was aided by the fact that I use Das Blog as a blogging engine. This gave me two advantages:
1. I could select a Das Blog template from the Azure Web Site gallery, automatically configuring the appropriate settings for my site; and
2. Das Blog uses XML files instead of a database to store blog posts, so I was able to xcopy my entire blog to Azure.

The only real work was changing my DNS settings to point to Azure, which took a few minutes. I set the site to user the SHARED hosting plan, which lets me point a custom domain to it. More popular blogs (like yours) may need to use the BASIC or STANDARD Web Hosting Plan, but I stuck with the cheap one and it works fine for me.

The story here is what a non-story this migration was. My site was down less than an hour and most of that was because I messed up the DNS settings the first time. It is servicing requests just fine and I am saving money because this hosting plan is cheaper than what I paid to my old provider.

Currently, I'm not using any advanced features, such as Scaling, Autoscaling, and Web Jobs but those are available to me if I need them.

I love the simplicity of Azure Web Sites. If you are considering using Azure, this is a good place to start.

Saturday, 01 November 2014 23:27:51 (GMT Standard Time, UTC+00:00)
# Monday, 27 October 2014
Monday, 27 October 2014 23:17:10 (GMT Standard Time, UTC+00:00)
# Monday, 20 October 2014
# Saturday, 18 October 2014

What is Demand Elasticity, how does it affect my apps, why should I care, and how does Azure address this?

Demand Elasticity is an issue because almost no app has a constant demand over time: Some apps are used primarily during business hours and very little during the night; some apps have abnormally high demand during specific events, such as the launch of a new product or while NFL games are broadcasting; some businesses have peak seasons when they do nearly all their business (I once worked for an electronics retail store that earned over 80% of their revenue between Thanksgiving and New Years Day.)

Each of the above examples describes demand variability that you can plan for. An even more difficult problem is unexpected changes in demand. Imagine if a popular TV show recommends your online service. Demand would likely skyrocket. Could your services handle this extra, unexpected load?

Because of this change in demand, you need to decide how much hardware to deploy for your application. If you deploy too much hardware, you are wasting your money, but if you deploy too little, you will miss out on potential users and revenue. And in the fact that hardware is not easy or quick to deploy - It may take your organization weeks or months to respond to a sudden, unexpected increase in demand. And what do you do with that extra hardware when demand falls? For most organizations, it's not practical to buy and sell hardware as demand goes up and down.

Ideally, as demand increases and places higher load on your servers, you would increase the amount of hardware to which your application is deployed. Then, you would remove that hardware (and stop paying for it) as demand and workload decrease.  If you are managing and deploying the hardware yourself, this is not really practical. There is no quick market to buy and sell servers and most organizations take days – if not weeks – to provision a new server.

But Azure allows you to deploy more servers to your application and it automatically deploys them for you in a matter of minutes. Most services in Azure have a setting that allows you to change the number of running instances. This can be the number of web sites, web roles, mobile service, virtual machines, or dozens of other service instances available.

Below is the setting for configuring the number of instances of an Azure Web Site.
Scale-1
figure 1

Some services even allow you to automate this process. For example, you can configure Azure to monitor the CPU used by your web sites and automatically deploy a new instance of your site when CPU rises above a certain percent and remove an instance when it falls below a given percent. You can set a minimum and maximum to keep the number of instances within this range.

For Azure Web Sites, this Auto-scaling feature is available if we select the "Standard" hosting plan. Below are the controls that allows you to set these configuration.
Scale-2

Figure 2

Scaling up helps your service deal with extra usage (planned or unplanned), while scaling down helps you save money. The quicker you can do both, the more agile you will be.

Azure allows you the flexibility to scale up and down to meet changing demand.

Saturday, 18 October 2014 14:34:45 (GMT Daylight Time, UTC+01:00)