0% found this document useful (0 votes)
266 views109 pages

Introduction To WCF

This document provides an introduction and overview of Windows Communication Foundation (WCF). WCF is a framework for building distributed network services in .NET. It combines features of web services, remoting, MSMQ, and COM+ into a single programming model. WCF provides interoperability, reliability, security, and other advantages over older .NET communication technologies. The document discusses WCF concepts like endpoints, bindings, contracts, and development tools for building WCF services and applications.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
266 views109 pages

Introduction To WCF

This document provides an introduction and overview of Windows Communication Foundation (WCF). WCF is a framework for building distributed network services in .NET. It combines features of web services, remoting, MSMQ, and COM+ into a single programming model. WCF provides interoperability, reliability, security, and other advantages over older .NET communication technologies. The document discusses WCF concepts like endpoints, bindings, contracts, and development tools for building WCF services and applications.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 109

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. 2. 3. 4. WCF is interoperable with other services when compared to .Net Remoting,where the client and service have to be .Net. WCF services provide better reliability and security in compared to ASMX web services. 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. 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:

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

NetMsmqBinding

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.


<system.serviceModel> <services> <service name="MathService" behaviorConfiguration="MathServiceBehavior"> <endpoint address="http://localhost:8090/MyService/MathService.svc" contract="IMathService" binding="wsHttpBinding"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="MathServiceBehavior"> <serviceMetadata httpGetEnabled="True"/> <serviceDebug includeExceptionDetailInFaults="true" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel>

Binding and Behavior

Binding
Simple definition for Binding describes how the client will communicate with service. We can understand with an example. Consider a scenario say, I am creating a service that has to be used by two type of client. One of the client will access SOAP using http and other client will access Binary using TCP. 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.
<system.serviceModel> <services> <service name="MathService" behaviorConfiguration="MathServiceBehavior"> <endpoint address="http://localhost:8090/MyService/MathService.svc" contract="IMathService" binding="wsHttpBinding"/> <endpoint address="net.tcp://localhost:8080/MyService/MathService.svc" contract="IMathService" binding="netTcpBinding"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="MathServiceBehavior"> <serviceMetadata httpGetEnabled="True"/> <serviceDebug includeExceptionDetailInFaults="true" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel>

See how simple it is in WCF. Microsoft is making everything simple.cording to its scope: common behaviors affect all endpoints globally, service behaviors affect only service-related aspects, endpoint behaviors affect only endpoint-related properties, and operation-level behaviors affect particular operations.
Example:

In the below configuration information, I have mentioned the Behavior at Service level. In the service behavior I have mention the servieMetadata node with attribute httGetEnabled='true'. This attribute will specifies the publication of the service metadata. Similarly we can add more behavior to the service.
<system.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.serviceModel>

Contracts and Service Host


Contracts
In WCF, all services are exposed as contracts. Contract is a platform-neutral and standard way of describing what the service does. Mainly there are four types of contracts available in WCF

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

Data Contract
Data contract describes the custom data type which is exposed to the client. This defines the data types, that are passed to and from service. Data types like int, 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.g. 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 DataContract see DataContract tutorial.

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

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

Service Host
Service Host object is in the process of hosting the WCF service and registering endpoints. It loads the service configuration endpoints, apply the settings and start the listeners to handle the incoming request. System.ServiceModel.ServiceHost namespace hold this object. This object is created while self hosting the WCF service. In the below example you can find that WCF service is self hosted using console application.
//Creating uri for the hosting the service Uri uri = new Uri("http://localhost/CategoryService"); //Creating the host object for MathService ServiceHost host = new ServiceHost(typeof(CategoryService), uri); //Adding endpoint to the Host object host.AddServiceEndpoint(typeof(ICategoryService),new WSHttpBinding(), uri); host.Open(); //Hosting the Service Console.WriteLine("Waiting for client invocations"); Console.ReadLine(); host.Close();

Message and Channel


Message
WCF Message is the unit of data exchange between client and service. It consists of several parts, including a body and headers.

WCF Runtime
WCF runtime is the set of object responsible for sending and receiving message. For example formatting the message, applying security and transmitting and receiving message using various protocol.

Channels:

Channels are the core abstraction for sending message to and receiving message from an Endpoint. Broadly we can categories channels as
Transport Channels

- Handles sending and receiving message from network. Protocols like HTTP, TCP name pipes and MSMQ.
Protocol Channels

- Implements SOAP based protocol by processing and possibly modifying message. e.g. WSSecurity and WS-Reliability.

WCF Client and Metadata


WCF Client
WCF client is a client application creates to expose the service operations as method. Any application can host a WCF client, including an application that host a service. Therefore it is possible to create a service that includes WCF clients of other services. 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. 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. Example type the following sentence in the Visual studio command prompt, this will generate the class file and configuration file which contain information about the endpoints. svcutil /language:vb /out:ClientCode.vb /config:app.config http://localhost:8090/MyService/SimpleCalculator.svc?wsdl 2. Call operations. Add this class files in the client application. Then create the object for this class and invoke the service operation. Configuration information we got from the above step has to be added to the client application configuration file. When the client application calls the first operation, WCF automatically opens the underlying channel. This underlying channel is closed, when the object is recycled.
//Creating the proxy on client side MyCalculatorServiceProxy.MyServiceProxy proxy = new MyCalculatorServiceProxy.MyServiceProxy();

Console.WriteLine("Counter: " + proxy.MyMethod());

3. Close the WCF client object. After using the object created in the above steps, we have to dispose the object. Channel will be closed with the service, when the object is cleared.

Metadata
Characteristics of the service are described by the metadata. This metadata can be exposed to the client to understand the communication with service. Metadata can be set in the service by enabling the ServiceMetadata node inside the servcieBehaviour node of the service configuration file.
<system.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.serviceModel>

This metadata can be viewed while creating WCF client application using SvcUtil.exe

WCF Architecture
The following figure illustrates the major components of WCF.

Figure 1: WCF Architecture

Contracts
Contracts layer are next to that of Application layer. Developer will directly use this contract to develop the service. We are also going to do the same now. Let us see briefly what these contracts will do for us and we will also know that WCF is working on message system.

Service contracts
- Describe about the operation that service can provide. Example, Service provided to know the temperature of the city based on the zip code, this service we call as Service contract. It will be created using Service and Operational Contract attribute.

Data contract

- It describes the custom data type which is exposed to the client. This defines the data types, are passed to and from service. Data types like int, string are identified by the client because it is already mention in XML schema definition language document, but custom created class or datatype cannot be identified by the client e.g. Employee data type. By using DataContract we can make client aware that we are using Employee data type for returning or passing parameter to the method.

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

Policies and Binding


- Specify conditions required to communicate with a service e.g security requirement to communicate with service, protocol and encoding used for binding.

Service Runtime
- It contains the behaviors that occur during runtime of service.

Throttling Behavior- Controls how many messages are processed. Error Behavior - Specifies what occurs, when internal error occurs on the service. Metadata Behavior - Tells how and whether metadata is available to outside world. Instance Behavior - Specifies how many instance of the service has to be created while running. Transaction Behavior - Enables the rollback of transacted operations if a failure occurs. Dispatch Behavior - Controls how a message is processed by the WCF Infrastructure.

Messaging
- Messaging layer is composed of channels. A channel is a component that processes a message in some way, for example, by authenticating a message. A set of channels is also known as a channel stack. Channels are the core abstraction for sending message to and receiving message from an Endpoint. Broadly we can categories channels as

Transport Channels Handles sending and receiving message from network. Protocols like HTTP, TCP, name pipes and MSMQ.

Protocol Channels Implements SOAP based protocol by processing and possibly modifying message. E.g. WS-Security and WS-Reliability.

Activation and Hosting


- Services can be hosted or executed, so that it will be available to everyone accessing from the client. WCF service can be hosted by following mechanism

IIS Internet information Service provides number of advantages if a Service uses Http as protocol. It does not require Host code to activate the service, it automatically activates service code.

Windows Activation Service (WAS) is the new process activation mechanism that ships with IIS 7.0. In addition to HTTP based communication, WCF can also use WAS to provide message-based activation over other protocols, such as TCP and named pipes.

Self-Hosting WCF service can be self hosted as console application, Win Forms or WPF application with graphical UI.

Windows Service WCF can also be hosted as a Windows Service, so that it is under control of the Service Control Manager (SCM).

IIS 5/6 Hosting


The main advantage of hosting service in IIS is that, it will automatically launch the host process when it gets the first client request. It uses the features of IIS such as process recycling, idle shutdown, process health monitoring and message based activation. The main disadvantage of using IIS is that, it will support only HTTP protocol. Let as do some hands on, to create service and host in IIS Step 1:Start the Visual Studio 2008 and click File->New->Web Site. Select the 'WCF Service' and Location as http. This will directly host the service in IIS and click OK.

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

MyService.cs
public class MyService : IMyService { #region IMyService Members public string HelloWorld(string name) { return "Hello " + name; } #endregion }

Step 3: Service file (.svc) contains name of the service and code behind file name. This file is used to know about the service. MyService.svc
<%@ ServiceHost Language="C#" Debug="true" Service="MyService" CodeBehind="~/App_Code/MyService.cs" %>

Step 4: Server side configurations are mentioned in the config file. Here I have mention only one end point which is configured to 'wsHttpBinding', we can also have multiple end point with differnet binding. Since we are going to hosted in IIS. We have to use only http binding. We will come to know more on endpoints and its configuration in later tutorial. Web.Config
<system.serviceModel> <services> <service behaviorConfiguration="ServiceBehavior" name="MyService"> <endpoint address="http://localhost/IISHostedService/MyService.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 avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --> <serviceMetadata httpGetEnabled="true"/> <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --> <serviceDebug includeExceptionDetailInFaults="false"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel>

Note: You need to mention the service file name, along with the Address mention in the config file. IIS Screen shot

This screen will appear when we run the application.

Step 5: Now we successfully hosted the service in IIS. Next we have to consume this service in client application. Before creating the client application, we need to create the proxy for the service. This proxy is used by the client application, to interact with service. To create the proxy, run the Visual Studio 2008 command prompt. Using service utility we can create the proxy class and its configuration information.
svcutil http://localhost/IISHostedService/MyService.svc

After executing this command we will find two file generated in the default location.

MyService.cs - Proxy class for the WCF service output.config - Configuration information about the service.

Step 6: Now we will start creating the Console application using Visual Studio 2008(Client application).

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

Step 8: Create the object for the proxy class and call the HelloWorld method.
static void Main(string[] args) { //Creating Proxy for the MyService MyServiceClient client = new MyServiceClient(); Console.WriteLine("Client calling the service..."); Console.WriteLine(client.HelloWorld("Ram")); Console.Read(); }

Step 9: If we run the application we will find the output as shown below.

I hope you have enjoyed the Service hosted in IIS. Now let start the look on the self hosted service.

Self Hosting
In web service, we can host the service only in IIS, but WCF provides the user to host the service in any application (e.g. console application, Windows form etc.). Very interestingly developer is responsible for providing and managing the life cycle of the host process. Service can also be inpro i.e. client and service in the same process. 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, which typically means you have to prelaunch it. Step 1: First let's start create the Service contract and it implementation. Create a console application and name it as MyCalculatorService. This is simple service which return addition of two numbers.

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

Step 3: Create an ISimpleCalculator interface, Add ServiceContract and OperationContract attribute to the class and function as shown below. You will know more information about these contracts in later session. These contracts will expose method to outside world for using this service. IMyCalculatorService.cs
using using using using using System; System.Collections.Generic; System.Linq; System.Text; System.ServiceModel;

namespace MyCalculatorService { [ServiceContract()] public interface ISimpleCalculator { [OperationContract()] int Add(int num1, int num2); } }

Step 4: MyCalculatorService is the implementation class for IMyCalculatorService interface as shown below.

MyCalculatorService.cs
using using using using System; System.Collections.Generic; System.Linq; System.Text;

namespace MyCalculatorService { class SimpleCalculator : ISimpleCalculator { public int Add(int num1, int num2) { return num1 + num2; } } }

Step 5: Now we are ready with service. Let's go for implementing the hosting process. Create a new console application and name it as 'MyCalculatorServiceHost'

Step 6: ServiceHost is the core class use to host the WCF service. It will accept implemented contract class and base address as contractor parameter. You can register multiple base addresses separated by commas, but address should not use same transport schema.

Uri httpUrl = new Uri("http://localhost:8090/MyService/SimpleCalculator"); Uri tcpUrl = new Uri("net.tcp://localhost:8090/MyService/SimpleCalculator"); ServiceHost host = new ServiceHost(typeof(MyCalculatorService.SimpleCalculator), httpUrl, tcpUrl);

Multiple end points can be added to the Service using AddServiceEndpoint() method. Host.Open() will run the service, so that it can be used by any client. Step 7: Below code show the implementation of the host process.
using using using using using using System; System.Collections.Generic; System.Linq; System.Text; System.ServiceModel; System.ServiceModel.Description;

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"); //Create ServiceHost ServiceHost host = new ServiceHost(typeof(MyCalculatorService.SimpleCalculator), httpUrl); //Add a service endpoint host.AddServiceEndpoint(typeof(MyCalculatorService.ISimpleCalculator) , new WSHttpBinding(), ""); //Enable metadata exchange ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; host.Description.Behaviors.Add(smb); //Start the Service host.Open(); Console.WriteLine("Service is host at " + DateTime.Now.ToString()); Console.WriteLine("Host is running... Press <Enter> key to stop"); Console.ReadLine(); } }

Step 8: Service is hosted, now we need to implement the proxy class for the client. There are different ways of creating the proxy

Using SvcUtil.exe, we can create the proxy class and configuration file with end points. Adding Service reference to the client application. Implementing ClientBase<T> class

Of these three methods, Implementing ClientBase<T> is the best practice. If you are using rest two method, we need to create proxy class every time when we make changes in Service implementation. But this is not the case for ClientBase<T>. It will create the proxy only at runtime and so it will take care of everything. MyCalculatorServiceProxy.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; using MyCalculatorService; namespace MyCalculatorServiceProxy { public class MyCalculatorServiceProxy : //WCF create proxy for ISimpleCalculator using ClientBase ClientBase<ISimpleCalculator>, ISimpleCalculator { public int Add(int num1, int num2) { //Call base to do funtion return base.Channel.Add(num1, num2); } } }

Step 9: In the client side, we can create the instance for the proxy class and call the method as shown below. Add proxy assembly as reference to the project.
using using using using using System; System.Collections.Generic; System.Linq; System.Text; System.ServiceModel;

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

MyCalculatorServiceProxy.MyCalculatorServiceProxy proxy ; proxy= new MyCalculatorServiceProxy.MyCalculatorServiceProxy(); Console.WriteLine("Client is running at " + DateTime.Now.ToString()); Console.WriteLine("Sum of two numbers... 5+5 ="+proxy.Add(5,5)); Console.ReadLine(); } } }

Step 10 : End point (same as service) information should be added to the configuration file of the client application.
<?xml version="1.0" encoding="utf-8" ?> <configuration> <system.serviceModel> <client> <endpoint address ="http://localhost:8090/MyService/SimpleCalculator" binding ="wsHttpBinding" contract ="MyCalculatorService.ISimpleCalculator"> </endpoint> </client> </system.serviceModel> </configuration>

Step 11: Before running the client application, you need to run the service. Output of the client application is shown below.

This self host shows advantage such as in-Pro hosting, programmatic access and it can be used when there need singleton service. I hope you have enjoyed the Self hosting session, now let go for hosting using Windows Activation service.

Types of Binding

Let us see more detailed on predefined binding

BasicHttpBinding

It is suitable for communicating with ASP.NET Web services (ASMX)-based services that comfort with WS-Basic Profile conformant Web services. This binding uses HTTP as the transport and text/XML as the default message encoding. Security is disabled by default This binding does not support WS-* functionalities like WS- Addressing, WS-Security, WS-ReliableMessaging It is fairly weak on interoperability.

WSHttpBinding

Defines a secure, reliable, interoperable binding suitable for non-duplex service contracts. It offers lot more functionality in the area of interoperability. It supports WS-* functionality and distributed transactions with reliable and secure sessions using SOAP security. It uses HTTP and HTTPS transport for communication. Reliable sessions are disabled by default.

WSDualHttpBinding
This binding is same as that of WSHttpBinding, except it supports duplex service. Duplex service is a service which uses duplex message pattern, which allows service to communicate with client via callback. In WSDualHttpBinding reliable sessions are enabled by default. It also supports communication via SOAP intermediaries.

WSFederationHttpBinding
This binding support federated security. It helps implementing federation which is the ability to flow and share identities across multiple enterprises or trust domains for authentication and authorization. It supports WS-Federation protocol.

NetTcpBinding
This binding provides secure and reliable binding environment for .Net to .Net cross machine communication. By default it creates communication stack using WS-ReliableMessaging protocol for reliability, TCP for message delivery and windows security for message and authentication at run time. It uses TCP protocol and provides support for security, transaction and reliability.

NetNamedPipeBinding

This binding provides secure and reliable binding environment for on-machine cross process communication. It uses NamedPipe protocol and provides full support for SOAP security, transaction and reliability. By default it creates communication stack with WSReliableMessaging for reliability, transport security for transfer security, named pipes for message delivery and binary encoding.

NetMsmqBinding

This binding provides secure and reliable queued communication for cross-machine environment. Queuing is provided by using MSMQ as transport. It enables for disconnected operations, failure isolation and load leveling

NetPeerTcpBinding

This binding provides secure binding for peer-to-peer environment and network applications. It uses TCP protocol for communication It provides full support for SOAP security, transaction and reliability.

HTTP_GET Enabled Metadata


We will use ServiceBehaviour to publish the metadata using HTTP-GET. This can be configures either administratively or Programmatically. Http and Https can expose by appending "?wsdl" to the end of the service address. For example service address is http://localhost:9090/MyCalulatorService , HTTP-Get metadata address is given by http://localhost:9090/MyCalulatorService?wsdl.

Administrative (Configuration file):


In the below mention configuration information, you can find the behavior section in the ServiceBehavior. You can expose the metadata using ServiceMetadata node with httpGetEnable='True'.
<system.serviceModel> <services> <service behaviorConfiguration="ServiceBehavior" name="MyService"> <endpoint address="http://localhost/IISHostedService/MyService.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.serviceModel>

Progarmming Model:
Using ServiceMetadataBehavior you can enable the metadata exchange. In the following code, I have created the ServiceMetadataBehavior object and assigned HttpGetEnabled property to true. Then you have to add the behavior to host description as shown. 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"); //Create ServiceHost ServiceHost host = new ServiceHost(typeof(MyCalculatorService.SimpleCalculator), httpUrl); //Add a service endpoint host.AddServiceEndpoint (typeof(MyCalculatorService.ISimpleCalculator), new WSHttpBinding(), ""); //Enable metadata exchange ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); //Enable metadata exchange using HTTP-GET smb.HttpGetEnabled = true; host.Description.Behaviors.Add(smb); //Start the Service host.Open(); Console.WriteLine("Service is host at " + DateTime.Now.ToString()); Console.WriteLine("Host is running... Press Console.ReadLine();

key to stop");

Metadata Exchange Endpoint


Exposing the metadata using HTTP-GET has a disadvantage, such that there is no guarantee that other platforms you interact will support it. There is other way of exposing the using special endpoint is called as Metadata Exchange Endpoint. You can have as many metadata exchange endpoints as you want.

Address

It is basically Uri to identify the metadata. You can specify as address in the endpoint but append with "mex" keyword. For example "http://localhost:9090/MyCalulatorService/mex"
Binding

There are four types of bindings supported for metadata exchange. They are mexHttpBinding, mexHttpsBinding, mexNamedPipesBinding, mexTcpBinding.
Contract

IMetadataExchange is the contract used for MEX endpoint. WCF service host automatically provides the implementation for this IMetadataExcahnge while hosting the service. You can create the Metadata Exchange Endpoint either Administrative (configuration file) or programmatically.

Administrative (Configuration file):


In the configuration file of the hosting application, you can add metadata exchange endpoint as shown below.
<system.serviceModel> <services> <service name="MyService"> <endpoint address="http://localhost/IISHostedService/MyService.svc" binding="wsHttpBinding" contract="IMyService"> <identity> <dns value="localhost"/> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> </system.serviceModel>

Programming Model:
In the following code I have mention about creating the Metadata Exchange Endpoint through coding. Steps to create the metadata endpoint are

Create the ServiceMetadataBehavior object and add to Service host description.


ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); host.Description.Behaviors.Add(smb);

Create the metadata binding object using MetadataExchangeBinding

Binding mexBinding = MetadataExchangeBindings.CreateMexHttpBinding ();

3. Add the endpoint to the service host with address, binding and contract.
host.AddServiceEndpoint(typeof(IMetadataExchange), mexBinding, "mex");

Complete code for hosting the service with metadata exchange endpoint is shown below.
//Create a URI to serve as the base address Uri httpUrl = new Uri("http://localhost:8090/MyService/SimpleCalculator"); //Create ServiceHost ServiceHost host = new ServiceHost(typeof(MyCalculatorService.SimpleCalculator), httpUrl); //Add a service endpoint host.AddServiceEndpoint (typeof(MyCalculatorService.ISimpleCalculator), new WSHttpBinding(), ""); //Enable metadata exchange ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); host.Description.Behaviors.Add(smb); Binding mexBinding = MetadataExchangeBindings.CreateMexHttpBinding (); //Adding metadata exchange endpoint host.AddServiceEndpoint(typeof(IMetadataExchange), mexBinding, "mex"); //Start the Service host.Open(); Console.WriteLine("Service is host at " + DateTime.Now.ToString()); Console.WriteLine("Host is running... Press Console.ReadLine();

key to stop");

Service Contract
Service contract describes the operation that service provide. A Service can have more than one service contract but it should have at least one Service contract. Service Contract can be define using [ServiceContract] and [OperationContract] attribute. [ServiceContract] attribute is similar to the [WebServcie] attribute in the WebService and [OpeartionContract] is similar to the [WebMethod] in WebService.

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. Some service operations might be one-way; 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, and then decorate the interface with the ServiceContract Attribute to indicate it is a service contract. Methods in the interface that should be included in the service contract are decorated with the OperationContract Attribute.
[ServiceContract()] public interface ISimpleCalculator { [OperationContract()] int Add(int num1, int num2); }

Once we define Service contract in the interface, we can create implement class for this interface.
public { class SimpleCalculator : ISimpleCalculator public int Add(int num1, int num2) { return num1 + num2; } }

With out creating the interface, we can also directly created the service by placing Contract in the implemented class. But it is not good practice of creating the service
[ServiceContract()] public class SimpleCalculator { [OperationContract()] public int Add(int num1, int num2) { return num1 + num2; } }

Now you have some fundamental idea on Service contract. Next we will look into Data Contract.

Data Contract
A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged.

Data contract can be explicit or implicit. Simple type such as int, string etc has an implicit data contract. User defined object are explicit or Complex type, for which you have to define a Data contract using [DataContract] and [DataMember] attribute. A data contract can be defined as follows:

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. Through serialization, you convert an object into a sequence of bytes that can be transmitted over a network. Through deserialization, you reassemble an object from a sequence of bytes that you receive from a calling application. It is a versioning system that allows you to manage changes to structured data

We need to include System.Runtime.Serialization reference to the project. This assembly holds the DataContract and DataMember attribute. Create user defined data type called Employee. This data type should be identified for serialization and deserialization by mentioning with [DataContract] and [DataMember] attribute.
[ServiceContract] public interface IEmployeeService { [OperationContract] Employee GetEmployeeDetails(int EmpId); } [DataContract] public class Employee { private string m_Name; private int m_Age; private int m_Salary; private string m_Designation; private string m_Manager; [DataMember] public string Name { get { return m_Name; } set { m_Name = value; } } [DataMember] public int Age { get { return m_Age; } set { m_Age = value; } } [DataMember]

public int Salary { get { return m_Salary; } set { m_Salary = value; } } [DataMember] public string Designation { get { return m_Designation; } set { m_Designation = value; } } [DataMember] public string Manager { get { return m_Manager; } set { m_Manager = value; } } }

Implementation of the service class is shown below. In GetEmployee method we have created the Employee instance and return to the client. Since we have created the data contract for the Employee class, client will aware of this instance whenever he creates proxy for the service.
public class EmployeeService : IEmployeeService { public Employee GetEmployeeDetails(int empId) { Employee empDetail = new Employee(); //Do something to get employee details and assign to 'empDetail' properties return empDetail; } }

Client side
On client side we can create the proxy for the service and make use of it. The client side code is shown below.
protected void btnGetDetails_Click(object sender, EventArgs e) { EmployeeServiceClient objEmployeeClient = new EmployeeServiceClient(); Employee empDetails; empDetails = objEmployeeClient.GetEmployeeDetails(empId); //Do something on employee details }

MessageHeaderArray Attribute
Consider the Message contract type definition as shown below.
[MessageContract] public class Department { [MessageHeader] public string DepartmentID; [MessageHeader] public string DepartmentName; [MessageHeader] public Employees Employee(); }

In this we are having array of Employee type as message header. When this converted to SOAP Header it looks as shown below.
<Department> <DepartmentID>PRO1243</DepartmentID> <DepartmentName>Production</DepartmentName> <Employees> <Employee>Sam</Employee> <Employee>Ram</Employee> <Employee>Raja</Employee> </Employees> </Department>

Suppose you want to show the all employee detail in same level. We can use MessageHeaderArray attribute which will serialize the array element independently. If you use the MessageHeaderArray attribute of Employees, SOAP message will look as shown below.
<Department> <DepartmentID>PRO1243</DepartmentID> <DepartmentName>Production</DepartmentName> <Employee>Sam</Employee> <Employee>Ram</Employee> <Employee>Raja</Employee> </Department>

Note: MessageHeaderArray Attribute is applicable only for Array, not for collection.

Message Contract Properties


ProtectionLevel

You can mention the MessageHeader or MessageBodyMember to be signed or Encrypted using ProtectionLevel property. Example
using System.Net.Security; [MessageContract] public class EmployeeDetails { [MessageHeader(ProtectionLevel=ProtectionLevel.None)] public string EmpID; [MessageBodyMember(ProtectionLevel = ProtectionLevel.Sign )] public string Name; [MessageBodyMember(ProtectionLevel = ProtectionLevel.Sign )] public string Designation; [MessageBodyMember(ProtectionLevel=ProtectionLevel.EncryptAndSign)] public int Salary; }

In the above type definition, we have made the different protection level for body. But the protection level of the body is determind by the highest ProtectionLevel property. By default if you are not specifying the protection level it takes 'EncryptAndSign'. So it good if you specify minimum ProtectionLevel required.

Name and Namespace:


SOAP representation of the message element can be change by mentioning Name and Namespace property of the Header and Body member. By default namespace is the same as the namespace of the service contract that the message is participating. In the below example, I have mention the Name property to the EmpID and Name.
[MessageContract] public class EmployeeDetails { [MessageHeader(Name="ID")] public string EmpID; [MessageBodyMember(Name="EmployeeName")] public string Name; [MessageBodyMember()] public string Designation; [MessageBodyMember()] public int Salary; }

When SOAP message representation, its name is changed to ID and EmployeeName.


<EmployeeDetails>

<ID>45634</ID> <EmployeeName>Sam</EmployeeName> <Designation>Software Engineer</Designation> <Salary>25000</Salary> </EmployeeDetails>

Order
The order of the body elements are alpehabetical by default. But you can control the order, usiing Order property in the MessageBody attribute.
[MessageContract] public class EmployeeDetails { [MessageHeader()] public string EmpID; [MessageBodyMember(Order=2)] public string Name; [MessageBodyMember(Order=3)] public string Designation; [MessageBodyMember(Order=1)] public int Salary; }

Fault Contract
Service that we develop might get error in come case. This error should be reported to the client in proper manner. Basically when we develop managed application or service, we will handle the exception using try- catch block. But these exceptions handlings are technology specific. In order to support interoperability and client will also be interested only, what wents wrong? not on how and where cause the error. By default when we throw any exception from service, it will not reach the client side. WCF provides the option to handle and convey the error message to client from service using SOAP Fault contract. Suppose the service I consumed is not working in the client application. I want to know the real cause of the problem. How I can know the error? For this we are having Fault Contract. Fault Contract provides documented view for error accorded in the service to client. This help as to easy identity the what error has accord. Let us try to understand the concept using sample example. 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, int num2); } //Service implementation public class SimpleCalculator : ISimpleCalculator { public int Add(int num1, int num2) { //Do something throw new Exception("Error while adding number"); } }

Step 2: On client side code. Exceptions are handled using try-Catch block. Even though I have capture the exception when I run the application. I got the message that exceptions are not handled properly.
try { MyCalculatorServiceProxy.MyCalculatorServiceProxy proxy = new MyCalculatorServiceProxy.MyCalculatorServiceProxy(); Console.WriteLine("Client is running at " + DateTime.Now.ToString()); Console.WriteLine("Sum of two numbers... 5+5 =" + proxy.Add(5, 5)); Console.ReadLine(); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.ReadLine(); }

Step 3: Now if you want to send exception information form service to client, you have to use FaultException as shown below.

public int Add(int num1, int num2) { //Do something throw new FaultException("Error while adding number"); }

Step 4: Output window on the client side is show below.

Step 5: You can also create your own Custom type and send the error information to the client using FaultContract. These are the steps to be followed to create the fault contract.

Define a type using the data contract and specify the fields you want to return. Decorate the service operation with the FaultContract attribute and specify the type name. Raise the exception from the service by creating an instance and assigning properties of the custom exception.

Step 6: Defining the type using Data Contract


[DataContract()] public class CustomException { [DataMember()] public string Title; [DataMember()] public string ExceptionMessage; [DataMember()] public string InnerException; [DataMember()] public string StackTrace; }

Step 7: Decorate the service operation with the FaultContract


[ServiceContract()] public interface ISimpleCalculator { [OperationContract()] [FaultContract(typeof(CustomException))] int Add(int num1, int num2); }

Step 8: Raise the exception from the service

public int Add(int num1, int num2) { //Do something CustomException ex = new CustomException(); ex.Title = "Error Funtion:Add()"; ex.ExceptionMessage = "Error occur while doing add function."; ex.InnerException = "Inner exception message from serice"; ex.StackTrace = "Stack Trace message from service."; throw new FaultException(ex,"Reason: Testing the Fault contract") ; }

Step 9: On client side, you can capture the service exception and process the information, as shown below.
try { MyCalculatorServiceProxy.MyCalculatorServiceProxy proxy = new MyCalculatorServiceProxy.MyCalculatorServiceProxy(); Console.WriteLine("Client is running at " + DateTime.Now.ToString()); Console.WriteLine("Sum of two numbers... 5+5 =" + proxy.Add(5, 5)); Console.ReadLine(); } 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. This Service instance will be disposed after response is sent back to client.

Following diagram represent the process of handling the request from client using Per-Call instance mode.

Let as understand the per-call instance mode using example. Step 1: Create the service contract called IMyService and implement the interface. Add service behavior attribute to the service class and set the InstanceContextMode property to PerCall as show below.
[ServiceContract()] public interface IMyService { [OperationContract] int MyMethod(); }

Step 2: In this implementation of MyMethod operation, increment the static variable(m_Counter). Each time while making call to the service, m_Counter variable is incremented and return the value to the client.
[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall)] public class MyService:IMyService { static int m_Counter = 0;

public int MyMethod() { m_Counter++; return m_Counter; } }

Step 3: Client side, create the proxy for the service and call "myMethod" operation multiple time.
static void Main(string[] args) { Console.WriteLine("Service Instance mode: Per-Call"); Console.WriteLine("Client making call to service..."); //Creating the proxy on client side MyCalculatorServiceProxy.MyServiceProxy proxy = new MyCalculatorServiceProxy.MyServiceProxy(); Console.WriteLine("Counter: " + proxy.MyMethod()); Console.WriteLine("Counter: " + proxy.MyMethod()); Console.WriteLine("Counter: " + proxy.MyMethod()); Console.WriteLine("Counter: " + proxy.MyMethod()); Console.ReadLine(); }

Surprisingly, all requests to service return '1', because we configured the Instance mode to PerCall. Service instance will created for each request and value of static variable will be set to one. While return back, service instance will be disposed. Output is shown below.

Fig: PercallOutput.

Per-Session Service
When WCF service is configured for Per-Session instance mode, logical session between client and service will be maintained. When the client creates new proxy to particular service instance, a dedicated service instance will be provided to the client. It is independent of all other instance.

Following diagram represent the process of handling the request from client using Per-Session instance mode.

Let as understand the Per-Session instance mode using example. Step 1: Create the service contract called IMyService and implement the interface. Add service behavior attribute to the service class and set the InstanceContextMode property to PerSession as show below.
[ServiceContract()] public interface IMyService { [OperationContract] int MyMethod(); }

Step 2: In this implementation of MyMethod operation, increment the static variable (m_Counter). Each time while making call to the service, m_Counter variable will be incremented and return the value to the client.
[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession)] public class MyService:IMyService { static int m_Counter = 0; public int MyMethod() { m_Counter++; return m_Counter; } }

Step 3: Client side, create the proxy for the service and call "myMethod" operation multiple time.
static void Main(string[] args) { Console.WriteLine("Service Instance mode: Per-Session"); Console.WriteLine("Client making call to service..."); //Creating the proxy on client side MyCalculatorServiceProxy.MyServiceProxy proxy = new MyCalculatorServiceProxy.MyServiceProxy(); Console.WriteLine("Counter: " + proxy.MyMethod()); Console.WriteLine("Counter: " + proxy.MyMethod()); Console.WriteLine("Counter: " + proxy.MyMethod()); Console.WriteLine("Counter: " + proxy.MyMethod()); Console.ReadLine(); }

All request to service return incremented value (1, 2, 3, 4), because we configured the instance mode to Per-Session. Service instance will be created once the proxy is created at client side. So each time request is made to the service, static variable is incremented. So each call to MyMethod return incremented value. Output is shown below.

Fig: PersessionOutput.

Singleton Service
When WCF service is configured for Singleton instance mode, all clients are independently connected to the same single instance. This singleton instance will be created when service is hosted and, it is disposed when host shuts down. Following diagram represent the process of handling the request from client using Singleton instance mode.

Let as understand the Singleton Instance mode using example. Step 1: Create the service contract called IMyService and implement the interface. Add service behavior attribute to the service class and set the InstanceContextMode property to Single as show below.
[ServiceContract()] public interface IMyService { [OperationContract] int MyMethod(); }

Step 2: In this implementation of MyMethod operation, increment the static variable(m_Counter). Each time while making call to the service, m_Counter variable is incremented and return the value to the client
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)] public class MyService:IMyService { static int m_Counter = 0; public int MyMethod() { m_Counter++; return m_Counter; } }

Step 3: Client side, create the two proxies for the service and made a multiple call to MyMethod.
static void Main(string[] args) { Console.WriteLine("Service Instance mode: Singleton"); Console.WriteLine("Client 1 making call to service...");

//Creating the proxy on client side MyCalculatorServiceProxy.MyServiceProxy proxy = new MyCalculatorServiceProxy.MyServiceProxy(); Console.WriteLine("Counter: " + proxy.MyMethod()); Console.WriteLine("Counter: " + proxy.MyMethod()); Console.WriteLine("Counter: " + proxy.MyMethod()); Console.WriteLine("Client 2 making call to service..."); //Creating new proxy to act as new client MyCalculatorServiceProxy.MyServiceProxy proxy2 = new MyCalculatorServiceProxy.MyServiceProxy(); Console.WriteLine("Counter: " + proxy2.MyMethod()); Console.WriteLine("Counter: " + proxy2.MyMethod()); Console.ReadLine(); }

When two proxy class made a request to service, single instance at service will handle it and it return incremented value (1, 2, 3, 4), because instance mode is configured to 'Single'. Service instance is created when it is hosted. So this instance will remain till host is shutdown. Output is shown below.

Fig: SingletonOutput.

Instance Deactivation
In Instance Management System tutorial, you learn how to create sessionful service instance. Basically service instance is hosted in a context. Session actually correlated the client message not to the instance, but to the context that host it. When session starts, context is created and when it closes, context is terminated. WCF provides the option of separating the two lifetimes and deactivating the instance separately from its context. ReleaseInstanceMode property of the OberationalBehavior attribute used to control the instance in relation to the method call.

Followings are the list Release mode available in the ReleaseInstanceMode 1. 2. 3. 4. RealeaseInstanceMode.None RealeaseInstanceMode.BeforeCall RealeaseInstanceMode.AfterCall RealeaseInstanceMode.BeforeAndAfterCall

Below code show, how to add the 'ReleaseInstanceMode' property to the operational behavior.
[ServiceContract()] public interface ISimpleCalculator { [OperationContract()] int Add(int num1, int num2); } [OperationBehavior(ReleaseInstanceMode=ReleaseInstanceMode.BeforeCall] public int Add(int num1, int num2) { return num1 + num2; }

ReleaseInstanceMode.None
This property means that it will not affect the instance lifetime. By default ReleaseInstanceMode property is set to 'None'.

ReleaseInstanceMode.BeforeCall
This property means that it will create new instance before a call is made to the operation. If the instance is already exist,WCF deactivates the instance and calls Dispose() before the call is done. This is designed to optimize a method such as Create()

ReleaseInstanceMode.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.BeforeAndAfterCall
This is means that it will create new instance of object before a call and deactivates the instance after call. This has combined effect of using ReleaseInstanceMode.BeforeCall and ReleaseInstanceMode.AfterCall

Explicit Deactivate

You can also explicitly deactivate instance using InstanceContext object as shown below.
[ServiceContract()] public interface IMyService { [OperationContract] void MyMethod(); } [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)] public class MyService:IMyService { public void MyMethod() { //Do something OperationContext.Current.InstanceContext.ReleaseServiceInstance(); } }

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. Step 1: Start the Visual Studio 2008 and click File->New->Web Site. Select the 'WCF Service' as shown below.

Step 2: Create interface and decorate with Service and Operation contract.
[ServiceContract()] public interface ISimpleCalculator { [OperationContract] int Add(int num); [OperationContract] int Subtract(int num); [OperationContract] int Multiply(int num); [OperationContract] void EndPersistence(); }

Step 3: You need to add [Serializable] And [DurableService()] attribute to the service implementation. 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. In this implementation, we are going to persist the 'currentValue' variable value to the database.

using System.Runtime.Serialization; using System.ServiceModel; using System.Text; using System.ServiceModel.Description; [Serializable] [DurableService()] public class SimpleCalculator :ISimpleCalculator { int currentValue = default(int); [DurableOperation(CanCreateInstance = true)] public int Add(int num) { return (currentValue += num); } [DurableOperation()] public int Subtract(int num) { return (currentValue -= num); } [DurableOperation()] public int Multiply(int num) { return (currentValue *= num); } [DurableOperation(CompletesInstance = true)] public void EndPersistence() { }

Step 4: Before configuring the database information in the durable service, you need to set up DataStore environment. Microsoft provides inbuilt sqlPersistance provider. To set up the database environment, run the these sql query located at following location 'C:\Windows\Microsoft.NET\Framework\v3.5\SQL\EN'

SqlPersistenceProviderSchema.sql SqlPersistenceProviderLogic.sql

Step 5: In order to support durable service, you need to use Context binding type. <persistenceProvider> tag is used to configure the persistence provider.
<system.serviceModel> <services> <service name="SimpleCalculator" behaviorConfiguration="ServiceBehavior"> <!-- Service Endpoints --> <endpoint address="" binding="wsHttpContextBinding" bindingConfiguration="browConfig" contract="ISimpleCalculator"> <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"/> <persistenceProvider type="System.ServiceModel.Persistence.SqlPersistenceProviderFactory, System.WorkflowServices, Version=3.5.0.0, Culture=neutral, 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.serviceModel> <connectionStrings> <add name="DurableServiceStore" connectionString="Data Source=saravanakumar;Initial Catalog =DurableServiceStore;Integrated Security=True"/> </connectionStrings>

Step 6: Create the console client application and name it as DurableServiceClient

Step 7: Add following reference to client application


System.ServiceModel System.WorkflowService

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

Step 9: Create the Helper class called it as Helper.cs. This helper class is used to Store, Retrieve and set the context at the client side. Context information will be saved in 'token_context.bin' file. Copy and paste the below code to your helper file. Helper.cs
using using using using using System.ServiceModel.Channels; System.ServiceModel; System.Net; System.IO; System.Runtime.Serialization.Formatters.Binary;

public class Helper { static readonly String TokenContextFileName = "token_context.bin"; public static IDictionary<String, String> LoadContext() { IDictionary<String, String> ctx = null; try {

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

IDictionary<String, String> ctx) { IContextManager cm = channel.GetProperty<IContextManager>(); if (cm != null) { cm.SetContext(ctx); } } }

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

End of the proxy 1, service instance saved in the database as shown below.

Serialized XML instance state save in the database is shown below.

Output of the client application.

Throttling
WCF throttling provides some properties that you can use to limit how many instances or sessions are created at the application level. Performance of the WCF service can be improved by creating proper instance. Attribute maxConcurrentCalls Description Limits the total number of calls that can currently be in progress across

all service instances. The default is 16. maxConcurrentInstances maxConcurrentSessions The number of InstanceContext objects that execute at one time across a ServiceHost. The default is Int32.MaxValue. A positive integer that limits the number of sessions a ServiceHost object can accept. The default is 10.

Service Throttling can be configured either Adminstractive or Programatically

Administrative(configuration file)
Using <serviceThrottling> tag of the Service Behavior, you can configure the maxConcurrentCalls, maxConcurrentInstances , maxConcurrentSessions property as shown below.
<system.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.serviceModel>

Programming Model
Use ServiceThrottlingBehavior object to set concurrent calls, session and instance property.
ServiceHost host = new ServiceHost(typeof(MyService)); ServiceThrottlingBehavior throttle = host.Description.Behaviors.Find(); if (throttle == null) { throttle = new ServiceThrottlingBehavior(); throttle.MaxConcurrentCalls = 500; throttle.MaxConcurrentSessions = 200;

throttle.MaxConcurrentInstances = 100; host.Description.Behaviors.Add(throttle); } host.Open();

Request-Reply
By default all WCF will operated in the Request-Replay mode. It means that, when client make a request to the WCF service and client will wait to get response from service (till receiveTimeout). After getting the response it will start executing the rest of the statement. If service doesn't respond to the service within receiveTimeout, client will receive TimeOutException. Apart from NetPeerTcpBinding and the NetMsmqBinding all other bindings will support requestreply operations.

One-Way
In One-Way operation mode, client will send a request to the server and does not care whether it is success or failure of service execution. There is no return from the server side, it is one-way communication. Client will be blocked only for a moment till it dispatches its call to service. If any exception thrown by service will not reach the server. Client can continue to execute its statement, after making one-way call to server. There is no need to wait, till server execute. Sometime when one-way calls reach the service, 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, according to the service's configured concurrency mode behavior. If the number of queued messages has exceeded the queue's capacity, the client will be blocked even if it's issued a one-way call. However, once the call is queued, the client will be unblocked and can continue executing, while the service processes the operation in the background.

Definition :
One-way operation can be enabled by setting IsOneWay property to true in Operation contract attribute.
[ServiceContract] public interface IMyService { [OperationContract(IsOneWay=true)] void MyMethod(EmployeeDetails emp); }

One-Way Operations and Sessionful Services


Let us see the example, what will happen when you use the one-way communication with Sessionful service.
[ServiceContract(SessionMode = SessionMode.Required)] interface IMyContract { [OperationContract(IsOneWay = true)] void MyMethod(); }

As per above configuration, when client makes one-way call using MyMethod() operation and if it close the proxy. Client will be blocked until operation completes. It will be good practice, that one-way operation should be applied on per-call and singleton service. Suppose If you want to make use of One-way operation in Sessionful service, use in the last operation of the service which will terminate the session. This operation should not return any value.
[ServiceContract(SessionMode = SessionMode.Required)] interface IMyContract { [OperationContract] void MyMethod1(); [OperationContract]

string MyMethod2(); [OperationContract(IsOneWay = true, IsInitiating = false, IsTerminating = true)] string CloseSessionService(int id); }

One-Way Operations and Exceptions


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( );

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

Step 2 : Add System.ServiceModel reference to the project Step 3: Create the Callback and Service contract as shown below. You need to mention CallbackContract property in the ServiceContract attribute. Implementation of the Callback contract will be done on the client side. IMyContract.cs
using using using using using System; System.Collections.Generic; System.Linq; System.Text; System.ServiceModel;

namespace CallbackService { public interface IMyContractCallback { [OperationContract] void OnCallback(); }

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

Step 4: Implement the Service contract as shown below. In the below code you will find using OperationContext is used to receive the reference to Callback instance. Using that instance we are calling the OnCallback() method from client side. MyService.cs
using using using using using System; System.Collections.Generic; System.Linq; System.Text; System.ServiceModel;

namespace CallbackService { [ServiceBehavior(ConcurrencyMode=ConcurrencyMode.Multiple )] public class MyService:IMyContract { public void MyMethod() { //Do something IMyContractCallback callbackInstance =OperationContext.Current.GetCallbackChannel(); callbackInstance.OnCallback(); } } }

You can also note that We have set the ConcurrencyMode to Multile. If you are not using ConcurrencyMode to Multiple or Reentent, you will be end up with deadlock exception as shown below. This is because when a client made a call to the service, channel is created and lock by WCF service. If you are calling the Callback method inside the service method. Service will try to access the lock channel, this may leads to deadlock. So you can set ConcurrencyMode to Multiple or Reentent so it will release the lock silently.

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

Step 6: Main method


static void Main(string[] args) { Uri httpUrl = new Uri("http://localhost:8090/MyService/"); ServiceHost host = new ServiceHost(typeof(CallbackService.MyService), httpUrl); host.Open(); Console.WriteLine("Service is Hosted at {0}", DateTime.Now.ToString()); Console.WriteLine("Host is running...Press key to stop the service."); Console.ReadLine(); host.Close(); }

Step 7: Use Duplex binding to support Callback operation. Web.Config


<system.serviceModel> <services > <service behaviorConfiguration="ServiceBehavior" name="CallbackService.MyService"> <endpoint address="http://localhost:8090/MyService" binding="wsDualHttpBinding" contract="CallbackService.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>

Step 8: Run the host application

Step 9: Create Console Application using Visual Studio 2008 and name it as CallbackClient. This is the client application which contain Callback implementation.

Step10: Add System.ServiceModel and CallbackService as reference to the project Step 11: Create the proxy class as shown below. Use DuplexClientBase to create the proxy, because it will support bidirectional communication. Create the contractor which will accept InstanceContext as parameter.
using using using using using using System; System.Collections.Generic; System.Linq; System.Text; System.ServiceModel; CallbackService;

namespace CallbackClient { class MyServiceClient:DuplexClientBase<IMyContract>,IMyContract { public MyServiceClient(InstanceContext callbackCntx)

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

Step12: Create the implementation for Callback Contract


class MyCallback : IMyContractCallback { public void OnCallback() { Console.WriteLine("Callback method is called from client side."); } }

Step 13: Implementation of main method


static void Main(string[] args) { IMyContractCallback callback=new MyCallback(); InstanceContext cntx=new InstanceContext(callback); MyServiceClient proxy = new MyServiceClient(cntx); Console.WriteLine("Client call the MyMethod Operation from Service."); proxy.MyMethod(); Console.ReadLine(); }

Step14: Run the client application. In the output, you can see the OnCallback method called by the service

Events

Events allow the client or clients to be notified about something that has occurred on the service side. An event may result from a direct client call, or it may be the result of something the service monitors. The service firing the event is called the publisher, and the client receiving the event is called the subscriber.

Publisher will not care about order of invocation of subscriber. Subscriber can be executed in any manner. Implementation of subscriber side should be short duration. Let us consider the scenario in which you what to publish large volume of event. Publisher will be blocked, when subscriber is queued on previous subscription of the event. These make publishers to put in wait state. It may lead Publisher event not to reach other subscriber. 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. It will not affect the client; publisher can even use .Net delegates to manage the list of subscribers. Event should always one-Way operation and it should not return any value

Definition
public interface IMyEvents { [OperationContract(IsOneWay = true)] void Event1(); }

Let us understand more on Event operation by creating sample service

Step 1 : Create ClassLibrary project in the Visual Studio 2008 and name it as WCFEventService as shown below.

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

[OperationContract] void SubscribeEvent(); }

Step 3: Implementation of the Service Contract is shown below. In the Subscription operation, 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. MyPublisher.cs
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] public class MyPublisher : IMyContract { static Action m_Event1 = delegate { }; public void SubscribeEvent() { IMyEvents subscriber = OperationContext.Current.GetCallbackChannel(); m_Event1 += subscriber.Event1; } public static void FireEvent() { m_Event1(); } public void DoSomethingAndFireEvent() { MyPublisher.FireEvent(); } }

Step 4: Create the Console application using Visual Studio 2008 and name it as WcfEventServiceHost. This application will be used to self-host the service.

Step 5: Add System.ServiceModel and WcfEventService as reference to the project.


static void Main(string[] args) { Uri httpUrl = new Uri("http://localhost:8090/MyPublisher/"); ServiceHost host = new ServiceHost(typeof(WcfEventService.MyPublisher), httpUrl); host.Open(); Console.WriteLine("Service is Hosted at {0}", DateTime.Now.ToString()); Console.WriteLine("Host is running...Press key to stop the service."); Console.ReadLine(); host.Close(); }

Step 6: Use Duplex binding to support Callback operation. Web.Config


<system.serviceModel> <services > <service behaviorConfiguration="ServiceBehavior" name="WcfEventService.MyPublisher"> <endpoint address="http://localhost:8090/MyPublisher"

binding="wsDualHttpBinding" contract="WcfEventService.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.

Step 8: Create the console application using visual studio and name it as WcfEventServiceClient as shown below. This application will act a client which is used to subscribe the event from service.

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

Step 10: Implementation of IMyEvents at client side is shown below. This method will be called when service publish the event.
class MySubscriber : IMyEvents { public void Event1() { Console.WriteLine("Event is subscribed from the service at {0}",DateTime.Now.ToString() ); } }

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(); InstanceContext evntCntx = new InstanceContext(evnt); EventServiceClient proxy = new EventServiceClient(evntCntx); Console.WriteLine("Client subscribe the event from the service at {0}",DateTime.Now.ToString()); proxy.SubscribeEvent(); Console.WriteLine("Client call operation which will fire the event"); proxy.DoSomethingAndFireEvent(); Console.ReadLine(); }

Step 12: Run the client application and you see the when event is fired from the service. Subscriber got notification.

Streaming
Client and Service exchange message using Streaming transfer mode, receiver can start processing the message before it is completely delivered. Streamed transfers can improve the scalability of a service by eliminating the requirement for large memory buffers. If you want to transfer large message, streaming is the best method.

Supported Bindings

BasicHttpBinding NetTcpBinding NetNamedPipeBinding

Restrictions
There are some restriction, when streaming is enabled in WCF

Digital signatures for the message body cannot be performed Encryption depends on digital signatures to verify that the data has been reconstructed correctly. 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. 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 .Net stream class for Streaming the message. Stream in base class for streaming, all subclasses like FileStream,MemoryStream, NetworkStream are derived from it. Stream the data, you need to do is, to return or receive a Stream as an operation parameter.
[ServiceContract] public interface IMyService { [OperationContract] void SaveStreamData(Stream emp); [OperationContract] Stream GetStreamData(); }

Note: 1. Stream and it's subclass can be used for streaming, but it should be serializable 2. Stream and MemoryStream are serializable and it will support streaming 3. FileStream is non serializable, and it will not support streaming

Streaming and Binding


Only the TCP, IPC, and basic HTTP bindings support streaming. With all of these bindings streaming is disabled by default. TransferMode property should be set according to the desired streaming mode in the bindings.

public enum TransferMode { Buffered, //Default Streamed, StreamedRequest, StreamedResponse } public class BasicHttpBinding : Binding,... { public TransferMode TransferMode {get;set;} //More members }

StreamedRequest - Send and accept requests in streaming mode, and accept and return responses in buffered mode StreamResponse - Send and accept requests in buffered mode, and accept and return responses in streamed mode Streamed - 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, but default message size is 64K. So you can increase the message size using maxReceivedMessageSize attribute in the binding element as shown below.
<system.serviceModel> <bindings > <netTcpBinding> <binding name="MyService.netTcpBinding" transferMode="Buffered" maxReceivedMessageSize="1024000"> </binding> </netTcpBinding> </bindings> </system.serviceModel>

Two-phase committed protocol


Consider the scenario where I am having single client which use single service for communication and interacting with single database. In which service starts and manage the transaction, now it will be easy for the service to manage the transaction. Consider for example client calling multiple service or service itself calling another service, this type of system are called as Distributed Service-oriented application. Now the questions arise that which service will begin the transaction? Which service will take responsibility of committing the transaction? How would one service know what the rest of the service feels about

the transaction? Service could also be deployed in different machine and site. Any network failure or machine crash also increases the complexity for managing the transaction.

In order to overcome these situations, WCF come up with distributed transaction using two way committed protocol and dedicated transaction manager. Transaction Manager is the third party for the service that will manage the transaction using two phase committed protocol. Let us see how Transaction manager will manage the transaction using two-phase committed protocols.

Transaction Propagation
In WCF, transaction can be propagated across service boundary. This enables service to participate in a client transaction and it includes multiple services in same transaction, Client itself will act as service or client. We can specify whether or not client transaction is propagated to service by changing Binding and operational contract configuration
<bindings> <netTcpBinding> <binding transactionFlow="true"></binding> </netTcpBinding> </bindings>

Even after enabling transaction flow does not mean that the service wants to use the clients transaction in every operation. We need to specify the TransactionFlowAttribute in operational contract to enable transaction flow.
[ServiceContract]

public interface IService { [OperationContract] [TransactionFlow(TransactionFlowOption.Allowed)] int Add(int a, int b); [OperationContract] int Subtract(int a, int b); }

Note: TransactionFlow can be enabled only at the operation level not at the service level. TransactionFlowOption Binding configuration NotAllowed transactionFlow="true" Client cannot propagate its transaction to or service even client has transaction transactionFlow="false" Service will allow to flow client transaction. transactionFlow="true" It is not necessary that service to use client transaction. If service disallows at binding level, client transactionFlow="false" also should disable at binding level else error will be occurred. transactionFlow="true" Both Service and client must use transaction aware binding

Allowed

Allowed Mandatory

Mandatory

InvalidOperationException will be throw when serice binding disables at binding level. transactionFlow="false" FaultException will be thrown when client disable at its binding level.

Transaction Protocols
As a developer we no need to concern about transaction protocols and transaction manager used by WCF. WCF itself will take care of what kind of transaction protocols should be used for different situation. Basically there are three different kinds of transaction protocols used by WCF.

Custom message header


Attachment:
CustomMessageHeader.zip This article explains about customizing the wcf message flowing between service and client. There are certain scenario in which you to pass some information from client to service, but not as parameter in operation contracts. Example, logging system at the service we need to log user or machine information, which made request to the service. In this kind of scenario we should not pass user or machine information as parameter in operation contract. Instead we can pass the information through message flowing between client and service vice versa. The information we need to send can be appended with message header and it can be received at the server side. Let as create sample service and client application, in which client will send User name information through request message and service will respond with confirmation message. I have created Math service with Add and Subtract functionality. Client consuming this service will send his user name information as string with requested message. Once request reached the

service, it will read the information from the message header and display using console window. When service responding to the client, along with operation result, it will also send confirmation message to client through message header. Step 1: Create IMathService interface decorated with Service and Operational contract attribute IMathService.vb
<ServiceContract()> _ Public Interface IMathService <OperationContract()> _ Function Add(ByVal a As Integer, ByVal b As Integer) As Integer <OperationContract()> _ Function Subtract(ByVal a As Integer, ByVal b As Integer) As Integer End Interface

Step 2:In this class, we have implemented Add and Subtract functionality. PrintRequestedUserID() method will read the UserID message header from incoming message using OperationContext. This User information is displayed in console window. SendResponseWithMessage() method will send a confirmation message to the client as Message header through Operation context. MathService.vb
Public Class MathService Implements IMathService Public Function Add(ByVal a As Integer, ByVal b As Integer) As Integer Implements IMathService.Add 'This method call will retrive message send from client using MessageHeader PrintRequestedUserID() 'This method call will send message to client using MessageHeader SendResponseWithMessage() Return a + b End Function Public Function Subtract(ByVal a As Integer, ByVal b As Integer) As Integer Implements IMathService.Subtract 'This method call will retrive message send from client using MessageHeader PrintRequestedUserID() 'This method call will send message to client using MessageHeader SendResponseWithMessage() Return a - b End Function Private Sub PrintRequestedUserID()

Dim userID As String = String.Empty 'Read the message header using "Name" and "NameSpace" userID = OperationContext.Current.IncomingMessageHeaders .GetHeader(Of String)("UserID", "ns") Console.WriteLine("Requested user: " + userID) End Sub Private Sub SendResponseWithMessage() 'Creating new message header with "Content" value assigned in constructor Dim mess As New MessageHeader(Of String)("This is sample message from service") 'Assigning Name and NameSpace to the message header value at server side Dim header As System.ServiceModel. Channels.MessageHeader = mess.GetUntypedHeader("ServiceMessage", "ns") 'Adding message header with OperationContext 'which will be received at the client side OperationContext.Current.OutgoingMessageHeaders.Add(header) End Sub End Class

Step 3: Hosting the MathService using console application MyServiceHost.vb


Module MyServiceHost Sub Main() 'Hosting the Math service using console application Dim host As New ServiceHost(GetType(MyService.MathService)) host.Open() Console.WriteLine("Service is running... Press to exit.") Console.ReadLine() End Sub End Module

Web.Config
<system.serviceModel> <services><service name="MyService.MathService" behaviorConfiguration="MyServiceBehavior"> <endpoint address ="MathService" binding="basicHttpBinding" contract="MyService.IMathService"/> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> <host> <baseAddresses> <add baseAddress="http://localhost:8090/MyService"/> </baseAddresses> </host> </service>

</services> <behaviors> <serviceBehaviors > <behavior name ="MyServiceBehavior"> <serviceMetadata httpGetEnabled ="true"/> <serviceDebug includeExceptionDetailInFaults ="True"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel>

Step 4: Created console client application which add UserID as message header to service using Operation context before calling Add() functionality. Once the response is received from the service, it is trying to read the confirmation message from service using Operation context.
Sub Main() 'Creating proxy class for service Dim proxy As IMathService = Nothing proxy = ChannelFactory(Of IMathService).CreateChannel(New BasicHttpBinding(), New EndpointAddress("http://localhost:8090/MyService/MathService")) 'Lifetime of OperationContextScope defines the scope for OperationContext. Dim scope As OperationContextScope = Nothing scope = New OperationContextScope(proxy) 'Creating new message header with "Content" value assigned in constructor Dim mess As New MessageHeader(Of String) (System.Security.Principal.WindowsIdentity.GetCurrent().Name) 'Assigning Name and NameSpace to the message header value at client side Dim header As System.ServiceModel.Channels.MessageHeader = mess.GetUntypedHeader("UserID", "ns") 'Adding message header with OperationContext 'which will be received at the server side OperationContext.Current.OutgoingMessageHeaders.Add(header) 'Making service call Console.WriteLine("Sum of {0},{1}={2}", 1, 2, proxy.Add(1, 2)) 'Displaying confrimation message from service Console.WriteLine("Response Message: " + OperationContext.Current. IncomingMessageHeaders.GetHeader(Of String)("ServiceMessage", "ns")) Console.ReadLine() End Sub End Module <ServiceContract()> _ Public Interface IMathService Inherits IClientChannel

<OperationContract()> _ Function Add(ByVal a As Integer, ByVal b As Integer) As Integer <OperationContract()> _ Function Subtract(ByVal a As Integer, ByVal b As Integer) As Integer End Interface

Step 5: Run the MyServiceHost

Step 6: Run the MyClientApplication Below figure shows the message flowing between service and client Client application output

Console hosted service output screen

Introdution to WCF 4.0


This article explains about the new features introduced in WCF 4.0. .Net framework comes with new features and improved areas of WCF. It was mainly focused on simplifying the developer experience, enabling more communication scenario and providing rich integration with WWF. The following items specifies the new features of WCF 4.0 Simplified configuration This new feature shows simplification of WCF configuration section by providing default endpoint, binding and behavior configuration. It is not mandatory to provide endpoint while hosting service. Service will automatically create new endpoint if it does find any endpoint while hosting service. These changes make it possible to host configuration-free services. Discovery service There are certain scenario in which endpoint address of the service will be keep on changing. In that kind of scenario, client who consume this service also need to change the endpoint address dynamically to identify the service. This can be achieved using WS-Discovery protocol. Routing service This new feature introduces routing service between client and actual business service. This intermediated service Act as broker or gateways to the actual business services and provides features for content based routing, protocol bridging and error handling

REST Service There are few features helps while developing RESTful service.

Automatic help page that describes REST services to consumer Support for declarative HTTP catching

Workflow service

Improves development experience Entire service definition can be def define in XAML Hosting workflow service can be done from .xamlx file, without using .svc file Introduce new Context bindings like BasicHttpContextBinding, WSHttpContextBinding, or NetTcpContextBinding In .Net4.0, WorkflowServiceHost class for hosting workflow kflow services was redesigned and it is available in System.ServiceModel.Activities assembly. In .Net3.5, WorkflowServiceHost class is available in System.WorkflowServices assembly New messaging activities SendReply and ReceiveReply are added in .Net4.0

Creating an XML Web Service Proxy


Visual Studio 2005 Other Versions

By definition, Web services can be communicated with over a network using industry standard protocols, including SOAP. That is, a client and a Web service commun communicate icate using SOAP messages, which encapsulate the in and out parameters as XML. Fortunately, for Web service clients, the proxy class handles the work of mapping parameters to XML elements and then sending the SOAP message over the network. As long as a service vice description exists, a proxy class can be generated if the service description conforms to the Web Services Description Language (WSDL). A service description defines how to communicate with a Web service. With a service description, a proxy class can be created with the Wsdl.exe tool. In turn, a Web service client can then invoke methods of the proxy class, which communicate with a Web service over the network by processing the SOAP messages sent to and from the Web service. Because the proxy class com communicates with the Web service across the Internet, it is a good idea to verify that the Url property of the proxy class references a trusted destination. By default, the proxy class uses SOAP over HTTP to communicate with the Web service. However, Wsdl.exe can generate proxy classes to communicate with a Web service, using either the HTTP HTTP-GET GET protocol or HTTP-POST HTTP protocol. To specify that t the proxy class should use HTTP HTTP-GET or HTTP-POST, provide the /protocol switch to the Wsdl.exe tool, as described in the table below.

Using Wsdl.exe to Generate an XML Web Service Proxy Class


You can use the Web Services Description Language tool (Wsdl.e (Wsdl.exe) xe) from a command prompt to create a proxy class, specifying (at a minimum) the URL to a Web service or a service description, or the path to a saved service description.

Copy Wsdl /language:language /protocol:protocol /namespace:myNameSpace /out:filename /username:username /password:password /domain:domain <url or path>

Note
The arguments listed here are the commonly used arguments for Wsdl.exe. For the full syntax of Wsdl.exe, see Web Services Description Language Tool (Wsdl.exe).

Parameter
<url or path>

Value
A URL or path to a service description (a file describing a Web service in Web Services Description Language). If you specify a file, supply a file containing the service description. For example: mywebservice.wsdl If you specify a URL, the URL must reference an .asmx page or return a service description. For Web services created using ASP.NET, you can return a service description by appending ?WSDL to the URL of the Web service. For example, http://www.contoso.com/MyWebService.asmx?WSDL

/language:language

The language the proxy class is generated in. Available options include CS, VB, and JS, referring to C#, Visual Basic .NET, and JScript .NET, respectively. The default language is C#. (Optional)

/protocol:protocol

The protocol used to communicate with the Web service methods. Available options include SOAP, HTTP-GET, and HTTP-POST. The default protocol is SOAP. (Optional)

/namespace:myNameSpace The namespace of the generated proxy. The default value is the global namespace. (Optional)

/out:filename

The name of the file to create containing the proxy class. The default name is based

on the name of the class implementing the Web service. (Optional)

/username:username

The user name to use when connecting to a Web server that requires authentication. (Optional)

/password:password

The password to use when connecting to a Web server that requires authentication. (Optional)

/domain:domain

The domain to use when connecting to a Web server that requires authentication. (Optional)

Generated Proxy Class Details


When Wsdl.exe is used to generate a proxy class, a single source file is generated in the specified language. This file contains a proxy class exposing both synchronous and asynchronous methods for each Web service method of the Web service. For instance, if a Web service contains a Web service method named Add, the proxy class has the following methods for calling the Add Web service method: Add, BeginAdd, and EndAdd. The Add method of the proxy class is used to communicate with the Add Web service method synchronously, but the BeginAdd and EndAdd methods are used to communicate with a Web service method asynchronously. For more information on communicating with Web service methods asynchronously, see Communicating with XML Web Services Asynchronously. Each method of the generated proxy class contains the appropriate code to communicate with the Web service method. If an error occurs during communication with the Web service and the proxy class, an exception is thrown. For details on handling exceptions, see Handling and Throwing Exceptions in XML Web Services. The parameter order may differ between the defined order in the Web service method and the associated method of the proxy class. In most cases, the parameter order will match. However, if the Web service expects Document formatted SOAP messages, there is one case where the parameter order will not match. If a Web service method has out parameters defined prior to an in parameter, the out parameters are placed after all the in parameters in the proxy class. For instance, in the following code example, the Web service method MyWebMethod has the outStr out parameter declared prior to the inStr in parameter. However, in the proxy class, the inStr parameter is declared prior to outStr.

// Declare MyWebMethod in the Web service. MyWebMethod(out string outStr, string inStr)

// This is the corresponding MyWebMethod in the proxy class. MyWebMethod(string inStr, out string outStr).
In some cases, the proxy class generated by WSDL.exe uses a least common denominator approach for casting objects to a type specified in a service description. As a result, the generated type in the proxy class might not be what the developer wants or expects. For example, when WSDL.exe encounters an ArrayList type in a service description, it creates an Object array in the generated proxy class. To ensure correct object type casts, open the file containing the generated proxy class and change any incorrect object types to the expected object type.

Warnings Thrown by Wsdl.exe


When supplying multiple service descriptions to Wsdl.exe, two of the error messages that might be raised are the following:

Warning: Ignoring duplicate service description with TargetNamespace=<schema namespace> from location <schema URI>. Indicates the TargetNamespace for two or more of the supplied service descriptions are identical. As the TargetNamespace is supposed to be a unique identifier for a particular XML document, which in this case is a service description, Wsdl.exe assumes that the two service descriptions are identical. In doing so, Wsdl.exe builds just one proxy class for one of the service descriptions. If this is not your intended result, you can change this. For service descriptions representing Web services created using ASP.NET, you can apply a WebService attribute specifying a unique Namespace property to the class implementing the Web service. That Namespace property is then used as the TargetNamespace in the service description to uniquely identify the Web service. For more information on setting the Namespace property, see Applying a WebService attribute.

Warning: Ignoring duplicate schema with TargetNamespace=<schema Namespace> from location <schema URI>. Indicates the TargetNamespace for two or more XML schemas within the supplied service descriptions are identical. Because the TargetNamespace is supposed to be a unique identifier for a particular XML document, which in this case is the XML schema, Wsdl.exe assumes that the two XML schemas are identical. In doing so, Wsdl.exe builds a class for just one of the schemas. If this is not the intended result, the TargetNamespace for each XML schema must be changed to a unique URI. Exactly how the TargetNamespace is modified depends on the origin of the particular XML schemas.

Create and Consume WCF service using Visual Studio 2010


In this article I am going to demonstrate how to create a WCF service, that can be hosted inside IIS and a windows application that consume the WCF service.

To support service oriented architecture, Microsoft developed the programming model named Windows Communication Foundation (WCF). ASMX was the prior version from Microsoft, was completely based on XML and .Net framework continues to support ASMX web services in future versions also. While ASMX web services was the first step towards the service oriented architecture, Microsoft has made a big step forward by introducing WCF. An overview of planning for WCF can be found from this link http://msdn.microsoft.com/enus/library/ff649584.aspx . The following are the important differences between WCF and ASMX from an asp.net developer point of view. 1. ASMX web services are easy to write, configure and consume 2. ASMX web services are only hosted in IIS 3. ASMX web services can only use http 4. WCF, can be hosted inside IIS, windows service, console application, WAS(Windows Process Activation Service) etc 5. WCF can be used with HTTP, TCP/IP, MSMQ and other protocols. The detailed difference between ASMX web service and WCF can be found here. http://msdn.microsoft.com/en-us/library/cc304771.aspx Though WCF is a bigger step for future, Visual Studio makes it simpler to create, publish and consume the WCF service. In this demonstration, I am going to create a service named SayHello that accepts 2 parameters such as name and language code. The service will return a hello to user name that corresponds to the language. So the proposed service usage is as follows. Caller: SayHello(Sreeju, en) -> return value -> Hello Sreeju Caller: SayHello(, ar) -> return value -> Caller: SayHello(Sreeju, es) - > return value -> Hola Sreeju Note: calling an automated translation service is not the intention of this article. If you are interested, you can find bing translator API and can use in your application. http://www.microsofttranslator.com/dev/ So Let us start

First I am going to create a Service Application that offer the SayHello Service. Open Visual Studio 2010, Go to File -> > New Project, from your preferred language from the templates section select WCF, select WCF service ce application as the project type, give the project a name(I named it as HelloService), click ok so that visual studio will create the project for you. In this demonstration, I have used C# as the programming language.

Visual studio will create the nece necessary ssary files for you to start with. By default it will create a service with name Service1.svc and there will be an interface named IService.cs. The screenshot for the project in solution explorer is as follows

Since I want to demonstrate how to create ne new w service, I deleted Service1.Svc and IService1.cs files from the project by right click the file and select delete. Now in the project there is no service available, I am going to create one. From the solution explorer, right click the project, select Add -> New Item Add new item dialog will appear to you. Select WCF service from the list, give the name as HelloService.svc, and click on the Add button.

Now Visual studio will create 2 files with name IHelloService.cs and HelloService.svc. These files are basically the service definition (IHelloService.cs) and the service implementation (HelloService.svc). Let us examine the IHelloService interface.

The code state that IHelloService is the service definition and it provides an operation/method (similar to o web method in ASMX web services) named DoWork(). Any WCF service will have a definition file as an Interface that defines the service. Let us see what is inside HelloService.svc

The code illustrated is implementing the interface IHelloService. The cod code e is self-explanatory; self the HelloService class needs to implement all the methods defined in the Service Definition. Let me do the service as I require. Open IHelloService.cs in visual studio, and delete the DoWork() method and add a definition for SayHello(), o(), do not forget to add OperationContract attribute to the method. The modified IHelloService.cs will look as follows

Now implement the SayHello method in the HelloService.svc.cs file. Here I wrote the code for SayHello method as follows.

I am done with the service. Now you can build and run the service by clicking f5 (or selecting start debugging from the debug menu). Visual studio will host the service in give you a client to test it. The screenshot is as follows.

In the left pane, it shows the services ervices available in the server and in right side you can invoke the service. To test the service sayHello, double click on it from the above window. It will ask you to enter the parameters and click on the invoke button. See a sample output below.

Now I have done with the service. The next step is to write a service client. Creating a consumer application involves 2 steps. One generating the class and configuration file corresponds to the service. Create a project that utilizes the generated class and c configuration file. First I am going to generate the class and configuration file. There is a great tool available with Visual Studio named svcutil.exe, this tool will create the necessary class and configuration files for you. Read the documentation for t the he svcutil.exe here http://msdn.microsoft.com/en-us/library/aa347733.aspx us/library/aa347733.aspx . Open Visual studio command prompt, you can find it under Start Menu -> > All Programs -> Visual Studio 2010 -> Visual sual Studio Tools -> Visual Studio command prompt

Make sure the service is in running state in visual studio. Note the url for the service(from the running window, you can right click and choose copy address). Now from the command prompt, enter the svcutil.exe il.exe command as follows.

I have mentioned the url and the /d switch for the directory to store the output files(In this case d:\temp). temp). If you are using windows drive(in my case it is c: ) , make sure you open the command prompt with run as administrator ator option, otherwise you will get permission error(Only in windows 7 or windows vista). The tool has created 2 files, HelloService.cs and output.config. Now the next step is to create a new project and use the created files and consume the service. Let us do that now. I am going to add a console application to the current solution. Right click solution name in the solution explorer, right click, Add Add-> New Project

Under Visual C#, select console application, give the project a name, I named it TestService

Now navigate to d:\temp temp where I generated the files with the svcutil.exe. Rename output.config to app.config. Next step is to add both files (d:\temp temp\helloservice.cs helloservice.cs and app.config) to the files. In the solution explorer, right click the project, Add -> Add existing item, browse to the d:\temp temp folder, select the 2 files as mentioned before, click on the add button.

Now you need to add a reference to the System.ServiceModel to the project. From solution explorer, right click the references under testse testservice rvice project, select Add reference. In the Add reference dialog, select the .Net tab, select System.ServiceModel, and click ok

Now open program.cs by double clicking on it and add the code to consume the web service to the main method. The modified file looks as follows

Right click the testservice project and set as startup project. Click f5 to run the project. See the sample output as follows

Publishing WCF service under IIS is similar to publishing ASP.Net application. Publish the application to a folder using Visual studio publishing feature, create a virtual directory and create it as an application. Dont forget to set the application pool to use ASP.Net version 4. One last thing you need to check is the app.config file you have added to the solu solution. See the element client under ServiceModel element. There is an endpoint element with address attribute that points to the published service URL. If you permanently host the service under IIS, you can simply change the address parameter to the corresp corresponding onding one and your application will consume the service.

Consuming
We have several options for consuming Web Services. Since this article is about ASP.NET, we'll focus on .NET technologies that can consume Web Services. However, I should point out that any platform or framework that understands SOAP should be able to communicate with our Web Service. Building the Web Service with ASP.NET does not mean that the service is only available to other Microsoft applications. Consumers of a Web Service need to know what the service offers offersfor for example, what its Web callable method look like. Therefore, all Web Services optionally share another common XML document: a contract (note, Web Services built with ASP.NET always have a contract provided automatically).

Contract
In the examples above when we discussed testing a Web Service, we didn't discuss the link found within Web Service Help Page: SDL Contract. If we were to follow that link, instead of pressing the Invoke button for the GetCounters() Web Method, we would uld be presented with the following XML document:

Figure 3. XML document presented when following the link found within the Web Service Help Page This XML document is a contract that describes our Web Service. It details the protocols supported as well as the semantics for calling and returning values. It additionally defines an XML schema for our Counters class. Tools can use this XML schema to build proxy classes for our Web Service. A proxy class is a class that looks and feels like a local object, but it is in fact doing the work to serialize, send, receive, and de-serialize our method request to a SOAP endpoint. Note Beta 1 of .NET surfaces an "SDLService Description Language" contract, Beta 2 will switch to use the more recent "WSDLWeb Service Description Language" contract. Semantically they are very different. WSDL

is the collaborative work of Microsoft, IBM, and several other companies to better standardize the XML contract language. We have various options for consuming Web Services, however, I'd like to call out three in particular:

Visual Studio .NET: Visual Studio .NET does the work of creating the proxy from the SDL or WSDL and adds the appropriate code to our project. This is done by simply selecting Project | Web References, and then pointing at a valid contract. Note that for beta 1 the contract must be SDL. Command Line Tools: The .NET SDK ships with a tool called WebServiceUtil.exe that accepts an SDL contract and can generate the proxy source code for Visual Basic .NET, C#, or JScript.NET. IE 5.5. Behavior: A browser specific behavior that allows for rich client interaction with SOAP endpoints. For those of you familiar with Remote Scripting, you're going to love this! To learn more about the IE 5.5 behavior, please see WebService Behavior.

Unfortunately, we don't have the space to discuss these three options in detail. However, I thought it would be worthwhile to briefly cover building a proxy with the command line tool, as this is applicable to those who have installed .NET; not just those that have Visual Studio .NET. Command line tool .NET, whether you install it as part of Visual Studio .NET or the .NET SDK, includes a command line proxy generation tool called WebServiceUtil.exe. The path to this command line tool, as well as several other command line tools, is added to our path when we installed .NET. WebServiceUtil.exe allows us to name a SDL, or contract, as one of the command line arguments and the tool can then generate the source code for a proxy to our Web Service. If, for example, we were to save the SDL from our PerfCounters.asmx example, we could use WebServiceUtil.exe to generate a Visual Basic .NET proxy to this Web Service:

WebServiceUtil.exe /command:proxy PerfCounter.sdl /language:VB

This generates a source file PerfCounters.vb that we now need to compile. Using the VB.NET command line compiler, vbc.exe, we can compile our VB source file:

vbc /t:library /r:system.web.dll /r:system.web.services.dll /r:system.xml.serialization.dll perfcounters.vb

What we've done with the command line compiler is specify that we want to create a library (dll) rather than an executable (exe), and in addition to naming the source file to compile, we've specified some .NET assemblies (libraries containing classes our source file requires) as arguments to the compiler. The result is PerfCounters.dll, a complete proxy to our PerfCounters.asmx ASP.NET Web Service that we can now use in .NET applications to communicate via SOAP to our Web Service. Let's use this proxy to build a simple ASP.NET page that consumes and uses our Web Service.

Using the Web Service


First we need to deploy the compiled proxy, known as an assembly, to a Web application's \bin directory. Although we haven't discussed deploying compiled code in this column yet (yet another topic for a future column), suffice to say that to 'register' an assembly on the system simply requires copying the *.dll to a Web application's \bin directory. This is a feature of .NET, but the use of the \bin directory is specific for ASP.NET. To make things simple, we'll create a bin directory off of the server's root directory, c:\inetpub\wwwroot\bin for example. A \bin directory must exist in an application root, either the root of the Web or a folder marked as an application in IIS. Next, we copy our assembly, PerfCounters.dll, to our \bin directory. We can now author our ASP.NET page, which we'll deploy to c:\inetpub\wwwroot. We'll call it PerfCountersConsume.aspx:

<Script runat="server"> Public Sub Page_Load(sender As Object, e As EventArgs) Dim perfcounters As New PerfCounters Dim counters As Counters

counters = perfcounters.GetCounters()

webapp.InnerHtml = counters.ApplicationName restarts.InnerHtml = counters.WorkerProcessRestarts.ToString() procrunning.InnerHtml = counters.WorkerProcessRunning.ToString() apprunning.InnerHtml = counters.ApplicationsRunning.ToString() queued.InnerHtml = counters.RequestsQueued.ToString() totalrequests.InnerHtml = counters.RequestsTotal.ToString() failedrequests.InnerHtml = counters.RequestsFailed.ToString()

succeededrequests.InnerHtml = counters.RequestsSucceeded.ToString() activesessions.InnerHtml = counters.ActiveSessions.ToString() End Sub </Script> Web Application: <B id="webapp" runat="server"/><BR> Process Restarts: <B id="restarts" runat="server"/><BR> Processes Running: <B id="procrunning" runat="server"/><BR> Applications Running: <B id="apprunning" runat="server"/><BR> Requests Queued: <B id="queued" runat="server"/><BR> Requests Total: <B id="totalrequests" runat="server"/><BR> Requests Failed: <B id="failedrequests" runat="server"/><BR> Requests Succeeded: <B id="succeededrequests" runat="server"/><BR> Active Sessions: <B id="activesessions" runat="server"/><BR>

The code above creates an instance of our proxy class PerfCounters (available to us since it's a registered assembly in our \bin directory) calls its GetCounters() method and returns an instance of a Counters class. We then use the instance of the Counters class, counters, to request its member variables and populate ASP.NET server controls. The result is below:

Figure 4. ASP.NET server controls

WCF 101 Creating and consuming a basic WCF Service hosted in IIS
The WCF service I will create here (MyGameService) is one that will keep track of all the games for my game site. Creating a WCF Service and hosting it in IIS 1. In Visual Studio 2008, choose File / New / Web Site / WCF Service and put it in the location http://localhost/MyGameService. Note: You could have choose File / New / Project and Web / WCF Service Application as well but this would have created a file based one that you would later have to publish to IIS. 2. Since we want to call our service MyGameService rather than Service we have to make the following changes a) Rename Service.svc to MyGameService.svc b) Rename App_Code/IService.cs to IMyGameService.cs c) Rename APP_Code/Service.cs to MyGameService.cs d) In IMyGameService.cs rename the interface IService to IMyGameService and press Shift+Alt+F10 to rename it throughout the project e) Do the same to rename the class Service to MyGameService in MyGameService.cs f) change the markup in MyGameService.svc so that Service=MyGameService and CodeBehind=~/App_Code/MyGameService.cs 3. Remove all the contents of IMyGameService.cs except for using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; [ServiceContract] public interface IMyGameService { } and all the contents of MyGameService.cs except for using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization;

using System.ServiceModel; using System.Text; public class MyGameService : IMyGameService { } now we have a clean slate to work with 4. Add methods [OperationContract] and classes [DataContract] to the service The service will have 3 methods void AddGame(Game g); Game GetGameByID(int id); List<Game> GetAllGames(); Since we are passing Games back and forth we will also have to create a DataContract for the type Game To do so, add the following code to IMyGameService.cs [ServiceContract] public interface IMyGameService { [OperationContract] void AddGame(Game g); [OperationContract] List<Game> GetAllGames(); [OperationContract] Game GetGameByID(int id); } [DataContract] public class Game{ [DataMember] public int ID { set; get; } [DataMember] public string Name { set; get; } [DataMember] public string Publisher { set; get; } public Game() { } } 5. Implement the methods in MyGameService.cs public class MyGameService : IMyGameService { static List<Game> _games = new List<Game>(); static object locker = new object();

#region IMyGameService Members public void AddGame(Game g) { g.ID = GetNextID(); lock (locker) { _games.Add(g); } } public List<Game> GetAllGames() { return _games; } public Game GetGameByID(int id) { lock (locker) { foreach (Game g in _games) { if (g.ID == id) return g; } } return null; } #endregion private int GetNextID() { int maxID = 0; lock (locker) { foreach (Game g in _games) { if (g.ID > maxID) maxID = g.ID; } } return maxID + 1; } } Note: you can create stubs for the methods by marking IMyGameService and pressing shift+alt+f10 6. Browse to MyGameService.svc Note: if there is no mapping for .svc you may get the following error

A name was started with an invalid character. Error processing resource 'http://localhost/MyGameService/MyGameService.svc'....

<%@ ServiceHost Language="C#" Debug="true" Service="MyGameService" CodeBehind="~/App_Code/MyGameService.cs" %> -^


To fix this, add a mapping for .svc in inetmgr for the default website or for this particular vdir mapping to C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll. You may need to reset IIS for the mapping to take effect Creating an ASP.NET Client that consumes the WCF service 1. Add a new web site to the WCF service solution called http://localhost/MyGameSite 2. Add a web reference to the WCF service (http://localhost/MyGameService/MyGameService.svc) and call the reference MyGameService 3. In the browser, where you browsed to MyGameService.svc copy the svcutil.exe command svcutil.exe http://mymachine/MyGameService/MyGameService.svc?wsdl open up a Visual Studio 2008 command line and run this to generate the files MyGameService.cs and output.config. 4. Add a new folder to your asp.net project called app_code and add the generated MyGameService.cs file to this directory 5. Add everything between <system.ServiceModel> </system.ServiceModel> including the <system.ServiceModel> </system.ServiceModel> tags from output.config to your web.config file, right before the closing </configuration> tag. Now we are ready to call the WCF service from our ASP.NET application 6. Add two textboxes (txtName, txtPublisher), a button (btnAddGame) and a data grid to display games (grdGames) to default.aspx 7. Add the following code to default.aspx.cs protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { using (MyGameServiceClient gs = new MyGameServiceClient()) { grdGames.DataSource = gs.GetAllGames(); grdGames.DataBind(); } }

} protected void btnAddGame_Click(object sender, EventArgs e) { using (MyGameServiceClient gs = new MyGameServiceClient()) { gs.AddGame(new Game() { Name = txtName.Text, Publisher = txtPublisher.Text }); grdGames.DataSource = gs.GetAllGames(); grdGames.DataBind(); } } Remember to use a using statement or to explicitly close the MyGameServiceClient, otherwise you will end up with the hang shown in my previous post. And that is pretty much all there is to it. A word of caution you will be dealing with the same cross-domain/cross-application issues here as with normal web services, i.e. a potential for heavy serialization if you pass a lot of stuff back and forth, and other such issues, so be a bit careful when you design any apps that rely on sending data back and forth across domain or application boundaries.

You might also like