Fetching Data from SQL Azure table in Windows 7.1 [Mango] Phone using WCF Data Service

In this article, we will discuss about how to consume data from cloud [SQL Azure] in a Windows 7.1 [Mango] phone. SQL Azure and Windows 7.1 [Mango] phones are two common terms that you can hear about from many tech-savvy people. So I thought it is the right time to integrate these technologies. In this article, I have tried my best not to focus on the theoretical aspects. Instead, I will present a step-by-step approach on how to consume Data from cloud in a Windows 7 phone application.

What we intend to achieve is given below:

image

 

In this article, we will cover

  1. Migrating local Database to SQL Azure
  2. Creating Data Model on Database in Cloud
  3. Expose Data Model as WCF Data Service
  4. Consumption of Data from cloud in Windows 7.1 or Mango phone through WCF Data Service.

 

The block diagram for the same is given below. We have a School Database on our local (In premise) SQL Server. We will be moving the local school database along with the schema and data to SQL Azure. Then, we will create a Data Model on the school database in the cloud and expose that Data model as WCF Data Service. Once the data from cloud is exposed as WCF Data Service, we will fetch that in the Windows 7.1 phone

 

image

So, actually, there are two major steps involved,

  1. Exposing Data from cloud as WCF Data Service
  2. Consuming WCF Data Service in Windows 7 Phone

 

Creating local Database and migrating to SQL Azure

Creating Database

The first step is to create the database. We are going to use School database. Script of sample School Database copy from here

Generate Database Script for SQL Azure

Right click on School Database and select Tasks. From Tasks, select Generate Script.

 

image

From the Pop up, select Set Scripting option.

image

 

Give the file name by selecting Save to file option.

Now the main thing to be noticed here is that we need to so some change in the advanced setting. For that, click on advanced options.

 

image

 

And in types of data to script, select Script and Data – both options.

image

 

After that, click next and Finish. You can see that a SQL file is created, and we will be using this script to migrate our in-house school database to SQL Azure.

 

Create School Database in SQL Azure

Login the SQL Azure portal with your live credential

https://sql.azure.com/

SQL Azure can be explored by selecting Database option from the left panel.

image

To create School Database, select Data base server and from Database section, select Create option.

image

Provide Database name, Edition and Maximum Size.

image

 

Run the Script in SQL Azure

Open the SQL Server management studio

clip_image001

You will get Connect to server dialog box. Click on cancel.

clip_image002

After cancelling the dialog box, click on New Query (top left corner).

clip_image003

On clicking New Query, the Connect to Server dialog box appears again.

clip_image004

Now, here you need to provide the Server name of SQL Azure and Login credential of SQL Azure

You can get fully qualified server name in Properties tab of SQL Azure portal

image

You will get the server name in form of

abc.database.windows.net

where abc is name of your SQL Azure server. We need to provide this server name at the local SQL server management studio.

image

Make sure to select SQL Server Authentication and provide login user name and password of your SQL Azure database portal.

After that, before clicking Connect, click on Option

image

From Option, select School database.

image

Run the Script

Now once you have successfully connected to School Database in SQL Azure, copy the script and Run as given below.

 

image

 

After successfully run script, run the below command and all the tables name will get listed.

 

clip_image001[6]

In this way, you have successfully migrated database to SQL AZURE Smile

 

Exposing SQL Azure Database as WCF DATA Service

 

Create a Web Application

Create a new project and select ASP.Net Web Application project template from the Web tab. Give a meaningful name to the web application.

image

Create a Data Model

We can create a Data Model, which can be exposed as WCF Data Service in three ways

  1. Using ADO.Net Entity model.
  2. Using LINQ to SQL class.
  3. Custom Data Model.

Here, I am going to use ADO.Net Entity model to create the data model. So to create an entity model, do the following:

  1. Right click on web application and add a new item
  2. Select ADO.Net Entity model from Data tab.

image

3. Since we have table in SQL Azure DataBase, we are going to choose the option Select from database

image

 

4. Choose a new connection.

image

After clicking on New Connection, this is the important step. We need to give extra care here Smile

So provide the information as below,

image

Click on Test Connection to test if the connection established successfully or not? After this, you will get prompted if the Connection string contains sensitive data regarding if you want to keep that in configuration file or mange through program. You can select any one of these options according to what you need.

image

On providing your option, click on Next button; you can see that all the tables, Views, and Stored Procedures’ are available to be chosen as a part of the data model for WCF Data Service.

image

5. Select tables, views and stored procedure from the database you want to make as the part of your data model.

Creating WCF Data Service

  1. Right click on Web Application project and add a new item.
  2. Select WCF Data Service from Web tab. Give any meaningful name. I am leaving the default name here.

image

3. After adding the WCF Data Service, we can see a service file with extension .svc has been added to the solution explorer.

Very first, we need to put data source name. To do so, uncomment the first commented line and put the data source name. In our case, the name of the model which we created in the 2nd step is the data source. Our data model name is SchoolEntities

 

image

 

Now we need to set access rules for the entity or entity set. Since we have only one table; so either we can give name of the table explicitly or if we want to set the same access rule for all the table in the data model or data source, we can put *.

 

image

 

image

 

So we are setting the access rule that, on the entity in data source perform all the operations.

So finally, the svc file will look like

 

image

Run WCF Data Service

Just press F5 to run the WCF Data Service. The Data Service will be hosted in the default ASP.Net server.

On running, you can see all the table is listed there.

clip_image002

Append the URL with People and you will get all the records from People table

clip_image004

Note: If your browser is not showing the expected result, make sure that the Feed reading of the browser is off. To do so, from the menu of IE, select Tools-> Internet Options -> Content

clip_image005

clip_image006

So we have exposed data from cloud using WCF Data service. Now any OADTA client can consume the data from cloud by consuming WCF Data Service.  Smile

 

Consuming WCF Data Service in Windows 7 Phone

First, we need to do is to create proxy of WCF Data service for Windows 7 phone. So to do this,

  1. Open command prompt in administrator mode.
  2. Navigate to folder C:\Windows\Microsoft.Net\FrameWork\V4.0.30319 Version of framework may vary depending on .Net framework you are working on.
  3. Once navigated to this particular folder, run the below command to create proxy class. We will add this proxy class in Windows 7 mobile application.

 

image

Explanation of command

  • There is space between all /out, /uri and /version
  • We are redirecting the output to D drive and Temp folder. So make sure that the Temp folder exists in the D drive.
  • School.cs is name of proxy class. You can give any name of your choice here. Once the command runs successfully, you will get School.cs class in Temp folder of D drive.
  •  After uri tag, give the uri of WCF data service.

 

Now after the execution of this command, we will have School.cs in Temp folder of D Drive.  Smile

Download the ODATA client library for Windows 7 phone from the below link and save the dll on local drive. We will add this DLL in Windows 7 phone application.

Download OData client library for Windows 7 Phone from here

Create a windows 7.1 phone application. Open Visual Studio and select the Windows phone Application project template from Silverlight for Windows Phone tab.

 

image

Choose  Windows Phone 7.1

image

Right click on the project and add existing item. Then navigate to Temp folder where you have created the WCF Data Service proxy class. In our case, it is School.cs. We created this in the previous step.

clip_image001[8]

Now we need to add ODATA client library reference in the Windows 7 Phone application. Right click on the project and add reference. Navigate to the folder where you saved System.Data.Service.Clientdll

clip_image002[5]

Display Data from Person Table in Windows 7 Phone application

We are going to display records of Person table in the list box. So first, let us create an entity class at client side. Right click and add a class called Person

Person.cs

 



namespace PhoneClient
{
    public class Person
    {

        public string PersonID { get; set; }
        public string LastName { get; set; }
        public string FirstName { get; set; }


    }
}

 

Create a list box and we will bind the data in this list box. On click event of the Button, Data will get bound to the list box.

In below XAML ,

  1. We are creating a Button . On click event of Button , Data would be fetched from SQL Azure table.
  2. In List Box , we are binding the returned result

 

MainPage.xaml

 



<phone:PhoneApplicationPage
    x:Class="PhoneClient.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">

    <!--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="Mango with SQL Azure" Style="{StaticResource PhoneTextNormalStyle}"/>

            <Button x:Name="btnGetData" Height="100" Width="449" Content="Get Data From SQL Azure Table" Background=" blue" />
        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">

            <ListBox x:Name="lstDataFromCloud"
                 ItemsSource="{Binding}" >
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal" >
                            <TextBlock Text="{Binding PersonID}" Margin="20" />
                            <TextBlock Text="{Binding LastName}" Margin="20" />
                            <TextBlock Text="{Binding FirstName }" Margin="20" />
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>


        </Grid>
    </Grid>



</phone:PhoneApplicationPage>


 

 

Now on click event of the button, we need to call the WCF Data Service and bind the list box . We are making an asynchronous call here .

MainPage.xaml.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using Microsoft.Phone.Controls;
using System.Data.Services.Client;
using SchoolModel;


namespace PhoneClient
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        SchoolEntities schoolEntity;
        List<Person> lstPersonClient;
        List<SchoolModel.Person> lstpersonWcf;


        public MainPage()
        {
            InitializeComponent();
            schoolEntity = new SchoolEntities(new Uri("http://localhost:27274/WcfDataService1.svc/"));
            btnGetData.Click += new RoutedEventHandler(btnGetData_Click);

            lstPersonClient = new List<Person>();
            lstpersonWcf = new List<SchoolModel.Person>();

        }

        void btnGetData_Click(object sender, RoutedEventArgs e)
        {

            MessageBox.Show("Hi");

            var query = schoolEntity.CreateQuery<SchoolModel.Person>("People");
            query.BeginExecute(ar =>
            {
                DataLoad(ar);
            }, query);

        }

                private void DataLoad(IAsyncResult result)
        {
            DataServiceQuery<SchoolModel.Person> query = result.AsyncState as DataServiceQuery<SchoolModel.Person>;
            lstpersonWcf = query.EndExecute(result).ToList();
            Dispatcher.BeginInvoke(() =>
                   {
                       foreach (var r in lstpersonWcf)
                       {
                           lstPersonClient.Add(new Person {PersonID = r.PersonID.ToString() , LastName= r.LastName , FirstName = r.FirstName});
                       }
                       this.lstDataFromCloud.DataContext = lstPersonClient ;
                   }


                );
        }
    }
}




 

On running you should get output as below,  Smile

image

 

If this post was useful to you then buy me a coffee Smile .  Thanks for reading.

 

 

9 responses to “Fetching Data from SQL Azure table in Windows 7.1 [Mango] Phone using WCF Data Service”

  1. […] Fetching Data from SQL Azure table in Windows 7.1 [Mango] Phone using WCF Data Service (Dhananjay Kumar) […]

  2. […] See the original article here: Fetching Data from SQL Azure table in Windows 7.1 [Mango] Phone … […]

  3. Thats good one DJ… Lets catch up in CP again…. for coffee or for a beer ;)…

  4. Dhananjay Kumar

    Thanks Suchit …. and this time we will have beer not in CP .. we will go to Himalya 🙂

  5. Very useful! but how can i get the database value with image data type on the windows phone 7?

  6. […] Fetching Data from SQL Azure table in Windows 7.1 [Mango] Phone using WCF Data Service […]

  7. This is very helpful article. You made it really amazing, thanks for sharing this article with us. Here I’m posting some articles link too which having nice explanation on Using Table Service Data Model in windows azure……
    http://msdn.microsoft.com/en-us/library/windowsazure/gg432983.aspx

    http://www.mindstick.com/Articles/6e66e9a3-bc7e-4880-8eeb-e7afa7a32144/?Using%20Table%20Service%20Data%20Model%20in%20Windows%20Azure

    http://msdn.microsoft.com/en-us/library/windowsazure/dd179338.aspx

    Thanks Everyone for precious post!!

  8. Hi dude i know the post is old but I’m new to WPF development, so i was wondering if the azure cloud database is free, thanx in advance

Leave a comment

Create a website or blog at WordPress.com