SQLAuthority News – Guest Post – Walkthrough on Creating WCF Data Service (ODATA) and Consuming in Windows 7 Mobile application

This is guest post by one of my very good friends and .NET MVP, Dhananjay Kumar. The very first impression one gets when they meet him is his politeness. He is an extremely nice person, but has superlative knowledge in .NET and is truly helpful to all of us.

Objective

In this article, I will discuss

  1. How to create WCF Data Service
  2. How to remove digital signature on System.Data.Service.Client and add in Windows7 phone application.
  3. Consume in Windows 7 phone application and display data.

You can see three video here:

Creating WCF Data Service: http://dhananjaykumar.net/2010/06/08/wcfdataservicevideo/

Fixing the Bug of OData Client library for Windows7 Phone: http://dhananjaykumar.net/2010/07/01/videofixingodataclientlibraryissue/

Consuming WCF Data Service in Windows7 Phone: http://dhananjaykumar.net/2010/07/06/videodatainw7phone/

Expected Output

Flow Diagram


Step 1: Create WCF Data Service

Let us say, we have a table called Student of below structure below in our data base

In Student table RollNumber is a primary key.

Let us create WCF Data Service which will expose the above table as REST service

Create a Web Application

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

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.

For our purpose, I am going to use ADO.Net Entity model to create the data model. So to create an entity model

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

  1. Since we have table in data base. So we are going to choose option, select from database.

  1. Either choose the data base from drop down or create a new data connection.


In above connection string StudentDBEntities is name of the connection string. If we want, we can change this connection string as per our requirement.

If your required data base is not listed in drop down then, you can create a new data connection. To create new data connection click on New Connection

You can give the data base server name and press refresh. After pressing Refresh, you can choose the data base from the drop down. After selecting the data base click on Test Connection to test connection established successfully or not?

  1. Select tables, views and stored procedure from data base you want to make as the part of your data model. Since we are having only one table so we are selecting one table.


If you want you can change name of the data model. By default it is name of the data base appended by the term model. Click on Finish button to complete and create the data model.

  1. Now we can see that StudentDataModel.edmx has been created in the designer.


Since there is only one table, so there is only one table model at design surface.

Now we have created the data model which can be exposed as WCF Data Service. Now you can see in solution explorer, you have StudentModel.edmx and StdentModel.Designer.cs files.

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.

  1. After adding the WCF Data Service, we can see a service file with extension .svc has been added to the solution explorer. When we click on .svc.cs file, we can see the code generated for us.


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 name of the model, which we created in 2nd step is the data source. Our data source name is StudentDBEntities

Now we need to set access rules for 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 could put *.

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

Run the WCF Data Service

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

On running you can see, one table is listed. That table is Student

The above is the data in ATOM message format.

Note: If your browser is not showing the expected result, make sure Feed reading of browser is off. To do from menu of IE and select tool and then Internet Option then Content


So, to fetch all the records of entity Students

http://b263ltrv:3803/WcfDataService1.svc/Students

Step 2: Create Proxy of WCF Data Service

Download the ODATA client library for Windows 7 phone from below link and save the dll somewhere.

http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=b251b247-70ca-4887-bab6-dccdec192f8d

  1. Open command prompt in administrator mode.
  2. 2. Navigate to folder C:\Windows\Microsoft.Net\FrameWork\V4.0. Version of framework may vary depending on .Net framework, you are working on.
  3. 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.
  4. 4. Run the below command in command prompt to create the proxy class

C:\Windows\Microsoft.Net\FrameWork\V4.0.30319> DataSvcUtil.exe /out:D:\Abc\Students.cs /uri: http://b263ltrv:3803/WcfDataService1.svc/Students /verison:2.0

Explanation of command

  1. a. There is space between all /out , /uri and /version
  2. b. We are redirecting the output to D drive and Abc folder. So make sure ABC folder exist in the D drive.
  3. c. Student.cs is name of proxy class. You can give any name of your choice here. Once command will run successfully, you will get Student.cs class in ABC folder of D drive.
  4. d. After uri tag give the uri of wcf data service, which you created in previous step.

So, after successful execution of this command, you will get below message in command prompt.

Once you navigate to D drive and ABC folder, you will see Student.cs file there. Make sure the path you are giving in OUT parameter, that folder exists and you will get your proxy class in that particular folder.

Step 3: Removing digital signature from ODATA Client library for Windows7 phone

Note: I would like to thank Tim for his solution and this article has been referred to his this http://timh.me/bAfFvh

You can see video for this step

http://dhananjaykumar.net/2010/07/01/videofixingodataclientlibraryissue/

Background

When you download ODATA or WCF Data Service client library for Windows 7 phone and extract the System.Data.Service.Client.dll to some location and add this reference to your project. After adding this reference, when you run your application in emulator, you get DEPLOYEMNT FAILED error. This article, will explain how to fix this bug and continue using WCF Data Service client library for Windows 7 phone application.

Assumption

I have assumed here that you have downloaded, ODATA or WCF Data Service client library for Windows 7 phone from below line

http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=b251b247-70ca-4887-bab6-dccdec192f8d

After download from here, run this, you will get the below screens


Extract the dll in a particular directory. Let us say you are extracting that in D:\DemoFolder. So, in this folder, you will have below three files.

So, here you are having System.Data.Service.Client.dll library. You need to add this as reference in your Windows7 Phone application to Consume WCF Data Service.

Working

Now when you add this reference in your windows7 phone application and try to run the application, you will find you are not getting any compile time error but your application is not loading. You may get below error message. You will get deployment error message.


Solution

To solve this deployment error, you need to follow below steps

  1. 1. Download power shell script from http://storage.timheuer.com/wp7ctpfix.ps1
  2. 2. Save the power script in the same folder where you have put your DLL.
  3. 3. Open the power script window, and run the script. see the video here

Command to be run

  1. Navigate to folder, where you copied and pasted ODATA client library DLL and Power shell script, you downloaded in previous step.
  2. Once you navigate to folder, you will able to see power scrip file you downloaded in previous steps.

Now just run the below command

.\wp7ctpfix.ps1 .\System.Data.Services.Client.dll

Now a new dll will get created in the same folder. Add this dll in your Windows7 phone application and you would be able to use the client library

Step 4: Consume Service in Windows 7 phone

  1. Create a new Windows Phone Application

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

  1. Right click on the project and add reference. Navigate to folder where you saved System.Data.Service.Client dll after removing the digital signature. (See the step 3)

  1. Create entity class. We have to create StudentEntityclass

  1. Design the phone page. There will be a button and a list box. We are binding the list box with StudentEntity class, we created in previous step.

  1. Declare the global variables. And make sure you have added the namespace System.Data.Service.Client

  1. Initializes them inside constructor of MainPage

Since Emulator of Windows7 phone is a virtual machine , so when you give http://localhost:3803/WcfDataService1.svc/Students as WCF Data Service URI , Windows7 phone emulator would not able to resolve localhost. So you need to give full uri with machine name http://b263ltrv:3803/WcfDataService1.svc/Students

  1. On click event of the button


Here asynchronously we are calling the function DataLoaded

DataLoaded function will look like

Here, making the List<StudentEntity > as data context for the ListBox.

So when you run the Windows 7 phone application in emulator, you will get below output

For Reference full source code is as below,


MainPage.Xaml
<phoneNavigation:PhoneApplicationPage
    x:Class="ConsumingODATA.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phoneNavigation="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Navigation"
    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="800"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}">

    <Grid x:Name="LayoutRoot" Background="{StaticResource PhoneBackgroundBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!--TitleGrid is the name of the application and page title-->
        <Grid x:Name="TitleGrid" Grid.Row="0">
            <TextBlock Text="Windows 7 Phone" x:Name="textBlockPageTitle" Style="{StaticResource PhoneTextPageTitle1Style}"/>
            <TextBlock Text="ODATA" x:Name="textBlockListTitle" Style="{StaticResource PhoneTextPageTitle2Style}"/>
        </Grid>

        <!--ContentGrid is empty. Place new content here-->
        <Grid x:Name="ContentGrid" Grid.Row="1">
            <Grid.RowDefinitions>
                <RowDefinition Height="*" />
                <RowDefinition Height="4*" />
            </Grid.RowDefinitions>
            <Button x:Name="myButton" Height="100" Content="Get Data"  Grid.Row="0" Background="Azure"
                    Foreground="Black"/>
            <ListBox Grid.Row="1" x:Name="MyList"
                     ItemsSource="{Binding}" Height="458"
                     HorizontalAlignment="Left" Margin="20,39,0,0"  VerticalAlignment="Top" Width="435"  >
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal" >
                            <TextBlock Text="{Binding RollNo}" Foreground="Red" Margin="20" />
                            <TextBlock Text="{Binding Name}" Margin="20" />
                            <TextBlock Text="{Binding Subject}" Margin="20"  />
                            
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </Grid>
    </Grid>
    
</phoneNavigation:PhoneApplicationPage>

MainePage.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 StudentDBModel;
using System.Data.Services.Client; 

namespace ConsumingODATA
{
    public partial class MainPage : PhoneApplicationPage
    {
        StudentDBEntities studentEntities = null;      
        List<Student> lstStd = null;
        List<StudentEntity> lstResult = null;
       

        public MainPage()
        {
            InitializeComponent();
            studentEntities = new StudentDBEntities(new Uri("http://b263ltrv:3803/WcfDataService1.svc/"));
            lstStd = new List<Student>();
            lstResult = new List<StudentEntity>();
            SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape;
            myButton.Click += new RoutedEventHandler(myButton_Click);
        }

        void myButton_Click(object sender, RoutedEventArgs e)
        {

            var query = studentEntities.CreateQuery<Student>("Students");
            query.BeginExecute(ar =>
                {
                 DataLoaded(ar);

                }, query);
          
        }

        private void  DataLoaded(IAsyncResult result)
        {
            DataServiceQuery<Student> query = result.AsyncState as DataServiceQuery<Student>;
           lstStd = query.EndExecute(result).ToList();

           Dispatcher.BeginInvoke(() =>
             {

                 foreach (var r in lstStd)
                 {
                     lstResult.Add(new StudentEntity{RollNo = r.RollNumber ,
                         Name = r.Name ,
                         Subject= r.Subject });
                 }
                 this.MyList.DataContext = lstResult;
             });              
        }
    }
}

Hope you have enjoyed this article regarding Win Mobile 7 and WCF.

Reference: Pinal Dave (http://blog.sqlauthority.com)

About these ads

3 thoughts on “SQLAuthority News – Guest Post – Walkthrough on Creating WCF Data Service (ODATA) and Consuming in Windows 7 Mobile application

  1. Hi Pinal/Dhananjay,

    It was nice and happy that I could attend your sessions at ahamedabad. Even though I am more into in SQL I did listen and made some notes about Dhananjay’s WCF session. And I could meet only Dhananjay that day, but not Pinal or Jacob. Both were surrounded by questions and people after the session. I could get a moment to meet Dhanjay and say a “Hi”.

    I thought Dhananjay is from Kerala, because 2-3 times Pinal mentioned that he came from “Thrvanthram” (Thiru-Anantha-Puram) :)).

    Anyway, Pinal/Dhananjay/Jacob, It was great. Looking for another session to attend soon.

    Like

  2. Dear Sir,

    When I write command like show above in Microsoft PowerShell, it show that “wp7ctpfix.ps1 cannot be loaded because running script is disabled in this system.”.
    I’m already download wp7ctpfix.ps1.

    Your Sincerely
    Thanks,

    Deab Sina

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s