Click here to Skip to main content
15,867,488 members
Articles / Programming Languages / C#

Windows Communcation Foundation - Simple Example, Step by Step

Rate me:
Please Sign up or sign in to vote.
4.61/5 (18 votes)
20 Feb 2009CPOL4 min read 65.4K   1.2K   51   12
This article demostrates a very basic example, can say simplest, of client/server design using Windows Communication Foundation(WCF)

Introduction

Windows Communication Foundation (WCF) is an integral part of .NET Framework 3.*. It enhances the productivity of developers to build distributed applications and services. The best part of WCF is that the underlying mechanism and service functionality are loosely coupled and so a single service can be configured to use via different protocols or mechanisms. WCF unifies earlier technologies such as WSE, Remoting, ASMX and MSMQ etc. Thus a developer does not need to go for different technologies but instead just use one programming model.

This article demostrates a very basic example, or rather simplest, client/server design using Windows Communication Foundation(WCF). First we will discuss how to make a WCF service from scratch and host it in an application, then we will create a client (consumer) which calls service methods. So let’s begin.

Pre-Requisites

The first thing you need is .NET framework 3.*, 3.5 SP1 in particular which you can download from Microsoft Download Center. Okay, the next thing is IDE. If you don’t have Visual Studio, there are express edition(s) available that are free to download and use. In particular, I’ve just downloaded Visual C# 2008 Express Edition which seems cool.

vcsharpIDE.JPG

Get Set Go!

Service (Server Side)

First of all we need to create a Service and for that I’m going to create a new project i.e. Class Library with the name RegistrationService as shown below. We are not using a WCF Service template which is available in Visual Studio 2008 and so we can see the assemblies required for a WCF project and move on from scratch.

projectType.PNG

Now we need to add a reference, System.ServiceModel, which is the main DLL required for WCF.

reference.JPG

Next we need to create a contract of Service. For now, consider contract as an interface of the service that will be exposed. The interface needs to have some required attributes on it as shown below:

[ServiceContract(Namespace="http://adil.com/RegistrationService/2009")]
public interface IRegistrationService
{
    [OperationContract]
    string RegisterName(string name);
}

Notice that the interface has ServiceContractAttribute which is mandatory and indicates that an interface defines a service contract in a WCF application. The namespace parameter is optional and is used to define a unique namespace to the service and by default its set to http://tempuri.org. Also notice that OperationContractAttribute is marked on the method(s) needed to be exposed to the client. The ServiceContractAttribute can be applied on the class as well but it's better to have a separate interface as contract.

Next we are going to add a class with the name RegistrationService.cs which will implement this interface.

public class  RegistrationService: IRegistrationService
{
    public string RegisterName(string name)
    {
        return string.Format("Registered Name : " + name);
    }
}

All right, till this point our service is ready. We have a contract to be exposed and we have a class implementing that contract. Now we need to have a Host Application (Executable). Every service needs to be hosted either on IIS or WinApp or Window Service etc. So, for this example, we will create a Console Application to Host our Registration Service.

serviceHost.JPG

Also you need to add a System.ServiceModel reference to this host (executable) application as well. The Host application needs to define the ABC of WCF which is

  • A-> Address (Address where service will be hosted)
  • B-> Binding (For now, take it as underlying protocol like HTTP, TCP etc)
  • C-> Contract (The interface of the service)

We will create a class Host for hosting this RegistrationService.

public class Host
{
    ServiceHost host;
    public void StartService()
    {
        try

        {
            host = new ServiceHost(typeof(RegistrationService));
            host.AddServiceEndpoint(typeof(IRegistrationService),
                new BasicHttpBinding(),
                "http://localhost:8000/RegistrationService");
            host.Open();
            Console.WriteLine("Service Started Successfully");
            Console.ReadLine();
        }
        catch (System.Exception exception)
        {
            Console.WriteLine("Unable to start service \n " + exception.Message);
        }
    }
    public void StopService()
    {
        if (host != null)
            host.Close();
    }
}

Notice that the line

host.AddServiceEndpoint(typeof(IRegistrationService),
    new BasicHttpBinding(),
    "http://localhost:8000/RegistrationService");

Basically adds an Endpoint where service will be hosted defining the type of contract i.e. IRegistrationService, the underlying protocal i.e. BasicHttpBinding and the Address. Let’s hit F5 and run it.

serviceStarted.JPG

That is all for the service.

Client

The client needs to have proxy of the service, in general, ABC of the service. For proxy we will copy the contract of the service at the client side and create proxy using ChannelFactory class of WCF. Further the type of contract, Binding and Endpoint Address is passed to ChannelFactory constructor. Consider the code snippet below:

[ServiceContract(Namespace = "http://adil.com/RegistrationService/2009")]
public interface IRegistrationService
{
    [OperationContract]
    string RegisterName(string name);
}

class Program
{
    static void Main(string[] args)
    {
        IRegistrationService proxy = ChannelFactory<IRegistrationService>.CreateChannel
            (new BasicHttpBinding(), new EndpointAddress(
                "http://localhost:8000/RegistrationService"));
        Console.WriteLine("\nCalling Service...\n");
        Console.WriteLine(proxy.RegisterName("Adil"));

        Console.ReadLine();

    }
}

That’s it. Let's hit F5,

callingRegService.JPG

Conclusion

We have just created a simple client/server application using WCF. Please note that this is very simple example in which both client and server know the address, contract and binding. In real scenario, the service information is exposed to client using WSDL (Web Services description Language).

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Australia Australia
Adil is an aspiring software craftsman. He is currently working as Senior Developer at Nintex and has extensive experience on designing and developing enterprise scale applications on Microsoft .NET Framework. Lately he is into cross platform mobile app development on Windows, Android and iOS.
Besides, day to day job, he is active in offline and online technical communities and often participates as speaker in technical events.
He blogs about his experience at http://www.AdilMughal.com

Comments and Discussions

 
QuestionSimple and useful Pin
Member 889629229-May-12 23:20
Member 889629229-May-12 23:20 
GeneralMy vote of 5 Pin
Jeffrey Schaefer23-Nov-11 18:59
Jeffrey Schaefer23-Nov-11 18:59 
Generalgreat jump start!!!! Pin
Arin Tahmasian1-Sep-10 15:08
Arin Tahmasian1-Sep-10 15:08 
QuestionNeed help Pin
riyo6-Jun-10 15:57
riyo6-Jun-10 15:57 
GeneralYou got my 5, but a suggestion Pin
jackmos4-Mar-09 2:16
professionaljackmos4-Mar-09 2:16 
Great intro. I'd suggest adding something about hosting the server on IIS. Many people develop clients that talk to servers hosted by ISP's.

You got my 5.
GeneralRe: You got my 5, but a suggestion Pin
Adil Mughal4-Mar-09 2:30
Adil Mughal4-Mar-09 2:30 
GeneralI agree with both Pin
John Whitmire24-Feb-09 11:57
professionalJohn Whitmire24-Feb-09 11:57 
GeneralRe: I agree with both Pin
Adil Mughal24-Feb-09 18:33
Adil Mughal24-Feb-09 18:33 
GeneralMy vote of 1 Pin
Pablo Barrientos24-Feb-09 0:38
Pablo Barrientos24-Feb-09 0:38 
GeneralRe: My vote of 1 Pin
Adil Mughal24-Feb-09 18:06
Adil Mughal24-Feb-09 18:06 
GeneralThank you Pin
wmolina20-Feb-09 13:36
wmolina20-Feb-09 13:36 
GeneralRe: Thank you Pin
Adil Mughal20-Feb-09 20:13
Adil Mughal20-Feb-09 20:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.