Introduction to WCF

Windows Communication Foundation (Code named Indigo) is a programming platform and runtime system for building, configuring and deploying network-distributed services. It is the latest service oriented technology; Interoperability is the fundamental characteristics of WCF. It is unified programming model provided in .Net Framework 3.0. WCF is a combined features of Web Service, Remoting, MSMQ and COM+. WCF provides a common platform for all .NET communication. Below figures shows the different technology combined to form WCF.

Advantage
1. WCF is interoperable with other services when compared to .Net Remoting,where the client and service have to be .Net. 2. WCF services provide better reliability and security in compared to ASMX web services.

3. In WCF, there is no need to make much change in code for implementing the security model and changing the binding. Small changes in the configuration will make your requirements. 4. WCF has integrated logging mechanism, changing the configuration file settings will provide this functionality. In other technology developer has to write the code.

Disadvantage
Making right design for your requirement is little bit difficult. I will try to help you on solving these difficulties in the following article.

Development Tools
WCF application can be developed by the Microsoft Visual Studio. Visual studio is available at different edition. You can use Visual Studio 2008 Expression edition for the development.
http://www.microsoft.com/express/product/default.aspx

Visual Studio 2008 SDK 1.1
http://www.microsoft.com/downloads/details.aspx?FamilyID=59ec6ec3-4273-48a3-ba25dc925a45584d...

Microsoft Visual Studio 2008
Microsoft Visual studio 2008 provides new features for WCF compared to Visual Studio 2005. These are the new features added to VS 2008.
1. Multi-targeting

You can create application in different framework like Framework 2.0, 3.0 and 3.5

2. Default template is available for WCF

3. WCF - Test Client tools for testing the WCF service.

Microsoft provides inbuilt application to test the WCF application. This can be done by opening the Visual Studio command prompt and type the wcfClient Serviceurl shows below. This will help the developer to test the service before creating the client application.

4. WCF services can be debugged now in Visual Studio 2008. Wcfsvchost.exe will do it for you because service will be self hosted when you start debugging.

5.Difference between WCF and Web service
6. Web service is a part of WCF. WCF offers much more flexibility and portability to develop a service when comparing to web service. Still we are having more advantages over Web service, following table provides detailed difference between them. Features Hosting Programming Model Operation XML Web Service It can be hosted in IIS [WebService] attribute has to be added to the class WCF It can be hosted in IIS, windows activation service, Self-hosting, Windows service [ServiceContraact] attribute has to be added to the class

[WebMethod] attribute represents the [OperationContract] attribute represents method exposed to client the method exposed to client One-way, Request- Response are the One-Way, Request-Response, Duplex are different operations supported in web different type of operations supported in service WCF System.Xml.serialization name space System.Runtime.Serialization namespace is used for serialization is used for serialization

Encoding Transports Protocols

XML 1.0, MTOM(Message Transmission Optimization Mechanism), DIME, Custom

XML 1.0, MTOM, Binary, Custom

Can be accessed through HTTP, TCP, Can be accessed through HTTP, TCP, Custom Named pipes, MSMQ,P2P, Custom Security Security, Reliable messaging, Transactions

EndPoint
WCF Service is a program that exposes a collection of Endpoints. Each Endpoint is a portal for communicating with the world. All the WCF communications are take place through end point. End point consists of three components.

Address
Basically URL, specifies where this WCF service is hosted .Client will use this url to connect to the service. e.g
http://localhost:8090/MyService/SimpleCalculator.svc

Binding
Binding will describes how client will communicate with service. There are different protocols available for the WCF to communicate to the Client. You can mention the protocol type based on your requirements. A binding has several characteristics, including the following:
y y

y

Transport -Defines the base protocol to be used like HTTP, Named Pipes, TCP, and MSMQ are some type of protocols. Encoding (Optional) - Three types of encoding are available-Text, Binary, or Message Transmission Optimization Mechanism (MTOM). MTOM is an interoperable message format that allows the effective transmission of attachments or large messages (greater than 64K). Protocol(Optional) - Defines information to be used in the binding such as Security, transaction or reliable messaging capability

The following table gives some list of protocols supported by WCF binding.
Binding Description

BasicHttpBinding WSHttpBinding WSDualHttpBinding

Basic Web service communication. No security by default Web services with WS-* support. Supports transactions Web services with duplex contract and transaction support

WSFederationHttpBinding Web services with federated security. Supports transactions MsmqIntegrationBinding Communication directly with MSMQ applications. Supports transactions NetMsmqBinding Communication between WCF applications by using queuing. Supports transactions Communication between WCF applications on same computer. Supports duplex contracts and transactions Communication between computers across peer-to-peer services. Supports duplex contracts Communication between WCF applications across computers. Supports duplex contracts and transactions

NetNamedPipeBinding

NetPeerTcpBinding

NetTcpBinding

Contract
Collection of operation that specifies what the endpoint will communicate with outside world. Usually name of the Interface will be mentioned in the Contract, so the client application will be aware of the operations which are exposed to the client. Each operation is a simple exchange pattern such as one-way, duplex and request/reply. Below figure illustrate the functions of Endpoint

Example: Endpoints will be mentioned in the web.config file on the created service.serviceModel> . <system.svc" contract="IMathService" binding="wsHttpBinding"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="MathServiceBehavior"> <serviceMetadata httpGetEnabled="True"/> <serviceDebug includeExceptionDetailInFaults="true" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> <services> <service name="MathService" behaviorConfiguration="MathServiceBehavior"> <endpoint address="http://localhost:8090/MyService/MathService.

svc" contract="IMathService" binding="netTcpBinding"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="MathServiceBehavior"> <serviceMetadata httpGetEnabled="True"/> <serviceDebug includeExceptionDetailInFaults="true" /> </behavior> </serviceBehaviors> </behaviors> </system. We can understand with an example.tcp://localhost:8080/MyService/MathService. and operation-level behaviors affect particular operations.serviceModel> <services> <service name="MathService" behaviorConfiguration="MathServiceBehavior"> <endpoint address="http://localhost:8090/MyService/MathService. <system.svc" contract="IMathService" binding="wsHttpBinding"/> <endpoint address="net. <system. How it can be done? With Web service it is very difficult to achieve. but in WCF its just we need to add extra endpoint in the configuration file. This attribute will specifies the publication of the service metadata. endpoint behaviors affect only endpoint-related properties. service behaviors affect only service-related aspects. Example: In the below configuration information.serviceModel> See how simple it is in WCF.serviceModel> <services> . In the service behavior I have mention the servieMetadata node with attribute httGetEnabled='true'. Similarly we can add more behavior to the service. Consider a scenario say.Binding and Behavior Binding Simple definition for Binding describes how the client will communicate with service. One of the client will access SOAP using http and other client will access Binary using TCP. I am creating a service that has to be used by two type of client. I have mentioned the Behavior at Service level. Microsoft is making everything simple.cording to its scope: common behaviors affect all endpoints globally.

configuring or through combination of both. string are identified by the client because it is already mention in XML schema definition language document. but custom created class or data types cannot be identified by the client e. Employee data type. By using DataContract we can make client to be aware of Employee data type that are returning or passing parameter to the method. To know more on Service contract see Service contract tutorial. Contracts In WCF. a Service provide to know the temperature of the city based on the zip code. Message Contract . all services are exposed as contracts. For Eg. This defines the data types. Data types like int.g. It will be created using Service and Operational Contract attribute. Specification mention in the configuration can also be overwritten in code. Data Contract Data contract describes the custom data type which is exposed to the client.serviceModel> Note: Application can be controlled either through coding. Contract is a platform-neutral and standard way of describing what the service does. that are passed to and from service. Mainly there are four types of contracts available in WCF Service Contract Service contracts describe the operation that service can provide.<service name="MathService" behaviorConfiguration="MathServiceBehavior"> <endpoint address="" contract="IMathService" binding="wsHttpBinding"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="MathServiceBehavior"> <serviceMetadata httpGetEnabled="True"/> <serviceDebug includeExceptionDetailInFaults="true" /> </behavior> </serviceBehaviors> </behaviors> </system. this service is called as Service contract. To know more on DataContract see DataContract tutorial.

including a body and headers. //Creating uri for the hosting the service Uri uri = new Uri("http://localhost/CategoryService"). To know more on Message Contract see Message contract tutorial.ServiceModel. Fault Contract provides documented view for error occurred in the service to client.WriteLine("Waiting for client invocations").ReadLine(). If it is not meeting your requirements then we can create our own message format. Console.Default SOAP message format is provided by the WCF runtime for communication between Client and service. //Hosting the Service Console. This helps us to easy identity. It loads the service configuration endpoints. host. //Creating the host object for MathService ServiceHost host = new ServiceHost(typeof(CategoryService). How I can know the error? For this we are having Fault Contract. \ Message and Channel Message WCF Message is the unit of data exchange between client and service. It consists of several parts. I want to know the real cause of the problem. Fault Contract Suppose the service I consumed is not working in the client application.AddServiceEndpoint(typeof(ICategoryService). To know more on Fault Contract see Fault Contract tutorial. uri). //Adding endpoint to the Host object host. System. WCF Runtime . uri).Open(). apply the settings and start the listeners to handle the incoming request. host. This can be achieved by using Message Contract attribute. what error has occurred.ServiceHost namespace hold this object. This object is created while self hosting the WCF service.Close(). Service Host Service Host object is in the process of hosting the WCF service and registering endpoints. In the below example you can find that WCF service is self hosted using console application.new WSHttpBinding().

svcutil /language:vb /out:ClientCode. Example type the following sentence in the Visual studio command prompt.config http://localhost:8090/MyService/SimpleCalculator.svc?wsdl 2. including an application that host a service.vb /config:app. Get the Proxy class and service end point information Using SvcUtil.exe we can create proxy class for the service and configuration information for endpoints. this will generate the class file and configuration file which contain information about the endpoints. Configuration information we got from the above step has .g. Channels: Channels are the core abstraction for sending message to and receiving message from an Endpoint. Any application can host a WCF client.WCF runtime is the set of object responsible for sending and receiving message. A client application is a managed application that uses a WCF client to communicate with another application. To create a client application for a WCF service requires the following steps: 1. WCF Client and Metadata WCF Client WCF client is a client application creates to expose the service operations as method. Protocol Channels . Then create the object for this class and invoke the service operation. WSSecurity and WS-Reliability. applying security and transmitting and receiving message using various protocol. Add this class files in the client application. TCP name pipes and MSMQ. Broadly we can categories channels as Transport Channels . Protocols like HTTP. For example formatting the message. Call operations.Handles sending and receiving message from network. e. Therefore it is possible to create a service that includes WCF clients of other services.Implements SOAP based protocol by processing and possibly modifying message.

This underlying channel is closed.serviceModel> This metadata can be viewed while creating WCF client application using SvcUtil.MyServiceProxy proxy = new MyCalculatorServiceProxy. Close the WCF client object. when the object is cleared. Metadata Characteristics of the service are described by the metadata.MyMethod()). .WriteLine("Counter: " + proxy. When the client application calls the first operation.MyServiceProxy(). After using the object created in the above steps. 3. //Creating the proxy on client side MyCalculatorServiceProxy.serviceModel> <services> <service name="MathService" behaviorConfiguration="MathServiceBehavior"> <endpoint address="" contract="IMathService" binding="wsHttpBinding"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="MathServiceBehavior"> <serviceMetadata httpGetEnabled="True"/> <serviceDebug includeExceptionDetailInFaults="true" /> </behavior> </serviceBehaviors> </behaviors> </system. WCF automatically opens the underlying channel. <system. Metadata can be set in the service by enabling the ServiceMetadata node inside the servcieBehaviour node of the service configuration file.exe The following figure illustrates the major components of WCF. when the object is recycled. Console. we have to dispose the object. This metadata can be exposed to the client to understand the communication with service.to be added to the client application configuration file. Channel will be closed with the service.

Service contracts . Data contract . this service we call as Service contract.Figure 1: WCF Architecture Contracts Contracts layer are next to that of Application layer.Describe about the operation that service can provide. We are also going to do the same now. Service provided to know the temperature of the city based on the zip code. Let us see briefly what these contracts will do for us and we will also know that WCF is working on message system. Example. Developer will directly use this contract to develop the service. It will be created using Service and Operational Contract attribute.

Specify conditions required to communicate with a service e.It contains the behaviors that occur during runtime of service. but custom created class or datatype cannot be identified by the client e.Messaging layer is composed of channels.Default SOAP message format is provided by the WCF runtime for communication between Client and service. By using DataContract we can make client aware that we are using Employee data type for returning or passing parameter to the method. This defines the data types.Controls how a message is processed by the WCF Infrastructure. Message Contract . Messaging . Instance Behavior . Broadly we can categories channels as y Transport Channels Handles sending and receiving message from network.Specifies what occurs. by authenticating a message. TCP. Channels are the core abstraction for sending message to and receiving message from an Endpoint. y y y y y y Throttling Behavior.g.Enables the rollback of transacted operations if a failure occurs. .. A channel is a component that processes a message in some way. string are identified by the client because it is already mention in XML schema definition language document. Error Behavior . name pipes and MSMQ. Metadata Behavior . protocol and encoding used for binding.g.g security requirement to communicate with service. Data types like int. Policies and Binding . If it is not meeting your requirements then we can create our own message format. Transaction Behavior . when internal error occurs on the service. This can be achieved by using Message Contract attribute. are passed to and from service. y Protocol Channels Implements SOAP based protocol by processing and possibly modifying message.Tells how and whether metadata is available to outside world. Dispatch Behavior . Service Runtime .It describes the custom data type which is exposed to the client. A set of channels is also known as a channel stack. for example. Employee data type. E. WS-Security and WS-Reliability. Protocols like HTTP.Specifies how many instance of the service has to be created while running.Controls how many messages are processed.

Select the 'WCF Service' and Location as http. such as TCP and named pipes. to create service and host in IIS Step 1:Start the Visual Studio 2008 and click File->New->Web Site. In addition to HTTP based communication. y Self-Hosting WCF service can be self hosted as console application. it will support only HTTP protocol. Win Forms or WPF application with graphical UI. so that it will be available to everyone accessing from the client. idle shutdown. This will directly host the service in IIS and click OK. y Windows Service WCF can also be hosted as a Windows Service. WCF service can be hosted by following mechanism y IIS Internet information Service provides number of advantages if a Service uses Http as protocol. so that it is under control of the Service Control Manager (SCM).Services can be hosted or executed. process health monitoring and message based activation. IIS 5/6 Hosting The main advantage of hosting service in IIS is that. The main disadvantage of using IIS is that.0.Activation and Hosting . it will automatically launch the host process when it gets the first client request. . It does not require Host code to activate the service. y Windows Activation Service (WAS) is the new process activation mechanism that ships with IIS 7. WCF can also use WAS to provide message-based activation over other protocols. it automatically activates service code. Let as do some hands on. It uses the features of IIS such as process recycling.

IMyService. Interface and implementation of the Service is shown below.Step 2: I have created sample HelloWorld service. } MyService.cs [ServiceContract] public interface IMyService { [OperationContract] string HelloWorld(string name). } #endregion } . which will accept name as input and return with 'Hello' and name.cs public class MyService : IMyService { #region IMyService Members public string HelloWorld(string name) { return "Hello " + name.

This file is used to know about the service. IIS Screen shot . set the value below to true.Config <system. Here I have mention only one end point which is configured to 'wsHttpBinding'. Set to false before deployment to avoid disclosing exception information --> <serviceDebug includeExceptionDetailInFaults="false"/> </behavior> </serviceBehaviors> </behaviors> </system.svc <%@ ServiceHost Language="C#" Debug="true" Service="MyService" CodeBehind="~/App_Code/MyService.serviceModel> <services> <service behaviorConfiguration="ServiceBehavior" name="MyService"> <endpoint address="http://localhost/IISHostedService/MyService.serviceModel> Note: You need to mention the service file name. We have to use only http binding.svc" binding="wsHttpBinding" contract="IMyService"> <identity> <dns value="localhost"/> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="ServiceBehavior"> <!-.To receive exception details in faults for debugging purposes. Web. we can also have multiple end point with differnet binding. MyService. Since we are going to hosted in IIS. We will come to know more on endpoints and its configuration in later tutorial.To avoid disclosing metadata information.Step 3: Service file (. along with the Address mention in the config file.svc) contains name of the service and code behind file name.cs" %> Step 4: Server side configurations are mentioned in the config file. set the value below to false and remove the metadata endpoint above before deployment --> <serviceMetadata httpGetEnabled="true"/> <!-.

.This screen will appear when we run the application.

y y MyService. svcutil http://localhost/IISHostedService/MyService.svc After executing this command we will find two file generated in the default location. . Before creating the client application. Using service utility we can create the proxy class and its configuration information. we need to create the proxy for the service. To create the proxy.Configuration information about the service.config .cs .Step 5:Now we successfully hosted the service in IIS. to interact with service. Step 6: Now we will start creating the Console application using Visual Studio 2008(Client application).Proxy class for the WCF service output. run the Visual Studio 2008 command prompt. This proxy is used by the client application. Next we have to consume this service in client application.

this is the core dll for WCF.ServiceModel'. .Step 7: Add the reference 'System.

WriteLine(client.Read(). .HelloWorld("Ram"))."). } Step 9: If we run the application we will find the output as shown below.Step 8: Create the object for the proxy class and call the HelloWorld method.. Console..WriteLine("Client calling the service. static void Main(string[] args) { //Creating Proxy for the MyService MyServiceClient client = new MyServiceClient(). Console. Console.

Step 1: First let's start create the Service contract and it implementation. Now let's us create the WCF service which is hosted in Console application. We will also look in to creating proxy using 'ClientBase' abstract class. Note: Host process must be running before the client calls the service.I hope you have enjoyed the Service hosted in IIS. This is simple service which return addition of two numbers. but WCF provides the user to host the service in any application (e. . Create a console application and name it as MyCalculatorService. Now let start the look on the self hosted service Self Hosting In web service. we can host the service only in IIS. client and service in the same process. Very interestingly developer is responsible for providing and managing the life cycle of the host process. Windows form etc. Service can also be inpro i.g. console application.e. which typically means you have to prelaunch it.).

.Step 2: Add the System.ServiceModel reference to the project.

namespace MyCalculatorService { [ServiceContract()] public interface ISimpleCalculator { [OperationContract()] int Add(int num1.Linq.cs using using using using using System.Step 3: Create an ISimpleCalculator interface. System.Text.Collections. System. . IMyCalculatorService.ServiceModel. These contracts will expose method to outside world for using this service. You will know more information about these contracts in later session. int num2). System.Generic. } } Step 4: MyCalculatorService is the implementation class for IMyCalculatorService interface as shown below. System. Add ServiceContract and OperationContract attribute to the class and function as shown below.

cs using using using using System. . System.Linq. Let's go for implementing the hosting process. It will accept implemented contract class and base address as contractor parameter. System.MyCalculatorService. } } } Step 5: Now we are ready with service. You can register multiple base addresses separated by commas. but address should not use same transport schema.Text. System.Generic. namespace MyCalculatorService { class SimpleCalculator : ISimpleCalculator { public int Add(int num1. int num2) { return num1 + num2.Collections. Create a new console application and name it as 'MyCalculatorServiceHost' Step 6: ServiceHost is the core class use to host the WCF service.

so that it can be used by any client. Uri tcpUrl = new Uri("net.Text. host. httpUrl).Open() will run the service. ServiceHost host = new ServiceHost(typeof(MyCalculatorService.ToString()).ServiceModel. httpUrl.Description. System. //Add a service endpoint host. Host.Behaviors. //Enable metadata exchange ServiceMetadataBehavior smb = new ServiceMetadataBehavior(). using using using using using using System.ISimpleCalculator) . "").Now. Press <Enter> key to stop").ServiceModel. Step 7: Below code show the implementation of the host process.Generic.tcp://localhost:8090/MyService/SimpleCalculator"). Console. } } .. tcpUrl). //Start the Service host.WriteLine("Host is running.SimpleCalculator).Uri httpUrl = new Uri("http://localhost:8090/MyService/SimpleCalculator").AddServiceEndpoint(typeof(MyCalculatorService. System.Description.Linq. Multiple end points can be added to the Service using AddServiceEndpoint() method.. smb.WriteLine("Service is host at " + DateTime. Console.HttpGetEnabled = true.Collections. new WSHttpBinding().ReadLine(). System.Open(). Console.Add(smb).SimpleCalculator). namespace MyCalculatorServiceHost { class Program { static void Main(string[] args) { //Create a URI to serve as the base address Uri httpUrl = new Uri("http://localhost:8090/MyService/SimpleCalculator"). System. //Create ServiceHost ServiceHost host = new ServiceHost(typeof(MyCalculatorService. System.

Implementing ClientBase<T> class Of these three methods.Text. ISimpleCalculator { public int Add(int num1. now we need to implement the proxy class for the client.Channel. using System. It will create the proxy only at runtime and so it will take care of everything. } } } Step 9: In the client side. int num2) { //Call base to do funtion return base.Add(num1.ServiceModel. Implementing ClientBase<T> is the best practice. There are different ways of creating the proxy y y y Using SvcUtil.Collections.Linq.Linq. Adding Service reference to the client application.ServiceModel. But this is not the case for ClientBase<T>.Collections.Generic. System. using MyCalculatorService. using System. namespace MyCalculatorServiceProxy { public class MyCalculatorServiceProxy : //WCF create proxy for ISimpleCalculator using ClientBase ClientBase<ISimpleCalculator>. using System. namespace MyCalculatorServiceClient { class Program { static void Main(string[] args) { . Add proxy assembly as reference to the project.Generic.exe. using System. MyCalculatorServiceProxy. System. If you are using rest two method. we can create the proxy class and configuration file with end points. using using using using using System.Text. num2). we can create the instance for the proxy class and call the method as shown below. we need to create proxy class every time when we make changes in Service implementation.} Step 8: Service is hosted. System.cs using System. System.

MyCalculatorServiceProxy().Add(5.MyCalculatorServiceProxy. Console.MyCalculatorServiceProxy proxy . proxy= new MyCalculatorServiceProxy. } } } Step 10 : End point (same as service) information should be added to the configuration file of the client application. This self host shows advantage such as in-Pro hosting.. Windows Activation Service .. <?xml version="1.Now.5)).0" encoding="utf-8" ?> <configuration> <system. Console. Console.ToString()). you need to run the service. Output of the client application is shown below. now let go for hosting using Windows Activation service.ISimpleCalculator"> </endpoint> </client> </system. 5+5 ="+proxy.WriteLine("Sum of two numbers. programmatic access and it can be used when there need singleton service.serviceModel> <client> <endpoint address ="http://localhost:8090/MyService/SimpleCalculator" binding ="wsHttpBinding" contract ="MyCalculatorService.serviceModel> </configuration> Step 11: Before running the client application.WriteLine("Client is running at " + DateTime. I hope you have enjoyed the Self hosting session.ReadLine().

It is available with IIS 7. Right click on the "Command Prompt" item. idle time management and common configuration system.HTTP Activation".0 supports only Http. Enable WCF for non-http protocols 2. 4.exe set site "Default Web Site" +bindings.config file located in the "C:\Windows\system32\inetsrv\config" directory. 3. C:\Windows\system32\inetsrv> appcmd. Expand 'Microsoft .0 because it supports Http. .Windows Activation service is a system service available with Windows vista and windows server 2008. isolation. Hosting WCF in Activation service takes many advantages such as process recycling.Net Framework 3. Enable different binding to the hosted service Enable WCF for non-http protocols Before Start creating the service we need to configure the system to support WAS. we will bind the default web site to the TCP protocol. Next we need to add Binding to the Default Web site. bindingInformation='808:*'] y That command adds the net. TCP and named pipes were IIS 6. and select "Run as administrator" from the context menu.[protocol='net. 2.tcp site binding to the default web site by modifying the applicationHost. 1. Open the Visual Studio 2008 and click New>WebSite and select WCF Service from the template and Location as HTTP as shown below. WAS hosted service can be created using following steps 1. Go to the Start menu -> Programs ->Accessories. Create WAS hosted service 3. Click Start -> Control Panel -> programs and Features and click 'Turn Windows Components On or Off' in left pane. Execute the following command 5.tcp'. Following are the step to configure WAS. As an example.0' and enable "Windows Communication Foundation HTTP Activation" and "Windows Communication Foundation Non. Similarly we can add different protocols to the Default Web site.0 and it is more powerful compared to IIS 6. Create WAS hosted service Step 1: Next we are going to create the service. It can be installed and configured separately.

Serialization.Text.Generic. int num2). System. System.cs using using using using using using System. System. IMathService. [ServiceContract] public interface IMathService { [OperationContract] int Add(int num1. int num2). .ServiceModel. [OperationContract] int Subtract(int num1.Step 2: Create the Contract by creating interface IMathService and add ServiceContract attribute to the interface and add OperationContract attribute to the method declaration.Runtime. System.Collections. System.Linq. } Step 3: Implementation of the IMathService interface is shown below.

create end point with 'netTcpBinding' binding and service metadata will be published using Metadata Exchange point. } public int Subtract(int num1.tcp://localhost/WASHostedService/MathService.tcp address (e.num2. System. MathService. System. public class MathService : IMathService { public int Add(int num1. System. System.Config <system.serviceModel> <services> <service name="MathService" behaviorConfiguration="ServiceBehavior"> <!-.To receive exception details in faults for debugging purposes.Service Endpoints --> <endpoint binding="netTcpBinding" contract="IMathService" > </endpoint> <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="ServiceBehavior"> <!-.Runtime.Serialization. Without publishing the service Metadata we cannot create the proxy using net.Generic.g svcutil.cs" %> Step 5: In web. int num2) { return num1 + num2. set the value below to true.To avoid disclosing metadata information.Config file.MathService.cs using using using using using using System.svc <%@ ServiceHost Language="C#" Debug="true" Service="MathService" CodeBehind="~/App_Code/MathService. } } Step 4: Service file is shown below.exe net. System. So create the Metada Exchange end point with address as 'mex' and binding as 'mexTcpBinding'. Set to false before deployment to avoid disclosing . set the value below to false and remove the metadata endpoint above before deployment --> <serviceMetadata httpGetEnabled="true"/> <!-. int num2) { return num1 .Linq.svc ) Web.ServiceModel.Collections.Text.

svc Proxy and configuration file are generated in the corresponding location. Creat the proxy class using Visual Studio Command prompt and execute the command svcutil. .exception information --> <serviceDebug includeExceptionDetailInFaults="false"/> </behavior> </serviceBehaviors></behaviors> </system. and select "Run as administrator" from the context menu.net. Next we can create the proxy class using service uttility and add the proxy class to the client application. Go to the Start menu -> Programs ->Accessories.serviceModel> Enable different binding to the hosted service 1.exe net. 2.tcp://localhost/WASHostedService/MathService. Right click on the "Command Prompt" item.tcp Output will be shown below. Execute the following command C:\Windows\system32\inetsrv>appcmd set app "Default Web Site/WASHostedServcie" /enabledProtocols:http. Step 6: Now the service is ready to use.

Step 6: Create the client application as shown below and add the reference 'System. this is the core dll for WCF.ServiceModel'. .

WriteLine(client. Program. Console.ReadLine().cs class Program { static void Main(string[] args) { MathServiceClient client = new MathServiceClient().Add(5. } } The output will be shown as below.6)). .6").WriteLine("Sum of two number 5.Step 8: Add the proxy class and configuration file to the client application. Console. Console. Create the object for the MathServiceClient and call the method.

So this tutorial clearly explains about the hosting the WCF in Windows Activation Service. This is same as hosting the service in IIS without message activated. . Open the Visual Studio 2008 and click New>Project and select Class Library from the template. Step 1: Now let start create the WCF service. There is some advantage of hosting service in Windows service. So next we can see how to host the service using Windows Service Windows Service Hosting In this tutorial we are going to see the hosting WCF service in Windows service. when system starts Process life time of the service can be controlled by Service Control Manager for windows service All versions of Windows will support hosting WCF service. We will use same set of code used for hosting the WCF service in Console application to this. y y y The service will be hosted.

ServiceModel.ServiceModel to the project. Step 3: Next we can create the ISimpleCalulator interface as shown below.cs using using using using using System. System.Collections. System.Text. [OperationContract] . namespace WindowsServiceHostedContract { [ServiceContract] public interface ISimpleCalculator { [OperationContract] int Add(int num1.Linq. Add the Service and Operation Contract attribute as shown below. This is the core assembly used for creating the WCF service. int num2). System.Step 2: Add reference System. ISimpleCalculator.Generic. System.

} public int Subtract(int num1.Linq. [OperationContract] int Multiply(int num1. Note:In this project. [OperationContract] double Divide(int num1.cs using using using using System. I have mention .int num2). System. int num2) { return num1-num2. System. } public double Divide(int num1.Collections. namespace WindowsServiceHostedService { class SimpleCalculator : ISimpleCalculator { public int Add(int num1.Text. } public int Multiply(int num1. int num2). else return 0. Now we are ready with WCF service. now we are going to see how to host the WCF Service in Windows service.Generic. int num2) { return num1*num2. int num2). } } Step 4: Implement the ISimpleCalculator interface as shown below. int num2) { return num1+num2. int num2) { if (num2 != 0) return num1 / num2. System. SimpleCalulator. } } } Step 5: Build the Project and get the dll.int Subtract(int num1.

Step 6: Open Visual Studio 2008 and Click New->Project and select Windows Service. It is always good practice if you have both in different project. Step 7: Add the 'WindowsServiceHostedService. This assembly will going to act as service.that we are creating both Contract and Service(implementation) are in same project.dll' as reference to the project. .

Collections. On stop method you need to close the Service Host. System.ComponentModel. We have to make sure that we are using only one service host object. System.Data.cs using using using using using using using using using using System.Diagnostics. } . } protected override void OnStart(string[] args) { if (m_Host != null) { m_Host.Text. we can write the hosting code for WCF.Generic. System. public WCFHostedWindowsService() { InitializeComponent(). System. System.Linq. Following code show how to host WCF service in Windows service.ServiceModel. System. namespace WCFHostedWindowsService { partial class WCFHostedWindowsService : ServiceBase { ServiceHost m_Host.ServiceProcess.Description. System.Close().ServiceModel. WCFHostedWindowsService. System. System.Step 8: OnStart method of the service.

ServiceInstaller.Text. Please find the below code for mentioning the Service name.Collections. //Create ServiceHost m_Host = new ServiceHost (typeof(WindowsServiceHostedService. new WSHttpBinding().Configuration.Configuration. //Add a service endpoint m_Host. which is inherited from the Installer class.ServiceProcess. m_Host.Description.SimpleCalculator). System. ServiceBase. System. //Enable metadata exchange ServiceMetadataBehavior smb = new ServiceMetadataBehavior(). So add new Installer class to the project. } } static void Main() { ServiceBase[] ServicesToRun. smb.//Create a URI to serve as the base address Uri httpUrl = new Uri("http://localhost:8090/MyService/SimpleCalculator"). m_Host = null.Add(smb).Open().Generic.HttpGetEnabled = true. System.cs using using using using using using using System.ComponentModel. ServicesToRun = new ServiceBase[] { new WCFHostedWindowsService() }. System. .ISimpleCalculator). //Start the Service m_Host.Close(). } protected override void OnStop() { if (m_Host != null) { m_Host. System. httpUrl).Run(ServicesToRun). System.Behaviors.Install. } } } Step 9: In order to install the service we need to have the Installer class for the Windows service.AddServiceEndpoint (typeof(WindowsServiceHostedService. StartUp type etc of the service. "").

namespace WCFHostedWindowsService { [RunInstaller(true)] public class WinServiceInstaller : Installer { private ServiceProcessInstaller process. process. Installers. } } } Step 10: Build the project.Add(service). service.Account = ServiceAccount. Next we need to install the service using Visual Studio Command Prompt. we will get the WCFHostedWindowsService.NetworkService.exe.Description = "WCF Service Hosted". service.Automatic. Installers. So open the command prompt by clicking Start->All Programs-> Microsoft Visual Studio 2008-> Visual Studio Tools-> Visual Studio Command Prompt Using installutil utility application.Add(process). . private ServiceInstaller service.DisplayName = "WCFHostedWindowsService". service. public WinServiceInstaller() { process = new ServiceProcessInstaller().ServiceName = "WCFHostedWindowsService".StartType = ServiceStartMode. service = new ServiceInstaller(). you can install the service as shown below. service.

it is a stack of channel components that all messages pass through during runtime processing. Bindings and Channel Stacks In WCF all the communication details are handled by channel. The transport channel uses a message encoder to read the incoming bytes into a logical Message object for further processing.Step 11: Now service is Hosted sucessfully and we can create the proxy class for the service and start using in the client applcaiton. This implements the given transport protocol and reads incoming messages off the wire. . The bottom-most component is the transport channel.

Types of Binding Let us see more detailed on predefined binding BasicHttpBinding . giving each protocol channel an opportunity to do its processing. until it eventually reaches the top and WCF dispatches the final message to your service implementation. So WCF provides easy way of achieving this using end point. the message bubbles up through the rest of the channel stack. The binding binds your service implementation to the wire through the channel stack in the middle. Messages undergo significant transformation along the way. It is very difficult for the developer to work directly with channel stack architecture.Figure 1: Bindings and Channel Stacks (draw new diagram) After that. binding and contract. and whether or not they are compatible with one other. Windows Communication Foundation follows the instructions outlined by the binding description to create each channel stack. To know more about end point. Because you have to be very careful while ordering the channel stack components. In end point we will specify address.

transaction and reliability. WSFederationHttpBinding This binding support federated security. It uses TCP protocol and provides support for security. reliable.Addressing. It supports WS-* functionality and distributed transactions with reliable and secure sessions using SOAP security. In WSDualHttpBinding reliable sessions are enabled by default. It supports WS-Federation protocol.Net to . By default it creates communication stack using WS-ReliableMessaging protocol for reliability.y y y y y It is suitable for communicating with ASP. NetTcpBinding This binding provides secure and reliable binding environment for . This binding uses HTTP as the transport and text/XML as the default message encoding. By default it creates communication stack with WS- . It offers lot more functionality in the area of interoperability. WSDualHttpBinding This binding is same as that of WSHttpBinding. transaction and reliability.NET Web services (ASMX)-based services that comfort with WS-Basic Profile conformant Web services. Security is disabled by default This binding does not support WS-* functionalities like WS. WSHttpBinding y y y y y Defines a secure. TCP for message delivery and windows security for message and authentication at run time. except it supports duplex service. WS-Security. which allows service to communicate with client via callback. It helps implementing federation which is the ability to flow and share identities across multiple enterprises or trust domains for authentication and authorization.Net cross machine communication. It also supports communication via SOAP intermediaries. interoperable binding suitable for non-duplex service contracts. Reliable sessions are disabled by default. Duplex service is a service which uses duplex message pattern. It uses NamedPipe protocol and provides full support for SOAP security. NetNamedPipeBinding This binding provides secure and reliable binding environment for on-machine cross process communication. It uses HTTP and HTTPS transport for communication. WS-ReliableMessaging It is fairly weak on interoperability.

serviceModel> <services> <service name="MyService"> <endpoint address="http://localhost/IISHostedService/MyService. It enables for disconnected operations. transaction and reliability. Binding configuration Binding can be configured either through configuration file or Programming.svc" binding="wsHttpBinding" bindingName="wshttpbind" contract="IMyService"> <identity> <dns value="localhost"/> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> <bindings> <wsHttpBinding> <binding name="wshttpbind" allowCookies="true" closeTimeout="00:01:00" receiveTimeout="00:01:00" /> </wsHttpBinding> . <system. Queuing is provided by using MSMQ as transport. It uses TCP protocol for communication It provides full support for SOAP security. named pipes for message delivery and binary encoding. Administrative (Configuration file): In the configuration file of the hosting application.serviceModel> element and add the properties to particular binding type. Name of the binding properties that you are going to use has to be mention in the end point. Let us see the binding representation in each method. Properties corresponding to the particular binding type can be mentioned below. NetMsmqBinding y y y This binding provides secure and reliable queued communication for cross-machine environment. failure isolation and load leveling NetPeerTcpBinding y y y This binding provides secure binding for peer-to-peer environment and network applications. transport security for transfer security.ReliableMessaging for reliability. you can add the <bindings> element inside the <system.

WriteLine("Service is host at " + DateTime. HTTP_GET Enabled Metadata We will use ServiceBehaviour to publish the metadata using HTTP-GET. wshttpbind. host.Add(smb). //Enable metadata exchange ServiceMetadataBehavior smb = new ServiceMetadataBehavior(). 0).ISimpleCalculator). HTTP-Get metadata address is given by http://localhost:9090/MyCalulatorService?wsdl.WriteLine("Host is running.</bindings> </system..ToString()).. //Add a service endpoint host.Now.AllowCookies = true. Console.AddServiceEndpoint (typeof(MyCalculatorService. 0). //Create a URI to serve as the base address Uri httpUrl = new Uri("http://localhost:8090/MyService/SimpleCalculator"). This binding object is added to the Service endpoint for client communication. Similarly you can also create any type of binding and add to endpoint. For example service address is http://localhost:9090/MyCalulatorService .Description. It is always good practice to represent in the configuration file. smb. because while moving to the production you no need to change in the code and recompile it. wshttpbind. //Create ServiceHost ServiceHost host = new ServiceHost(typeof(MyCalculatorService.Open().ReceiveTimeout = new TimeSpan(0. wshttpbind. key to stop"). I have created the WSHttpBinding object and assign the properties which to be configured.CloseTimeout = new TimeSpan(0.serviceModel> Programming Model: In the following code. This can be configures either administratively or Programmatically.ReadLine().SimpleCalculator). Console. //Create Binding to add to end point WSHttpBinding wshttpbind = new WSHttpBinding(). Http and Https can expose by appending "?wsdl" to the end of the service address. 1. Press Console. Note: It is always good if you configure the binding properties using configuration file. ""). //Start the Service host.HttpGetEnabled = true. httpUrl). wshttpbind.Behaviors. . 1.

<system. you can find the behavior section in the ServiceBehavior. Then you have to add the behavior to host description as shown.SimpleCalculator). ""). //Add a service endpoint host.serviceModel> <services> <service behaviorConfiguration="ServiceBehavior" name="MyService"> <endpoint address="http://localhost/IISHostedService/MyService. //Create ServiceHost ServiceHost host = new ServiceHost(typeof(MyCalculatorService.Administrative (Configuration file): In the below mention configuration information. httpUrl).Add(smb).serviceModel> Progarmming Model: Using ServiceMetadataBehavior you can enable the metadata exchange.Behaviors. host.ISimpleCalculator). //Start the Service . //Enable metadata exchange ServiceMetadataBehavior smb = new ServiceMetadataBehavior().HttpGetEnabled = true. This set of code will publish the metadata using HTTP-GET. //Create a URI to serve as the base address Uri httpUrl = new Uri("http://localhost:8090/MyService/SimpleCalculator").svc" binding="wsHttpBinding" contract="IMyService"> <identity> <dns value="localhost"/> </identity> </endpoint> </service> </services> <behaviors> <serviceBehaviors> <behavior name="ServiceBehavior"> <!-Setting httpGetEnabled you can publish the metadata --> <serviceMetadata httpGetEnabled="true"/> </behavior> </serviceBehaviors> </behaviors> </system. //Enable metadata exchange using HTTP-GET smb.Description.AddServiceEndpoint (typeof(MyCalculatorService. In the following code. I have created the ServiceMetadataBehavior object and assigned HttpGetEnabled property to true. new WSHttpBinding(). You can expose the metadata using ServiceMetadata node with httpGetEnable='True'.

you can add metadata exchange endpoint as shown below. Console.serviceModel> <services> <service name="MyService"> <endpoint address="http://localhost/IISHostedService/MyService. You can specify as address in the endpoint but append with "mex" keyword.Now.host.Open(). mexHttpsBinding.ReadLine(). You can have as many metadata exchange endpoints as you want. For example "http://localhost:9090/MyCalulatorService/mex" Binding There are four types of bindings supported for metadata exchange.WriteLine("Host is running. Metadata Exchange Endpoint Exposing the metadata using HTTP-GET has a disadvantage. Press Console. There is other way of exposing the using special endpoint is called as Metadata Exchange Endpoint. mexTcpBinding. You can create the Metadata Exchange Endpoint either Administrative (configuration file) or programmatically. Address It is basically Uri to identify the metadata. such that there is no guarantee that other platforms you interact will support it. mexNamedPipesBinding.WriteLine("Service is host at " + DateTime. <system. Administrative (Configuration file): In the configuration file of the hosting application. They are mexHttpBinding. Contract IMetadataExchange is the contract used for MEX endpoint...ToString()). Console.svc" binding="wsHttpBinding" contract="IMyService"> <identity> <dns value="localhost"/> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> . key to stop"). WCF service host automatically provides the implementation for this IMetadataExcahnge while hosting the service.

Behaviors.WriteLine("Host is running.</services> </system. binding and contract.. //Start the Service host.CreateMexHttpBinding (). host. y 3.AddServiceEndpoint (typeof(MyCalculatorService. Console. Press Console.Description.AddServiceEndpoint(typeof(IMetadataExchange).Now.ToString()).CreateMexHttpBinding ().Add(smb).ReadLine().ISimpleCalculator).. "mex").Description. //Create ServiceHost ServiceHost host = new ServiceHost(typeof(MyCalculatorService.WriteLine("Service is host at " + DateTime. host. y Create the metadata binding object using MetadataExchangeBinding Binding mexBinding = MetadataExchangeBindings.Add(smb). //Create a URI to serve as the base address Uri httpUrl = new Uri("http://localhost:8090/MyService/SimpleCalculator"). "mex").Behaviors. mexBinding. ServiceMetadataBehavior smb = new ServiceMetadataBehavior(). Steps to create the metadata endpoint are y Create the ServiceMetadataBehavior object and add to Service host description.SimpleCalculator).Open(). //Adding metadata exchange endpoint host.AddServiceEndpoint(typeof(IMetadataExchange). //Enable metadata exchange ServiceMetadataBehavior smb = new ServiceMetadataBehavior(). mexBinding. Service Contract . new WSHttpBinding(). "").serviceModel> Programming Model: In the following code I have mention about creating the Metadata Exchange Endpoint through coding. Complete code for hosting the service with metadata exchange endpoint is shown below. httpUrl). //Add a service endpoint host. host. Console. key to stop"). Binding mexBinding = MetadataExchangeBindings. Add the endpoint to the service host with address.

others might require a request-reply pattern It is analogous to the element in WSDL To create a service contract you define an interface with related methods representative of a collection of service operations. But it is not good practice of creating the service [ServiceContract()] public class SimpleCalculator { [OperationContract()] public int Add(int num1. Methods in the interface that should be included in the service contract are decorated with the OperationContract Attribute. y y y y It describes the client-callable operations (functions) exposed by the service It maps the interface and methods of your service to a platform-independent description It describes message exchange patterns that the service can have with another party. } } With out creating the interface. [ServiceContract()] public interface ISimpleCalculator { [OperationContract()] int Add(int num1.Service contract describes the operation that service provide. public { class SimpleCalculator : ISimpleCalculator public int Add(int num1. int num2) { return num1 + num2. } } . we can also directly created the service by placing Contract in the implemented class. [ServiceContract] attribute is similar to the [WebServcie] attribute in the WebService and [OpeartionContract] is similar to the [WebMethod] in WebService. Service Contract can be define using [ServiceContract] and [OperationContract] attribute. and then decorate the interface with the ServiceContract Attribute to indicate it is a service contract. Some service operations might be one-way. } Once we define Service contract in the interface. int num2) { return num1 + num2. int num2). we can create implement class for this interface. A Service can have more than one service contract but it should have at least one Service contract.

private string m_Manager. } . Data contract can be explicit or implicit. This data type should be identified for serialization and deserialization by mentioning with [DataContract] and [DataMember] attribute. Through serialization. private string m_Designation. Through deserialization. string etc has an implicit data contract. for which you have to define a Data contract using [DataContract] and [DataMember] attribute. [DataMember] public string Name { get { return m_Name.Now you have some fundamental idea on Service contract. private int m_Age. A data contract can be defined as follows: y y y y y It describes the external format of data passed to and from service operations It defines the structure and types of data exchanged in service messages It maps a CLR type to an XML Schema t defines how data types are serialized and deserialized. Create user defined data type called Employee. } [DataContract] public class Employee { private string m_Name. This assembly holds the DataContract and DataMember attribute. Next we will look into Data Contract. you convert an object into a sequence of bytes that can be transmitted over a network. you reassemble an object from a sequence of bytes that you receive from a calling application. Data Contract A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged.Serialization reference to the project. It is a versioning system that allows you to manage changes to structured data We need to include System. } set { m_Name = value. Simple type such as int.Runtime. [ServiceContract] public interface IEmployeeService { [OperationContract] Employee GetEmployeeDetails(int EmpId). User defined object are explicit or Complex type. private int m_Salary.

In GetEmployee method we have created the Employee instance and return to the client. } set { m_Salary = value. client will aware of this instance whenever he creates proxy for the service. } } [DataMember] public int Salary { get { return m_Salary. } set { m_Designation = value. public class EmployeeService : IEmployeeService { public Employee GetEmployeeDetails(int empId) { Employee empDetail = new Employee(). The client side code is shown below. } } Client side On client side we can create the proxy for the service and make use of it. Since we have created the data contract for the Employee class. } set { m_Age = value. } set { m_Manager = value. //Do something to get employee details and assign to 'empDetail' properties return empDetail. . } } [DataMember] public string Manager { get { return m_Manager. } } [DataMember] public string Designation { get { return m_Designation.} [DataMember] public int Age { get { return m_Age. } } } Implementation of the service class is shown below.

Header and Body. WCF uses SOAP message for communication. Diagram Soap envelope Message Pattern It describes how the programs will exchange message each other. WCF will automatically take care of message. 2.header and body element. WCF uses SOAP(Simple Object Access Protocol) Message format for communication. SOAP body contains information which is used by the target. Duplex . when source send message to the target. Employee empDetails. empDetails = objEmployeeClient.It is two way communication. EventArgs e) { EmployeeServiceClient objEmployeeClient = new EmployeeServiceClient(). Most of the time developer will concentrate more on developing the DataContract. WCF supports either RPC(Remote Procedure Call) or Message style operation model.It is two way communications. you can develop operation with Ref and out parameter.It is one way communication. //Do something on employee details } Message Contract Message Message is the packet of data which contains important information. WCF will automatically . both source and target can send and receive message simultaniouly. WCF uses these messages to transfer information from Source to destination. In that case WCF provides Message Contract to customize the message as per requirement. it will resend response message to the source. But at a time only one can send a message 3. On Some critical issue. Request/Replay . but target will not respond to the message. etc. SOAP message contain Envelope. SOAP Hear contain important information which are not directly related to message.GetEmployeeDetails(empId). What is Message contract? As I said earlier.SOAP envelope contails name. Simplex . developer will also require control over the SOAP message format. namespace. In the RPC model. Serializing the data. There are three way of communication between source and destination 1.protected void btnGetDetails_Click(object sender. Source will send message to target.

EmployeeDetails ModifyEmployeeDetails(EmployeeDetails emp). Note: If a type has both Message and Data contract. 8. .create the message for operation at run time. Location as extra member to the SOAP Body. Only one parameter can be used in servicie Operation 2. Designation. [MessageBodyMember] public string Designation. Salary. Service operation either should return Messagecontract type or it should not return any value 5. It also add Name. Service operation will accept and return only message contract type. WCF will add extra header call 'EmpID' to the SOAP envelope. } When I use this EmployeeDeatils type in the service operation as parameter. Rules : You have to follow certain rules while working with Message contract 1. EmployeeDetails GetEmployeeDetails(). void SaveEmployeeDetails(EmployeeDetails emp). In Message style operation WCF allows to customize the message header and define the security for header and body of the message. Custom Header and Body can be included to message using 'MessageHeader' and 'MessageBodyMember'atttribute. Let us see the sample message contract definition. When using Message contract type as parameter. [MessageContract] public class EmployeeDetails { [MessageHeader] public string EmpID. 4. 7. [MessageBodyMember] public string Name. [OperationContract] 6. service operation will accept only message contract. Other data types are not allowed. [OperationContract] 3. Defining Message Contract Message contract can be applied to type using MessageContract attribute. [OperationContract] 9. [MessageBodyMember] public string Location. [MessageBodyMember] public int Salary.

By default when we throw any exception from service. what wents wrong? not on how and where cause the error. How I can know the error? For this we are having Fault Contract. } } Step 2: On client side code. I want to know the real cause of the problem. This error should be reported to the client in proper manner. int num2). I got the message that exceptions are not handled properly. This help as to easy identity the what error has accord. WCF provides the option to handle and convey the error message to client from service using SOAP Fault contract. Fault Contract provides documented view for error accorded in the service to client. Even though I have capture the exception when I run the application. In order to support interoperability and client will also be interested only. Basically when we develop managed application or service. Exceptions are handled using try-Catch block.catch block. But these exceptions handlings are technology specific. Suppose the service I consumed is not working in the client application. } //Service implementation public class SimpleCalculator : ISimpleCalculator { public int Add(int num1.Fault Contract Service that we develop might get error in come case. Let us try to understand the concept using sample example. we will handle the exception using try. it will not reach the client side. Step 1: I have created simple calculator service with Add operation which will throw general exception as shown below //Service interface [ServiceContract()] public interface ISimpleCalculator { [OperationContract()] int Add(int num1. try { . int num2) { //Do something throw new Exception("Error while adding number").

.Message).ReadLine(). } Step 4: Output window on the client side is show below. These are the steps to be followed to create the fault contract. Decorate the service operation with the FaultContract attribute and specify the type name.Add(5.MyCalculatorServiceProxy proxy = new MyCalculatorServiceProxy. you have to use FaultException as shown below.Now. y y Define a type using the data contract and specify the fields you want to return. } Step 3: Now if you want to send exception information form service to client. 5)). Console. 5+5 =" + proxy.MyCalculatorServiceProxy..WriteLine("Sum of two numbers.MyCalculatorServiceProxy().ToString()). } catch (Exception ex) { Console. public int Add(int num1. Console.WriteLine(ex.ReadLine(). . Step 5: You can also create your own Custom type and send the error information to the client using FaultContract. int num2) { //Do something throw new FaultException("Error while adding number"). Console. Console.WriteLine("Client is running at " + DateTime.

ex. . throw new FaultException(ex.".". [DataMember()] public string ExceptionMessage. Console.MyCalculatorServiceProxy(). Console. [DataMember()] public string StackTrace. Console. 5+5 =" + proxy. } Step 9: On client side. } Step 8: Raise the exception from the service public int Add(int num1.y Raise the exception from the service by creating an instance and assigning properties of the custom exception. int num2) { //Do something CustomException ex = new CustomException(). you can capture the service exception and process the information.MyCalculatorServiceProxy proxy = new MyCalculatorServiceProxy.ReadLine().WriteLine("Sum of two numbers.Title = "Error Funtion:Add()". as shown below. ex.WriteLine("Client is running at " + DateTime.ToString()). ex. } Step 7: Decorate the service operation with the FaultContract [ServiceContract()] public interface ISimpleCalculator { [OperationContract()] [FaultContract(typeof(CustomException))] int Add(int num1. [DataMember()] public string InnerException.InnerException = "Inner exception message from serice". Step 6: Defining the type using Data Contract [DataContract()] public class CustomException { [DataMember()] public string Title. ex.. try { MyCalculatorServiceProxy.Now. int num2).StackTrace = "Stack Trace message from service.ExceptionMessage = "Error occur while doing add function. 5))."Reason: Testing the Fault contract") .Add(5..

} catch (FaultException<MyCalculatorService.CustomException> ex) { //Process the Exception } Per-Call Service When WCF service is configured for Per-Call instance mode. Service instance will be created for each client request. Following diagram represent the process of handling the request from client using Per-Call instance mode. This Service instance will be disposed after response is sent back to client. .

Step 1: Create the service contract called IMyService and implement the interface. return m_Counter.PerCall)] public class MyService:IMyService { static int m_Counter = 0. increment the static variable(m_Counter). public int MyMethod() { m_Counter++. Each time while making call to the service. Add service behavior attribute to the service class and set the InstanceContextMode property to PerCall as show below. } Step 2: In this implementation of MyMethod operation.Let as understand the per-call instance mode using example. [ServiceBehavior(InstanceContextMode=InstanceContextMode. m_Counter variable is incremented and return the value to the client. [ServiceContract()] public interface IMyService { [OperationContract] int MyMethod(). .

WriteLine("Counter: " + proxy. static void Main(string[] args) { Console. service instance will be disposed.WriteLine("Counter: " + proxy. all requests to service return '1'. Console..MyMethod()).WriteLine("Counter: " + proxy. It is independent of all other instance. Console. . Output is shown below.MyMethod()). Console.MyServiceProxy proxy = new MyCalculatorServiceProxy.ReadLine().WriteLine("Client making call to service.WriteLine("Service Instance mode: Per-Call").MyMethod()). Per-Session Service When WCF service is configured for Per-Session instance mode.} } Step 3: Client side.WriteLine("Counter: " + proxy. Console. While return back. When the client creates new proxy to particular service instance.. Service instance will created for each request and value of static variable will be set to one. a dedicated service instance will be provided to the client. Console.MyServiceProxy().").MyMethod()). } Surprisingly. Following diagram represent the process of handling the request from client using Per-Session instance mode. Fig: PercallOutput. because we configured the Instance mode to PerCall. logical session between client and service will be maintained. //Creating the proxy on client side MyCalculatorServiceProxy. create the proxy for the service and call "myMethod" operation multiple time. Console.

Step 1: Create the service contract called IMyService and implement the interface. create the proxy for the service and call "myMethod" operation multiple time.Let as understand the Per-Session instance mode using example. [ServiceBehavior(InstanceContextMode=InstanceContextMode. } } Step 3: Client side. m_Counter variable will be incremented and return the value to the client. public int MyMethod() { m_Counter++. return m_Counter. static void Main(string[] args) . Add service behavior attribute to the service class and set the InstanceContextMode property to PerSession as show below. increment the static variable (m_Counter). Each time while making call to the service. } Step 2: In this implementation of MyMethod operation.PerSession)] public class MyService:IMyService { static int m_Counter = 0. [ServiceContract()] public interface IMyService { [OperationContract] int MyMethod().

} All request to service return incremented value (1. . because we configured the instance mode to Per-Session. Console. Service instance will be created once the proxy is created at client side. Console.MyMethod()). Singleton Service When WCF service is configured for Singleton instance mode. Console.MyMethod()).{ Console. So each time request is made to the service. So each call to MyMethod return incremented value."). static variable is incremented. it is disposed when host shuts down.MyMethod()).ReadLine(). Console. Output is shown below.. Fig: PersessionOutput.WriteLine("Counter: " + proxy.MyMethod()). Console. all clients are independently connected to the same single instance.WriteLine("Service Instance mode: Per-Session"). 2.WriteLine("Client making call to service. This singleton instance will be created when service is hosted and..WriteLine("Counter: " + proxy. Console. 3. 4).MyServiceProxy proxy = new MyCalculatorServiceProxy.WriteLine("Counter: " + proxy.MyServiceProxy(). //Creating the proxy on client side MyCalculatorServiceProxy.WriteLine("Counter: " + proxy. Following diagram represent the process of handling the request from client using Singleton instance mode.

} Step 2: In this implementation of MyMethod operation. m_Counter variable is incremented and return the value to the client [ServiceBehavior(InstanceContextMode=InstanceContextMode. create the two proxies for the service and made a multiple call to MyMethod.WriteLine("Service Instance mode: Singleton"). Add service behavior attribute to the service class and set the InstanceContextMode property to Single as show below."). . static void Main(string[] args) { Console. Each time while making call to the service. public int MyMethod() { m_Counter++.. increment the static variable(m_Counter).Single)] public class MyService:IMyService { static int m_Counter = 0. return m_Counter.WriteLine("Client 1 making call to service. Console. Step 1: Create the service contract called IMyService and implement the interface. } } Step 3: Client side..Let as understand the Singleton Instance mode using example. [ServiceContract()] public interface IMyService { [OperationContract] int MyMethod().

//Creating the proxy on client side MyCalculatorServiceProxy. Instance Deactivation In Instance Management System tutorial. 3. Basically service instance is hosted in a context.. 2. you learn how to create sessionful service instance. Console. When session starts.MyServiceProxy().MyMethod()). single instance at service will handle it and it return incremented value (1. Console. context is terminated. but to the context that host it. Console.WriteLine("Counter: " + proxy2. //Creating new proxy to act as new client MyCalculatorServiceProxy. Console. ReleaseInstanceMode property of the OberationalBehavior attribute used to control the instance in relation to the method call."). WCF provides the option of separating the two lifetimes and deactivating the instance separately from its context.WriteLine("Counter: " + proxy.MyServiceProxy proxy = new MyCalculatorServiceProxy. context is created and when it closes.WriteLine("Counter: " + proxy.WriteLine("Counter: " + proxy.MyMethod()). Fig: SingletonOutput. 4). } When two proxy class made a request to service.MyMethod()).WriteLine("Counter: " + proxy2.ReadLine().MyMethod()). Output is shown below.MyServiceProxy proxy2 = new MyCalculatorServiceProxy. Console. Service instance is created when it is hosted. So this instance will remain till host is shutdown.MyServiceProxy().MyMethod()). because instance mode is configured to 'Single'. Console.. .WriteLine("Client 2 making call to service. Console. Session actually correlated the client message not to the instance.

Followings are the list Release mode available in the ReleaseInstanceMode 1.BeforeCall This property means that it will create new instance before a call is made to the operation. } [OperationBehavior(ReleaseInstanceMode=ReleaseInstanceMode.AfterCall RealeaseInstanceMode.BeforeCall] public int Add(int num1. This is designed to optimize a method such as Create() . 2.BeforeCall RealeaseInstanceMode.BeforeAndAfterCall Below code show. ReleaseInstanceMode.WCF deactivates the instance and calls Dispose() before the call is done.None This property means that it will not affect the instance lifetime. If the instance is already exist.None RealeaseInstanceMode. int num2) { return num1 + num2. } ReleaseInstanceMode. how to add the 'ReleaseInstanceMode' property to the operational behavior. RealeaseInstanceMode. int num2). 3. [ServiceContract()] public interface ISimpleCalculator { [OperationContract()] int Add(int num1. By default ReleaseInstanceMode property is set to 'None'. 4.

BeforeAndAfterCall This is means that it will create new instance of object before a call and deactivates the instance after call.AfterCall This property means that it will deactivate the instance after call is made to the method. This is designed to optimize a method such a Cleanup() ReleaseInstanceMode.BeforeCall and ReleaseInstanceMode. This has combined effect of using ReleaseInstanceMode.ReleaseInstanceMode.AfterCall Explicit Deactivate .

but content in the session environment is not persisted by default. Defining the Durable Service . It can use data store like SQL database for maintain instance state.InstanceContext.Current. data will be lost. Working: When Durable service is created with database as data store. We will call this GUID as instanceID. instanceId will be saved at the client side. When a client make a request to the service. a new GUID is generated.Net 3. It means that durable services have the capability to restore their own state when they are recycled. If the service is shut down or client closes the proxy.5 You might think that we can also maintain session using WCF sessions. So when ever client opening the proxy. Service will send the instanceID to the client. But in case of Durable service it is still maintained. It is new feature in . Even when client is shut down. it can get back the previous state. instance of the service is serialized.ReleaseServiceInstance().You can also explicitly deactivate instance using InstanceContext object as shown below.Single)] public class MyService:IMyService { public void MyMethod() { //Do something OperationContext. [ServiceContract()] public interface IMyService { [OperationContract] void MyMethod(). } } Durable Service Durable services are WCF services that persist service state information even after service host is restarted or Client. } [ServiceBehavior(InstanceContextMode=InstanceContextMode. so later it can use this id to get the instance state back. This serialized instance xml and key will be saved in the database. it will maintain all its state information in the table.

y y CanCreateInstance = true: Calling this operation results in creating the serialization and inserting it into the datastore. Select the 'WCF Service' as shown below. . It takes 'CanCreateInstance' and 'CompletesInstance' property to mention on which operation instance state has to be saved and destroyed. [Serializable] [DurableService()] public class MyService :IMyservice { [DurableOperation(CanCreateInstance = true)] public int StartPersistance() { //Do Something } [DurableOperation(CompletesInstance = true)] public void EndPersistence() { //Do Something } } How to Create Durable Service Let us understand more about the durable service by creating Simple Calculator service which persist the instance state in SQL server database.Durable service can be implemented using [DurableService()] attribute. Step 1: Start the Visual Studio 2008 and click File->New->Web Site. CompletesInstance = true: Calling this operation results in deleting the persisted instance from the datastore.

Set CanCreateInstance = true property to the operation in which instance state has to be persisted and set CompletesInstance = true when state has to be destroyed. [OperationContract] void EndPersistence().Step 2: Create interface and decorate with Service and Operation contract. we are going to persist the 'currentValue' variable value to the database. [OperationContract] int Subtract(int num). In this implementation. . } Step 3: You need to add [Serializable] And [DurableService()] attribute to the service implementation. [OperationContract] int Multiply(int num). [ServiceContract()] public interface ISimpleCalculator { [OperationContract] int Add(int num).

sql Step 5: In order to support durable service.Serialization. run the these sql query located at following location 'C:\Windows\Microsoft. [Serializable] [DurableService()] public class SimpleCalculator :ISimpleCalculator { int currentValue = default(int). <system. using System.sql SqlPersistenceProviderLogic.Runtime. } [DurableOperation()] public int Multiply(int num) { return (currentValue *= num).serviceModel> <services> <service name="SimpleCalculator" behaviorConfiguration="ServiceBehavior"> <!-. } [DurableOperation()] public int Subtract(int num) { return (currentValue -= num). } [DurableOperation(CompletesInstance = true)] public void EndPersistence() { } Step 4: Before configuring the database information in the durable service. Microsoft provides inbuilt sqlPersistance provider. <persistenceProvider> tag is used to configure the persistence provider. using System.using System.ServiceModel.Description. [DurableOperation(CanCreateInstance = true)] public int Add(int num) { return (currentValue += num). using System. you need to set up DataStore environment. you need to use Context binding type.ServiceModel. To set up the database environment.5\SQL\EN' y y SqlPersistenceProviderSchema.NET\Framework\v3.Text.Service Endpoints --> <endpoint address="" binding="wsHttpContextBinding" bindingConfiguration="browConfig" contract="ISimpleCalculator"> <identity> <dns value="localhost"/> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> .

serviceModel> <connectionStrings> <add name="DurableServiceStore" connectionString="Data Source=saravanakumar.5.ServiceModel.Integrated Security=True"/> </connectionStrings> Step 6: Create the console client application and name it as DurableServiceClient .WorkflowServices. Culture=neutral.0.Initial Catalog =DurableServiceStore. Version=3.SqlPersistenceProviderFactory. PublicKeyToken=31bf3856ad364e35" connectionStringName="DurableServiceStore" persistenceOperationTimeout="00:00:10" lockTimeout="00:01:00" serializeAsText="true"/> </behavior> </serviceBehaviors> </behaviors> <bindings> <wsHttpContextBinding > <binding name="browConfig" > <security mode="None"></security> </binding> </wsHttpContextBinding> </bindings> </system. System.</service> </services> <behaviors> <serviceBehaviors> <behavior name="ServiceBehavior"> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="true"/> <persistenceProvider type="System.0.Persistence.

ServiceModel System.WorkflowService .Step 7: Add following reference to client application y y System.

Step 8: Add WCF service as Service Reference to the project and name it as SimpleCalculatorService .

Retrieve and set the context at the client side. Helper.bin". System.Formatters.Step 9: Create the Helper class called it as Helper.Serialization.ServiceModel. System. String> LoadContext() { IDictionary<String. System. Copy and paste the below code to your helper file.ServiceModel. public static IDictionary<String. System.Net.Binary. This helper class is used to Store.Runtime.Channels.bin' file. Context information will be saved in 'token_context.cs using using using using using System. String> ctx = null.cs. try { .IO. public class Helper { static readonly String TokenContextFileName = "token_context.

GetContext() as IDictionary<String. String>.Delete(TokenContextFileName).Read)) { BinaryFormatter bf = new BinaryFormatter(). } } catch (Exception ex) { } return ctx. ctx = bf.Open. } public static void SaveContext(IClientChannel channel) { IDictionary<String. } catch (Exception ex) { } } public static void SetContext(IClientChannel channel. IContextManager cm = channel. .Deserialize(fs) as IDictionary<String. String> ctx = null. fs. ctx).Close(). FileMode. String>.using (FileStream fs = new FileStream(TokenContextFileName. fs. try { using (FileStream fs = new FileStream(TokenContextFileName. bf.Close(). } } catch (Exception ex) { } } } public static void DeleteContext() { try { File. if (cm != null) { ctx = cm.Serialize(fs. FileMode.CreateNew)) { BinaryFormatter bf = new BinaryFormatter(). FileAccess.GetProperty<IContextManager>().

InnerChannel. //Remove persistance state from the server client. When I call the Subtract and Multiply operation.Close().SaveContext(client.SetContext(client. static void Main(string[] args) { //Create the proxy for the service SimpleCalculatorService. it will operate on the previously saved value (instance state).Add(10000).Multiply(5). } } } Step 10: In the main method. //Call the Add method from the service currentValue = client. //Load the context from the client to start from saved state IDictionary<string. Console.ReadLine(). I was creating the proxy for the service and calling the Add operation. //Call the Subtract and Multiply method from service currentValue = client. Console. client. Console. service instance saved in the database as shown below.WriteLine("The current value is {0}".WriteLine("The current value is {0}". currentValue = client. currentValue). String> ctx) { IContextManager cm = channel.WriteLine("Press <ENTER> to shut down the client.").IDictionary<String. . Console.SimpleCalculatorClient ("WSHttpContextBinding_ISimpleCalculator"). } End of the proxy 1. //Delete the context from the client Helper. //Close the proxy client.string> cntx=Helper.Subtract(2).EndPersistence().GetProperty<IContextManager>(). Console. currentValue). if (cm != null) { cm. currentValue).LoadContext(). //Create new Instance of the proxy for the service client = new SimpleCalculatorService. Call to this method will add instance state to the database. cntx).WriteLine("The current value is {0}".DeleteContext().SimpleCalculatorClient "WSHttpContextBinding_ISimpleCalculator").SimpleCalculatorClient client = new SimpleCalculatorService. Now I have closed the proxy and creating new proxy instance.Close(). int currentValue = 0. //Set Context to context manager Helper.SetContext(ctx).InnerChannel). //Save the Context from the service to the client Helper.

Performance of the WCF service can be improved by creating proper instance. Attribute Description . Throttling WCF throttling provides some properties that you can use to limit how many instances or sessions are created at the application level. Output of the client application.Serialized XML instance state save in the database is shown below.

The default is 10. maxConcurrentInstances . ServiceThrottlingBehavior throttle = host. . The number of InstanceContext objects that execute at one time across a ServiceHost. throttle. if (throttle == null) { throttle = new ServiceThrottlingBehavior().Find(). session and instance property.serviceModel> <services > <service behaviorConfiguration="ServiceBehavior" name="MyService"> <endpoint address="" binding="wsHttpBinding" contract="IMyService"> <identity> <dns value="localhost"/> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="ServiceBehavior"> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="true "/> <serviceThrottling maxConcurrentCalls="500" maxConcurrentInstances ="100" maxConcurrentSessions ="200"/> </behavior> </serviceBehaviors> </behaviors> </system. Service Throttling can be configured either Adminstractive or Programatically Administrative(configuration file) Using <serviceThrottling> tag of the Service Behavior. A positive integer that limits the number of sessions a ServiceHost object can accept.serviceModel> Programming Model Use ServiceThrottlingBehavior object to set concurrent calls.Description. The default is 16.maxConcurrentCalls maxConcurrentInstances maxConcurrentSessions Limits the total number of calls that can currently be in progress across all service instances. maxConcurrentSessions property as shown below. <system.MaxConcurrentCalls = 500.Behaviors. ServiceHost host = new ServiceHost(typeof(MyService)). The default is Int32. you can configure the maxConcurrentCalls.MaxValue.

One-Way 3.Replay 2. host. along with that it also supports One-Way call(call and forget operation) and callback(service to call back the client) Three modes of communication between client and service are 1. and continue executing once the method returned.MaxConcurrentSessions = 200. Operations In classic object or component.Behaviors. WCF will support classical Request-Replay model.Open(). } host. Callback Request-Reply . Client will issue a call. block while the call was in progress.throttle. Request.MaxConcurrentInstances = 100.Description. throttle.Add(throttle).oriented programming model offered only single way for client to call a method.

client will receive TimeOutException. while the service processes the operation in the background. they may not be dispatched all at once but may instead be queued up on the service side to be dispatched one at a time. Apart from NetPeerTcpBinding and the NetMsmqBinding all other bindings will support requestreply operations. according to the service's configured concurrency mode behavior. One-Way In One-Way operation mode. once the call is queued. after making one-way call to server. There is no return from the server side. If service doesn't respond to the service within receiveTimeout. It means that. After getting the response it will start executing the rest of the statement. the client will be unblocked and can continue executing. it is one-way communication. If any exception thrown by service will not reach the server. Client will be blocked only for a moment till it dispatches its call to service. the client will be blocked even if it's issued a one-way call. .By default all WCF will operated in the Request-Replay mode. However. client will send a request to the server and does not care whether it is success or failure of service execution. when client make a request to the WCF service and client will wait to get response from service (till receiveTimeout). Sometime when one-way calls reach the service. till server execute. There is no need to wait. If the number of queued messages has exceeded the queue's capacity. Client can continue to execute its statement.

use in the last operation of the service which will terminate the session. } As per above configuration. what will happen when you use the one-way communication with Sessionful service. } One-Way Operations and Exceptions . } One-Way Operations and Sessionful Services Let us see the example. [ServiceContract] public interface IMyService { [OperationContract(IsOneWay=true)] void MyMethod(EmployeeDetails emp). when client makes one-way call using MyMethod() operation and if it close the proxy. [ServiceContract(SessionMode = SessionMode. Client will be blocked until operation completes. It will be good practice.Definition : One-way operation can be enabled by setting IsOneWay property to true in Operation contract attribute. [ServiceContract(SessionMode = SessionMode. IsInitiating = false. that one-way operation should be applied on per-call and singleton service. [OperationContract] string MyMethod2().Required)] interface IMyContract { [OperationContract] void MyMethod1(). [OperationContract(IsOneWay = true.Required)] interface IMyContract { [OperationContract(IsOneWay = true)] void MyMethod(). Suppose If you want to make use of One-way operation in Sessionful service. IsTerminating = true)] string CloseSessionService(int id). This operation should not return any value.

Suppose when we are using BasicHttpBinding or WSHttpBinding, i.e. no transport session is used, if any exception throw by service will not affect the client. Client can make a call to the service using same proxy
[ServiceContract] interface IMyContract { [OperationContract(IsOneWay = true)] void MethodWithError( ); [OperationContract] void MethodWithoutError( ); } //Client side without transport session MyContractClient proxy = new MyContractClient( ); proxy.MethodWithError( ); //No exception is thrown from serivce proxy.MethodWithoutError( ); //Operation will execute properly proxy.Close( );

In the presence of transport session, any exception thrown by service will fault the client channel. Client will not be able to make new call using same proxy instance.
//Client side transport session MyContractClient proxy = new MyContractClient( ); proxy.MethodWithError( ); proxy.MethodWithoutError( ); //Can not executre because channel is faulted proxy.Close( );

Callback Service
Till now we have seen that the all clients will call the service to get the things done. But WCF also provides the service to call the client. In which, service will act as client and client will act as service.
y y y

HTTP protocols are connectionless nature, so it is not supported for callback operation. So BasicHttpBinding and WSHttpBinding cannot be used for this operation. WCF support WSDualHttpBinding for call back operation. All TCP and IPC protocols support Duplex communication. So all these binding will be used for callback operation.

Defining and configuring a callback contract
Callback service can be enabled by using CallbackContract property in the ServiceContract attribute. In the below example you can find the decalration of the callback contract and it is configured in the ServiceContract attribute.
public interface IMyContractCallback { [OperationContract]

void OnCallback(); } [ServiceContract(CallbackContract = typeof(IMyContractCallback))] public interface IMyContract { [OperationContract()] void MyMethod(); }

Client Callback Setup
As I said earlier, in callback operation client will act as service and service will act as client. So client has to expose a callback endpoint to the service to call. In the earlier part of the tutorial I have mention that InstanceContext is the execution scope of inner most service instance. It provides a constructor that takes the service instance to the host.
IMyContractCallback callback=new MyCallback(); InstanceContext cntx=new InstanceContext(callback); MyServiceClient proxy = new MyServiceClient(cntx); proxy.MyMethod();

The client must use a proxy that will set up the bidirectional communication and pass the callback endpoint reference to the service. This can be achieved by creating the proxy using DuplexClientBase
class MyServiceClient:DuplexClientBase,IMyContract { public MyServiceClient(InstanceContext callbackCntx) : base(callbackCntx) {

} public void MyMethod() { base.Channel.MyMethod(); } }

Service-Side Callback Invocation
The client-side callback endpoint reference is passed along with every call the client makes to the service, and it is part of the incoming message. The OperationContext class provides the service with easy access to the callback reference via the generic method GetCallbackChannel<T>( ). Service can call the client side callback method using reference e to the client side callback instance. The following code shows the callback method invocation.
IMyContractCallback callbackInstance=OperationContext.Current.GetCallbackChannel(); callbackInstance.OnCallback();

How to Create Callback Service in WCF
This tutorial gives hands-on to create a sample Callback service. Step 1: Create the sample Classlibrary project using Visual Studio 2008 and name it as CallbackService

namespace CallbackService { public interface IMyContractCallback { [OperationContract] void OnCallback().Linq. IMyContract.cs using using using using using System.ServiceModel.Step 2 : Add System.Generic. System. } .Text.Collections. System. You need to mention CallbackContract property in the ServiceContract attribute. System. Implementation of the Callback contract will be done on the client side.ServiceModel reference to the project Step 3: Create the Callback and Service contract as shown below. System.

callbackInstance.Current. } } Step 4: Implement the Service contract as shown below.Text. this may leads to deadlock. namespace CallbackService { [ServiceBehavior(ConcurrencyMode=ConcurrencyMode. So you can set ConcurrencyMode to Multiple or Reentent so it will release the lock silently.OnCallback(). If you are calling the Callback method inside the service method. Using that instance we are calling the OnCallback() method from client side. you will be end up with deadlock exception as shown below. In the below code you will find using OperationContext is used to receive the reference to Callback instance.Multiple )] public class MyService:IMyContract { public void MyMethod() { //Do something IMyContractCallback callbackInstance =OperationContext.Collections. . System. System. channel is created and lock by WCF service. If you are not using ConcurrencyMode to Multiple or Reentent.Generic. MyService. } } } You can also note that We have set the ConcurrencyMode to Multile.[ServiceContract(CallbackContract = typeof(IMyContractCallback))] public interface IMyContract { [OperationContract()] void MyMethod().Linq.cs using using using using using System. Service will try to access the lock channel. System. System. This is because when a client made a call to the service.ServiceModel.GetCallbackChannel().

Step 5: Create a Console application using Visual Studio 2008 and name it a CallbackServiceHost. This application is used to self-host the WCF service .

Close().Config <system.MyService).serviceModel> Step 8: Run the host application .").Open(). DateTime. Web.. Console. host.WriteLine("Service is Hosted at {0}". Console.ReadLine().WriteLine("Host is running.Step 6: Main method static void Main(string[] args) { Uri httpUrl = new Uri("http://localhost:8090/MyService/"). httpUrl).IMyContract"> <identity> <dns value="localhost"/> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="ServiceBehavior"> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="true "/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> <services > <service behaviorConfiguration="ServiceBehavior" name="CallbackService.ToString())..Press key to stop the service.Now. } Step 7: Use Duplex binding to support Callback operation.MyService"> <endpoint address="http://localhost:8090/MyService" binding="wsDualHttpBinding" contract="CallbackService. Console. host. ServiceHost host = new ServiceHost(typeof(CallbackService.

System. This is the client application which contain Callback implementation. System. Step10: Add System. using using using using using using System. because it will support bidirectional communication.IMyContract { public MyServiceClient(InstanceContext callbackCntx) . Use DuplexClientBase to create the proxy.Text.Linq.ServiceModel and CallbackService as reference to the project Step 11: Create the proxy class as shown below.ServiceModel. namespace CallbackClient { class MyServiceClient:DuplexClientBase<IMyContract>.Generic.Step 9: Create Console Application using Visual Studio 2008 and name it as CallbackClient. System. System.Collections. CallbackService. Create the contractor which will accept InstanceContext as parameter.

MyServiceClient proxy = new MyServiceClient(cntx).Channel."). In the output. Console.MyMethod().: base(callbackCntx) { } public void MyMethod() { base. InstanceContext cntx=new InstanceContext(callback).").WriteLine("Callback method is called from client side. } } } Step12: Create the implementation for Callback Contract class MyCallback : IMyContractCallback { public void OnCallback() { Console. proxy. } } Step 13: Implementation of main method static void Main(string[] args) { IMyContractCallback callback=new MyCallback(). you can see the OnCallback method called by the service Events .MyMethod(). Console.ReadLine().WriteLine("Client call the MyMethod Operation from Service. } Step14: Run the client application.

The service firing the event is called the publisher. Large number of subscribers to the event makes the accumulated processing time of each subscriber could exceed the publisher's timeout Managing the list of subscribers and their preferences is a completely service-side implementation. Publisher will be blocked. } Let us understand more on Event operation by creating sample service . It will not affect the client. These make publishers to put in wait state.Net delegates to manage the list of subscribers. or it may be the result of something the service monitors. when subscriber is queued on previous subscription of the event. and the client receiving the event is called the subscriber. y y y y y Publisher will not care about order of invocation of subscriber. It may lead Publisher event not to reach other subscriber. Let us consider the scenario in which you what to publish large volume of event. An event may result from a direct client call. Implementation of subscriber side should be short duration. Event should always one-Way operation and it should not return any value Definition public interface IMyEvents { [OperationContract(IsOneWay = true)] void Event1().Events allow the client or clients to be notified about something that has occurred on the service side. Subscriber can be executed in any manner. publisher can even use .

Since service has to communicate to the client. } [ServiceContract(CallbackContract = typeof(IMyEvents))] public interface IMyContract { [OperationContract] void DoSomethingAndFireEvent(). . Here we are using one operation to subscribe the event and another for firing the event.ServiceModel to the project Create the Event operation at the service and set IsOnwWay property to true. Step 2: Add reference System. This operation should not return any value. public interface IMyEvents { [OperationContract(IsOneWay = true)] void Event1().Step 1 : Create ClassLibrary project in the Visual Studio 2008 and name it as WCFEventService as shown below. we need to use CallbackContract for duplex communication.

[OperationContract] void SubscribeEvent(). I am using Operationcontext to get the reference to the client instance and Subscription method is added as event handler to the service event. DoSomethingAndFireEvent operation will fire the event as shown. In the Subscription operation.Current.PerCall)] public class MyPublisher : IMyContract { static Action m_Event1 = delegate { }. m_Event1 += subscriber. } Step 3: Implementation of the Service Contract is shown below.Event1. } public void DoSomethingAndFireEvent() { MyPublisher. . } } Step 4: Create the Console application using Visual Studio 2008 and name it as WcfEventServiceHost.GetCallbackChannel(). public void SubscribeEvent() { IMyEvents subscriber = OperationContext.FireEvent().cs [ServiceBehavior(InstanceContextMode = InstanceContextMode. This application will be used to self-host the service. MyPublisher. } public static void FireEvent() { m_Event1().

Open(). host.WriteLine("Service is Hosted at {0}". Console. Web.Config <system.MyPublisher). Console.ServiceModel and WcfEventService as reference to the project.serviceModel> <services > <service behaviorConfiguration="ServiceBehavior" name="WcfEventService.").WriteLine("Host is running.ToString()).Close().MyPublisher"> <endpoint address="http://localhost:8090/MyPublisher" ..Now. host. } Step 6: Use Duplex binding to support Callback operation. DateTime..Press key to stop the service. Console. httpUrl).Step 5: Add System. static void Main(string[] args) { Uri httpUrl = new Uri("http://localhost:8090/MyPublisher/"). ServiceHost host = new ServiceHost(typeof(WcfEventService.ReadLine().

This application will act a client which is used to subscribe the event from service.IMyContract"> <identity> <dns value="localhost"/> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="ServiceBehavior"> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="true "/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> Step7: Run the host application as shown below.binding="wsDualHttpBinding" contract="WcfEventService. Step 8: Create the console application using visual studio and name it as WcfEventServiceClient as shown below. .

because it will support bidirectional communication.DoSomethingAndFireEvent(). } } .SubscribeEvent(). Use DuplexClientBase to create the proxy. } public void SubscribeEvent() { base.cs class EventServiceClient:DuplexClientBase<IMyContract>. EventServiceClient.Step 9: Create the proxy class as shown below.IMyContract { public EventServiceClient(InstanceContext eventCntx) : base(eventCntx) { } public void DoSomethingAndFireEvent() { base. Create the contractor which will accept InstanceContext as parameter.Channel.Channel.

Subscriber got notification.ToString()). } Step 12: Run the client application and you see the when event is fired from the service.DateTime.DoSomethingAndFireEvent().Now. WCF supports two modes for transferring messages .WriteLine("Client subscribe the event from the service at {0}". Transfer mode In our normal day today life. InstanceContext evntCntx = new InstanceContext(evnt).WriteLine("Event is subscribed from the service at {0}". This method will be called when service publish the event. Based on the size and other condition of the data transfer. proxy. we need to transfer data from one location to other location.ToString() ). If data transfer is taking place through WCF service.SubscribeEvent(). proxy.DateTime. message size will play major role in performance of the data transfer.Now. Console. EventServiceClient proxy = new EventServiceClient(evntCntx). Console.WriteLine("Client call operation which will fire the event").Step 10: Implementation of IMyEvents at client side is shown below. Console. class MySubscriber : IMyEvents { public void Event1() { Console.ReadLine(). } } Step 11: Main method of the client side you can find the creating Subscription instance and it passed to service using InstanceContext static void Main(string[] args) { IMyEvents evnt = new MySubscriber().

As a result. Stream transfer When client and Service exchange message using Streaming transfer mode.Buffer transfer When the client and the service exchange messages. StreamRequest In this mode of configuration. Configuration <system. receiver can start processing the message before it is completely delivered. these messages are buffered on the receiving end and delivered only once the entire message has been received. If you want to transfer large message. message send from client to service will be streamed StreamRespone In this mode of configuration. This is true whether it is the client sending a message to the service or the service returning a message to the client. when the client calls the service. likewise. the service is invoked only after the client's message has been received in its entirety. Streamed transfers can improve the scalability of a service by eliminating the requirement for large memory buffers.netTcpBinding" contract="IMyService"> <identity> <dns value="localhost"/> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="ServiceBehavior"> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="true "/> </behavior> </serviceBehaviors> </behaviors> <bindings > <netTcpBinding> . message send from service to client will be streamed.serviceModel> <services > <service behaviorConfiguration="ServiceBehavior" name="MyService"> <endpoint address="" binding="netTcpBinding" bindingConfiguration="MyService. streaming is the best method. the client is unblocked only once the returned message with the results of the invocation has been received in its entirety.

Streamed transfers can improve the scalability of a service by eliminating the requirement for large memory buffers.serviceModel> Differences between Buffered and Streamed Transfers Buffered Target can process the message once it is completely received. Performance will be good when message size is small Streamed Target can start processing the data when it is partially received Performance will be good when message size is larger(more than 64K) Native channels are IRequestChannel and IReplyChannel Native channel shape is IDuplexSessionChannel Comments on this article Streaming Client and Service exchange message using Streaming transfer mode.netTcpBinding" transferMode="Buffered" closeTimeout ="0:01:00" openTimeout="0:01:00"></binding> </netTcpBinding> </bindings> </system. streaming is the best method.<binding name="MyService. . If you want to transfer large message. receiver can start processing the message before it is completely delivered. when streaming is enabled in WCF y y Digital signatures for the message body cannot be performed Encryption depends on digital signatures to verify that the data has been reconstructed correctly. Supported Bindings y y y BasicHttpBinding NetTcpBinding NetNamedPipeBinding Restrictions There are some restriction.

Stream and MemoryStream are serializable and it will support streaming 3.. to return or receive a Stream as an operation parameter. StreamedRequest. all subclasses like FileStream.y y y Reliable sessions must buffer sent messages on the client for redelivery if a message gets lost in transfer and must hold messages on the service before handing them to the service implementation to preserve message order in case messages are received out-ofsequence. StreamedResponse } public class BasicHttpBinding : Binding. [OperationContract] Stream GetStreamData(). and it will not support streaming Streaming and Binding Only the TCP. and basic HTTP bindings support streaming. { public TransferMode TransferMode {get. you need to do is. Stream and it's subclass can be used for streaming. Streaming is not available with the Message Queuing (MSMQ) transport Streaming is also not available when using the Peer Channel transport I/O Streams WCF uses . //Default Streamed. NetworkStream are derived from it. but it should be serializable 2.set. With all of these bindings streaming is disabled by default. TransferMode property should be set according to the desired streaming mode in the bindings. FileStream is non serializable. Stream in base class for streaming.. [ServiceContract] public interface IMyService { [OperationContract] void SaveStreamData(Stream emp). public enum TransferMode { Buffered.Net stream class for Streaming the message.MemoryStream. } Note: 1. Stream the data.} //More members } . IPC..

Recovery Challenge Let us discuss more on challenge we will phased and how to recover from it. So you can increase the message size using maxReceivedMessageSize attribute in the binding element as shown below.y y y y StreamedRequest . 2. Consider a system maintained in consistent state.serviceModel> <bindings > <netTcpBinding> <binding name="MyService.Send and receive requests and responses in streamed mode in both directions Buffered -Send and receive requests and responses in Buffered mode in both directions Streaming and Transport The main aim of the Streaming transfer mode is to transfer large size data. <system. In addition. It provides way to logically group single piece of work and execute them as a single unit. 3.Send and accept requests in buffered mode. you should recover from it and place the system in the consistent state. Solution . Because we have to recover all these state to its previous consistence state.netTcpBinding" transferMode="Buffered" maxReceivedMessageSize="1024000"> </binding> </netTcpBinding> </bindings> </system. 1. While doing singe operation. there will be multiple atomic sub operation will happen. Performance will be decreased because you need to execute huge amount of code. WCF allows client applications to create transactions and to propagate transactions across service boundaries. and accept and return responses in streamed mode Streamed .serviceModel> Transaction A transaction is a collection or group of one or more units of operation executed as a whole.Send and accept requests in streaming mode. We are not considering about sub operation which are failed. but default message size is 64K. Productivity penalty has to be payee for all effort required for handcrafting the recovery logic 4. These operations might success or fail. when application fail to perform particular operation. We mainly consider about the success operation. and accept and return responses in buffered mode StreamResponse .

Consistent . you had to inform a resource that you would like to perform transactional work against it. Isolated . Traditionally. Such resources have been around in one form or another for decades. y y y y Atomic . Below figure gives idea about transaction. Some resources support auto-enlisting. This act is called enlisting. indivisible operation.When transaction completes.Resources participating in the transaction should be locked and it should not be access by other third party.Durable transactions must survive failures.transaction must leave the system in consistent state. Durable . y y y Committed transaction: Transaction that execute successfully and transfer the system from consistence state A to B. Transaction Resources Transactional programming requires working with a resource that is capable of participating in a transaction. In-doubt transaction: Transactions fail to either in commit or abort. all the individual changes made to the resource while process must be made as to they were all one atomic. Aborted transaction: Transaction encounters an error and rollback to Consistence State A from intermediate state.Best way to maintain system consistence and handling error-recovery challenge is to use transactions. and being able to commit or roll back the changes made during the transaction. . Transaction Properties Transaction can be said as pure and successful only if meets four characteristics.

Sign up to vote on this title
UsefulNot useful