Windows Communication Foundation (WCF) Basic tutorial


I am writing this blog for those who are new in WCF and Start Learning WCF. I am giving Example in C# language.
This blog is created by just a R&D on web and collect useful material from different web sites.

What Exactly is the Windows Communication Foundation (WCF)?

WCF is a framework that abstract basically all kind of communications, from web services to socket binary communication, and you pretty much do what you wish with it. With WCF, we can define our service once and then configure it in such a way that it can be used via HTTP, TCP, IPC, and even Message Queues. We can consume Web Services using server side scripts (ASP.NET), JavaScript Object Notations (JSON), and even REST (Representational State Transfer).


Here we start with some basic terminologies and definitions of WCF components. 

End Points : In simple words we can say that an End point is a access point to world for communicating with WCF service. All WCF communications are take place through end point.
It has mainly three components-
  •      Address (Where)
  •      Binding (How)
  •      Contract (What)
Address : It is a location where  WCF service hosted. Client will use this URL to connect to the service.

Binding : It defines how the client will communicate with WCF service. Here is the meaning for communication is Protocols used for communication. WCF Provide more flexibility and option for choosing protocols according to our requirements. Following protocols are available in the wcf for communicating with client.
  • HTTP
  • Named 
  • Pipes
  • TCP
  • MSMQ
 Contract : The contract is a platform-neutral and standard way of describing what the service does. In other words Contracts are 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.
In WCF four types of contracts defines.
  1. Service contract
  2. Data contract
  3. Message contract
  4. Fault contract
Now we start step by step implementation of WCF service with practical example. 

Step: 1
How to: Define a Windows Communication Foundation Service Contract
.NET Framework 4

When creating a basic WCF service, the first task is to define a contract. The contract specifies what operations the service supports. An operation can be thought of as a Web service method. Contracts are created by defining a C++, C#, or Visual Basic (VB) interface. Each method in the interface corresponds to a specific service operation. Each interface must have the ServiceContractAttribute applied to it and each operation must have the OperationContractAttribute applied to it. If a method within an interface that has the ServiceContractAttribute does not have the OperationContractAttribute, that method is not exposed.
The code used for this task is provided in the example following the procedure.
To create a Windows Communication Foundation contract with an interface
Open Visual Studio 2010 as an administrator by right-clicking the program in the Start menu and selecting Run as administrator.
Create a new console application project. Click the File menu and select New, Project. In the New Project dialog, select Visual Basic or Visual C#, and choose the Console Application template, and name it Service. Use the default Location.
For a C# project Visual Studio creates a file called Program.cs. This class will contain an empty method called Main(). For a VB project, Visual Studio creates a file called Module1.vb with an empty subroutine called Main(). These methods are required for a console application project to build correctly, so you can safely leave them in the project.
Change the default Service namespace to Microsoft.ServiceModel.Samples. To do this, right-click the project in the Solution Explorer and select Properties. Make sure that the Application tab on the left side of the Properties dialog is selected. For a C# project, type Microsoft.ServiceModel.Samples in the edit box labeled Default Namespace. For a VB project, type Microsoft.ServiceModel.Samples in the edit box labeled Root namespace. Click the File menu and select Save All to save your changes.
If you are using C#, change the namespace in the generated Program.cs file to Microsoft.ServiceModel.Samples as shown in the following example.
namespace Microsoft.ServiceModel.Samples
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}

If you are using VB, add a Namespace statement and an End Namespace statement to the generated Module1.vb as shown in the following example.
Add a reference to System.ServiceModel.dll to the project:
In the Solution Explorer, right-click the References folder under the project folder and choose Add Reference.
Select the .NET tab in the Add Reference dialog and scroll down until you see System.ServiceModel (version 4.0.0.0), select it, and click OK.

   Note:
When using a command-line compiler (for example, Csc.exe or Vbc.exe), you must also provide the path to the assemblies. By default, on a computer running Windows Vista for example, the path is: "Windows\Microsoft.NET\Framework\v4.0".
Add a using statement (Imports in Visual Basic) for the System.ServiceModel namespace.
using System.ServiceModel;

In Program.cs (Module1.vb for VB), define a new interface called ICalculator and apply the ServiceContractAttribute attribute to the interface with a Namespace value of "http://Microsoft.ServiceModel.Samples". Specifying the namespace explicitly is a best practice because it prevents the default namespace value from being added to the contract name.

Note:
When using attributes to annotate an interface or class, you can drop the "Attribute" part from the attribute name. So ServiceContractAttribute becomes [ServiceContract] in C#, or <ServiceContract> in Visual Basic.


[ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]
public interface ICalculator

Declare a method for each of the operations the ICalculator contract exposes (add, subtract, multiply, and divide) within the interface and apply the OperationContractAttribute attribute to each method that you want to expose as part of the public WCF contract.
[OperationContract]
double Add(double n1, double n2);
[OperationContract]
double Subtract(double n1, double n2);
[OperationContract]
double Multiply(double n1, double n2);
[OperationContract]
double Divide(double n1, double n2);

Example
The following code example shows a basic interface that defines a service contract.
using System;
// Step 5: Add the using statement for the System.ServiceModel namespace
using System.ServiceModel;
namespace Microsoft.ServiceModel.Samples
{
  // Step 6: Define a service contract.
  [ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]
  public interface ICalculator
  {
    // Step7: Create the method declaration for the contract.
    [OperationContract]
    double Add(double n1, double n2);
    [OperationContract]
    double Subtract(double n1, double n2);
    [OperationContract]
    double Multiply(double n1, double n2);
    [OperationContract]
    double Divide(double n1, double n2);
  }
}

 Step: 2
How to: Implement a Windows Communication Foundation Service Contract
.NET Framework 4

Creating a WCF service requires that you first create the contract, which is defined using an interface. For more information about creating the interface, see How to: Define a Windows Communication Foundation Service Contract. The next step, shown in this example, is to implement the interface. This involves creating a class called CalculatorService that implements the user-defined ICalculator interface. The code used for this task is provided in the example following the procedure.
To implement a WCF service contract
  1. Create a new class called CalculatorService in the same file where you defined the ICalculator interface. The CalculatorService implements the ICalculator interface.

public class CalculatorService : ICalculator

  1. Implement each method defined in the ICalculator interface within the CalculatorService class.

public double Add(double n1, double n2)
{
    double result = n1 + n2;
    Console.WriteLine("Received Add({0},{1})", n1, n2);
    // Code added to write output to the console window.
    Console.WriteLine("Return: {0}", result);
    return result;
}

public double Subtract(double n1, double n2)
{
    double result = n1 - n2;
    Console.WriteLine("Received Subtract({0},{1})", n1, n2);
    Console.WriteLine("Return: {0}", result);
    return result;
}

public double Multiply(double n1, double n2)
{
    double result = n1 * n2;
    Console.WriteLine("Received Multiply({0},{1})", n1, n2);
    Console.WriteLine("Return: {0}", result);
    return result;
}

public double Divide(double n1, double n2)
{
    double result = n1 / n2;
    Console.WriteLine("Received Divide({0},{1})", n1, n2);
    Console.WriteLine("Return: {0}", result);
    return result;
}


 Note:
The write output code has been added to make testing convenient.
Example
The following code example shows both the interface that defines the contract and the implementation of the interface.
using System;
using System.ServiceModel;

namespace Microsoft.ServiceModel.Samples
{
    // Define a service contract.
    [ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]
    public interface ICalculator
    {
        [OperationContract]
        double Add(double n1, double n2);
        [OperationContract]
        double Subtract(double n1, double n2);
        [OperationContract]
        double Multiply(double n1, double n2);
        [OperationContract]
        double Divide(double n1, double n2);
    }

    // Step 1: Create service class that implements the service contract.
    public class CalculatorService : ICalculator
    {
         // Step 2: Implement functionality for the service operations.
        public double Add(double n1, double n2)
        {
            double result = n1 + n2;
            Console.WriteLine("Received Add({0},{1})", n1, n2);
            // Code added to write output to the console window.
            Console.WriteLine("Return: {0}", result);
            return result;
        }

        public double Subtract(double n1, double n2)
        {
            double result = n1 - n2;
            Console.WriteLine("Received Subtract({0},{1})", n1, n2);
            Console.WriteLine("Return: {0}", result);
            return result;
        }

        public double Multiply(double n1, double n2)
        {
            double result = n1 * n2;
            Console.WriteLine("Received Multiply({0},{1})", n1, n2);
            Console.WriteLine("Return: {0}", result);
            return result;
        }

        public double Divide(double n1, double n2)
        {
            double result = n1 / n2;
            Console.WriteLine("Received Divide({0},{1})", n1, n2);
            Console.WriteLine("Return: {0}", result);
            return result;
        }
    }
}

Compiling the Code
If you are using a command-line compiler, you must reference the System.ServiceModel assembly.
If you are using Visual Studio, on the Build menu click Build Solution (or press CTRL+SHIFT+B).


 Step: 3

How to: Host and Run a Basic Windows Communication Foundation Service
.NET Framework 4

This is the third of six tasks required to create a basic Windows Communication Foundation (WCF) service and a client that can call the service. For an overview of all six of the tasks, see the Getting Started Tutorial topic.
This topic describes how to run a basic Windows Communication Foundation (WCF) service. This procedure consists of the following steps:
  • Create a base address for the service.
  • Create a service host for the service.
  • Enable metadata exchange.
  • Open the service host.
A complete listing of the code written in this task is provided in the example following the procedure. Add the following code into the Main() method defined in the Program class. This class was generated when you created the Service solution.
To configure a base address for the service
  1. Create a Uri instance for the base address of the service. This URI specifies the HTTP scheme, your local machine, port number 8000, and the path ServiceModelSample/Service to the service that was specified for the namespace of the service in the service contract.
Uri baseAddress = new Uri("http://localhost:8000/ServiceModelSamples/Service");

To host the service
  1. Import the System.ServiceModel.Description namespace. This line of code should be placed at the top of the Program.cs/Program.vb file with the rest of the using or imports statements.
using System.ServiceModel.Description;

  1. Create a new ServiceHost instance to host the service. You must specify the type that implements the service contract and the base address. For this sample the base address is http://localhost:8000/ServiceModelSamples/Service and CalculatorService is the type that implements the service contract.
ServiceHost selfHost = new ServiceHost(typeof(CalculatorService), baseAddress);

  1. Add a try-catch statement that catches a CommunicationException and add the code in the next three steps to the try block. The catch clause should display an error message and then call selfHost.Abort().
try
{
    // ...
}
catch (CommunicationException ce)
{
    Console.WriteLine("An exception occurred: {0}", ce.Message);
    selfHost.Abort();
}

  1. Add an endpoint that exposes the service. To do this, you must specify the contract that the endpoint is exposing, a binding, and the address for the endpoint. For this sample, specify ICalculator as the contract, WSHttpBinding as the binding, and CalculatorService as the address. Notice here the endpoint address is a relative address. The full address for the endpoint is the combination of the base address and the endpoint address. In this case the full address is http://localhost:8000/ServiceModelSamples/Service/CalculatorService.


selfHost.AddServiceEndpoint(
    typeof(ICalculator),
    new WSHttpBinding(),
    "CalculatorService");
Note:

Starting with .NET Framework 4, if no endpoints are explicitly configured for the service then the runtime adds default endpoints when the ServiceHost is opened. This example explicitly adds an endpoint to provide an example of how to do so. For more information aboutdefault endpoints, bindings, and behaviors, see Simplified Configuration and Simplified Configuration for WCF Services.
  1. Enable Metadata Exchange. To do this, add a service metadata behavior. First create a ServiceMetadataBehavior instance, set the HttpGetEnabled property to true, and then add the new behavior to the service. For more information about security issues when publishing metadata, see Security Considerations with Metadata.

ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
selfHost.Description.Behaviors.Add(smb);

  1. Open the ServiceHost and wait for incoming messages. When the user presses the ENTER key, close the ServiceHost.


selfHost.Open();
Console.WriteLine("The service is ready.");
Console.WriteLine("Press <ENTER> to terminate service.");
Console.WriteLine();
Console.ReadLine();

// Close the ServiceHostBase to shutdown the service.
selfHost.Close();

To verify the service is working
  1. Run the service.exe from inside Visual Studio. When running on Windows Vista, the service must be run with administrator privileges. Because Visual Studio was run with Administrator privileges, service.exe is also run with Administrator privileges. You can also start a new command prompt running it with Administrator privileges and run service.exe within it.
  2. Open Internet Explorer and browse to the service's debug page at http://localhost:8000/ServiceModelSamples/Service.
Example
The following example includes the service contract and implementation from previous steps in the tutorial and hosts the service in a console application. Compile the following into an executable named Service.exe.
Be sure to reference System.ServiceModel.dll when compiling the code.


using System;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace Microsoft.ServiceModel.Samples
{
    // Define a service contract.
    [ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]
    public interface ICalculator
    {
        [OperationContract]
        double Add(double n1, double n2);
        [OperationContract]
        double Subtract(double n1, double n2);
        [OperationContract]
        double Multiply(double n1, double n2);
        [OperationContract]
        double Divide(double n1, double n2);
    }

    // Service class that implements the service contract.
    // Added code to write output to the console window.
    public class CalculatorService : ICalculator
    {
        public double Add(double n1, double n2)
        {
            double result = n1 + n2;
            Console.WriteLine("Received Add({0},{1})", n1, n2);
            Console.WriteLine("Return: {0}", result);
            return result;
        }

        public double Subtract(double n1, double n2)
        {
            double result = n1 - n2;
            Console.WriteLine("Received Subtract({0},{1})", n1, n2);
            Console.WriteLine("Return: {0}", result);
            return result;
        }

        public double Multiply(double n1, double n2)
        {
            double result = n1 * n2;
            Console.WriteLine("Received Multiply({0},{1})", n1, n2);
            Console.WriteLine("Return: {0}", result);
            return result;
        }

        public double Divide(double n1, double n2)
        {
            double result = n1 / n2;
            Console.WriteLine("Received Divide({0},{1})", n1, n2);
            Console.WriteLine("Return: {0}", result);
            return result;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {

            // Step 1 of the address configuration procedure: Create a URI to serve as the base address.
            Uri baseAddress = new Uri("http://localhost:8000/ServiceModelSamples/Service");

            // Step 2 of the hosting procedure: Create ServiceHost
            ServiceHost selfHost = new ServiceHost(typeof(CalculatorService), baseAddress);

            try
            {


                // Step 3 of the hosting procedure: Add a service endpoint.
                selfHost.AddServiceEndpoint(
                    typeof(ICalculator),
                    new WSHttpBinding(),
                    "CalculatorService");


                // Step 4 of the hosting procedure: Enable metadata exchange.
                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                selfHost.Description.Behaviors.Add(smb);

                // Step 5 of the hosting procedure: Start (and then stop) the service.
                selfHost.Open();
                Console.WriteLine("The service is ready.");
                Console.WriteLine("Press <ENTER> to terminate service.");
                Console.WriteLine();
                Console.ReadLine();

                // Close the ServiceHostBase to shutdown the service.
                selfHost.Close();
            }
            catch (CommunicationException ce)
            {
                Console.WriteLine("An exception occurred: {0}", ce.Message);
                selfHost.Abort();
            }

        }
    }
}

  Step: 4
How to: Create a Windows Communication Foundation Client
.NET Framework 4

This is the fourth of six tasks required to create a basic Windows Communication Foundation (WCF) service and a client that can call the service. For an overview of all six of the tasks, see the Getting Started Tutorial topic.
This topic describes how to retrieve metadata from a WCF service and use it to create a WCF proxy that can access the service. This task is completed by using the ServiceModel Metadata Utility Tool (Svcutil.exe) provided by WCF. This tool obtains the metadata from the service and generates a managed source code file for a proxy in the language you have chosen. In addition to creating the client proxy, the tool also creates the configuration file for the client that enables the client application to connect to the service at one of its endpoints. 
Note:

You can add a service reference to your client project inside Visual Studio 2010 to create the client proxy instead of using the ServiceModel Metadata Utility Tool (Svcutil.exe).
 Caution:
When calling a WCF service from a class library project in Visual Studio 2010 you can use the Add Service Reference feature to automatically generate a proxy and associated configuration file. The configuration file will not be used by the class library project. You will need to copy the configuration file to the directory that contains the executable that will call the class library.
The client application uses the generated proxy to create a WCF client object. This procedure is described in How to: Use a Windows Communication Foundation Client.
The code for the client generated by this task is provided in the example following the procedure.
To create a Windows Communication Foundation client
  1. Create a new project within the current solution for the client in Visual Studio 2010 by doing the following steps:
    1. In Solution Explorer (on the upper right) within the same solution that contains the service, right-click the current solution (not the project), and select Add, and then New Project.
    2. In the Add New Project dialog, select Visual Basic or Visual C#, and choose the Console Application template, and name it Client. Use the default Location.
    3. Click OK.
  2. Add a reference to the System.ServiceModel.dll for the project:
    1. Right-click the References folder under the Client project in the Solution Explorer and select Add Reference.
    2. Select the .NET tab and select System.ServiceModel.dll (version 4.0.0.0) from the list box and click OK.

Note:
When using a command-line compiler (for example, Csc.exe or Vbc.exe), you must also provide the path to the assemblies. By default, on a computer running Windows Vista for example, the path is: Windows\Microsoft.NET\Framework\v4.0.
  1. Add a using statement (Imports in Visual Basic) for the System.ServiceModel namespace in the generated Program.cs or Program.vb file.
using System.ServiceModel;
  1. In Visual Studio, press F5 to start the service created in the previous topic. For more information, see How to: Host and Run a Basic Windows Communication Foundation Service.
  2. Run the ServiceModel Metadata Utility Tool (Svcutil.exe) with the appropriate switches to create the client code and a configuration file by doing the following steps:
    1. On the Start menu click All Programs, and then click Visual Studio 2010. Click Visual Studio Tools and then click Visual Studio 2010 Command Prompt.
    2. Navigate to the directory where you want to place the client code. If you created the client project using the default, the directory is C:\Users\<user name>\My Documents\Visual Studio 10\Projects\Service\Client.
    3. Use the command-line tool ServiceModel Metadata Utility Tool (Svcutil.exe) with the appropriate switches to create the client code. The following example generates a code file and a configuration file for the service.

svcutil.exe /language:cs /out:generatedProxy.cs /config:app.config http://localhost:8000/ServiceModelSamples/service
By default, the client proxy code is generated in a file named after the service (in this case, for example, CalculatorService.cs or CalculatorService.vb where the extension is appropriate to the programming language: .vb for Visual Basic or .cs for C#). The /out switch changes the name of the client proxy file to GeneratedProxy.cs. The /config switch changes the name of the client configuration file from the default Output.config to App.config.  Note that both of these files get generated in the C:\Users\<user name>\My Documents\Visual Studio 10\Projects\Service\Client directory.
  1. Add the generated proxy to the client project in Visual Studio, right-click the client project in Solution Explorer and select Add and then Existing Item. Select the generatedProxy file generated in the preceding step.
Example
This example shows the client code generated by the ServiceModel Metadata Utility Tool (Svcutil.exe).


//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:2.0.50727.1366
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------



[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(Namespace="http://Microsoft.ServiceModel.Samples", ConfigurationName="ICalculator")]
public interface ICalculator
{
   
    [System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.ServiceModel.Samples/ICalculator/Add", ReplyAction="http://Microsoft.ServiceModel.Samples/ICalculator/AddResponse")]
    double Add(double n1, double n2);
   
    [System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.ServiceModel.Samples/ICalculator/Subtract", ReplyAction="http://Microsoft.ServiceModel.Samples/ICalculator/SubtractResponse")]
    double Subtract(double n1, double n2);
   
    [System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.ServiceModel.Samples/ICalculator/Multiply", ReplyAction="http://Microsoft.ServiceModel.Samples/ICalculator/MultiplyResponse")]
    double Multiply(double n1, double n2);
   
    [System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.ServiceModel.Samples/ICalculator/Divide", ReplyAction="http://Microsoft.ServiceModel.Samples/ICalculator/DivideResponse")]
    double Divide(double n1, double n2);
}

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
public interface ICalculatorChannel : ICalculator, System.ServiceModel.IClientChannel
{
}

[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
public partial class CalculatorClient : System.ServiceModel.ClientBase<ICalculator>, ICalculator
{
   
    public CalculatorClient()
    {
    }
   
    public CalculatorClient(string endpointConfigurationName) :
            base(endpointConfigurationName)
    {
    }
   
    public CalculatorClient(string endpointConfigurationName, string remoteAddress) :
            base(endpointConfigurationName, remoteAddress)
    {
    }
   
    public CalculatorClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) :
            base(endpointConfigurationName, remoteAddress)
    {
    }
   
    public CalculatorClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :
            base(binding, remoteAddress)
    {
    }
   
    public double Add(double n1, double n2)
    {
        return base.Channel.Add(n1, n2);
    }
   
    public double Subtract(double n1, double n2)
    {
        return base.Channel.Subtract(n1, n2);
    }
   
    public double Multiply(double n1, double n2)
    {
        return base.Channel.Multiply(n1, n2);
    }
   
    public double Divide(double n1, double n2)
    {
        return base.Channel.Divide(n1, n2);
    }
}




  Step: 5
How to: Configure a Basic Windows Communication Foundation Client
.NET Framework 4

This is the fifth of six tasks required to create a basic Windows Communication Foundation (WCF) service and a client that can call the service. For an overview of all six of the tasks, see the Getting Started Tutorial topic.
This topic adds the client configuration file that was generated using the ServiceModel Metadata Utility Tool (Svcutil.exe) to the client project and explains the contents of the client configuration elements. Configuring the client consists of specifying the endpoint that the client uses to access the service. An endpoint has an address, a binding and a contract, and each of these must be specified in the process of configuring the client.
The content of the configuration files generated for the client is provided in the example after the procedure.
To configure a Windows Communication Foundation client
  1. Add the App.config configuration file generated in the previous How to: Create a Windows Communication Foundation Client procedure to the client project in Visual Studio. Right-click the client project in Solution Explorer, select Add and then Existing Item. Next select the App.config configuration file from the directory from which you ran SvcUtil.exe in the previous step. (This is named the App.config file because you used the /config:app.config switch when generating this with Svcutil.exe tool.) Click OK. By default, the Add Existing Item dialog box filters out all files with a .config extension. To see these files select All Files (*.*) from the drop-down list box in the lower right corner of the Add Existing Item dialog box.
  2. Open the generated configuration file. Svcutil.exe generates values for every setting on the binding. The following example is a view of the generated configuration file. Under the <system.serviceModel> section, find the <endpoint> element. The following configuration file is a simplified version of the file generated.
3.  <?xml version="1.0" encoding="utf-8"?>
4.  <configuration>
5.    <system.serviceModel>
6.      <bindings>
7.        <wsHttpBinding>
8.          <binding name="WSHttpBinding_ICalculator">
9.          </binding>
10.      </wsHttpBinding>
11.    </bindings>
12.    <client>
13.      <endpoint
14.           address="http://localhost:8000/ServiceModelSamples/Service/CalculatorService"
15.           binding="wsHttpBinding"
16.           bindingConfiguration="WSHttpBinding_ICalculator"
17.           contract="Microsoft.ServiceModel.Samples.ICalculator"
18.           name="WSHttpBinding_ICalculator">
19.      </endpoint>
20.    </client>
21.  </system.serviceModel>
22.</configuration>
This example configures the endpoint that the client uses to access the service that is located at the following address: http://localhost:8000/ServiceModelSamples/service
The endpoint element specifies that the Microsoft.ServiceModel.Samples.ICalculator contract is used for the communication, which is configured with the system-provided WsHttpBinding. This binding specifies HTTP as the transport, interoperable security, and other configuration details.
  1. For more information about how to use the generated client with this configuration, see How to: Use a Windows Communication Foundation Client.
Example
The example shows the content of the configuration files generated for the client.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.serviceModel>
    <bindings>
      <wsHttpBinding>
        <binding name="WSHttpBinding_ICalculator"    
          closeTimeout="00:01:00"
          openTimeout="00:01:00"
          receiveTimeout="00:10:00"
          sendTimeout="00:01:00"
          bypassProxyOnLocal="false"
          transactionFlow="false" 
          hostNameComparisonMode="StrongWildcard"
          maxBufferPoolSize="524288"
          maxReceivedMessageSize="65536"
          messageEncoding="Text"
          textEncoding="utf-8"
          useDefaultWebProxy="true"
          allowCookies="false">
          <readerQuotas maxDepth="32"
            maxStringContentLength="8192"
            maxArrayLength="16384"
            maxBytesPerRead="4096"
            maxNameTableCharCount="16384" />
          <reliableSession ordered="true"
            inactivityTimeout="00:10:00"
            enabled="false" />
          <security mode="Message">
            <transport clientCredentialType="Windows"
              proxyCredentialType="None"
              realm="" />
            <message clientCredentialType="Windows"
              negotiateServiceCredential="true"
              algorithmSuite="Default"
              establishSecurityContext="true" />
           </security>
      </binding>
    </wsHttpBinding>
  </bindings>
  <client>
    <endpoint address="http://localhost:8000/ServiceModelSamples/Service/CalculatorService"
      binding="wsHttpBinding"
      bindingConfiguration="WSHttpBinding_ICalculator"
      contract="ICalculator"
      name="WSHttpBinding_ICalculator">
        <identity>
          <userPrincipalName value="user@contoso.com" />
        </identity>
      </endpoint>
    </client>
  </system.serviceModel>
</configuration>



  Step: 6


 How to: Use a Windows Communication Foundation Client
.NET Framework 4

This is the last of six tasks required to create a basic Windows Communication Foundation (WCF) service and a client that can call the service. For an overview of all six of the tasks, see the Getting Started Tutorial topic.
Once a Windows Communication Foundation (WCF) proxy has been created and configured, a client instance can be created and the client application can be compiled and used to communicate with the WCF service. This topic describes procedures for creating and using a WCF client. This procedure does three things:
  1. Creates a WCF client.
  2. Calls the service operations from the generated proxy.
  3. Closes the client once the operation call is completed.
The code discussed in the procedure is also provided in the example following the procedure. The code in this task should be placed in the Main() method of the generated Program class in the client project.
To use a Windows Communication Foundation client
  1. Create an EndpointAddress instance for the base address of the service you are going to call and then create an WCF Client object.
//Step 1: Create an endpoint address and an instance of the WCF Client.
CalculatorClient client = new CalculatorClient();

  1. Call the client operations from within the Client.
No code example is currently available or this language may not be supported.
// Step 2: Call the service operations.
// Call the Add service operation.
double value1 = 100.00D;
double value2 = 15.99D;
double result = client.Add(value1, value2);
Console.WriteLine("Add({0},{1}) = {2}", value1, value2, result);

// Call the Subtract service operation.
value1 = 145.00D;
value2 = 76.54D;
result = client.Subtract(value1, value2);
Console.WriteLine("Subtract({0},{1}) = {2}", value1, value2, result);

// Call the Multiply service operation.
value1 = 9.00D;
value2 = 81.25D;
result = client.Multiply(value1, value2);
Console.WriteLine("Multiply({0},{1}) = {2}", value1, value2, result);

// Call the Divide service operation.
value1 = 22.00D;
value2 = 7.00D;
result = client.Divide(value1, value2);
Console.WriteLine("Divide({0},{1}) = {2}", value1, value2, result);

static void Main(string[] args)
{

    // Step 1 of the address configuration procedure: Create a URI to serve as the base address.
    Uri baseAddress = new Uri("http://localhost:8000/ServiceModelSamples/Service");

    // Step 2 of the hosting procedure: Create ServiceHost
    ServiceHost selfHost = new ServiceHost(typeof(CalculatorService), baseAddress);

    try
    {
        // Step 3 of the hosting procedure: Add a service endpoint.
        selfHost.AddServiceEndpoint(
            typeof(ICalculator),
            new WSHttpBinding(),
            "CalculatorService");


        // Step 4 of the hosting procedure: Enable metadata exchange.
        ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
        smb.HttpGetEnabled = true;
        selfHost.Description.Behaviors.Add(smb);

        // Step 5 of the hosting procedure: Start (and then stop) the service.
        selfHost.Open();
        Console.WriteLine("The service is ready.");
        Console.WriteLine("Press <ENTER> to terminate service.");
        Console.WriteLine();
        Console.ReadLine();

        // Close the ServiceHostBase to shutdown the service.
        selfHost.Close();
    }
    catch (CommunicationException ce)
    {
        Console.WriteLine("An exception occurred: {0}", ce.Message);
        selfHost.Abort();
    }

}

  1. Call Close on the WCF client and wait until the user presses ENTER to terminate the application.
//Step 3: Closing the client gracefully closes the connection and cleans up resources.
client.Close();


Console.WriteLine();
Console.WriteLine("Press <ENTER> to terminate client.");
Console.ReadLine();
Example
The following example shows you how to create a WCF client, how to call the operations of the client, and how to close the client once the operation call is completed.
Compile the generated WCF client and the following code example into an executable named Client.exe. Be sure to reference System.ServiceModel when compiling the code.
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;

namespace ServiceModelSamples
{

    class Client
    {
        static void Main()
        {
            //Step 1: Create an endpoint address and an instance of the WCF Client.
            CalculatorClient client = new CalculatorClient();


            // Step 2: Call the service operations.
            // Call the Add service operation.
            double value1 = 100.00D;
            double value2 = 15.99D;
            double result = client.Add(value1, value2);
            Console.WriteLine("Add({0},{1}) = {2}", value1, value2, result);

            // Call the Subtract service operation.
            value1 = 145.00D;
            value2 = 76.54D;
            result = client.Subtract(value1, value2);
            Console.WriteLine("Subtract({0},{1}) = {2}", value1, value2, result);

            // Call the Multiply service operation.
            value1 = 9.00D;
            value2 = 81.25D;
            result = client.Multiply(value1, value2);
            Console.WriteLine("Multiply({0},{1}) = {2}", value1, value2, result);

            // Call the Divide service operation.
            value1 = 22.00D;
            value2 = 7.00D;
            result = client.Divide(value1, value2);
            Console.WriteLine("Divide({0},{1}) = {2}", value1, value2, result);

            //Step 3: Closing the client gracefully closes the connection and cleans up resources.
            client.Close();
           

            Console.WriteLine();
            Console.WriteLine("Press <ENTER> to terminate client.");
            Console.ReadLine();

        }
    }
}

Ensure the service is running before attempting to use the client. For more information, see How to: Host and Run a Basic Windows Communication Foundation Service.
To launch the client, right-click Client in the Solution Explorer and choose Debug, Start new instance.
Add(100,15.99) = 115.99
Subtract(145,76.54) = 68.46
Multiply(9,81.25) = 731.25
Divide(22,7) = 3.14285714285714
Press <ENTER> to terminate client.
If you see this output, you have successfully completed the tutorial. This sample demonstrates how to configure the WCF client in code.



Some Extra Facts about WCF:
  • Service Contract:-Service Contract is used to define the service name.
  • Operation Contract:-Operation contract defines the methods in the services.
  • Data Contract:-Data contract defines custom data types in the services
  1. Don't confuse the difference between the contract and the proxy. The contract is a sort of a way to communicate, and the proxy is a way to get access to another remote contract. The other two libraries are almost self-explaining, the WCFClient and the WCFService.
  2. In WCF terms, this is the contract that the client must obey in order to be able to communicate with the server. This contract is in fact an interface that the client(s) communicates through. The ServiceLibrary contains all the methods that can be called by the client.
  3. The DataContract has the mark [DataContract] that indicates that it's an object that can be transferred. In WCF, it does not matter if it is a simple type, like a string, or a complex type like an object that is transferred over the wire.
  4. 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.

Comments

Popular posts from this blog

A pure soul Born