October 21, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

How to Create a Windows Store Leaderboard Application Powered by Windows Azure Mobile Services

  • October 11, 2012
  • By Vipul Patel
  • Send Email »
  • More Articles »

In this article, we will walk through an exercise of building a working Windows 8 application that is powered by the recently announced Windows Azure Mobile Services. This application demonstrates the ease of building a working application for mobile devices in a very short time, using the tools offered by Microsoft.

Get the tools now:

Introduction

Microsoft recently announced the availability of Windows Azure Mobile Services – which allowed developers to easily connect their mobile applications to the Windows Azure powered back-end. We looked at an introduction on Windows Azure Mobile Services in a prior article - http://www.developer.com/net/introduction-to-windows-azure-mobile-services.html.

In this article, we will walk through the entire experience to build a mobile application that is powered by Windows Azure Mobile Services. Since the feature is still in pre-release mode, the support for Windows Azure Mobile Services is only available for Windows 8. Therefore, in this walkthrough, we will build a Windows 8 application that will show leader dashboard data, with the back-end being powered by the cloud services from Microsoft.

The Tool Bench

To build an application that can leverage Windows Azure Mobile Services, you will need the following tools:

  1. Visual Studio Express for Windows 8 - http://solutions.devx.com/ms/msdn/marketing/visual-studio-2012-express-for-windows-8-rc-banner-link.html  - This is available for free. If you have a license for Visual Studio 2012 Ultimate or some other 2012 SKU, you can also use that.
  2. Mobile Services SDK - http://go.microsoft.com/fwlink/?LinkId=257545 

Once the tools are installed, we can proceed to the next step of building our application.

Getting the Plumbing Ready

To get started, download the free 90-day trail from here, or visit https://manage.windowsazure.com. If you have yet applied for access to Windows Azure Mobile Services, you can refer to our earlier article http://www.developer.com/net/introduction-to-windows-azure-mobile-services.html  to learn how to request access.

Once you request permissions, you will be able to see a special node called “Mobile services” on the left side of the Portal page.

Windows Azure - Mobile Services
Windows Azure - Mobile Services

To create a new Mobile Service, click “New” at the bottom of the page, select “Compute” -> “MOBILE SERVICE” and click Create.

Create a new Mobile Service
Create a new Mobile Service

Next, you will need to provide information about the mobile service you want to create. For our walkthrough, type “Leaderboard” in the URL.  Also, select to create a new SQL database and then click the “->” arrow to proceed to the next step.

Provide information about the Mobile Service
Provide information about the Mobile Service

On the next screen, we will need to provide the information for the database. Here, I am specifying “Leaderboard” as the database name and the credentials for SQL user.

 Database Information
Database Information

On the last step, we specify a few extra details about the database. Leave the default and click the “checkbox” to complete the wizard.

 Database Settings
Database Settings

In a few moments, the Mobile service is created and ready for use in our application.

The Mobile Service is Created
The Mobile Service is Created

Notice that the URL for our mobile service is https://leaderboard.azure-mobile.net and the status is “Ready”.

To proceed with the next steps, click the “->” next to the “Leaderboard service.

Mobile Service status is ready
Mobile Service status is ready

On this page, we will configure how to connect the mobile service to a Windows Store application.

Configure connection of Mobile Service to a Windows Store app
Configure connection of Mobile Service to a Windows Store app

If you have an existing Windows Store application, click the “Connect an existing Windows Store app” link. In our case, we will select “Create a new Windows Store app”.

Create a new Windows Store app
Create a new Windows Store app

When we click the link, we see the instructions on how to connect a mobile service to the Windows Store application. We have already completed step 1 as part of the pre-requisite of this walkthrough.

Since our leaderboard application will need a datastore to store information, we will need to create a database. To make things simpler, Microsoft has provided a 1-click sample for a TodoItem table. We can use that to get the underlying infrastructure for our Windows Store application.

Click on “Create TodoItem Table” to create the application. Finally, click Download on step #3 to download a Windows Store application boilerplate code, which works on the TodoItem table.

The boilerplate code you will download will be similar to Leaderboard-ori.zip (downloadable below).

Now, we need to create the table to keep tab of the player scores we will display in the leaderboard application.

To create the table, click on the “SQL DATABASES” link on the left side and click on the Database name.

Click on the SQL DATABASES link
Click on the SQL DATABASES link

At the bottom of the page, click the link titled “Manage”.

This will open the Management portal for the SQL database.

Management portal for the SQL database
Management portal for the SQL database

Type in the username and password you have provided when you created the database and click “Log in”.

Database Properties
Database Properties

Click the “Design” link on the left side and then click on the “new table” link.

 Click the new table link
Click the new table link

Create a table named “ScoreBoard” with the following fields: id (bigint), name (nvarchar(50)) and score (int).

Save the table and close the window.

We will now open the solution, which we had downloaded. Extract the contents of the ZIP file and open the solution with Visual Studio 2012.

If this is the first time you are using Visual Studio 2012 to create a Windows Store application, you will be prompted to get the developer license for Windows 8.

Get a developer license for Windows 8
Get a developer license for Windows 8

When you click “I agree”, you will be asked for your Microsoft account. If you have not created one, you can create one now. If you already have a Microsoft account, you can provide your credentials.

Sign in or create an account
Sign in or create an account

After the credentials are verified, you should get a configuration of the developer license.

Developer License
Developer License

Since the template code that we downloaded was generated to work with the TodoItem table, we need to update to work with the ScoreBoard table.

To do that, open up MainPage.xaml.cs and replace class TodoItem with the following.

Replace

public class TodoItem
    {
        public int Id { get; set; }
 
        [DataMember(Name = "text")]
        public string Text { get; set; }
 
        [DataMember(Name = "complete")]
        public bool Complete { get; set; }
    }

With

public class ScoreBoard
    {
        public int Id { get; set; }
 
        [DataMember(Name = "name")]
        public string Name { get; set; }
 
        [DataMember(Name = "score")]
        public int Score { get; set; }
    }

In the snippet above, we created properties to match every column of the ScoreBoard table.

Next, we need to replace every reference of TodoItem with ScoreBoard.

Change

public sealed partial class MainPage : Page
    {
        // MobileServiceCollectionView implements ICollectionView (useful for databinding to lists) and 
        // is integrated with your Mobile Service to make it easy to bind your data to the ListView
        private MobileServiceCollectionView<TodoItem> items;
 
        private IMobileServiceTable<TodoItem> todoTable = App.MobileService.GetTable<TodoItem>();

with

public sealed partial class MainPage : Page
    {
        // MobileServiceCollectionView implements ICollectionView (useful for databinding to lists) and 
        // is integrated with your Mobile Service to make it easy to bind your data to the ListView
        private MobileServiceCollectionView<ScoreBoard> items;
 
        private IMobileServiceTable<ScoreBoard> todoTable = App.MobileService.GetTable<ScoreBoard>();

Now, we will update MainPage.xaml and add a few controls.

First, we need to add another textbox to allow adding the score of a new player as well as the player name as part of Step #1.

Next, we need to change the default controls for Step #2 to show two controls per record  - one will be a TextBlock and the other TextBox.

The changes from the default code are highlighted.

###############################################################

<Page
    x:Class="LeaderBoard.MainPage"
    IsTabStop="false"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:LeaderBoard"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
 
    <Grid Background="White">
 
        <Grid Margin="50,50,10,10">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="*" />
            </Grid.RowDefinitions>
 
            <Grid Grid.Row="0" Grid.ColumnSpan="2" Margin="0,0,0,20">
                <StackPanel>
                    <TextBlock Foreground="#0094ff" FontFamily="Segoe UI Light" Margin="0,0,0,6">CODEGURU.COM</TextBlock>
                    <TextBlock Foreground="Gray" FontFamily="Segoe UI Light" FontSize="45" >LeaderBoard</TextBlock>
                </StackPanel>
            </Grid>
            <Grid Grid.Row="1">
                <StackPanel>
                    <local:Task Number="1" Title="Insert a player with score" Description="Enter the player name and score below and click Save to insert it into the database" />
                    <StackPanel Orientation="Horizontal" Margin="72,0,0,0">
                        <TextBox Name="TextInput" Margin="5" MinWidth="150"></TextBox>
                        <TextBox Name="ScoreInput" Margin="5" MinWidth="150"></TextBox>
                        <Button Name="ButtonSave" Click="ButtonSave_Click">Save</Button>
                    </StackPanel>
 
                </StackPanel>
            </Grid>
 
            <Grid Grid.Row="1" Grid.Column="1">
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                    <RowDefinition />
                </Grid.RowDefinitions>
                <StackPanel>
                    <local:Task Number="2" Title="Refresh LeaderBoard" Description="Click refresh below to refresh the the leaderboard. To update the score of a particular player, update the score next to the player and move focus away from the scorebox. This will update the score for the player and cause the leaderboard to refresh the data." />
                    <Button Margin="72,0,0,0" Name="ButtonRefresh" Click="ButtonRefresh_Click">Refresh</Button>
                </StackPanel>
                <ListView Name="ListItems" Margin="62,13,0,-3" Grid.Row="1">
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <TextBlock Name="ScoreName" Text="{Binding Name, Mode=OneWay}" Margin="10,5" VerticalAlignment="Center" />
                                <TextBox Name="ScoreValue" Text="{Binding Score, Mode=TwoWay}" Margin="10,5" VerticalAlignment="Center" LostFocus="ScoreValue_LostFocus"/>
                            </StackPanel>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>
            </Grid>
        </Grid>
    </Grid>
</Page>

As you can see above, we added an event handler for LostFocus event on the TextBox names ScoreValue. We will use this event to update the changes to the database and refresh the leaderboard.

We will now right code to implement the eventhandler. In the event handler, we will process the changes in the TextBox and update the item. Finally, we will make a call to RefreshTodoItems() method, which already existed, to update the leaderboard.

private void ScoreValue_LostFocus(object sender, RoutedEventArgs e)
        {
            TextBox tb = (TextBox)sender;
            ScoreBoard item = tb.DataContext as ScoreBoard;
            item.Score = int.Parse(tb.Text);
            UpdateCheckedTodoItem(item);
            RefreshTodoItems();
        }
 

We can safely remove CheckBoxComplete_Checked from the code if there are no other references to it.

We also need to update the eventhandler for the Click event  on the Save  button. In this event handler, we will construct a new ScoreBoard item, and insert it into the table.

private void ButtonSave_Click(object sender, RoutedEventArgs e)
        {
            var todoItem = new ScoreBoard { Name = TextInput.Text, Score = int.Parse(ScoreInput.Text)};
            InsertTodoItem(todoItem);
        }

In the InsertTodoItem() method, we need to comment out the code that adds the newly added item to the list view. Instead we will make a call to RefreshTodoItems() method, which will ensure (we will see later) that the most recent values from the database are used.

private async void InsertTodoItem(ScoreBoard todoItem)
        {
            // This code inserts a new player into the database. When the operation completes
            // and Mobile Services has assigned an Id, the item is added to the CollectionView
            await todoTable.InsertAsync(todoItem);
            //items.Add(todoItem);                        
            RefreshTodoItems();
        }
 

Finally,  we make the changes in RefreshToDoItems() method to ensure that the data that is added to the collection view is always sorted in the descending order of scores.

Change

private void RefreshTodoItems()
        {
            // This code refreshes the entries in the list view be querying the TodoItems table.
            // The query excludes completed TodoItems
            items = todoTable
                .Where(todoItem => todoItem.Complete == false)
                .ToCollectionView();
            ListItems.ItemsSource = items;
        }

To

private void RefreshTodoItems()
        {
            // This code refreshes the entries in the list view be querying the ScoreBoard table.
            items = todoTable
                .OrderByDescending(todoItem => todoItem.Score )
                .ToCollectionView();
            ListItems.ItemsSource = items;
        }

Now, we are ready with all the changes. Build your application and run it.

If you are having trouble compiling the code or following along, you can download the code of the walkthrough below.

Running the Application

When you run the application, you will notice the screen below. The left side is used to add new players to the leaderboard. To add a new player, type the name and score and click Save.

Run the application
Run the application

For demo purposes, I will add Codeguru as a player with score of 1000. When I click Save, the record is persisted, and the listview, which displays the leaderboard is refreshed. Since Codeguru has a score of 1000, it will be displayed at the top of the list.

CodeGuru at the top of the list
CodeGuru at the top of the list

Now, let us consider the case where another player (for example vipul) gets a score of 1500.

To update the score, change the score of “vipul” from 0 to 1500. When you click anywhere else on the screen, the record is updated, and the view is refreshed.

The view is refreshed
The view is refreshed

Summary

In this walkthrough, we have built a Windows Store leaderboard application powered by Windows Azure Mobile services. We can see how easy it is to build a mobile application powered by the cloud. I hope you have found this article useful.

About the author

Vipul Patel is a Program Manager currently working at Amazon Corporation. He has formerly worked at Microsoft in the Lync team and in the .NET team (in the Base Class libraries and the Debugging and Profiling team). He can be reached at vipul_d_patel@hotmail.com


Tags: Microsoft, mobile, application, Windows Azure




Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel