Skip to main content

A basic WCF Service

The Windows Communication Foundation (WCF) service enables to manage the interoperability of the distributed applications and also supports the service oriented architecture. In this post I will illustrate the various steps required for creating, implementing and hosting of WCF. And also learn about creating the WCF client, its configuration and consuming the WCF service in an application. Let's understand the steps involved in Creating and Running a WCF service.

The Microsoft Visual Studio also contains pre-built template for creating the WCF service that can be created and implemented by following few wizard steps. Here we will use a C# class to create the WCF service, then will create a client application to consume the methods exposed by the WCF service. Following are the steps that we will cover to create a working WCF service:

  1. Defining Service Contract in WCF: the first step to create a WCF service contract using a C# interface that will outline the functionality offered by the service.
  2. Implementing Service Contract in WCF: the second step to implement the methods described in the interface created in the previous step.
  3. Hosting and Running a Basic WCF Service: the third step to host the service inside the application by providing an endpoint in C# code.
  4. Creating a WCF Client: the fourth step to retrieve the service metadata using Service Model Metadata Utility Tool provided by WCF. It enables to create a WCF client in relation to the underlying WCF service.
  5. Configuring a WCF Client: the fifth step to configure the WCF client by specifying the endpoint of the WCF service to access it.
  6. Using a WCF Client: the last step to invoke the functionality exposed by the WCF service and consuming it in the WCF client application.

Defining Service Contract in WCF

In this first step we will start with defining the Service contract in WCF. The WCF service contract involves the code for defining an outline of the service by creating a user defined interface. The interface includes all the methods and functionality that the underlying WCF service will expose to its corresponding client application.
The methods defined in the interfaces created for WCF service outlines its expected functionality. When an interface is created it must have the ServiceContractAttribute applied to it. The ServiceContractAttribute indicates that the interface or class is defined as a service contract in application. Each method defined inside the interfaces must have the OperationContractAttribute applied to it. The OperationCtractAtttribute indicates that the method is defined as a part of service contract in the application.

Creating WCF Service Contract with an Interface

1. Open the Microsoft Visual C# 2010 Express and select a new Console Application template from under the File menu -> New Project option.
2. In the Name box enter WCFService as application name and press ok to create an empty console application.
3. After creating the console application, it will show the Program.cs file by default containing the following Main method code:
namespace WCFService
{
    class Program
    {
        static void Main(string[] args)
        {


        }

    }
}
4. Next add a new interface to the application by right-clicking on the project in solution explorer and choosing New Item under the Add menu option. Specify IArea as interface name.
5. Add a reference to System.ServiceModel.dll by right-clicking the project in solution explorer and choosing Add Reference option.
6. In the Add Reference dialog box choose the System.ServiceModel and click ok to add its reference in to the application.
7. Include the System.ServiceModel namespace at the top of the IArea interface that we created earlier:
using System.ServiceModel;
8. Define the service contract and methods for the IArea interface as shown in the following code:
namespace WCFService
{
    [ServiceContract(Namespace = "http://WCFService")]
    public interface IArea
    {
        [OperationContract]
        double AreaOfRectangle(double length, double width);


        [OperationContract]

        double AreaOfCircle(double radius);
    }
}

Implementing Service Contract in WCF

1. Create a new class with name AreaService by right-clicking on the project in the solution explorer by choosing New Item from the Add menu.
2. Next implement the IArea interface to the class:
public class AreaService : IArea
3. Implement each method defined in the IArea interace within the AreaService class:
namespace WCFService
{
    public class AreaService : IArea
    {
        public double AreaOfRectangle(double length, double width)
        {
            double area = length * width;
            Console.WriteLine("length: {0}; width: {1}", length, width);
            Console.WriteLine("Area: {0}", area);
            return area;
        }


        public double AreaOfCircle(double radius)

        {
            double area = Math.PI * radius;
            Console.WriteLine("radius: {0}", radius);
            Console.WriteLine("Area: {0}", area);
            return area;
        }
    }
}
Now we are finished with creation of service contract and its implementation steps.

Hosting and Running a Basic WCF Service

The code for hosting and running a WCF service enables to run the service that can be consumed by the WCF client application. This third step involves a sequence of programming commands which enable to run a basic Windows Communication Foundation service. It consists of the following steps to self-host and run a service:
1. creating a base address for the service.
2. creating an instance for self-hosting the service.
3. enabling the metadata behavior
4. opening the service host
Self-Hosting and Running a WCF Service
1. Specify a base address for the WCF service using Uri class instance. The following Uri will open the port number 5000 to expose the service instance:
Uri serviceBaseAddress = new Uri("http://localhost:5000/WCFService/Sample");
2. Next create the ServiceHost instance for self-hosting the WCF service over the specified base address:
ServiceHost selfServiceHost = new ServiceHost(typeof(AreaService), serviceBaseAddress);
3. Then add a service endpoint that enables to expose the service:
selfServiceHost.AddServiceEndpoint(typeof(IArea), new WSDualHttpBinding(), "AreaService");
4. To enable the metadata information exchange functionality of a WCF service, you must import the System.ServiceModel.Description namespace at the top of the program.cs file:
using System.ServiceModel.Description;
5. You can use the following C# code inside the Main method of program.cs file to run the basic WCF service.
static void Main(string[] args)
{
    // creating base address for self-hosting the WCF service
    Uri serviceBaseAddress = new Uri("http://localhost:5000/WCFService/Sample");


    // creating an instance for self-hosting

    ServiceHost selfServiceHost = new ServiceHost(typeof(AreaService), serviceBaseAddress);


    try

    {
        // adding a service endpoint
        selfServiceHost.AddServiceEndpoint(typeof(IArea), new WSDualHttpBinding(), "AreaService");


        // enabling metadata behavior of service

        ServiceMetadataBehavior serviceMetadataBehavior = new ServiceMetadataBehavior();
        serviceMetadataBehavior.HttpGetEnabled = true;
        selfServiceHost.Description.Behaviors.Add(serviceMetadataBehavior);


        // starting the WCF service instance

        selfServiceHost.Open();
        Console.WriteLine("The service is running now.");
        Console.WriteLine("Press any key to stop the service...");
        Console.WriteLine();
        Console.ReadLine();
        // stopping the WCF service instance
        selfServiceHost.Close();
    }
    catch(CommunicationException ex)
    {
        // abort the service in case any error occurs
        Console.WriteLine("An exception occurred: {0}", ex.Message);
        selfServiceHost.Abort();
    }
}
6. Press F5 to compile and run the service and try to browse the base address URL in the Internet Explorer. If it shows the web service information without any error, it means you have created a service successfully.

Creating a WCF Client

The fourth step involves creating the Windows Communication Foundation (WCF) client. It can be created using a Service Model Metadata Utility Tool (svcutil.exe) that can be found inside the Visual Studio SDK. This utility tool enables to extract the metadata associated to the WCF service and auto-generates a managed code for WCF service proxy in the specified programming language. It also generates a configuration file containing the information about WsDualHttpBinding and service endpoints which enable the client to communicate with the WCF Service.

Steps to Create a WCF Client

1. Add a new Console Application into the same WCFService solution by selecting its template from under the File menu -> New Project option.
2. In the Name box enter WCFService_Client as application name and press ok to create an empty console application.
3. After creating the console application, it will show the Program.cs file by default containing the following Main method code:
namespace WCFService_Client
{
    class Program
    {
        static void Main(string[] args)
        {


        }

    }
}
4. Add a reference to System.ServiceModel.dll by right-clicking the project in solution explorer and choosing Add Reference option. 
5. Now before proceeding further we need to create a proxy class using Service Model Utility Tool. Locate the tool inside the Microsoft SDK under the following path:
For x64 windows:
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin
For x86 windows:
C:\Program Files\Microsoft SDKs\Windows\v7.0A\Bin
First run the WCFService application to self-host and run the created WCF service then open the command prompt and change directory to the above specified path and run the following command to generate the managed source code in C#:
svcutil.exe /language:cs /out:wcfServiceProxy.cs /config:app.config http://localhost:5000/WCFService/Sample
After executing the above comment it will generate two output files inside the located tool path in the command prompt where the svcutil.exe exists. It will generate wcfServiceProxy.cs and app.config file there. The Service Model Metadata Utility Tool will generate the following code in wcfServiceProxy.cs file:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:2.0.50727.4952
//
//     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://WCFService", ConfigurationName="IArea")]
public interface IArea
{
    
    [System.ServiceModel.OperationContractAttribute(Action="http://WCFService/IArea/AreaOfRectangle", ReplyAction="http://WCFService/IArea/AreaOfRectangleResponse")]
    double AreaOfRectangle(double length, double width);
    
    [System.ServiceModel.OperationContractAttribute(Action="http://WCFService/IArea/AreaOfCircle", ReplyAction="http://WCFService/IArea/AreaOfCircleResponse")]
    double AreaOfCircle(double radius);
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
public interface IAreaChannel : IArea, System.ServiceModel.IClientChannel
{
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
public partial class AreaClient : System.ServiceModel.ClientBase<IArea>, IArea
{
    
    public AreaClient()
    {
    }
    
    public AreaClient(string endpointConfigurationName) : 
            base(endpointConfigurationName)
    {
    }
    
    public AreaClient(string endpointConfigurationName, string remoteAddress) : 
            base(endpointConfigurationName, remoteAddress)
    {
    }
    
    public AreaClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : 
            base(endpointConfigurationName, remoteAddress)
    {
    }
    
    public AreaClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : 
            base(binding, remoteAddress)
    {
    }
    
    public double AreaOfRectangle(double length, double width)
    {
        return base.Channel.AreaOfRectangle(length, width);
    }
    
    public double AreaOfCircle(double radius)
    {
        return base.Channel.AreaOfCircle(radius);
    }
}

Configuring a WCF Client

The WCF service can be consumed in a WCF Client application only if its endpoint configured properly. In the previous tutorial: Creating a WCF Client we used the Service Model Metadata Utility Tool (svcutil.exe) to generate a proxy class and a configuration file. The configuration step for WCF client consists of specifying the endpoints to enable the client application to access the WCF service. An endpoint configuration contains the base address, binding such as WsDualHttpBinding, and service contract.
Steps to Configure a WCF Client
1. For adding the auto-generated proxy class i.e. wcfServiceProxy.cs that we created in the previous tutorial, right click on the project in the solution explorer and click the Existing Item option from the Add menu. Then browse and select the wcfServiceProxy.cs class file from the Add Existing Item dialog box. Click the Add button to include the managed source code class file into the WCFService_Client application.
2. Repeat the above step to add the existing app.config file, generated using svcutil.exe tool, into the client application. The app.config file includes the endpoint required for accessing the WCF service. Following is the app.config file code auto-generated by Service Model Metadata Utility tool:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.serviceModel>
        <bindings>
            <wsDualHttpBinding>
                <binding name="WSDualHttpBinding_IArea" 
                         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">
                    <readerQuotas maxDepth="32" 
                                  maxStringContentLength="8192" 
                                  maxArrayLength="16384"
                                  maxBytesPerRead="4096" 
                                  maxNameTableCharCount="16384" />
                  
                    <reliableSession ordered="true" 
                                     inactivityTimeout="00:10:00" />
                    <security mode="Message">
                        <message clientCredentialType="Windows" 
                                 negotiateServiceCredential="true"
                                 algorithmSuite="Default" />
                    </security>
                </binding>
            </wsDualHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost:5000/WCFService/Sample/AreaService"
                      binding="wsDualHttpBinding" 
                      bindingConfiguration="WSDualHttpBinding_IArea"
                      contract="IArea" 
                      name="WSDualHttpBinding_IArea">
                <identity>
                    <userPrincipalName value="Rayat-PC\Rayat" />
                </identity>
            </endpoint>
        </client>
    </system.serviceModel>
</configuration>
Now the WCF client application is ready to access the WCF service.

Using a WCF Client

Now our client application is ready to access the WCF client and consume the service contracts. The Windows Communication Foundation (WCF) proxy class included inside the client application it enables to initialize the client instance that further allows consuming the service contracts exposed by the WCF service.
The code required for using a WCF client must be placed inside the Main() method of program.cs class file of the client application.
C# Code to Use WCF Client
1. It is an optional step to specify the endpoint programmatically, but if required anywhere then you can use the following code to specify the endpoint address using C# code:
// specify the same endpoint address that we got in the generated app.config file
EndpointAddress endPointAddress = new EndpointAddress("http://localhost:5000/WCFService/Sample/AreaService");
2. For providing the endpoint address explicitly, you can use the following code to initialize an instance of WCF client:
// initialize an instance of WCF client
AreaClient areaclient = new AreaClient(new WSDualHttpBinding(), endPointAddress);
  
3. You can call the client operations by the following way:
double length = 85.5;
double width = 35.5;


Console.WriteLine(areaclient.AreaOfRectangle(length, width));

4. Alternatively you can also use the following code to access and use a WCF Client that requires no endpoint specification explicitly:
static void Main(string[] args)
{
    // initialize an instance of WCF client
    AreaClient areaclient = new AreaClient();


    double length = 85.5;

    double width = 35.5;


    Console.WriteLine(areaclient.AreaOfRectangle(length, width));

}
For running the WCF client, ensure that the WCF service instance is already running. Otherwise run the WCF service instance and then run the WCF client instance to execute the specified client operation.
You can get further information from my article hosted at Scribd

Comments

Anonymous said…
Seems useful for a novice in SOA. Nice article.
Vini said…
Can u also give any reference about developing a chat service using both WPF and WCF?
Ravi said…
My next topic is about sharable services like Chatting and Confrencing. For this u must be familiar with .net Remoting and Interop services. Will get back to u soon...

Popular posts from this blog

TAPI : A gateway to VOiP in .net

As I have promised earlier, here I'm going to present the VOiP enhancements in .net framework. To implement Voice and Video services you need to incorporate TAPI dll in your application. TAPI is Telephony Application Programming Interface and in this post I am quoting TAPI v3.0. Here is a C# program which will exemplify the procedure which needs to be followed while doing TAPI programming using TAPI 3.0. The program shows you how you can use the TAPI 3.0 functions to create a TAPI application of your own. Microsoft provides more than 100 functions as part of the TAPI library. TAPI 2.1 was more difficult to use as it was a set of API functions but TAPI 3.0 which comes as part of Windows 2000 has ActiveX controls that make the TAPI application creation much easier. The TAPI SDK that can be downloaded from the Microsoft site. Learning to use different TAPI functions require lot of time investment but once you create some applications using these TAPI functions, it becomes easier for

Welcome Note

Hi Guest, This may seem to be just another blog but my endeavors are to make this blog useful for programmers and developers...to share the ideas...to exchange the technology enhancements...and also to solve critical issues related to SOA, WEB 2.0, Enterprise Apps Programming, Distributed Apps, Cross Platform Developments, VOiP Applications, and anything you can code on.... I hope that your visit will be useful for US :) /* HAPPY CODING */