Share via


Supporting Billions of entities/rows for Mobile – Mobile to Cloud Series - Part 10 – Writing a Windows Phone 7 Client to consume RESTful data from Azure (Microsoft Cloud)


  This is the last post in a long series. This is a post about connecting Windows Phone 7 applications to a RESTful service hosted in the Microsoft cloud, aka Windows Azure. Before moving on into this particular post, I’m making a few assumptions about what you’ve already done. First, I expect that you have already created a RESTful service, which was explained in detail in previous posts. Complete source code was provided as well as guidance about building the service itself. Second, I will assume that you follow the guidance about what operating systems and developer tooling you are running.

  Supported Operating Systems
  Before you commit writing Windows Phone 7 applications you need the right operating system. I am a super big fan of Windows 7. I've had the same instance loaded (in and out of sleep mode) for weeks. It is incredible how stable and efficient Windows 7 is. I am not saying this because I work for Microsoft. I've been using MS operating systems since DOS 3.0. Windows 7 rocks. 'Nuf said.         Supported Operating Systems
Windows 7, Windows Vista (x86 and x64) with Service Pack 2, all editions except Starter Edition
Windows 7 (x86 and x64) - all editions except Starter Edition
Installation requires 4 GB of free disk space on the system drive.
3 GB RAM
Windows Phone Emulator requires a DirectX 10 or above capable graphics card with a WDDM 1.1 driver

  Windows Phone SDK
  The Windows Phone SDK includes a number of powerful tools, in addition to Visual Studio. Let's talk about what is included.
The Windows Phone SDK includes Visual Studio 2010 Express for Windows Phone, Windows Phone Emulator, XNA Game Studio, Expression Blend for Windows Phone, samples, and documentation.
If Visual Studio 2010 Professional or higher is already installed on your development computer, an add-in for Visual Studio 2010 Professional is automatically installed as well.
In case you don't know there are two types of applications you can write for Windows Phone 7 - Silverlight and XNA. Silverlight is a great approach because the GUI design and construction part is done with XAML, which is a powerful declarative markup language, much like what HTML5 is aiming to be. XNA is all about an animation engine that facilitates game programming. After all, most of the big apps today on mobile platforms are all about gaming. Expression Blend is a tool to help you write XAML code using a WYSIWYG editor. It is very powerful and even plays a big role in the future of MS application construction. I also encourage you to download and install "Clipboard Loader," which is a Windows application which contains the source code for this application. Remember that both WP7.exe and WP7.xml need to be in the same folder or directory. Finally, I have also provided the download link for the entire Windows Phone 7 application. Important Downloads for this post
Clipboard Loader Executable [ put in the same folder as wp7.xml below] https://brunoblogfiles.com/clipboard/wp7.exe
Clipboard Loader XML file [ put in the same folder as wp7.exe above] https://brunoblogfiles.com/clipboard/wp7.xml
Source Code to Windows Phone 7 Code application in this post https://brunoblogfiles.com/cloudclient/CloudClient.zip

  Download Link for the Windows Phone SDK
  This is the download link for the Windows Phone 7 SDK. Everything I talked about earlier in this post, is included. It is your one-stop-shopping link. image

  You will need the Azure SDK
 

  Starting Visual Studio and Creating Your Project
  I always like to start from the very beginning. So be sure to start Visual Studio as "administrator." This can be done with a simple right-mouse click. Once Visual Studio is loaded, select "File / New / Project." image

  Silverlight for Windows Phone 7
  Select "Silverlight for Windows Phone 7" in the left template pane. Next select "Windows Phone Application" in the middle pane. Finally, specify a "Name" and "Location" for your project. image

  Version 7.1 – Mango – Windows Phone 7
  For the Phone OS version, choose 7.1. You could select an earlier version, but I will select 7.1 here. This version represents the "Mango" release, the release with over 500 new features. image

  The files we will modify – Only 2
  This is what the generated solution looks like. We will only need to modify two files. We will modify these 2 files: image
MainPage.xaml The visual interface
MainPage.xaml.cs The code behind (C# code)

  Modifying MainPage.xaml
  The red box represents the page title. The next screen will demonstrate how we can modify the page title by changing the XAML markup. image

  Changing the Page Title
  You can see the XAML code here. Notice I changed the "Text" property to "Fast Bikes" and it shows up in the designer on the left. You could have also changed this through a "Properties Window." But I did it directly with XAML just to illustrate the point. Notice the "PageTitle" is of type "<TextBlock />." image

  Implementing the ListBox
  You can see here that I've dragged a ListBox control into the Grid control. You can see that it generated the XAML tag "<ListBox />." You could have also typed the XAML in directly and not use the "Toolbox" on the left. It is up to you. I like doing both. Typically, after I drag the control from the tool box to the designer surface, I modify the dragged control direclty in XAML code. image

  Modifying Code Behind – MainPage.xaml.cs
  Code behind is where developers provide C# code to do things. In this case we want to connect to the RESTful service and get a list of fast motorcycles. To write code behind, right-mouse click on MainPage.xaml.cs and select "View Code." image

  Adding code to MainPage Constructor
  To keep things simple I decided to load the list box in the MainPage constructor. Notice I typed in the method, "LoadListBox." But I haven't implemented "LoadListBox()" yet. That is the next step. image

  Generating LoadListBox()
  I love this feature in Visual Studio. After typing in "LoadListBox();" I right-mouse click and select "Generate / Method Stub." This will actually create an empty method called "LoadListBox()," where I will add my code. image image

  Erasing Code Not Needed
  Here is what the empty method looks like. I will erase "throw new NotImplementedException()" with the real code that I want to execute. image        

  Pointing to the RESTful Service – the URI
 

Notice that I added a property called "_baseServiceAddress." You will need to go to the Windows Azure Portal to get the address of your hosted service. This was covered in detail in previous posts. See Step 3 - DNS name below.

Also note I've added some code that builds the URI that will access our RESTful service. See "LoadListBox()."

image 


  Adding References
  Adding a reference gives our Windows Phone 7 application access to additional functionality not provided with the default Windows Phone 7 project. In this case we will add "System.Servicem odel.Web." This assembly will let us parse the JSON code that comes back from the Azure-hosted RESTful service. image
See Step 3 - DNS Name https://blogs.msdn.com/b/brunoterkaly/archive/2011/10/07/supporting-billions-of-entities-rows-for-mobile-android-series-part-7-migrating-your-azure-cloud-restful-service-to-be-hosted-in-a-microsoft-data-center.aspx

  Adding using statements to Code Behind
  Return back to the code-behind for "MainPage.xaml.cs." There are a few using statements we will need to add. Don't add them right now - I'm just showing them to you. They are somewhat self explanatory. "using" statements allow us to abbreviate our code, essentially.         image

  Loading our Clipboard – Using WP7.exe
  Start the previously mentioned "WP7.exe" application. To populate your clipboard with the previously mentioned "using" statements, click on "WP7 References." Return back to Visual Studio.         image

  Pasting code from the Clipboard – adding the “using” statements
  Right-mouse click just below the last "using" statement and select "Paste."         image

  Implementing all the code in LoadListBox()
  We will now finish implementing "LoadListBox()." Don't type in this code. The next section will help you load your clipboard. Notice a few things here:         q5nkndxa Notes about code
The object WebRequest is how we make RESTful calls
GET is used because we are doing a query
The code is asynchronous as evidensed by AsyncCallback
A List<string> is created from the JSON data using (List<string>)jsonDeserializer.ReadObject(webResponse.GetResponseStream());
We loop through the list of strings and populate the listbox.

  Loading our Clipboard – Using WP7.exe
  Start the previously mentioned "WP7.exe" application. To populate your clipboard with the code for "LoadListBox()", click on "LoadListBox()." Return back to Visual Studio.         image

  Pasting code from the Clipboard – adding code to LoadListBox()
  Highlight the entire method "LoadListBox()," right-mouse click, and select "Paste." Congratulations. We are done. You are ready to compile and run the application.         Explained earlier in the post. Be sure that you put wp7.exe and wp7.xml in the same folder.
Clipboard Loader Software https://brunoblogfiles.com/clipboard/wp7.zip
                 Highlight the entire method "LoadListBox()," right-mouse click, and select "Paste." Congratulations. We are done. You are ready to compile and run the application. image

  Compile our Application
  To compile your application, go to the menu and select "Build / Rebuild Solution." The output window should indicate "O failed." image

  Run our application
  You are ready to run the application in the emulator. Go to the menu system and select "Debug / Start Debugging." image

  MainPage.xaml
 
 <phone:PhoneApplicationPage    x:Class="CloudClient.MainPage"    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"    xmlns:d="https://schemas.microsoft.com/expression/blend/2008"    xmlns:mc="https://schemas.openxmlformats.org/markup-compatibility/2006"    mc:Ignorable="d"    d:DesignWidth="480"    d:DesignHeight="768"    FontFamily="{StaticResource PhoneFontFamilyNormal}"    FontSize="{StaticResource PhoneFontSizeNormal}"    Foreground="{StaticResource PhoneForegroundBrush}"    SupportedOrientations="Portrait"    Orientation="Portrait"    shell:SystemTray.IsVisible="True">    <!--LayoutRoot is the root grid where all page content is placed-->    <Grid        x:Name="LayoutRoot"        Background="Transparent">        <Grid.RowDefinitions>            <RowDefinition                 Height="Auto"/>            <RowDefinition                 Height="*"/>        </Grid.RowDefinitions>        <!--TitlePanel contains the name of the application and page title-->        <StackPanel            x:Name="TitlePanel"            Grid.Row="0"            Margin="12,17,0,28">            <TextBlock                x:Name="ApplicationTitle"                Text="Cloud RESTful Client"                Style="{StaticResource PhoneTextNormalStyle}"/>            <TextBlock                x:Name="PageTitle"                Text="Fast Bikes"                Margin="9,-7,0,0"                Style="{StaticResource PhoneTextTitle1Style}"/>        </StackPanel>        <!--ContentPanel - place additional content here-->        <Grid            x:Name="ContentPanel"            Grid.Row="1"            Margin="12,0,12,0">            <ListBox x:Name="fastBikeListBox"            FontSize="32" />          </Grid>    </Grid>    <!--Sample code showing usage of ApplicationBar-->    <!--<phone:PhoneApplicationPage.ApplicationBar>    <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">    <shell:ApplicationBarIconButton IconUri="/Images/appbar_button1.png" Text="Button 1"/>    <shell:ApplicationBarIconButton IconUri="/Images/appbar_button2.png" Text="Button 2"/>    <shell:ApplicationBar.MenuItems>    <shell:ApplicationBarMenuItem Text="MenuItem 1"/>    <shell:ApplicationBarMenuItem Text="MenuItem 2"/>    </shell:ApplicationBar.MenuItems>    </shell:ApplicationBar>    </phone:PhoneApplicationPage.ApplicationBar>--></phone:PhoneApplicationPage>

  MainPage.xaml.cs
 
 using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Windows;using System.Windows.Controls;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Animation;using System.Windows.Shapes;using Microsoft.Phone.Controls;using System.IO;using System.Threading;using System.Windows.Data;using System.Text;using Microsoft.Phone.Shell;using System.Runtime.Serialization.Json;namespace CloudClient{    public partial class MainPage : PhoneApplicationPage    {        // Constructor        private string _baseServiceAddress =             "https://[**GET THIS FROM THE PORTAL**].cloudapp.net/FastMotorcycleListService.svc";                public MainPage()        {            InitializeComponent();            LoadListBox();        }        private void LoadListBox()        {            string uri = string.Format("{0}/list/{1}", _baseServiceAddress, "Bruno");            var webRequest = (HttpWebRequest)WebRequest.Create(uri);            webRequest.Method = "GET";            try            {                webRequest.BeginGetResponse(new AsyncCallback((result) =>                {                    var webResponse = (HttpWebResponse)webRequest.EndGetResponse(result);                    if (webResponse.StatusCode == HttpStatusCode.OK)                    {                        var jsonDeserializer = new DataContractJsonSerializer(typeof(List<string>));                        List<string> items = (List<string>)jsonDeserializer.ReadObject(                                                                    webResponse.GetResponseStream());                        fastBikeListBox.Dispatcher.BeginInvoke(new Action(() =>                        {                            fastBikeListBox.Items.Clear();                            foreach (var item in items)                            {                                fastBikeListBox.Items.Add(item);                            }                        }));                    }                }), null);            }            catch            { // ignored             }        }    }}