Monday 30 May 2011

WCF Concurrancy and WCF throttling

Three types of WCF concurrency

There are three ways by which you can handle concurrency in WCF Single, multiple and reentrant. To specify WCF concurrency we need to use the ‘ServiceBehavior’ tag as shown below with appropriate ‘ConCurrencyMode’ property value.

Single: - A single request has access to the WCF service object at a given moment of time. So only one request will be processed at any given moment of time. The other requests have to wait until the request processed by the WCF service is not completed.

Multiple: - In this scenario multiple requests can be handled by the WCF service object at any given moment of time. In other words request are processed at the same time by spawning multiple threads on the WCF server object.
So you have great a throughput here but you need to ensure concurrency issues related to WCF server objects.

Reentrant: - A single request thread has access to the WCF service object, but the thread can exit the WCF service to call another WCF service or can also call WCF client through callback and reenter without deadlock.

By default WCF services are Single concurrency – Sample code demonstration

By default WCF services are set to concurrency type ‘single’ and instancing mode ‘per call’. In order to demonstrate the same, let’s create a simple sample code as shown below. We will create a simple WCF service with a method name called as ‘Call’. When any client calls this WCF service it will display the following details:-
• Client name that made the call. This value will be provided as an input when the client wants to make call to the WCF service.
• Instance number, this will represent number of WCF instance count which is serving the request.
• Thread number which is executing the method.
• Time when the ‘Call’ method was actually called.

Below is the service contract of the ‘Call’ method. Please note that the ‘OperationContract’ is defined as ‘IsOneWay’ true.
public interface IHelloWorldService
void Call(string ClientName);
Below is the simple implementation of the service contract ‘IHelloWorldService’ interface defined below. It has a instance variable ‘i’ which helps us to maintain the instance counter and simple console.writeline which displays client name, instance number , thread number and time when the method was called.

This method waits for 5 seconds using the ‘Thread.Sleep’ function.

public class HelloWorldService : IHelloWorldService
// maintain instance count 
public int i;
public void Call(string ClientName)
// increment instance counts

// display client name, instance number , thread number and time when 
// the method was called

Console.WriteLine("Client name :" + ClientName + " Instance:" + i.ToString() + " Thread:" + Thread.CurrentThread.ManagedThreadId.ToString() + " Time:" + DateTime.Now.ToString() + "\n\n");

// Wait for 5 seconds

This WCF service will be self hosted using ‘WsHttpBinding’ as shown below. We have chosen self hosting so that we can monitor the time, threads and number of instances of WCF service.

static void Main(string[] args)
//Create a URI to serve as the base address
Uri httpUrl = new Uri("http://localhost:8010/MyService/HelloWorld");

//Create ServiceHost
ServiceHost host = new ServiceHost(typeof(ClassLibrary1.HelloWorldService), httpUrl); 

//Add a service endpoint
host.AddServiceEndpoint(typeof(ClassLibrary1.IHelloWorldService), new WSHttpBinding(), "");

//Enable metadata exchange
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;

//Start the Service

Console.WriteLine("Service is host at " + DateTime.Now.ToString());
Console.WriteLine("Host is running... Press <Enter> key to stop");

From the client side we will make 5 continuous calls simultaneously on the WCF service. Below is the code snippet for the same.

Console.WriteLine("Enter Client name");
string str = Console.ReadLine();
ServiceReference1.HelloWorldServiceClient obj = new ServiceReference1.HelloWorldServiceClient();

for(int i=0;i<5;i++)

If you run the above project and monitor your WCF server service you will see the screen shot. There are 2 important points to note:-

• By default the WCF service is configure to run with instance mode of per call. So new instances are created every time the service runs. Instance 1 indicate new instances created for every method call.
• By default the concurrency is single so same thread is use to service all the 5 request’s which are sent from the WCF client side. You can see the value of the thread is always 4.
• The most important factor is time. As the concurrency is configured as single it will be called one after another sequentially. You can notice the same from the time difference of method call of 5 seconds.

Let’s go and change the concurrency mode to multiple. In order to change the concurrency mode to multiple we need to specify ‘Multiple’ in the concurrency mode as shown in the below code snippet.

If you run the client now you can see different threads (i.e. thread 4, 5, 6, 7 and 8) are spawned to serve the request and the time of the method calls are almost same. In other words the methods are executed concurrently on different threads.

In short you are now having higher throughput in less amount of time.

9 combinations of Instancing and Concurrency

There are 9 combination of concurrency and instancing methodology as shown in the below table. In the further coming section we will discuss in more detail about the same.
Single (Default) Multiple Reentrant
(Single instance for all client)
Single thread for all clients. Multiple threads for all clients. Single threads for all clients, locks are released when calls diverted to other WCF services.
(Multiple instance per client)
Single thread for every client. Multiple threads for every request. Single threads for all clients, locks are released when calls diverted to other WCF services.
PerCall (Default)
(Multiple instance for every method call)
Single thread for every client Single thread for every client Single threads for all clients, locks are released when calls diverted to other WCF services.

Instance mode = Per Call and Concurrency = Single

Instance mode ‘PerCall’ with ‘Single’ concurrency is the default setting in WCF. We have already seen and example and demonstration of the same.

With per call new WCF instances are created for every method calls made to the WCF server service. The default concurrency is single so only one thread will be used to serve all instances.

Below is a simple pictorial representation of what will happen in per call and single concurrency scenario:-

• For every client instance a single thread will be allocated.
• For every method call a new service instance will be created.
• A single thread will be used to serve all WCF instances generated from a single client instance.

If you refer the previous sample you can see how threads are same and the halt of 5 seconds on the WCF service.

Instance mode = per Call and Concurrency = Multiple

[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class HelloWorldService : IHelloWorldService

In this combination multiple instances are created for every call but multiple threads serve every method call to WCF service instance. You can see in the below figure we have two WCF service instance and every instance has multiple WCF service objects created for every method call. Every method call is handled by multiple threads.

In the above sample if you remember we have multiple threads serving every method call and the time difference between every method call is reduced considerably. The method calls are fired approximately same time.

Instance mode = per session and Concurrency = single

[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession, ConcurrencyMode = ConcurrencyMode.Single)]
public class HelloWorldService : IHelloWorldService

In this combination one WCF service instance is created for every WCF client session because the WCF instance mode is set to per session. All the method calls are executed in a sequential manner one by one. In other words only one thread is available for all method calls for a particular service instance.

If you run the sample code with the per session and single combination mode you will find the same thread executes all request with same WCF instance per session.

Instance mode = per session and Concurrency = Multiple

[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class HelloWorldService : IHelloWorldService

In this combination one WCF instance is created for every WCF client session and every method call is run over multiple threads. Below is the pictorial representation of the same.

If you run the sample code attached with this article you will find same instance with every method call running on different methods.

To get a better idea you can run with different client exe instance with different names as shown below. You can notice how every client get his own WCF service instance with every method allocated to run on different threads.

Instance mode = Single and Concurrency = Single

[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Single)]
public class HelloWorldService : IHelloWorldService
In this combination only one instance of WCF service instance is created which serves all requests which are sent from all WCF clients. These entire requests are served using only one thread.

You can see in the below figure approximately one thread is assigned for every WCF client call and only one instance of the WCF service is created.

Instance mode = Single and Concurrency = Multiple

[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class HelloWorldService : IHelloWorldService
In this combination one WCF service instance is created for serve all WCF clients. All request are served using multiple / different threads.

You can see from the output we have 6 threads serving 10 requests as compared previously we had approximately only 2 threads.


In mode only thread runs to serve all requests. If your WCF service makes an outbound call to some other WCF service or makes a client call it releases the thread lock. In other words until the outbound call is completed other WCF clients can make call.

Throttling behavior

WCF throttling settings helps you to put an upper limit on number of concurrent calls, WCF instances and concurrent session. WCF provides 3 ways by which you can define upper limits MaxConcurrentCalls, MaxConcurrentInstances and MaxConcurrentSessions.

MaxConcurrentCalls: - Limits the number of concurrent requests that can be processed by WCF service instances.

MaxConcurrentInstances: - Limits the number of service instances that can be allocated at a given time. When it’s a PerCall services, this value matches the number of concurrent calls. For PerSession services, this value equals the number of active session instances. This setting doesn’t matter for Single instancing mode, because only one instance is ever created.

MaxConcurrentSessions: - Limits the number of active sessions allowed for the service.

All the above 3 setting can be defined in the ‘servicebehaviors’ tag as shown in the below XML snippet.


<behavior name="serviceBehavior"> 

<serviceThrottling maxConcurrentCalls="16"

maxConcurrentInstances="2147483647" maxConcurrentSessions="10" /> 



Default values for WCF throttling

Below is a simple table which shows default settings for throttling as per different WCF versions.

  MaxConcurrentSessions MaxConcurrentSessions MaxConcurrentSessions
WCF 3.0 / 3.5 6 26 10
WCF 4.0
16 * processorcount MaxConcurrentCalls
MaxConcurrentSessions 100 * processorcount
100 * processorcount

WCF Authentication

WCF is a distributed technology, you build the WCF service to serve the functionality to the Client, The Client could be on Intranet or on Internet. It is almost always mandatory for the Service to know its client (Authenticate) before accepting the message or sending the message to the client.
WCF provides various ways to accept the credential from client and authenticate it. The following table shows the possible credential types that you can use when creating an application. You can use these values in either code or configuration files.
Setting Description
None Specifies that the client does not need to present a credential. This translates to an anonymous client.
Windows Allows SOAP message exchanges to occur under the security context established with a Windows credential.
Username Allows the service to require that the client be authenticated with a user name credential. Note that WCF does not allow any cryptographic operations with user names, such as generating a signature or encrypting data. WCF ensures that the transport is secured when using user name credentials.
Certificate Allows the service to require that the client be authenticated using an X.509 certificate.
Issued Token A custom token type configured according to a security policy. The default token type is Security Assertions Markup Language (SAML). The token is issued by a secure token service. For more information, see Federation and Issued Tokens.
In this Article, I will cover Authentication using User Name (How to authenticate client using User Name and Password)

Configure a service to authenticate with a user name and password

Authenticate the client with the User Name and Password can be configured either using Code or using Configuration file.

Using Code

  1. Create an instance of the WSHttpBinding class.
  2. Set the Mode property of the WSHttpSecurity class to Message. The WSHttpSecurity object is accessible through the Security property of the WSHttpBinding class.
  3. Set the ClientCredentialType property of the MessageSecurityOverHttp class to UserName. The MessageSecurityOverHttp is accessed through the Message property of the WSHttpSecurity class, as shown in the following code.
    WSHttpBinding myBinding = new WSHttpBinding(); myBinding.Security.Mode = SecurityMode.Message; myBinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;

Using Configuration file

  1. Add a wsHttpBinding Element to the <bindings> section of the Web.config file.
  2. Add a binding element to the wsHttpBinding element and set the configurationName attribute to a value appropriate to your needs.
  3. Add a <security> for <wsHttpBinding> element to the binding and set the mode attribute to "Message".
  4. Add a <message> for <security> for <wsHttpBinding> to the security binding, and set the clientCredentialType attribute to "UserName", as shown in the following code:
      <system.serviceModel> <bindings> <wsHttpBinding> <binding name=”Binding1″> <security mode=”Message”> <message clientCredentialType=”UserName”/> </security> </binding> </wsHttpBinding> </bindings> </system.serviceModel>

  • Create a service that uses the new binding, as shown in the following code.

    1. <services> <service type=”Microsoft.ServiceModel.Samples.CalculatorService” behaviorConfiguration=”CalculatorServiceBehavior”> <!– Use the base address provided by the host. –> <endpoint address=”" binding=”wsHttpBinding” bindingConfiguration=”Binding1″ contract=”Microsoft.ServiceModel.Samples.ICalculator” /> </service> </services>

    Client Code to sent the User Name and Password to Service

    1. Create an instance of the client class as shown in the following code.
        CalculatorClient client = new CalculatorClient("default");
    2. Set the Password property of the UserNamePasswordClientCredential class to the password. The class is accessible from the client object, as shown in the following code.
        client.ClientCredentials.UserName.Password = "Your Password";
    3. Set the UserName property to the user’s user name.
        client.ClientCredentials.UserName.UserName = "Your User Name";
    4. Call the methods of the service.
        double value1 = client.Add(100, 15.99);

    Friday 6 May 2011

    WCF Configuration Setting

    WCF services are powerful as you have just seen.  It is possible to expose a single service in more ways than just one.  This allows developers to support things like net.tcp binary messages and SOAP messages from the same service.  If you are an enterprise developer supporting multiple clients this is a blessing since it means .Net consumers of your service can use TCP while other consumers use WS*.  The nice thing is the developer doesn’t have to code it, just declaratively express how he wants the service configured.

    Setting Up Basic Http Binding

    Before we add multiple bindings to our single service, let’s focus on adding one binding.  In order to configure our service we are going to use the Microsoft Service Configuration Editor.  This editor allows us to configure our WCF service and can be launched right from Visual Studio.  To launch the editor, right click on the web.config file.  An option should be in the menu that says “Edit WCF Configuration”.  If it doesn’t don’t worry, sometimes, Visual Studio doesn’t pickup this option.  A trick is to go to the tools menu in Visual Studio and select the editor from there.  After the editor is launched it will then show up in the menu when you right click the web.config file.
    For this example I have removed everything from the web.config file before launching so I can configure the service completely from scratch.  Opening the web.config with the editor shows a blank configuration as follows.
    Follow the steps to initialize the configuration.
    Step 1
    Make sure your solution builds.
    Step 2
    Click “Create a New Service” in the right panel of the editor.
    Step 3
    Browse to the bin directory and select the WcfService1.dll (if the file doesn’t show up, go back to step 1)
    Double click this file and select your service implementation.
    Step 4
    The service type should be displayed on the previous screen.  Press Next->.
    Step 5
    Select the contract.  This should automatically be selected to WcfService1.IMyService.  Press Next->.
    Step 6
    Since we are using IIS to host our service select the HTTP option for the communication mode.
    Step 7
    Select the basic web services interoperability.  We’ll come back later on and add advance web services interoperability.
    Step 8
    Delete the “http://” from the address field.  Since we are developing we don’t know which port this will get assigned as of yet.
    Press Next->.  A dialog will appear.  Select Yes.
    Press Finish on the next screen.
    At this point we have an almost configured service.  If you drill down into the Services folder within the tool down to the end point the configuration should look something like this.
    Step 9
    Let’s clean up our configuration.  In the screen shot above in the configuration section.  Give this endpoint a name of “Basic”.  This will let us know later on this endpoint is our BasicHttpBinding configuration which supports the SOAP1.1 protocol.
    Step 10
    Click on the “Services” folder in the editor.
    Step 11
    Next to the binding configuration there is a link that says “Click to Create”.  Click this link to create a binding configuration.  While this isn’t necessary in all instances it is a good practice to have a binding configuration.  This gives you more control over how your binding is configured and is a good practice to initialize early on.
    Clicking this link will create a new binding.  In the name field under the configuration section, give it a name of “Basic”.  The defaults for this example are fine.
    Note:  Clicking on the Security tab in the above screen the Mode should be set to None. 
    At this point you should be able to save your configuration and press F5 in Visual Studio to launch your service in debug mode.  You should be presented with a web page that looks like the following:

    Exposing Our Service’s WSDL

    Unlike previous ASMX services, the WSDL (web service definition language) for WCF services is not automatically generated.  The previous image even tells us that “Metadata publishing for this service is currently disabled.”.  This is because we haven’t configured our service to expose any meta data about it.  To expose a WSDL for a service we need toconfigure our service to provide meta information.  Note:  The mexHttpBinding is also used to share meta information about a service.  While the name isn’t very “gump” it stands for Meta Data Exchange.  Toget started configuring the service to expose the WSDL follow the following steps.
    Step 1
    Under the Advanced folder in the editor, select the “Service Behaviors”.
    Click the “New Service Behavior Configuration” link in the right pane.
    Step 2
    Name the behavior “ServiceBehavior”.  In the bottom section press the add button and select the “serviceMetaData” option and press Add.
    The end result should look like the following.
    Step 3
    Under the “Service Behaviors” folder, select the newly created “ServiceBehavior” option and then the “serviceMetadata” option underneath that.  In the right pane change the HttpGetEnabled to True.
    Step 4
    Select the service under the Services folder and apply the new service behavior to the service.
    Step 5
    Save the configuration and reload the service in the browser.  The page should be changed to the following:
    Clicking on the link should display the WSDL for the service.
    At this point our service is configured to support the SOAP1.1 protocol through the BasicHttpBinding and is also exposing the WSDL for the service. What if we want to also expose the service with the SOAP1.2 protocol and support secure and non-secure messages?  No problem.  We can expose the service all of those ways without touching any code only the configuration.

    Adding More Bindings and Endpoints To Our Service

    Now that we have the basic binding working let’s expose two additional endpoints for our service which support the WS* protocol but are configured differently.  We’ll expose a plain SOAP1.2 protocol message using the wsHttpBinding that is a plain message as well as a secured message using the wsHttpBinding.
    Step 1
    Under the Services folder select the EndPoints folder for the service and add a new service endpoint.  Give it a name of WsPlain.  This endpoint will serve as a standard SOAP1.2 message that isn’t encrypted.  Change the binding to wsHttpBinding.  In the address field, copy the address from your browser.  In my case, my project used the address of http://localhost:5606/Service.svc.  Paste this into the address field and add /WsPlain to the end of it so it looks like the following:
    Each binding for each endpoint has to have a separate address.  Doing it this way allows us to keep our one service file and offer it up in various configurations.  In the contract option browse to the DLL in the bin directory and select the contract used previously.  The end result should look similar to this:
    Step 2
    Just as we did previously, click on the Services folder and create a binding configuration for this endpoint.  Refer to step 10 and 11 above.
    Provide a name of WsPlain for the new binding.  In the security tab change the mode to “None” and set all other options to false or none.  This is setting up our binding so there is no security on our message.  By default the binding is configured to be secure.
    The final settings for the WsPlain endpoint should be similar to this.
    Step 3
    To configure a secure binding using wsHttpBinding follow these same steps above but leave the default values in the security tab of the binding configuration.  Call this end point and binding WsSecured.  The new endpoint should look like this:
    That’s it, our service is now configured three different ways and is configured to support SOAP1.1, SOAP1.2 and WS*.  Pretty cool huh?

    Tuesday 3 May 2011

    WCF and Binding Syntax

    As I always forget the syntax for different esoteric WCF-bindings, I've decided to assemble it into a table for a quick reference:

    Name Transport Binding Name (config)
    Basic HTTP/HTTPS basicHttpBinding
    TCP TCP netTcpBinding
    Peer P2P netPeerBinding
    IPC IPC netNamedPipeBinding
    WS HTTP/HTTPS wsHttpBinding
    Federated WS HTTP/HTTPS wsFederationHttpBinding
    Duplex HTTP wsDualHttpBinding
    MSMQ MSMQ netMsmqBinding
    MSMQ Integration MQMQ msmqIntegrationBinding

    Hey friends U like my Article ..............

    WCF: how to call asynchronously

    It happens that I get a question on how to call webservices in an asynchronous manner. It is actually not that hard, even the tools does not support this out of the box (or so it seems ;-)).
    To generate a proxy that supports the async-pattern (Begin<method>/End<method>); you have 2 directions to go:

    1) SvcUtil.exe:
    You can use the svcutil.exe utility from WCF. The syntax is this:
    svcutil.exe /async <url to wsdl-file> (this is the most basic form! More advanced versions exists)
    2) VS service reference Visual Studio does actually support this behavior if you are a bit careful when generating the proxy. If you check this box, you do get methods named Begin<method>/End<method>.


    Hey all my friends this may help u ..............  Please Reply to this post

    WCF Exception Handling

    If you desire to communicate your own custom exceptions and at the same time include custom data in that exception, you are better off by using the built-in DataContractSerializer. This stands in contrast to the previous way (see above post) of declaring exceptions; but the ease and “ready-to-use” condition of the DataContractSerializer makes it very difficult to argue for rolling your own serialization mechanism.
    WCF uses by default the DataContractSerializer to serialize/deserialize data on the wire between the Server and Client, hence this is already in operation out-of-the-box.
    How to create this? In this scenario, I have full control of both Client and Server side – hence I can easily share a “contract” between the two. In the below image, you see the 3 projects in effect.

    Shared Contracts "Contracts"

    Shared ContractThe contract will declare my custom exception called CalculationFaultContract. Note, that this is decorated with [DataContract] attributes as well as [DataMember] attributes. This will make the DataContractSerializer able to serialize this object between Server –> Client just fine.
    /// <summary>
    /// A custom type to convey error 
    data to the Client/// </summary>[DataContract]
    public class CalculationFaultContract{
        /// <summary>
        /// Gets or sets the argument A.
        /// </summary>
        /// <value>
        /// The arg A.
        /// </value>
        public int ArgA { get; set; }
        /// <summary>
        /// Gets or sets the argument B.
        /// </summary>
        /// <value>
        /// The arg B.
        /// </value>
        public int ArgB { get; set; }

    Server SideOn the server side, you still need to declare what exceptions your methods will throw. This is done using the [FaultContract]-attribute like below. This will inform WCF, that your method will throw this kind of exception to the Client in case of an error has occurred.
    /// <summary>
    /// </summary>[ServiceContract]
    public interface ICalculator{
        /// <summary>
        /// Adds the specified arguments.
        /// </summary>
        /// <param name="a">A.</param>
        /// <param name="b">The b.</param>
        /// <returns></returns>
        int Add(int a, int b);
        /// <summary>
        /// Subtracts the specified arguments.
        /// </summary>
        /// <param name="a">A.</param>
        /// <param name="b">The b.</param>
        /// <returns></returns>
        int Subtract(int a, int b);

    The ICalculator-implementation will, in case of an error, throw the fault like below. Note, that when programming with services, we are principally dealing with “Faults” over “Exceptions”. An exception is a platform specific entity, that can not be carried from Server –> Client. Remember, the Client could potentially be running on a Java-platform, so how would you communicate a .NET exception to this platform?
    /// <summary>
    /// Calculation implementation.
    /// </summary>
    public class CalculatorService : ICalculator {
        /// <summary>
        /// Adds the specified arguments.
        /// </summary>
        /// <param name="a">A.</param>
        /// <param name="b">The b.</param>
        /// <returns></returns>
        public int Add(int a, int b)
            Console.WriteLine("Add called...");
            //check not negative (to show exception)
            if(a < 0)
      throw new FaultException<CalculationFaultContract>(
    new CalculationFaultContract(){ArgA = a, ArgB = b}, 
    "Argument is negative");
            //normal operation
            return a + b;

    Also note, that the message set in the fault (“Argument is negative”) is a so-called FaultReason. Again this is an abstraction that makes the WCF/WS-paradigm operational cross-platform. It is not tied to a specific platform.

    Client SideFinally, on the Client side you surround the proxy-call to the CalculatorService in a try/catch structure of the proper kind. You need to anticipate FaultException<T> here, to be able to receive the proper values from the Server side.
    class Program{
        static void Main(string[] args)
            Console.WriteLine("Starting CLIENT...");
            Console.WriteLine("Press key to call..");
            var fac = new ChannelFactory<ICalculator>(
                new NetTcpBinding(), 
            var proxy = fac.CreateChannel();
            using (proxy as IDisposable)
                  //this SHOULD throw errors as 'a' < 0
                 proxy.Add(-3, 5);
         catch (FaultException<CalculationFaultContract>ex)
       var msg = string.Format("Caught the RIGHT exception.
     ArgA={0}, ArgB={1}, Error={2}", 
                catch (CommunicationException ex)
      Console.WriteLine("Caught the WRONG exception.");

    This is basically all there is to communicating your custom data to the calling Client from the server side. On the side note, you maybe can see that this allows you do declare a complete structure of appropriate exception types in your system to very precisely communicate the reason of error from the Server to the calling Client.

    It is actually not all that difficult ;-)

    Creating a WCF service


    To begin with, we are going to create a very simple WCF service and WCF client in C#/VB.NET first. After this article, we will have a working WCF application. Then in the next article, we will create a Java client to connect to the WCF service created in this article.

    Creating a WCF service

    Using Visual Studio 2008, we can easily create Windows Communication Foundation (WCF) service and client. This topic describes how to create a basic WCF service and a client that can call the service.
    To create a basic WCF service, please follow the steps below:
    1. Open Visual Studio 2008.
    2. Create a new WCF Service Application project. In Visual Studio 2008, click menu File -> New -> Project. In the New Project dialog, expand Visual Basic or Visual C# and choose the WCF Service Application template to create a project named “WcfService1″. Click OK.

    Now, we have created a basic WCF service application. In Solution Explorer, we can see four files in the “WcfService1″ project.

    IService1 interface, a WCF service contract
    A service file, accessed by the client as a part of URL
    A class, implements the IService1interface
    Service configuration file

    In the “Service1.svc.cs” file, we can find a class named “Service” which includes two functions, “GetData” and “GetDataUsingDataContract”.
    You can create a new service or add more functions to the existing service. I will talk about these in the future. Now we can run the server in the Debug mode. The ASP.NET Deployment Server will start and the service will be deployed to the server:

    Creating a WCF client

    To create a WCF client that calls the service, please follow the steps below:
    1. Open Visual Studio 2008.
    2. Create a new Console Application project. In Visual Studio 2008, click menu File -> New -> Project. In the New Project dialog, expand Visual Basic or Visual C# and choose the Console Application template to create a project named “WcfClient1″. Click OK.

    3. Add a service reference to the project. Go to Solution Explorer, right-click the “References” node in the “WcfClient1″ project, and click Add Service Reference.

    4. In the Add Service Reference dialog, input the server URL above in Address. Click Go and then click OK.

    5. We can find a node named “ServiceReference1″ under Service References.

    6. Add a using statement (Imports in Visual Basic) for the System.ServiceModel namespace in the generated “Program.cs” file.
    using System.ServiceModel;
    7. Add the following code into the Main function in the “Program.cs” file:
    Service1Client client = new Service1Client();
    String strResponse = client.GetData(100);

    8. Then we can run the client application in the Debug mode. If we see the following result, our WCF application is working properly.

    Sunday 1 May 2011

    WCF For Beginers

    Overview of WCF

    - Windows Communication Foundation.
    - It combines functionalities of Asp.Net Web services, remoting, MSMQ and Enterprise Services.
    - It’s more reliable and secured then Web services.
    - All the major changes can be done in the configuration file instead of code file.

    Differences with Webservices

    WCF can be hosted on IIS, WAS, of self-hosting.
    WS can be hosted on IIS.

    WCF has [ServiceContract] attribute attached with the class.
    WS has [WebService] attribute attached with the class.
    WCF has [OperationContract] attribute attached with methods.
    WS has [WebMethod] attribute attached with methods.

    WCF uses System.Runtime.Serialization namespace for serialization.
    WS uses System.Xml.Serialization namespace for serialization.

    WCF supports XML, MTOM (Messaging Transmission Optimization Mechanizm),Binary.
    WS supports XML, MTOM, DIME (Direct Internet Message Encapsulation).

    WCF supports Http, Tcp, Msmq, P2P transport protocols.
    WS supports Http protocol.

    WCF provides reliable security for messaging and transactions over net.
    WS doesn’t provide method level security & message delivery is’t assured & can be lost without acknowledgement.

    3 major Points in WCF

    WCF service location that client can use to expose its features

    Configuration for Transport protocol, security and encoding mechanism.

    It defines type of data and type of oprtaions, a client application can use from WCF service.

    Service Contract in WCF

    It has 2 attributes: ServiceContract & OperationContract

    Interface ITestContract 
     string MyMethod();
    Class myService : ITestContract
     public  string myMethod()
      return "Hello World!!";

    Data Contract in WCF

    It has 2 attributes: DataContract & DataMember

    class TestDataContract
     public string EmployeeName;
     public DateTime JoiningDate;

    WCF configurations in config file

    It declares information about endpoint name, address, binding and contract.

            <endpoint name = "MyEndpoint"
                      address = "http://localhost:8000/MyService/"
                      binding = "wsHttpBinding"
                      contract = "IMyContract"

    WCF proxy

    It provides the same operations as that of a Service Contract. There are 2 ways to generate WCF proxies.

    In Visual Studio 2008
    Right click reference > Add service reference

    In Visual Studio - Command Prompt
    Using SvcUtil.exe tool

    ex: ScvUtil    http://localhost/MyWCFService/MyService.svc    /out:MyProxy.cs

    Fault Contract

    It provides the implementation to handle the error raised by WCF
    It also propagates the errors to its client applications.

    Collection Types Supported by WCF


    Dictionary Collection Types Supported by WCF


    I hope, I am able to cover main topics about WCF in this article.