Authentication on WCF Data Service or OData: Windows Authentication Part#1

In this article, I am going to show how to enable windows authentication on WCF Data Service.

Follow the below steps

Step 1

Create WCF Data Service.

Read below how to create WCF Data Service and introduction to OData.

http://dhananjaykumar.net/2010/06/13/introduction-to-wcf-data-service-and-odata/

While creating data model to be exposed as WCF Data Service, we need to take care of only one thing that Data model should be created as SQL Login

So while creating data connection for data model connect to data base through SQL Login.

Step 2

Host WCF Data Service in IIS. WCF Data Service can be hosted in exactly the same way a WCF Service can be hosted.

Read below how to host WCF 4.0 service in IIS 7.5

http://dhananjaykumar.net/2010/09/07/walkthrough-on-creating-wcf-4-0-service-and-hosting-in-iis-7-5/

Step 3

Now we need to configure WCF Service hosted in IIS for Windows authentication.

Here I have hosted WCF Data Service in WcfDataService IIS web site.

Select WcfDataService and in IIS category you can see Authentication tab.

On clicking on Authentication tab, you can see various authentication options.

Enable Windows authentication and disable all other authentication

To enable or disable a particular option just click on that and at left top you can see the option to toggle

Now by completing this step you have enabled the Windows authentication on WCF Data Service hosted in IIS.

Passing credential from .Net Client

If client windows domain is having access to server then

If client is not running in windows domain which is having access to server then credential we need to pass the as below,

So to fetch all the records

Program.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Services.Client;
using ConsoleApplication1.ServiceReference1;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            NorthwindEntities1 entity = new NorthwindEntities1
                                       (new Uri("http://localhost:7890/wcfdataservice1.svc/"));
            entity.Credentials = System.Net.CredentialCache.DefaultCredentials;
            entity.Credentials = new System.Net.NetworkCredential("UserName", "Password", "Domian");
            try
            {

                var result = from r in entity.Products select r;
                foreach (var r in result)
                {
                    Console.WriteLine(r.ProductName);
                }
            }
            catch (DataServiceQueryException ex)
            {
                Console.WriteLine(ex.StackTrace);
            }




        }


    }
}



In above article we saw how to enable Windows authentication on WCF Data Service and then how to consume from .Net client. In next article we will see how to consume Windows authenticated WCF Data Service from SilverLight client.

Expand and Load: Fetching related entities in WCF Data Service

Objective

In this post, I will show you how to retrieve data from related entities in WCF Data Service.

If you are new to this topic, please read Introduction to WCF Data service and ODATA before going through below article

Let us say, we want to fetch details from related entities Customers and Order.

clip_image001

There are two ways to fetch data from both related entities.

1. Expand

2. LoadProperty

Using LoadProperty

Program.cs

  NorthwindEntities context = new NorthwindEntities(new Uri("http://localhost:61091/WcfDataService1.svc/"));
                try
                {
                    foreach (Order o in context.Orders)
                    {
                        context.LoadProperty(o, "Customer");
                        Console.WriteLine("Customer : {0}- Order Id: {1}", o.Customer.ContactName, o.OrderID);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                Console.Read();
            }

In above code clip_image003 So in above code load property is being used to load data from related entities. Output clip_image005 Using Expand Program.cs

 DataServiceQuery<Order> query =
                context.Orders.Expand("Order_Details,Customer");
            try
            {
                foreach (Order order in query.Take(4))
                {
                    Console.WriteLine("Customer: {0}", order.Customer.ContactName);
                    Console.WriteLine("Order ID: {0}", order.OrderID);
                    foreach (Order_Detail item in order.Order_Details)
                    {
                        Console.WriteLine("\tProduct: {0} - Quantity: {1}",
                            item.ProductID, item.Quantity);
                    }
                }
            }
            catch (DataServiceQueryException ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.Read();

So in above code

clip_image007

In above code Orders relation is expanded to Order_detail and Customer.

clip_image009

In above code retrieving top 4th record and iterating through the records to display.

Output

clip_image011

WebException or Remote server name could not be resolved in WCF Data Service

Objective

This article will give a brief explanation on how to handle remote server name could not resolved exception in WCF Data Service

If you are new to this topic, please read Introduction to WCF Data service and ODATA before going through below article

Let us say, there is a WCF Data Service up and running on a particular server. We access that using below code at the client side

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Services.Client;
using ConsoleApplication1.ServiceReference1;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            DataServiceContext context = new DataServiceContext(
                                         new Uri("http://localhost:61091/WcfDataService1.svc/"));
            DataServiceQuery<Employee> query = context.CreateQuery<Employee>("Employees");
                foreach (Employee e in query)
                {
                    Console.WriteLine(e.FirstName);
                }
            Console.Read();
        }
    }
}

And output is as below,

clip_image002

Every this is fine till this point. Now let us go ahead and modify the WCF Data Service URL to a false URL

clip_image004

And URL, I am giving is false one. Server abc does not exist. Now after modification code will look like

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Services.Client;
using ConsoleApplication1.ServiceReference1;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            DataServiceContext context = new DataServiceContext(
                                         new Uri("http://abc:61091/WcfDataService1.svc/"));
            DataServiceQuery<Employee> query = context.CreateQuery<Employee>("Employees");
                foreach (Employee e in query)
                {
                    Console.WriteLine(e.FirstName);
                }
            Console.Read();
        }
    }
}

And when you try to run, you will get the run time exception as below,

clip_image005

Now to handle this exception put the foreach statement in try catch , so no modified code will look like

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Services.Client;
using ConsoleApplication1.ServiceReference1;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            DataServiceContext context = new DataServiceContext(
                                         new Uri("http://abc:61091/WcfDataService1.svc/"));
            DataServiceQuery<Employee> query = context.CreateQuery<Employee>("Employees");
            try
            {
                foreach (Employee e in query)
                {
                    Console.WriteLine(e.FirstName);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.Read();
        }
    }
}

And now running output will be as below,

clip_image007

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.

Video on consuming WCF Data Service (OData) in Windows 7 Phone Application

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>

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.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/"));

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 ;

});

}

}

}

StudentEntity.cs

using System;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Ink;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

namespace ConsumingODATA

{

public class StudentEntity

{

public string RollNo { get; set; }

public string Name { get; set; }

public string Subject { get; set; }

}

}

Student.cs

//------------------------------------------------------------------------------

// <auto-generated>

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

// </auto-generated>

//------------------------------------------------------------------------------

// Original file name: Student.cs

// Generation date: 7/5/2010 6:06:44 PM

namespace StudentDBModel

{

/// <summary>

/// There are no comments for StudentDBEntities in the schema.

/// </summary>

public partial class StudentDBEntities : global::System.Data.Services.Client.DataServiceContext

{

/// <summary>

/// Initialize a new StudentDBEntities object.

/// </summary>

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]

public StudentDBEntities(global::System.Uri serviceRoot) :

base(serviceRoot)

{

this.OnContextCreated();

}

partial void OnContextCreated();

/// <summary>

/// There are no comments for Students in the schema.

/// </summary>

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]

public global::System.Data.Services.Client.DataServiceQuery<Student> Students

{

get

{

if ((this._Students == null))

{

this._Students = base.CreateQuery<Student>("Students");

}

return this._Students;

}

}

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]

private global::System.Data.Services.Client.DataServiceQuery<Student> _Students;

/// <summary>

/// There are no comments for Students in the schema.

/// </summary>

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]

public void AddToStudents(Student student)

{

base.AddObject("Students", student);

}

}

/// <summary>

/// There are no comments for StudentDBModel.Student in the schema.

/// </summary>

/// <KeyProperties>

/// RollNumber

/// </KeyProperties>

[global::System.Data.Services.Common.DataServiceKeyAttribute("RollNumber")]

public partial class Student

{

/// <summary>

/// Create a new Student object.

/// </summary>

/// <param name="rollNumber">Initial value of RollNumber.</param>

/// <param name="name">Initial value of Name.</param>

/// <param name="subject">Initial value of Subject.</param>

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]

public static Student CreateStudent(string rollNumber, string name, string subject)

{

Student student = new Student();

student.RollNumber = rollNumber;

student.Name = name;

student.Subject = subject;

return student;

}

/// <summary>

/// There are no comments for Property RollNumber in the schema.

/// </summary>

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]

public string RollNumber

{

get

{

return this._RollNumber;

}

set

{

this.OnRollNumberChanging(value);

this._RollNumber = value;

this.OnRollNumberChanged();

}

}

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]

private string _RollNumber;

partial void OnRollNumberChanging(string value);

partial void OnRollNumberChanged();

/// <summary>

/// There are no comments for Property Name in the schema.

/// </summary>

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]

public string Name

{

get

{

return this._Name;

}

set

{

this.OnNameChanging(value);

this._Name = value;

this.OnNameChanged();

}

}

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]

private string _Name;

partial void OnNameChanging(string value);

partial void OnNameChanged();

/// <summary>

/// There are no comments for Property Subject in the schema.

/// </summary>

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]

public string Subject

{

get

{

return this._Subject;

}

set

{

this.OnSubjectChanging(value);

this._Subject = value;

this.OnSubjectChanged();

}

}

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]

private string _Subject;

partial void OnSubjectChanging(string value);

partial void OnSubjectChanged();

}

}

Fixing of ODATA or WCF Data Service Client library bug 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 on this article

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_image001

clip_image002

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_image003

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_image004

clip_image005

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_image007

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. Thanks for reading. I hope, this post was useful. Happy Coding.

Server side paging in WCF Data Service

Objective

In this article, I will show you, how we can achieve server side paging in WCF Data service?

Note: IF you are new to WCF Data Service, please read my other articles on WCF Data Service.

PPT on WCF Data Service

Introduction to WCF Data Service

Here, I am assuming that, you have basic understanding of WCF Data service. So I will start with the code in .svc file or service file.

WcfDataService.svc.cs

clip_image002

If we see in above code, we are setting the access rule for all the entity in the model to allow only the read operation.

How to enable paging at server side?

To enable paging at server side, we need to set the page the entity page size and also we need to explicitly set the version of the protocol to V2.

clip_image004

clip_image006

We are telling here that return only one record for all the entities .

WcfDataService.svc.cs

using System;

using System.Collections.Generic;

using System.Data.Services;

using System.Data.Services.Common;

using System.Linq;

using System.ServiceModel.Web;

using System.Web;

namespace PagingSample

{

public class WcfDataService1 : DataService<StudentDBEntities >

{

public static void InitializeService(DataServiceConfiguration config)

{

config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);

config.SetEntitySetPageSize("*", 1);

config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;

}

}

}

Now when, we run the service, we can see

clip_image008

When, we navigate to Students table, we get the above result.

clip_image010

If , we notice above result , we can see , a link that will be used to navigate to next records.

clip_image012

How to fetch paged data at client side?

If we fetch the data at the client side in normal way as below,

clip_image014

Output, you will get name of only first student, because page size at server side is set to 1 .

clip_image016

So, if we want to get all the record through paging, we need to use Continuation property of DataServiceCollection.

clip_image018

So, above code will load the DataServiceCollection with all the data from the service. And then we can use normal foreach statement to print all the records

Programs.cs



using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Data.Services.Client;

using ConsoleApplication1.ServiceReference1;

namespace ConsoleApplication1

{

class Program

{

static void Main(string[] args)

{

StudentDBEntities ent = new StudentDBEntities(new Uri("http://localhost:11518/WcfDataService1.svc/"));

DataServiceCollection<Student> students = new DataServiceCollection<Student>(ent.Students);

while (students.Continuation != null)

{

students.Load(ent.Execute<Student>(students.Continuation));

}

foreach (var r in students)

{

Console.WriteLine(r.Name);

}

Console.Read();

}

}

}

When you run output would be as below,

clip_image020

So, this was all about how to enable server side paging in WCF Data Service. Thanks for reading. I hope article was useful. Happy Coding.