Walkthrough on Creating WCF Data Service (ODATA) and Consuming in Windows 7 Mobile application

Note : Now you can consume ODATA in very simpler way ย updated post can be read ย at below link

https://debugmode.net/2011/06/11/consuming-odata-in-windows-phone-7-1-or-mango-phone/

 

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

clip_image001

Flow Diagram

clip_image002

Step 1: Create WCF Data Service

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

clip_image003

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.

clip_image005

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.

clip_image007

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

clip_image008

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

clip_image009

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

clip_image010

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?

5. 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.

clip_image011

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.

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

clip_image012

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.

clip_image013

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.

clip_image015

3. 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.

clip_image017

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

clip_image018

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 *.

clip_image020

clip_image021

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

clip_image023

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

clip_image024

clip_image025

So, to fetch all the records of entity Students

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

clip_image027

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. Navigate to folder C:\Windows\Microsoft.Net\FrameWork\V4.0. 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.

4. Run the below command in command prompt to create the proxy class

clip_image028

Explanation of command

a. There is space between all /out , /uri and /version

b. We are redirecting the output to D drive and Abc folder. So make sure ABC folder exist in the D drive.

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.

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.

clip_image030

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

clip_image031

clip_image032

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.

clip_image033

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.

clip_image034

clip_image035

Solution

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

1. Download power shell script from http://storage.timheuer.com/wp7ctpfix.ps1

2. Save the power script in the same folder where you have put your DLL.

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

clip_image037

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

clip_image039

2. 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.

clip_image040

3. 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)

clip_image041

4. Create entity class. We have to create StudentEntityclass

clip_image043

5. 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.

clip_image045

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

clip_image046

7. Initializes them inside constructor of MainPage

clip_image048

clip_image049

8. On click event of the button

clip_image051

Here asynchronously we are calling the function DataLoaded

DataLoaded function will look like

clip_image053

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

clip_image001[1]

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&#8221;

xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml&#8221;

xmlns:phoneNavigation=“clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Navigation”

xmlns:d=http://schemas.microsoft.com/expression/blend/2008&#8221;

xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006&#8221;

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

using StudentDBModel;

namespace ConsumingODATA

{

public partial class MainPage : PhoneApplicationPage

{

StudentDBEntities studentEntities = null ;

List<Student> lstStdย  = null ;

List<StudentEntity> lstResultStd = null ;

public MainPage()

{

InitializeComponent();

SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape;

studentEntities = new StudentDBEntities(new Uri (http://b263ltrv:3803/WcfDataService1.svc/&#8221;));

lstResultStd = new List<StudentEntity>();

lstStd = new List<Student>();

myButton.Click += new RoutedEventHandler(myButton_Click);

}

void myButton_Click(object sender, RoutedEventArgs e)

{

var query = studentEntities.CreateQuery<Student>(“Students”);

query.BeginExecute(ar=>

{

GetData(ar);

},query);

}

public void GetData(IAsyncResult result)

{

DataServiceQuery<Student> query = result.AsyncState as DataServiceQuery<Student>;

lstStd = query.EndExecute(result).ToList();

Dispatcher.BeginInvoke(()=>

{

foreach(var r in lstStd)

{

lstResultStd.Add(new StudentEntity{RollNo=r.RollNumber ,

Name = r.Name ,

Subject = r.Subject });

}

this.MyList.DataContext = lstResultStd ;

});

}

}

}

Thanks for reading. I hope, this article was useful. Happy coding.

16 responses to “Walkthrough on Creating WCF Data Service (ODATA) and Consuming in Windows 7 Mobile application”

  1. tq for ur info.. in your article “Walkthrough on Creating WCF Data Service (ODATA) and Consuming in Windows 7 Mobile application” i see MyData Folder in D. refer to command to run> image clip_image037 in ur windows powershell the coding PS D:> cd .\MyData .\wp7ctpfix.ps1 .\System.Data.Services.Client.dll, where MyData Folder. because there no My Data in my D directory. help

  2. im still have problem with powershell script
    when i run the command.\wp7ctpfix.ps1 .\System.Data.Services.Client.dll in windows powershell its say wp7ctpfix.ps1 cannot be loaded because execution script disable in system. i couldn’t understand it. i try by set-executionpolicy unrestricted but i say no names od parameter..please help me.. i’m new beginner in this Windows 7 and still in learning process.. i’m very glad if you willing to help me.. tq

  3. Dhananjay Kumar

    Do you have admin right on the system where you are running the power shell script ? Make sure you have the ADMIN right

  4. im used my own computer…

  5. Dhananjay Kumar

    If you have ADMIN right .. just follow the step by step as I discussed or see the video you would able to do that ๐Ÿ™‚ Thank you ๐Ÿ™‚ else please share me with the screen short of your error

  6. Finally i got it.. its the executionpolicy problem.. dunno why i cann’t run the execution command..so i do it step by step by get-help and explorer it..tq very much i very appreciate it..tq

  7. Dhananjay Kumar

    Glad it is working for you ๐Ÿ™‚

  8. how can i submit my project to you for get more helper? i have done this coding and no error but there are no output.. my mobile application run with blank output…

  9. how can i combine binding text with text to view output like this to this application:

    Name: Hidayah

  10. Hi Dhananjay, thanks for your WP7 instructions. Very inhelpful – I got it up except error below! Its the only error left when doing the BUILD

    environment: W7 Ult 64bit, vs2010 express for wcf service, VS 2010 express for Phone 7

    below code has been generated by the ‘DataSvcUtil.exe’ creating the Wcf service. When building the WP7 application I get below error! Well I can read the error message but have no clue what to do – although I’ve read quite some articles in the forums!?

    Any ideas what I can/should do?
    Thanks for your time
    ed

    error message:
    Inconsistent accessibility: property type ‘System.Data.Services.Client.DataServiceQuery’
    is less accessible than property ‘contactsModel.contactsEntities.address’

    beginning of generated code for the service:
    //——————————————————————————
    //
    // This code was generated by a tool.
    // Runtime Version:4.0.30319.1
    //
    // Changes to this file may cause incorrect behavior and will be lost if
    // the code is regenerated.
    //
    //——————————————————————————

    // Original file name: address.cs
    // Generation date: 23-11-2010 17:24:32
    namespace contactsModel
    {

    ///
    /// There are no comments for contactsEntities in the schema.
    ///
    public partial class contactsEntities : global::System.Data.Services.Client.DataServiceContext
    {
    ///
    /// Initialize a new contactsEntities object.
    ///
    [System.CodeDom.Compiler.GeneratedCodeAttribute(“System.Data.Services.Design”, “1.0.0”)]
    public contactsEntities(global::System.Uri serviceRoot) :
    base(serviceRoot)
    {
    this.OnContextCreated();
    }
    partial void OnContextCreated();
    ///
    /// There are no comments for address in the schema.
    ///
    [System.CodeDom.Compiler.GeneratedCodeAttribute(“System.Data.Services.Design”, “1.0.0”)]
    public global::System.Data.Services.Client.DataServiceQuery address <========= error
    {
    get
    {
    if ((this._address == null))
    {
    this._address = base.CreateQuery(“address”);
    }
    return this._address;
    }
    }
    [System.CodeDom.Compiler.GeneratedCodeAttribute(“System.Data.Services.Design”, “1.0.0”)]
    private global::System.Data.Services.Client.DataServiceQuery _address;
    ///
    /// There are no comments for address in the schema.
    ///
    [System.CodeDom.Compiler.GeneratedCodeAttribute(“System.Data.Services.Design”, “1.0.0”)]
    public void AddToaddress(address address)
    {
    base.AddObject(“address”, address);
    }
    }

    …………. etc etc

  11. Are you using the latest release of the OData Client Libraries. Apparently this example will not work with the final release
    http://blogs.msdn.com/b/astoriateam/archive/2010/10/28/data-services-client-for-win-phone-7-now-available.aspx
    as
    “LINQ support in the client library has been removed as the core support is not yet available on the phone platform. That said, we are actively working to enable this in a future release. Given this, the way to formulate queries is via URIs.”

    Do please add the disclaimer. Although a neat and otherwise helpful example this may take up time of developers trying to implement the newest version and they should rather use the example at
    http://phonetocloud.info/2011/03/03/introducing-the-odata-client-library-for-windows-phone-part-3/

  12. […] the operations from Phone. You can read previous article here In Beta release of Windows Phone 7.1 or Mango phone consuming OData has been improved very […]

  13. Dhananjay Kumar

    Hi Nilav

    Blog post is updated . Thanks for the reply. Please read first two lines of blog post now . ๐Ÿ™‚

  14. Hi Dhananjay,

    The first two lines speak about OData access in Mango. However i had been talking about the latest OData client libraries for the current edition released around October (The RTM version) which accesses data as mentioned in

    http://phonetocloud.info/2011/03/03/introducing-the-odata-client-library-for-windows-phone-part-3/

    If you could also put the same in it would help.

    Thanks

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 )

Connecting to %s

Create a website or blog at WordPress.com