How to create first Windows 7 mobile Application Video

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.

Creating WCF Data Service from scratch and Hosting in Console Application

Objective

In this article, I will show how

1. WCF Service can be created from the scratch

2. WCF Service can be hosted in Console Application

You can see video of this article here

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

clip_image001

In Student table RollNumber is a primary key.

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

Step 1

Create a new project. Select the project template Console Application from Windows tab.

clip_image003

Step 2: 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 Console application and add a new item

2. Select ADO.Net Entity model from Data tab.

clip_image005

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

clip_image006

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

clip_image007

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_image008

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_image009

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_image010

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_image011

Step 3

Add reference of

System.ServiceModel;

System.ServiceModel.Web;

System.Data.Services;

System.Data.Services.Client

Step 4

Right click and add a class in console application. I am giving name here MyDataService to the class.

clip_image013

Step 5

Add the below namespaces in the class MyDataService

clip_image014

Step 6

In this step we will create WCF Data Service class.

clip_image016

1. Make the class as public.

2. Inherit DataService class.

3. Create a public method InitializeService

4. Pass the input parameter of the type DataServiceConfiguration

5. Set the protocol version to DataServiceProtocol version 2.0

MyDataService.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.ServiceModel;

using System.ServiceModel.Web;

using System.Data.Services;

using System.Data.Services.Common;

namespace SelfHosted

{

public class MyDataService :DataService<StudentDBEntities>

{

public static void InitializeService(DataServiceConfiguration config)

{

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

config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;

}

}

}


Step 7

Host the WCF Data Service in Console application. So to do that , write the below code in Program.cs

clip_image018

1. Create instance of WebServiceHost.

2. Create instance of WebHttpBinding.

3. Add service end point with Contract IRequestHandler

4. Open the host

Full source code for hosting program is as below ,

Programs.cs


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.ServiceModel;

using System.ServiceModel.Web;

using System.Data.Services;

using System.Data.Services.Common;

namespace SelfHosted

{

class Program

{

static void Main(string[] args)

{

WebServiceHost host = new WebServiceHost(typeof(MyDataService),

new Uri("http://localhost:9999/DataService"));

WebHttpBinding binding = new WebHttpBinding();

host.AddServiceEndpoint(typeof(IRequestHandler),

binding, "WebServiceHost");

host.Open();

Console.WriteLine("Service at http://localhost:9999/DataService ");

Console.WriteLine("Press any key to stop the Service ");

Console.Read();

host.Close();

}

}

}


Step 8

Just press F5 to run the WCF Data Service. Data Service will be hosted in the console application.

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

clip_image020

So, we are able to run the WCF Data Service and this service Is hosted in console application. We can consume the service in any client in the same way; we consume WCF Data service hosted in any other web server.

I hope this post was useful, thanks for reading. Happy coding.

Video on Hosting WCF Data Service in Console Application

MyDataService.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.ServiceModel;

using System.ServiceModel.Web;

using System.Data.Services;

using System.Data.Services.Common;

namespace DemoHostingInConsole

{

public class MyDataService : DataService<StudentDBEntities>

{

public static void InitializeService(DataServiceConfiguration config)

{

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

config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;

}

}

}


Program.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.ServiceModel;

using System.ServiceModel.Web;

using System.Data.Services;

using System.Data.Services.Common;

namespace DemoHostingInConsole

{

class Program

{

static void Main(string[] args)

{

WebServiceHost host = new WebServiceHost(typeof(MyDataService),

new Uri("http://localhost:9786/MyService"));

WebHttpBinding binding = new WebHttpBinding();

host.AddServiceEndpoint(typeof(IRequestHandler), binding, "abc");

host.Open();

Console.WriteLine("Service is running at http://localhost:9786/MyService ");

Console.WriteLine("To stop the service press a Key ");

Console.ReadKey();

host.Close();

}

}

}

I hope post was useful. Happy Coding

Hosting WCF Service with netTcpBinding in Windows Service

Objective

This article will explain

1. How to create a WCF service with netTcpBinding ?

2. How to host the WCF service in Windows service ?

3. How to start windows service ?

4. How to consume the service ?

You can see video of this article HERE

Create WCF Service

Step 1

Create a WCF Library project.

clip_image002[4]

Step 2

Create Contract. Delete all the default code generated by WCF for you. And create a contract as below,

clip_image004[4]

Step 3

Implement the Service

clip_image006[4]

Step 4

Configure End Point for the service on netTcp Binding.

1. Configure Service Behavior

clip_image008[4]

2. Configure end point with netTcpBinding

clip_image010[4]

3. Configure the meta data exchange end point

clip_image011[4]

Note: Make sure, you are providing name of the endpoints. Else you will catch up with run time exception while adding the service at client side

Full App.Config of WCF library project will look like

App.Config

<?xml version=1.0 encoding=utf-8 ?>

<configuration>

<system.web>

<compilation debug="true" />

</system.web>

<system.serviceModel>

<services>

<service name="ServicetohostinWindow.Service1" behaviorConfiguration ="MyBeh">

<host>

<baseAddresses>

<add baseAddress = "net.tcp://localhost:9292/Service1/" />

</baseAddresses>

</host>

<endpoint name ="TcpEndPoint"

address =""

binding="netTcpBinding"

contract="ServicetohostinWindow.IService1">

</endpoint>

<endpoint name ="MetaDataTcpEndpoint"

address="mex"

binding="mexTcpBinding"

contract="IMetadataExchange"/>

</service>

</services>

<behaviors>

<serviceBehaviors>

<behavior name ="MyBeh">

<serviceMetadata httpGetEnabled="False"/>

<serviceDebug includeExceptionDetailInFaults="False" />

</behavior>

</serviceBehaviors>

</behaviors>

</system.serviceModel>

</configuration>


Create Windows Service

Step 1

Right click and add a new project in same solution. Choose the project type Windows Services from windows tab.

clip_image013[4]

Step 2

Right click on Windows service project and add reference of

1. System.ServiceModel

2. Project reference of WCF Library project created in previous step

clip_image014[4]

clip_image015[4]

Step 3

Copy App.Config from WCF Service Library project and paste in Windows service project. To do so right click on App.config in WCF Library project and select copy then right click on Windows Service project and click on paste.

clip_image016[4]

clip_image017[4]

After copy and paste of APP.Config , we can see App.Config file in Windows Service Project also.

clip_image018[4]

Step 4

Add Service Installer. To do so right click on Service1.cs in windows service project and click on view designer.

clip_image019[4]

Once designer page is open, right click on designer page and click on add installer

clip_image021[4]

Once we will right click on design surface of Service.cs file and click add Installer, it will add ProjectInstaller.cs file.

clip_image022[4]

Right click on the ProjectInstaller.cs file and select view designer.

clip_image024[4]

On designer page, we can see there is ServiceProcessInstaller1 and serviceInstaller1 is there.

Right click on ServiceProcessInstaller1 and select properties. In properties set the Account attribute to NetworkServices

clip_image025[4]

Right click on ServiceInstaller1 and select properties. In properties set the Start Type attribute to Automatic

clip_image026[4]

Step 5

Modify Window service to host the WCF service. To do, open Service1.cs file in Windows service project.

1. Add the below name spaces

clip_image028[4]

2. Declare a variable

clip_image029[4]

clip_image030[4]

3. On Start method of Window service

clip_image032[4]

4. On Stop method of Window service

clip_image033[4]

5. On the event of back ground worker

clip_image035[4]

So full source code of Service1.cs in windows service project will be like below,

Service1.cs

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Diagnostics;

using System.Linq;

using System.ServiceProcess;

using System.Text;

using System.ServiceModel;

using ServicetohostinWindow;

namespace HostingWindowsService

{

public partial class Service1 : ServiceBase

{

internal static ServiceHost myHost = null;

BackgroundWorker worker;

public Service1()

{

InitializeComponent();

}

protected override void OnStart(string[] args)

{

worker = new BackgroundWorker();

worker.DoWork += new DoWorkEventHandler(worker_DoWork);

}

void worker_DoWork(object sender, DoWorkEventArgs e)

{

//throw new NotImplementedException();

if (myHost != null)

{

myHost.Close();

}

myHost = new ServiceHost(typeof(ServicetohostinWindow.Service1));

myHost.Open();

}

protected override void OnStop()

{

if (myHost != null)

{

myHost.Close();

myHost = null;

}

}

}

}

Step 6

Build the solution. After successful built of solution, you can see exe file in debug folder of bin folder. After building the solution, right click on solution and select open folder in Windows Explorer. Once folder is open Windows service project folder. Inside that open bin folder. Inside that open Debug folder. Inside Debug folder you should able to see windows service exe file.

clip_image037[4]

Click on the address bar of the folder and copy the full path of this exe file.

Step 7

Install the windows service.

1. First search what is the path of InstallUtil in your machine. To search this path , click on start and open find and if you are using Windows 7 then browse to your C drive and type InstallUtil , in top right corner search text box.

2. Once you get the full path of InstallUtil , Open your command prompt ad change directory to full path of InstallUtil.

3. Now just type InstallUtil.exe and press enter, you will get help details on how to use InstallUtil.exe.

4. Now to install window service we created, type the below command on your command prompt. Make sure you are giving correct and full path of window service exe.

clip_image039[4]

5. After successful installation, you will get below message.

clip_image041[4]

6. Click on Start and type run and in run window type Service.msc

clip_image042[4]

It will open all the services. We can see Service1 is listed there. If you remember Service1 is name of the service class in Windows service project.

clip_image044[4]

clip_image046[4]

This service is automatic started. Right click on the service and click on the Start.

Now our WCF Service is up and hosted in Windows Services.

Step 8

Create the client.

1. To create the client right click on solution and add a new project of type Console application.

2. Right click on the console application and add service reference. Copy base address from App.config of windows services and paste it here.

clip_image047[4]

3. Now simply create the instance of Service1Client and call the service

Programs.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using Client.ServiceReference1;

namespace Client

{

class Program

{

static void Main(string[] args)

{

Service1Client proxy = new Service1Client();

Console.WriteLine(proxy.GetData(9));

Console.Read();

}

}

}


Press F5 to run the console application. Make sure client console application is set as startup project.

clip_image049[4]

So it was all about, how to create a WCF Service with netTcpBinding and host in windows service. I hope this post was useful. Thanks for reading. Happy Coding

Video tutorial on Hosting WCF Service with netTcpBinding in Windows Service

WCF Service

IService1.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

namespace NetTcpServicetoHostinWindowsServices

{

[ServiceContract]

public interface IService1

{

[OperationContract]

string GetData(int value);

}

}

Service1.svc.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

namespace NetTcpServicetoHostinWindowsServices

{

public class Service1 : IService1

{

public string GetData(int value)

{

return string.Format("You entered: {0}", value);

}

}

}

App.Config

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<system.web>

<compilation debug="true" />

</system.web>

<system.serviceModel>

<services>

<service name="NetTcpServicetoHostinWindowsServices.Service1" behaviorConfiguration ="MyBehavior">

<host>

<baseAddresses>

<add baseAddress = "net.tcp://localhost:9999/Service1/" />

</baseAddresses>

</host>

<endpoint name ="NetTcpEndPoint"

address =""

binding="netTcpBinding"

contract="NetTcpServicetoHostinWindowsServices.IService1">

</endpoint>

<endpoint name ="NetTcpMetadataPoint"

address="mex"

binding="mexTcpBinding"

contract="IMetadataExchange"/>

</service>

</services>

<behaviors>

<serviceBehaviors>

<behavior name ="MyBehavior">

<serviceMetadata httpGetEnabled="False"/>

<serviceDebug includeExceptionDetailInFaults="False" />

</behavior>

</serviceBehaviors>

</behaviors>

</system.serviceModel>

</configuration>

Windows Service

Service1.cs

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Diagnostics;

using System.Linq;

using System.ServiceProcess;

using System.Text;

using System.ServiceModel;

using NetTcpServicetoHostinWindowsServices;

namespace HostingWindowsService

{

public partial class Service1 : ServiceBase

{

internal static ServiceHost myHost = null;

BackgroundWorker worker;

public Service1()

{

InitializeComponent();

}

protected override void OnStart(string[] args)

{

worker = new BackgroundWorker();

worker.DoWork += new DoWorkEventHandler(worker_DoWork);

}

void worker_DoWork(object sender, DoWorkEventArgs e)

{

if (myHost != null)

{

myHost.Close();

}

myHost = new ServiceHost(typeof(NetTcpServicetoHostinWindowsServices.Service1));

myHost.Open();

}

protected override void OnStop()

{

if (myHost != null)

{

myHost.Close();

myHost = null;

}

}

}

}

Client Application

Program.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using ConsoleClient.ServiceReference1;

namespace ConsoleClient

{

class Program

{

static void Main(string[] args)

{

Service1Client proxy = new Service1Client();

Console.WriteLine(proxy.GetData(9));

Console.Read();

}

}

}

Introduction to WCF Data service and ODATA

You can see video tutorial of this article

Creating WCF Data Service

Consuming WCF Data Service

WCF Data Service, Project Astoria, OData and ADO.Net Data Service are same thing.

Img1

What is ODATA?

Img2

· ODATA is HTTP or web protocol to querying or manipulating data.

· ODATA uses HTTP, JOSN or ATOM.

· ODATA can be implemented through any platform supports, HTTP, XML or JSON.

· ODATA can expose data/information from relational database, File systems, Web sites, services etc.

· ODATA specification available under Microsoft’s Open Specification Promise (OSP) so third parties, including open source projects, can build Open Data Protocol clients and services.

What is WCF Data Service?

· WCF Data service framework provides an API that allows data to be created and consumed over HTTP using RESTful service.

· WCF Data service supports all database operations using URI.

· WCF Data service can expose an entity model via an URI.

· WCF Data service is RESTful service to support CRUD operations on database.

· WCF Data service could be consumed by any type of client like Windows, SilverLight, Web, AJAX and console.

Img3

Block diagram explaining working of WCF Data Service

Img4

1. Create a Data Access layer using ADO.Net Entity model or LINQ.

2. Make sure Data model is implementing IQueryable and IUpdateable .

3. Expose the data model as REST service using WCF Data service.

CRUD Operations and HTTP verb

Img5

Supported Message Format

Img6

Sample on WCF Data Service

Img7

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

Img8

In Student table RollNumber is a primary key.

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

Step 1: 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.

Img9

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

Img10

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

Img11

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

Img12

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

Img13

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.

Img14

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.

Img15

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.

Img16

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

Img17

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.

Img18

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

Img19

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

Img20

Img21

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

Step 4: 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

Img22

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

Img27 Img28

MetaData

· One feature of WCF data service is that, they provide operation to retrieve Metadata about the service and offer of the service.

· This is very useful in determining structure before requesting them.

· WCF Data service provides metadata accessible.

· Metadata expose all the resource and custom services.

· Metadata could be accessed by appending $metadata to service URI.

Img22

So, the URI to access metadata is

http://localhost:29409/WcfDataService1.svc/$metadata

URI Query options

We can perform various queries in the browser itself using the URI query options.

Options

Options Descriptions
expand Request set of related entities to be retrieved.
orderby Indicates the sequence entity to be retrieved
skip Skip number of data items.
top At most returns top number of data items
filter Applies the filtering condition

Operators

Operators Descriptions
eq Equal
ne Not Equal
gt Greater Than
ge Greate than or equal to
lt Less than
le Less than or equal to
and Logical AND
or Logical OR
not Logical NOT

Math Operators

Operators Descriptions
add add
sub Subtract
mul multiply
div Division
mod remainder

Various queries

1. Fetch all the records from the table Student

URI: http://localhost:29409/WcfDataService1.svc/Students

Result

Img23

2. Fetch the student details with roll number 1

URI: http://localhost:29409/WcfDataService1.svc/Students?$filter=RollNumber eq’1′

Img24

3. Fetch top 2 record from the student table

URI: http://localhost:29409/WcfDataService1.svc/Students?$top =2

Img25

4. Fetch the records of the student with roll number 1 or 3

URI: http://localhost:29409/WcfDataService1.svc/Students?($filter=RollNumber eq’1′)or($filter=rollnumber eq ‘3’)

Img26

Different Access rules on the entity set

Enumerator Description
All All Read and Write are permitted
AllRead All Read permitted
AllWrite All Write is permitted
None No access is permitted
ReadMultiple Reading multiple row is permitted
ReadSingle Reading a single row is permitted
WriteAppend Creating New data is permitted
WriteDelete Deleting data is permitted
WriteMerge Merge updating is permitted
WriteReplace Replace updating is permitted

As we discussed above we can set access rule for a particular entity or whole entity set in data source.

config.SetEntitySetAccessRule(“*”, EntitySetRights.All);

This will permit all right access on all entity set.

config.SetEntitySetAccessRule(“Students”, EntitySetRights.AllWrite);

This will permit all write access on Student entity set.

Creating a client to consume WCF Data Service

Step 1

Add a new project in the same solution of type console application.

Img29

Step 2

Add the service reference of WCF Data Service. To add right click on the console project and add a service reference. Since WCF Data Service and client project in the same solution , click on Discover to discover the service in the solution.

Img30

Add the reference of System.Data.Service.Client in client project also.

Img31

Step 3

Add namespaces

Img32

Step 4

Need to create instance of DataContext and StudentDBEntities. These two classes take as parameter in their constructor. Parameter is base URI of the WCF Data Service.

Img33

Img34

Img35

Retrieving all the records of table Students

Img36

Adding one record in the table Student

Img37

Updating a record in the table Student

Img38

Delete a record in the table Student

Img39

For Reference Full Source Code is here

Program.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using ConsoleClient.ServiceReference1;

using System.Data.Services.Client;

namespace ConsoleClient

{

class Program

{

static DataServiceContext context;

static StudentDBEntities studentEntities;

static void Main(string[] args)

{

context = new DataServiceContext

(new Uri(http://localhost:3803/WcfDataService1.svc/&#8221;));

studentEntities = new StudentDBEntities

(new Uri(http://localhost:3803/WcfDataService1.svc/&#8221;));

//Get all The Records

foreach (var r in GetAllStudents())

{

Console.WriteLine(r.Name);

}

Console.Read();

// Insert one Record

AddStudent(new Student() { RollNumber = “100”, Name = “Pinal dave”, Subject = “Sql” });

Console.Read();

// Update the Record

UpdateStudent(new Student() { RollNumber = “100”, Name = “KMUG”, Subject = “Sql” });

Console.Read();

// Delete the Record

DeleteStudent(“100”);

// Get all the Records

foreach (var r in GetAllStudents())

{

Console.WriteLine(r.Name);

}

Console.Read();

}

static List<Student> GetAllStudents()

{

var res = from r in studentEntities.Students select r;

return res.ToList();

}

static void AddStudent(Student std)

{

context.AddObject(“Students”, std);

context.SaveChanges();

// Other way

//Student std1 = new Student() { RollNumber = “9999”,

//    Name = “Pinale Dave”,

//    Subject = “SQL Server” };

//studentEntities.AddToStudents(std);

//studentEntities.SaveChanges();

}

static void UpdateStudent(Student std)

{

Student stdtoUpdate = (from r in studentEntities.Students

where r.RollNumber == std.RollNumber

select r).First();

stdtoUpdate.Name = std.Name;

stdtoUpdate.Subject = std.Subject;

context.AttachTo(“Students”, stdtoUpdate);

context.UpdateObject(stdtoUpdate);

context.SaveChanges();

// Other way to Update

// studentEntities.UpdateObject(stdtoUpdate);

//studentEntities.SaveChanges();

}

static void DeleteStudent(string stdRollNo)

{

Student stdtoUpdate = (from r in studentEntities.Students

where r.RollNumber == stdRollNo

select r).First();

//context.AttachTo(“Students”, stdtoUpdate);

context.DeleteObject(stdtoUpdate);

context.SaveChanges();

//Other way

//studentEntities.DeleteObject(stdtoUpdate);

//studentEntities.SaveChanges();

}

}

}


I hope this article was useful. Thanks for reading. Happy Coding.