Windows wcf data service

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

WCF Data Services

Introduction

There are many Ajax/RIA/Rich Client/etc. applications, which access data directly from the client. Mashups also combine data that is available on the web mostly in the form of RSS/Atom feeds and present it to the user in the more meaningful way.
Writing an entire web service to expose the data layer over Http requires a significant developer investment. WCF Data Services (originally known as ADO.NET Data Services) is a framework that automatically exposes data in the RESTful manner. It allows AJAX applications, access to the database via Http without writing a web service. It also provides access to data to third parties in a standardized fashion. WCF Data Services Framework exposes data from any Linq enabled data source. In addition, it allows the client to be extremely lightweight, only needing an Http request mechanism and a JSON or Atom parser, as opposed to a whole data access stack.

Creating a Windows Communication Foundation (WCF) Data Service

I have created a simple SQL Server database that contains the below three tables and a stored procedure, namely GetAvailableProducts. For simplicity, there will a one order for each product ordered. We will create a WCF Data Service that will expose this data via Http.

Figure 1

Create a new ASP.NET Web Application and name it as AdoNetDataServicesDemo.

Add an ADO.NET Entity Data Model to the Project. Let’s name it as CustomerOrdersModel. Once you click on OK button, it will start the Entity Data Model wizard. Follow the wizard to generate the Entity Model from the database. Provide the database connection information and choose the above tables and stored procedure in the database objects list. After you click on the Finish button, Entity Data Model will be generated and added to the project as shown below:

Figure 2

Now add an ADO.NET Data Service to the project and name it as CustomerOrders. CustomerOrders.svc and CustomerOrders.svc.cs files will be generated and added to the project. In CustomerOrders.svc.cs files there will be an auto-generated class, namely CustomerOrders. This class inherits from DataService class. Specify the generic parameter as CustomerOrdersC, which is the data context class generated by the Entity data Model.

Add the below new method to this class to expose the data returned by stored procedure as an IQueryable property.


[WebGet]        
public IQueryable<Products> ProductList()        
{    
return new CustomerOrdersC().GetAvailableProducts().AsQueryable<Products>();
}
By default no entity or operation is made visible/updatable/etc. Add the below lines in the InitializeService method to make all the entities and operations visible/updatable/etc.
public static void InitializeService(IDataServiceConfiguration config)        
{
config.SetEntitySetAccessRule(“*”, EntitySetRights.All);
config.SetServiceOperationAccessRule(“ProductList”, ServiceOperationRights.All);
}

We have given all the permissions to all the entities/operations above but we can control that at more granular level, if required.

Now press F5 to launch the WCF Data Service and type the below URIs in the address bar and observe the data displayed in the browser.


http://localhost:1371/CustomerOrders.svc/ProductList
http://localhost:1371/CustomerOrders.svc/Customers?$top=1

There are different options available that we can be used to filter/sort the data. Below are the options that we can use in the URIs.

Figure 3

In the filter expression we can use the below operators.

Figure 4

Consuming the Windows Communication Foundation (WCF) Data Service

Add a Windows Forms Application to the solution and name it as DemoClient.

Open the Add Service Reference dialog box and discover/add CustomerOrder.svc service reference to the project. Alternatively you can also use the DataServiceUtil.exe to generate the client-side classes.

Change the default Form so that it looks like below.

Figure 5

Double click on the View Orders button to open the Click event handler and write the below code in it.


private void ViewOrdersButton_Click(object sender, EventArgs e)        
{            
CustomerOrdersC svcContext = new CustomerOrdersC(new Uri(“http://localhost:1371/CustomerOrders.svc/”));            
int id = Convert.ToInt32(CustomerId.Text.Trim());            
var customer = svcContext.Customers.Where(c => c.CustomerId == id).FirstOrDefault();
CustomerName.Text = customer.LastName + “, ” + customer.FirstName;          
var orders = svcContext.Orders.Expand(“Products”)                                        
.Where(o => o.Customers.CustomerId == id)                                        
.ToList();             
OrderGridView.DataSource = orders.Select(o => new                                            
{Id = o.OrderId,                                                
Product = o.Products.ProductName,                                                
Quantity = o.Quantity}).ToList();
}

In the above event handler we created an instance of CustomerOrdersC auto-generated class, and queried the customer details based on the Id entered by the user on the UI. Then we pulled the orders of that customer with the product details. Then we showed the data on the UI, returned by the WCF Data Service. WCF Data Service doesn’t support Joins; we need to use Expand extension method to get the data in the related tables, as shown above.

In the Click event handler of Add New button, write the below code.


private void NewProductButton_Click(object sender, EventArgs e)        
{
CustomerOrdersC svcContext = new CustomerOrdersC(new Uri(“http://localhost:1371/CustomerOrders.svc/”))            
svcContext.AddToProducts(                
new Products()                 
{ProductName = ProductName.Text.Trim()});
           svcContext.SaveChanges();
}
In the above event handler we create a new Product and saved it in the database. Finally in the Click event handler of View Products button, write the below code.
private void ViewProductsButton_Click(object sender, EventArgs e)        
{
CustomerOrdersC svcContext = new CustomerOrdersC(new Uri(“http://localhost:1371/CustomerOrders.svc/”));
           ProductsGridView.DataSource = svcContext.Products.ToList<Products>();        
}

In the above event handler we simply query all the records in the Products table and display them on the UI.

Now set the DemoClient as the default project and press F5 to launch it. Type 1 in the Customer Id textbox and click the View Orders button to see all the orders of the customer.

Click on the View Products button and all the products will be shown on the screen as can be seen in the below screen shot.

Figure 6

Now type Printers in the Product Name textbox and click on Add New button. In addition, click on the View Products button to see the updated list of products in the database. You will see a new row has been added for the Printers at the bottom of the Products table as shown below.

Figure 7

If you see under the covers, all the Linq queries are converted to WCF Data Services URI, which are used to retrieve/update the data in the database. In fact, we can directly use that URI in the client application. In that case we don’t even need to add the service reference. We just have to create the instance of DataServiceContext class, which is the base class of CustomerOrdersC class in the above example and pass the URI to its Execute method.

We have successfully created a WCF Data Service and consumed the same in Windows Forms application. WCF Data Service Framework made it possible to get the data service up and running in just few minutes.

Happy Coding!
Sajad Deyargaroo

From Wikipedia, the free encyclopedia

WCF Data Services

Original author(s) Microsoft
Initial release August 11, 2008; 16 years ago
Stable release

5.6.0

Operating system Microsoft Windows, Linux, macOS
Website docs.microsoft.com/en-us/previous-versions/dotnet/wcf-data-services/hh487257(v=vs.103)

WCF Data Services (formerly ADO.NET Data Services,[1] codename «Astoria»[2]) is a platform for what Microsoft calls Data Services. It is actually a combination of the runtime and a web service through which the services are exposed. It also includes the Data Services Toolkit which lets Astoria Data Services be created from within ASP.NET itself. The Astoria project was announced at MIX 2007, and the first developer preview was made available on April 30, 2007. The first CTP was made available as a part of the ASP.NET 3.5 Extensions Preview. The final version was released as part of Service Pack 1 of the .NET Framework 3.5 on August 11, 2008. The name change from ADO.NET Data Services to WCF data Services was announced at the 2009 PDC.

WCF Data Services exposes data, represented as Entity Data Model (EDM) objects, via web services accessed over HTTP. The data can be addressed using a REST-like URI. The data service, when accessed via the HTTP GET method with such a URI, will return the data. The web service can be configured to return the data in either plain XML, JSON or RDF+XML. In the initial release, formats like RSS and ATOM are not supported, though they may be in the future. In addition, using other HTTP methods like PUT, POST or DELETE, the data can be updated as well. POST can be used to create new entities, PUT for updating an entity, and DELETE for deleting an entity.

Windows Communication Foundation (WCF) comes to the rescue when we find ourselves not able to achieve what we want to achieve using web services, i.e., other protocols support and even duplex communication. With WCF, we can define our service once and then configure it in such a way that it can be used via HTTP, TCP, IPC, and even Message Queues. We can consume Web Services using server side scripts (ASP.NET), JavaScript Object Notations (JSON), and even REST (Representational State Transfer).

Understanding the basics

When we say that a WCF service can be used to communicate using different protocols and from different kinds of applications, we will need to understand how we can achieve this. If we want to use a WCF service from an application, then we have three major questions:

1.Where is the WCF service located from a client’s perspective?
2.How can a client access the service, i.e., protocols and message formats?
3.What is the functionality that a service is providing to the clients?

Once we have the answer to these three questions, then creating and consuming the WCF service will be a lot easier for us. The WCF service has the concept of endpoints. A WCF service provides endpoints which client applications can use to communicate with the WCF service. The answer to these above questions is what is known as the ABC of WCF services and in fact are the main components of a WCF service. So let’s tackle each question one by one.

Address: Like a webservice, a WCF service also provides a URI which can be used by clients to get to the WCF service. This URI is called as the Address of the WCF service. This will solve the first problem of «where to locate the WCF service?» for us.

Binding: Once we are able to locate the WCF service, one should think about how to communicate with the service (protocol wise). The binding is what defines how the WCF service handles the communication. It could also define other communication parameters like message encoding, etc. This will solve the second problem of «how to communicate with the WCF service?» for us.

Contract: Now the only question one is left with is about the functionalities that a WCF service provides. The contract is what defines the public data and interfaces that WCF service provides to the clients.

The URIs representing the data will contain the physical location of the service, as well as the service name. It will also need to specify an EDM Entity-Set or a specific entity instance, as in respectively

http://dataserver/service.svc/MusicCollection

or

http://dataserver/service.svc/MusicCollection[SomeArtist]

The former will list all entities in the Collection set whereas the latter will list only for the entity which is indexed by SomeArtist.

The URIs can also specify a traversal of a relationship in the Entity Data Model. For example,

http://dataserver/service.svc/MusicCollection[SomeSong]/Genre

traverses the relationship Genre (in SQL parlance, joins with the Genre table) and retrieves all instances of Genre that are associated with the entity SomeSong. Simple predicates can also be specified in the URI, like

http://dataserver/service.svc/MusicCollection[SomeArtist]/ReleaseDate[Year eq 2006]

will fetch the items that are indexed by SomeArtist and had their release in 2006. Filtering and partition information can also be encoded in the URL as

http://dataserver/service.svc/MusicCollection?$orderby=ReleaseDate&$skip=100&$top=50

Although the presence of skip and top keywords indicates paging support, in Data Services version 1 there is no method of determining the number of records available and thus impossible to determine how many pages there may be. The OData 2.0 spec adds support for the $count path segment (to return just a count of entities) and $inlineCount (to retrieve a page worth of entities and a total count without a separate round-trip….).[3]

  1. ^ «Simplifying our n-tier development platform: making 3 things 1 thing». ADO.NET Data Services Team Blog. 2009-11-17. Retrieved 2009-12-17.
  2. ^ «ADO.NET Data Services CTP Released!». Retrieved 2007-11-12.
  3. ^ Archiveddocs. «What’s New in WCF Data Services 5.0». docs.Microsoft.com. Retrieved March 9, 2019.
  • «Codename «Astoria»: Data Services for the Web». Retrieved April 30, 2007.
  • ADO.NET Data Services Framework (formerly «Project Astoria»)
  • Using Microsoft ADO.NET Data Services
  • ASP.NET 3.5 Extensions Preview
  • ADO.NET Data Services (Project Astoria) Team Blog
  • Access Cloud Data with Astoria: ENT News Online

July 16, 2023
1 min read
views 686
Arthur C. Codex
Engineering
.Net

Windows Communication Foundation (WCF) is a powerful framework for building service-oriented applications. In this tutorial, we will learn how to create and use a WCF data service.

How to Create and Use a Windows Communication Foundation (WCF) Data Service image

1. Setting Up the Environment

Ensure that you have Visual Studio installed on your computer. If not, you can download it from the official Microsoft website. You should also have a .NET Framework (4.0 or later) installed.

2. Creating a New WCF Service Application

Open Visual Studio and create a new project. Select «WCF Service Application» from the list of templates.


using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;

[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service
{
    // Add [WebGet] attribute to use HTTP GET
    [OperationContract]
    public void DoWork()
    {
        // Add your operation implementation here
        return;
    }

    // Add more operations here and mark them with [OperationContract]
}

3. Defining a Data Contract

A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged. In WCF, a data contract can be defined using data contract attributes.


[DataContract]
public class Student
{
    [DataMember]
    public int ID { get; set; }

    [DataMember]
    public string Name { get; set; }
}

4. Implementing Service Operations

Service operations are methods defined in a service contract. They implement the functionality of the service.


[OperationContract]
public Student GetStudent(int id)
{
    // Implementation here
}

[OperationContract]
public List<Student> GetAllStudents()
{
    // Implementation here
}

5. Hosting the WCF Service

WCF services must be hosted in a Windows process called a host process. The host process can be a console application, a Windows service, or a Web application hosted in Internet Information Services (IIS).


c:\> cd C:\inetpub\wwwroot\WcfService
c:\inetpub\wwwroot\WcfService> ServiceHost.exe

6. Consuming the WCF Service

To consume a WCF service, a client application must have a proxy to the service. The proxy can be generated using the «Add Service Reference» option in Visual Studio.


ServiceClient client = new ServiceClient();

Student student = client.GetStudent(1);
List<Student> students = client.GetAllStudents();

We hope this tutorial helps you get started with WCF data services. Remember to always keep exploring and learning. If you need professional assistance, consider hiring .NET remote developers.

Provide feedback

Saved searches

Use saved searches to filter your results more quickly

Sign up

Creating WCF Data Service

In this article let’s understand WCF Data Service and OData by creating the WCF Data Service and expose the data using OData protocol. It is explained by exposing the «Person» details from «AdventureWorksDatabase» as data service using OData protocol.

Later we can see how to read the «Person» details from web browser in different format and using different filter condition.

Later .Net client application is created to consume the data service and query the «Person» information using query.

Step 1:

Create an empty web application project by selecting «ASP.NET Empty Web Application» template.

Step 2:

Now we need to create a Data model which needs to be exposed as service. So let’s try to add new data model to map the «Person» table from «AdventureWorksDatabase» as entity. This entity collection will later be exposed as service for querying.

Right click the project and select «Add»->»New Item» and select «ADO.Net Entity Data Model»

Step 3:

Entity Data Model Wizard will appear select «Generate from Database» and click «Next»

Step 4:

In the Database connection click the «New Connection» button and specify the server name and select «AdventureWorks» database and click «OK»

Step 5:

Now the connection string will be displayed as show below and click «Next»

Step 6:

This section is used to select the table, views or store produce for which entity need to be defined. Select «Person» table from «Person» schema and click «Finish». This will create the «Person» entity which is mapped to the database will be created.

Step 7:

Now Entity Data Model is created for the «Person» table and it is exposed as property with name «People».

File: «AdventureWorksModel.Context.cs»

    public partial class AdventureWorks2012Entities : DbContext
    {
        public AdventureWorks2012Entities()
            : base("name=AdventureWorks2012Entities")
        {

        }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }
    
        public DbSet<Person> People { get; set; }
    }

           

Step 8:

Let’s expose this data as resource using Data service. Right click the project select «Add»->»New Item» and select «WCF Data Service 5.6»

Step 9:

In Entity Data Model, data context object is the main type to map the all the table, views, SP from database to Entity collection using property. Data Service class can be defined based on the EDM data context as shown below.

You can also set the access rights like (Read, Write, Read/Write, delete etc) to the property of the EDM in data service. These operations are done using the HTTP verbs like GET, POST, PUT etc.

Below example, I have set the «Read» access to the «People» property of the data context. So collection of «Person» can be read by any one by applying query expression.

Step 10:

Run the service and you will see the output as shown below. This shows that services expose the collection of «People» entity.

Step 11:

Enter the URL as mention below to return all the «People» resources in form of AtomPub

URL : «http://localhost:24641/MyODataService.svc/People»

Step 12:

You can get the data in JSON format by mentioning the format in the URL

URL: «http://localhost:24641/MyODataService.svc/People()?$format=verbosejson»

Step 13:

Now we are done with data service creation, let’s start creating the client application to consume this OData service.

Create a new .Net console application and add service reference as shown below with OData service url

Step 14:

Enter the source code as shown below and run the application

Step 15:

While debugging the application, you can see that client application send the request to OData service through URL with all filter condition to read the resource information.

Step 16:

Output will all the resource information received using url are shown below

Tips!

  • Always create the service with Interface->Implementation format, mention the contract in Interface.
  • Define the service in Class library and refer the class library in Host project. Don’t use service class in host project.
  • Change the instance mode to per call as default.
  • Always catch exception using try/catch block and throw exception using FaultException < T >.
  • Logging and Include exception should be enable while compiling the project in debug mode. While in production deployment disable the logging and Include exception details.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Посмотреть открытые порты windows команда
  • Диалоговое окно windows предназначено для
  • Hp laserjet 1010 drivers windows 7 32bit
  • Windows embedded windows update
  • Как включить аппаратную виртуализацию на windows 10 через биос