List Aggregator App (SPFx)

WCF Service Tutorial with Examples

wcf service tutorial

In this WCF service tutorial, we will discuss, what is WCF service? ABC of WCF service, how to create a WCF service using the visual studio? And also we will discuss the advantages of WCF service in asp.net. How does the Windows Communication Foundation’s service model work?

Also, we will discuss how to generate WCF Proxy using SvcUtil.exe. And, what are the various behaviors managed by the Service Runtime layer in WCF? and various instance Provider in WCF.

SharePoint deveopment training course

What is wcf service?

Windows Communication Foundation (WCF) is an SDK for developing and deploying services on Windows. It uses System.ServiceModel.dll in the System.ServiceModel namespace.

The services can be local or remote, developed by multiple parties using any technology, versioned independently, and even execute on different timelines. Inside a service, you will find concepts such as languages, technologies, platforms, versions, and frameworks, yet between services, only prescribed communication patterns are allowed.

The client of a service is merely the party consuming its functionality. The client can be literally anything- a Windows Forms class, an ASP.NET page, or another service. Clients and services interact by sending and receiving messages.

Messages may transfer directly from client to service or via an intermediary. With WCF, all messages are SOAP messages. WCF services may communicate over a variety of transports, not just HTTP. WCF clients may interoperate with non-WCF services, and WCF services can interact with non-WCF clients.

In WCF the client never directly interact with the services rather uses proxy to forward calls to the services.On the same machine the client can consume services in the same app domain,across machine boundaries the client can interact with services in its intranet or across the Internet.


WCF provides the client with the same programming model regardless of the location of the service, whether the client is in local machine or in remote.

Advantages of WCF service in Asp.Net

Now we will see what are the advantages of WCF service in Asp.Net.

  • It supports HTTP, TCP, Named pipes, MSMQ, P2P bindings.
  • It can be hosted in IIS, windows activation service, Self-hosting, Windows service.
  • It’s made of a lot of different components, so you can create new components for security, transport, authentication.
  • In WCF, there is no need to make much change in the code for implementing the security model and changing the binding. Small changes in the configuration will make your requirements.
  • Its faster than ASMX
  • Supports Scaling/Load Balancing
  • WCF has integrated logging mechanism, changing the configuration file settings will provide this functionality. In other technology, the developer has to write the code.
  • It’s Interoperability, for Java, and more.
  • WCF is interoperable with other services when compared to .Net Remoting, where the client and service have to be .Net.
  • WCF services provide better reliability and security in compared to ASMX web services.

ABC (Address, Binding and Contract) of WCF Service

Now, we will discuss the major component of wcf service, known as the ABC of WCF service.

ABC of WCF in C#.Net composed of Address, Binding, Contract.

Address in wcf service

In WCF, every service is associated with a unique address. The address provides two important elements: the location of the service and the transport protocol or transport schema used to communicate with the service.

The location portion of the address indicates the name of the target machine, site, or network; a communication port, pipe, or queue; and an optional specific path or URI.

WCF provides the following transport schemas like HTTP, TCP, Peer Network, IPC(Inter Process Communication), MSMQ.

And the address will always be like: http://localhost:8001

Ex. TCP address:
net.tcp://localhost:8002/MyWCFService (with ip address)
net.tcp://localhost/MyWCFService (without ip address)

Also same port can contain 2 services like
net.tcp://localhost:800/MyWCFService
net.tcp://localhost:800/MyOtherService

Ex HTTP Address
http://localhost:8000 It also uses https for secure communications

Binding in WCF service

The endpoints also define a binding that specifies how a client will communicate with the service and the address where the endpoint is hosted.

Different types of bindings supported in WCF Service

  • BasicHttpBinding
  • NetTcpBinding
  • WSHttpBinding
  • NetMsmqBinding
  • NetNamedPipeBinding
  • NetPeerTcpBinding etc.

Contract in wcf service

The endpoints specify a Contract that defines which methods of the Service class will be accessible via the endpoint; each endpoint may expose a different set of methods.

Different contracts in WCF Service

  • Service Contract
  • Data Contract
  • Message Contract
  • Fault Contract

Service Contract:
Service contracts describe the operation that the service can provide. For Eg, a Service provides to know the temperature of the city based on the zip code, this service is called a Service contract. It will be created using the Service and Operational Contract attribute.

Data Contract:
Data contract describes the custom data type which is exposed to the client. This defines the data types, which are passed to and from service. Data types like int, string are identified by the client because it is already mentioned in XML schema definition language document, but custom created the class or data types cannot be identified by the client e.g. Employee data type.

By using Data Contract we can make the client be aware of Employee data type that is returning or passing a parameter to the method.

Message Contract:
Default SOAP message format is provided by the WCF runtime for communication between Client and service. If it is not meeting your requirements then we can create our own message format. This can be achieved by using Message Contract attribute.

Fault Contract:
Suppose the service I consumed is not working in the client application. I want to know the real cause of the problem. How can I know the error? For this, we are having a Fault Contract. Fault Contract provides a documented view of error occurred in the service to the client. This helps us to easy identity, what error has occurred.

Various behaviors managed by Service Runtime layer in WCF

Let us discuss What are the various behaviors managed by the Service Runtime layer in WCF?

The following are the different behaviors managed by the Service Runtime layer in WCF.

  • Throttling Behavior: Throttling behavior determines the number of processed messages.
  • Error Behavior: The Error behavior specifies what action will be taken if an error occurs during service runtime.
  • Metadata Behavior: The Metadata behavior controls whether or not metadata is exposed to the outside world.
  • Instance Behavior: The Instance behavior drives how many instances of the service will be available to process messages.
  • Message Inspection: Message Inspection gives the service the ability to inspect all or parts of a message.
  • Transaction Behavior: Transaction behavior enables transacted operations. That is if a process fails during the service runtime it has the ability to rollback the transaction.
  • Dispatch Behavior: When a message is processed by the WCF infrastructure, the Dispatch Behavior service determines how the message is to be handled and processed.
  • Concurrency Behavior: The Concurrency behavior determines how each service, or instance of the service, handles threading. This behavior helps control how many threads can access a given instance of a service.
  • Parameter Filtering: Parameter Filtering filters the message headers and executes preset actions based on the filter of the message headers.

How the Windows Communication Foundation’s service model works?

Now, we will discuss the understanding of how the Windows Communication Foundation’s service model works.The following sequence of events occurs in wcf service model:

  • The client operation selector determines to which operation of the service to direct a request, based on which method of the client was invoked.
  • Any parameter inspectors attached to the client runtime components specific to that operation get to see the data that the developer’s code is passing as arguments Extending the Service Model with to the operation, and can modify that data, too. Parameter inspectors might be used to confirm that the values of outbound data items fall within a specific range, and to adjust them if they do not.
  • The client message formatter serializes the data items into XML and writes the XML into the body of a Windows Communication Foundation message.
  • The System.ServiceModel.Channels.Message object representing the message is passed to the client runtime component at the endpoint level.
  • The client message inspector is permitted to examine and optionally modify the System.ServiceModel.Channels.Message object representing the message.
  • The message is passed to the Windows Communication Foundation’s Channel Layer for delivery.
  • The message is received by the service and passed from the Channel Layer to the channel dispatcher, which passes it on to the dispatcher component of the appropriate endpoint.
  • The instance context provider retrieves any state information.
  • The dispatch operation selector determines to which operation, Based on the addressing of the message.
  • The dispatch message inspector is permitted to examine and optionally modify the System.ServiceModel.Channels.Message object representing the incoming message.
  • The instance provider creates or retrieves the instance of the service type that will be passed the data extracted from the message.
  • The message is passed to the dispatcher component for the operation identified by the dispatch operation selector.
  • The dispatch message formatter for the operation deserializes the body of the message into an array of data items.
  • Parameter inspectors attached to the dispatcher components for the operation are permitted to examine and optionally modify the data items.
  • The operation invoker for the operator invokes the method of the service by which the operation is implemented, passing the data items deserialized from the body of the message as arguments to the method.
  • If the method returns data, the parameter inspectors attached to the dispatcher components for the operation are allowed to look at and modify that data.
  • The dispatch message formatter for the operation serializes the data returned by the method into a System.ServiceModel.Channels.Message object that represents the response to the message received from the client.
  • That response message is passed to the dispatcher component at the endpoint level.
  • The dispatch message inspector is permitted to examine and modify the response message.
  • The instance context provider is allowed to persist or discard the state information.
  • The instance provider is given the opportunity to dispose of the instance of the service type that it created or retrieved to process the message.
  • The response message is passed to the channel dispatcher, which passes it on for transmission to the uppermost channel in the hierarchy of channels that the Windows Communication Foundation builds in accordance with the binding selected for the endpoint.
  • The response message is received by the client and passed from its Channel Layer to the client runtime component for the receiving endpoint.
  • The client message inspector of that client runtime component examines and optionally modifies the response message.
  • The client operation selector identifies the operation to which the response message pertains based on the addressing of the message.
  • The response message is passed to the client runtime component for that operation.
  • The client message formatter deserializes the body of the response message into an array of data items.
  • That array of data items is passed to any parameter inspectors attached to the client runtime component of the operation for examination and optional modification.

Create WCF service using visual studio in C#.net.

Now, we will discuss how to create a WCF service using visual studio and how we to consume the WCF service in C#.net.

Follow below steps to create a WCF service:

Step-1:
Open Visual Studio 2010, then go to File -> New -> Project. Then from the New Project dialog box, From the Installed Templates Select WCF from the left-hand side, And then Choose WCF Service Library and Give a proper name and Click on OK as shown in the figure below:

create wcf service
create wcf service

Step-2:
Now if you will look at the solution explorer, then 3 files are important App.Config, IService1.cs and Service1.cs.

First Open the IService1.cs file and add a method declaration in that like below:

The full IService1 interface will look like below:

[ServiceContract]
public interface IService1
{
[OperationContract]
string GetData(int value);

[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);

[OperationContract]
int Add(int firstNumber, int secondNumber);
// TODO: Add your service operations here
}

Now we have declared the Add method in the Interface file, now it is time to define the method in the Service1.cs file. Open the Service1.cs file and define the method like below:

int Add(int firstNumber, int secondNumber)
{
return firstNumber + secondNumber;
}

Step-3:
As of now do not modify anything in the app.config file. Check the base address http://localhost:8732/Design_Time_Addresses/WcfTestServiceLibrary/Service1/

We will use this address while calling this wcf service.

Step-4:
Now rebuild the project and then run the project. You should able to see the WCF test client dialog box as shown in the figure below, Also you will able to see the custom method that we have added.

create wcf service c#
create wcf service c#

Do not stop the service. This finishes our WCF creation part. Now it is time to consume the WCF service.

Consume WCF service using visual studio in C#.net

To consume the WCF service follow the below steps:

Step-1:
Start Visual Studio 2010. Go to File -> New -> Web Site. From New Web Site dialog box selects ASP.NET Web Site. Give a proper name and click on OK as shown in the figure below.

create wcf service in asp.net
create wcf service in asp.net

Step-2:
Now Right click on the solution explorer and click on Add Service Reference… as shown in the figure below:

create wcf service in visual studio 2015
create wcf service in visual studio 2015

Step-3:
Now in the Add Service Reference dialog box give the base WCF URL (You can get from the App.Config file) and click on GO. If the service is running then it will find the service, Here you can give a Namespace and then click on OK as shown in the figure below:

create wcf service in asp.net application
create wcf service in asp.net application

Step-4:
After you add the Service reference, it will create a folder with name as App_WebReferences and put the necessary files there.

Step-5:
Now it is time to call the Add method that we have defined in the WCF service.

Open the Default.aspx.cs file and write the using statement to add the wcf reference namespace like below:

using ServiceReference1;

Now it is time to call the method. For this first create an object of the Service1Client class and the call the method. The full code is given below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ServiceReference1;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Service1Client svcClient = new Service1Client();
int result = svcClient.Add(5, 5);
}
}

Here result will contain value of 10.

Instance Provider in WCF

Instance providers can be applied to services.

Service: Here are the steps for applying an instance provider to a service.

Declare: Implement the System.ServiceModel.Dispatcher.IInstanceProvider interface:

public class RajInstanceProvider:IInstanceProvider
{
public object GetInstance(
InstanceContext instanceContext,
Message message)
{
//create the service instance here.
}
public object GetInstance(
InstanceContext instanceContext)
{
//create the service instance here.
}
public void ReleaseInstance(
InstanceContext instanceContext,
object instance)
{
//dispose of the service instance.
}
}

Attach: Implement the ApplyDispatchBehavior() method of the System.ServiceModel.

Description.IEndpointBehavior interface:

public class RajInstanceProvider : IInstanceProvider,IEndpointBehavior
{
public void ApplyDispatchBehavior(
ServiceEndpoint serviceEndpoint,
EndpointDispatcher endpointDispatcher)
{
endpointDispatcher.DispatchRuntime.InstanceProvider = this;
}
……..
}

Inform In the code for a Windows Communication Foundation service host, add the instance context provider to the Behaviors collection of a System.ServiceModel.Description.EndpointDescription object:

ServiceHost host = new ServiceHost(typeof(Service));
host.Description.Endpoints[0].Behaviors.Add(
new RajInstanceProvider());

Generate WCF Proxy using SvcUtil.exe

Svcutil.exe is a command line tool that helps to generate proxy class in C#.Net. Then in the address bar give the address of the WCF service and click on Go.

Example:

net.tcp://localhost/Design_Time_Addresses/SLicense/Service1/
http://localhost/Design_Time_Addresses/SLicense/Service1

Optionally you can change the Namespace and click on Ok. Now you can access your WCF service.But what will happen if you are going to call that WCF in the production environment where there will be no Visual studio, you can not go for the above (Add Service Reference approach). Here it comes the SvcUtil.exe.

To use that go to Start -> All Programs -> Microsoft Visual Studio 2010 -> Visual Studio Tools -> Visual Studio Command Prompt (2010). Then type

svcutil /language:cs /out:generatedproxy.cs /config:app.config net.tcp://localhost/Design_Time_Addresses/SLicense/Service1/
svcutil /language:cs /out:generatedproxy.cs /config:app.config http://localhost/Design_Time_Addresses/SLicense/Service1

generatedproxy: It is the class name, you can provide any name.
language:cs: This is to select the language, for Vb.Net you can type language:VB

After this SvcUtil will generate 2 files one with the class name you have provided above and other is the app.config file.

The location of the files are:
C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\generatedproxy.cs
C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\app.config

You can copy the generatedproxy.cs class file and app.config file and paste in the project directory. But If you are calling the WCF service inside a Web Site or Web Application, then you must have a web.config file. Then copy from to and paste it in the web.config before.

Now you can create a object of the proxy class and use that.


You may like following asp.net c#.net tutorials:

Hope this tutorial, what is WCF service, advantages of using WCF service, how to create a WCF service in asp.net using visual studio, how to generate WCF Proxy using SvcUtil.exe. And, what are the various behaviors managed by the Service Runtime layer in WCF? and various instance Provider in WCF.

Check out Best Alternative to InfoPath -> Try Now

free sharepoint training

SharePoint Online FREE Training

JOIN a FREE SharePoint Video Course (3 Part Video Series)

envelope
envelope

About Bijay Kumar

I am Bijay from Odisha, India. Currently working in my own venture TSInfo Technologies in Bangalore, India. I am Microsoft Office Servers and Services (SharePoint) MVP (5 times). I works in SharePoint 2016/2013/2010, SharePoint Online Office 365 etc. Check out My MVP Profile.. I also run popular SharePoint web site SharePointSky.com

View all posts by Bijay Kumar →