Wednesday, December 5, 2012

Windows Azure: Challenge Number One

While I was at BUILD 2012 a few weeks ago, the Windows Azure team put together a series of challenges for enthusiasts to solve during the conference. They were giving a prize for each completed challenge, and I’m happy to say, I tackle them all!

As a follow up, I wanted to share the different challenges and the app I created and leveraged across Windows 8, Windows Phone 8 and Windows Azure. I’m a bit delayed on the publishing due to the monthly usage limits on the services, but hopefully they are still quite relevant. I’ll be publishing a series of posts going through the evolution of the app.


Through the series, I’ll be working on an app I just called TwitBook. The concept is pretty simple, and hopefully handy. I wanted to create a simple app to store the twitter usernames of the BUILD presenters and colleagues, to follow up later.

Challenge Number One

The first Windows Azure challenge was to create and activate your Azure account, download the SDK and complete the getting started tutorial. The tutorial teaches you how to create a Windows Phone 8 app that uses a Windows Azure Mobile Service.

Windows Azure Mobile Services is a quick, simple and powerful way to create backend services for mobile applications.

twitbook_08    twitbook_09

You will need Visual Studio 2012 (you can get the Express version here) and the Mobile Services SDK.

Creating the Mobile Service


The first step is to login into the Windows Azure Portal. Then select “New” at the bottom left corner, and choose to create a new Mobile Service. You can create a new SQL database instance for your service or use an existing one (I’d recommend reusing your SQL instances as much as possible to reduce the computing and storage consumption).



You can just follow up the tutorial which is presented in the dashboard of the new Mobile Service you just created. It will take you through the setup of the mobile service and the initial SQL setup and then it gives you a base Windows Phone 8 app that you will modify to connect to your cloud service.


In my case, I wanted to create my own Windows Phone 8 app based on the TwitBook concept.

The first thing that I needed to do is to create the SQL tables required. If you click on the Data tab of the service, you will see an empty table. Click on the “Add a Table” to create a new one. Give it a name and assign the permissions you require. Defaults are OK for now. Once that is done, you will see your new empty table.




Notice that you were able to create the table without defining any data structure. No columns, types or defaults so far. This is part of making the setup easier and a better fit for simple mobile services. The data structure of the table will be created when you submit the first set of data records.

Creating the Windows Phone Application

Now we are ready to switch to our local dev environment. Run Visual Studio 2012 and create a new Windows Phone blank application. Select Windows Phone OS 8 as the targeted platform.


I won’t go into much detail since the code and layout are straight forward and it is based on the sample project you can download from the Windows Azure portal. The app has one page only. It exposes a couple of text boxes to enter the contact’s full name and twitter handle. It has a button to save the contact’s information and a refresh button to load and update the contact’s list. Finally, it uses a LongListSelector items control to display the list of existing contacts (here’s a nice walkthrough for this powerful control and some design guidelines in case you want to go deeper on the subject).


The next step is to create the data model that will be used to store the contacts information. For this I have created a new class called “Contact” in my Model folder.

  1: public class Contact
  2: {
  3:   public int Id { get; set; }
  5:   [DataMember (Name="fullname")]
  6:   public string FullName { get; set; }
  8:   [DataMember(Name="twitterhandle")]
  9:   public string twitterhandle { get; set; }
 10: }

Now that we have the model, we can go ahead and build the logic to connect to the Windows Azure Mobile Service.

For a start, I always add my regions structure: fields, properties, constructors and methods. You will need to add a reference to the Windows Azure Mobile Services Managed Client assembly.



Once you have the assembly reference in place, we need to create our MobileServiceClient instance to connect to our service. We can do this in the App.xaml.cs file. Make sure to enter your service Url and Application key correctly.

  1: public static MobileServiceClient MobileService = 
  2:     new MobileServiceClient(
  3:     "",
  4:     "YourAppKey"
  5:     );

We have our service client in place and we can now switch to MainPage.xaml.cs. First, we will create two private fields. One will hold our collection of contacts, and the other will have a reference to our service’s Contact Table.

  1: private MobileServiceCollectionView<Contact> contacts;
  2: private IMobileServiceTable<Contact> contactTable = App.MobileService.GetTable<Contact>();

Next, we will implement the set of methods needed to interact with the service and manage the data flow between our mobile app and the cloud. We need two important methods. One to insert a new contact into our cloud table. This one needs to be an asynchronous operation since connecting to the cloud and writing a new entry on our cloud storage. Once the operation finishes, it adds the new record to our local collection. The second operation is for refreshing our contact list, which uses our local collection to display the contacts list.

  1: private async void InsertContact(Contact contact)
  2: {
  3:   // This code inserts a new contact into the database. When the operation completes
  4:   // and Mobile Services has assigned an Id, the item is added to the CollectionView
  5:   await contactTable.InsertAsync(contact);
  6:   contacts.Add(contact);
  7: }
  9: private void RefreshContactList()
 10: {
 11:   // This code refreshes the entries in the list view be querying the Contacts table.
 12:   contacts = contactTable.ToCollectionView();
 13:   ListItems.ItemsSource = contacts;
 14: }

To finish, we just need to implement our button’s event handlers to tie our UI actions to our logic. We need one handler for our Save button, and another for our Refresh button.

  1: private void ButtonRefresh_Click(object sender, RoutedEventArgs e)
  2: {
  3:   RefreshContactList();
  4: }
  6: private void ButtonSave_Click(object sender, RoutedEventArgs e)
  7: {
  8:   var contact = new Contact { FullName = FullNameInput.Text, TwitterHandle = TwitterHandleInput.Text };
  9:   InsertContact(contact);
 10: }

Now compile and run your application. Add a few contacts to test the app. You can use tools like Fiddler or Charles to monitor the http traffic, and make sure the service is up and running.


After you have added a few contacts, you can check the cloud storage records to see the data being received and stored by the Azure Mobile Service.


That’s it. You have the simple twitter contact manager up and running, integrated with a cloud storage service.

I hope you realize how easy is to create, host and maintain simple cloud services for your applications. The more you explore and use the Windows Azure cloud offerings, the more you will be able to take advantage of the different services to power and sync your application’s data.

I encourage you to go ahead and get your trial account. Follow the simple tutorials and try to replicate what I did for the first challenge. Please let me know your comments and experience. I’d appreciate your feedback and contributions.

No comments:

Post a Comment