Data From Cloud on Windows Phone



"Data from cloud on the phone" might seem to be a buzzword sentence to you. In this article, I try to minimize the complexity of accessing data from a cloud to be specific from SQL Azure in Windows Phone. In this article I will walk-through step by step accessing data from SQL Azure in Windows Phone.

cldWinPhn1.jpg

I have divided the task into three parts.

cldWinPhn2.jpg

We will expose all the operations on a Student database residing in SQL Azure as WCF REST Service. In this case REST is working on JSON data.

Setting up project

For the very first let us set up the project. We want to expose an operation as a WCF Service hosted in Windows Azure. So to do that, you need to create WCF Service Role.

cldWinPhn3.jpg

Creating Data Model

We are going to create a DataModel using LINQ to SQL Class. To create DataModel, right-click on the project then select add new item and choose LINQ to SQL Class form Data tab.

cldWinPhn4.jpg

Next you need to choose the option Server explorer and add a new connection. In Add new connection windows provide database information for SQL Azure.

cldWinPhn5.jpg

From the drop down you choose the database of your choice. In this case I am going to select Student database. After selecting database on the designer, I am dragging and dropping table Person. On the designer (dbml) you should have Person class. As of now we have created the DataModel. In the Solution Explorer you will find that the dbml and dbml.cs files have been created.

Creating Service

A Data Transfer Object class represents an entity from Data Model we want to expose as part of service contract. We need to create a Data Transfer Object class. This class will act as Data Contract between Service and Client. To add a Data Transfer Object class go ahead and add a new class to the project as shown below.
 
PersonDTO.cs

using System.Runtime.Serialization;

namespace RESTJSONStudentsData
{
   [DataContract]
    public class PersonDTO
    {
       [DataMember]
       public string StudentId { get; set; }
       [DataMember]
       public string FirstName { get; set; }
       [DataMember]
       public string LastName { get; set; }
 
    }
}


We have created a Data Contract. Now we need to create a Service Contract. A Service Contract must be attributed to behave as WCF REST Service. I have set request and response format as JSON.

IService1.cs

using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Web;
 
namespace RESTJSONStudentsData
{   
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebGet(UriTemplate="/Persons",
            RequestFormat=WebMessageFormat.Json,
            ResponseFormat=WebMessageFormat.Json]
        List<PersonDTO> GetPersons();      
    }  
}


Now we need to implement the service. In the service implementation, I am querying the Person table of the Student database using LINQ and constructing List of PersonDTO.

Service1.svc.cs

using System.Collections.Generic; using System.Linq;   namespace RESTJSONStudentsData
{      
   public class Service1 : IService1     
   {         
      public List<PersonDTO> GetPersons()         
      {             
            DataClasses1DataContext context = new DataClasses1DataContext();            
            List<PersonDTO> result = (from r in context.Persons  select new PersonDTO{FirstName = r.FirstName, LastName = r.LastName, StudentId = r.PersonID.ToString()}).ToList<PersonDTO>(); 
            return result;           
      }     
   }
}


Next in this section we need to configure the service. We need to configure service webHttpBinding to eanble it as REST Service. So in Web.Config we need to do the following changes.

Web.Config

<system.serviceModel>


      <behaviors>
        <
serviceBehaviors>
          <
behavior name ="servicebehavior">
            <serviceMetadata httpGetEnabled="true"/>
            <serviceDebug includeExceptionDetailInFaults="false"/>
          </behavior>
        </
serviceBehaviors>
        <
endpointBehaviors>
          <
behavior name="restbehavior">
            <webHttp/>
          </
behavior>
        </
endpointBehaviors>
      </
behaviors>
    <
services>
      <
service name ="RESTJSONStudentsData.Service1" behaviorConfiguration="servicebehavior" >
        <endpoint name ="RESTEndPoint"
                  contract ="RESTJSONStudentsData.IService1"
                  binding ="webHttpBinding"
                  address ="rest"
                  behaviorConfiguration ="restbehavior"/>

      </service>
    </
services>
 
      <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>

After configuring, the service ready for hosting. We need to host it in the Windows Azure Portal. For that, right-click on the Windows Azure project and select Package
and Upload this package to one of the hosted services. Up to this step we have created and hosted WCF REST Service returning JSON.

Consuming Service in Windows Phone

To consume REST Service in Windows Phone 7 and then parse JSON, you need to add following references in Windows Phone 7 project.

cldWinPhn6.jpg

We need a class to represent PersonDTO class. For that make a class called Person at client side.

Person.cs

namespace PhoneApp11
{
    public class Person
    {       
        public string StudentId { getset; }   
        public string FirstName { getset; }      
        public string LastName { getset; }
 
    }
}


For the design of the page I am using a ListBox. Data returned from cloud table will be bound to this ListBox.

MainPage.xaml

<phone:PhoneApplicationPage 
    x:Class="PhoneApp11.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://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="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://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"
    Loaded="PhoneApplicationPage_Loaded">

    <!--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="data from SQL Azure" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="students" 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="lstPerson" >
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Vertical">
                            <TextBlock Text="{Binding LastName}" Style="{StaticResource PhoneTextTitle1Style}" />
                            <StackPanel Orientation="Horizontal">
                                <TextBlock Text="{Binding StudentId}" Style="{StaticResource PhoneTextGroupHeaderStyle}" />
                                <TextBlock Text="{Binding FirstName}" Style="{StaticResource PhoneTextTitle2Style}" />                                
                            </StackPanel>
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

        </Grid>
    </Grid>

</phone:PhoneApplicationPage
>


We need to make a call to the service and on download of JSON data as string, we need to parse the JSON using System.RunTime.Serlization.JSON

MainPage.xaml.cs

using System;
using System.Collections.Generic;
using System.Net;
using System.Windows;
using Microsoft.Phone.Controls;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
 
namespace PhoneApp11
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }
 
        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
 
 
            WebClient proxy = new WebClient();
            proxy.DownloadStringCompleted +=
                       new DownloadStringCompletedEventHandler(proxy_DownloadStringCompleted);
            proxy.DownloadStringAsync(new Uri("http://debugmodesqlazurejson.cloudapp.net/Service1.svc/rest/Persons"));
 
 
        }
 
        void proxy_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            Stream stream = new MemoryStream(Encoding.Unicode.GetBytes(e.Result));
            DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(List<Person>));
            List<Person> result = (List < Person >) obj.ReadObject(stream);
            lstPerson.ItemsSource = result;
        } 
    }
}


In code shown above we are creating a DataContractJsonSerializer object and passing a List of Person to deseriliaze because the service is returning a list of PersonDTO.

And as mentioned earlier the Person class is representing PersonDTO class. Now go ahead and press F5 to run the application. You should be getting details of Person table from School database residing on SQL Azure.

cldWinPhn7.jpg

In a subsequent article we will explore further to perform other CRUD operations. I hope this article is useful. Thanks for reading.

Up Next
    Ebook Download
    View all
    Learn
    View all