Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

WCF for Beginners

4.56/5 (49 votes)
19 Sep 2008CPOL6 min read 1  
Basics of Windows Communication Foundation (WCF)

Introduction

My articles are only for beginners, this is not an exception. This article covers the very basics of Windows Communication Foundation (WCF) along with a basic implementation of a service with IIS host. Let’s have a small discussion on WCF, what WCF is and some of the common elements of WCF.

Windows Communication Foundation

We have seen or heard a number of communication technologies that .NET work on. Prior to the .NET 3.0, we were faced with 5 primary approaches to communicating remotely between applications. Each of these had value (hence their existence within the same framework) because each targeted a different set of problems. However, each functioned differently, having different programming models, hosting structures and configuration implementations. Targeting these various platforms required a varied knowledge base. In other words to work on all these communication technologies, a person had to know all the technologies which are quite different from each other.

Windows Communication Foundation (WCF) is a unified, simplified and optimized evolution of a number of communication technologies into a single model.

Most of the WCF functionalities are included in a single assembly called System.ServiceModel.dll in the System.ServiceModel namespace.

WCF’s Execution Boundaries

With WCF, the client never interacts with the service directly, even when dealing with a local, in-memory service. Instead, the client always uses a proxy to forward the call to the service. The proxy exposes the same operations as the service.

ABC (Address, Binding, Contract) of WCF

To do anything with WCF, we need ABC. Hence, let me explain it a bit as per my understanding.

Address

Address signifies “Where the service is?”

The address provides two important elements: the location of the service and the transport protocol used to communicate with the service.

The location portion of the address indicates the name of the target machine, site, or network; a communication port, pipe, or queue; and an optional specific path or URI.

And it supports the following transport protocol:

  • HTTP
  • TCP
  • Peer network
  • IPC (inter process communication over named pipes)
  • MSMQ

How the WCF Address Looks Like ?

It looks like this: http://localhost:8001/MyServicenet.msmq://localhost/private/MyService.

Binding

Binding specifies, “How do I talk to the service? how a service is accessible?”

WCF defines nine standard bindings. To name a few:

  1. Basic binding: This is designed to expose a WCF service as a legacy ASMX web service, so that old clients can work with new services.When used by the client, this binding enables new WCF clients to work with old ASMX services.
  2. TCP binding: This uses TCP for cross-machine communication on the intranet. It supports a variety of features, including reliability, transactions, and security, and is optimized for WCF-to-WCF communication. As a result, it requires both the client and the service to use WCF.

Other bindings are IPC, Peer network binding, Web Service binding, Duplex WS binding, MSMQ binding etc.

Contract

In WCF, all services expose contracts. The contract is a platform-neutral and standard way of describing what the service does. WCF defines four types of contracts.

  • Service contracts: Describe which operations the client can perform on the service.
  • Data contracts: Define which data types are passed to and from the service. WCF defines implicit contracts for built-in types such as int and string, but you can easily define explicit opt-in data contracts for custom types.
  • Fault contracts: Define which errors are raised by the service, and how the service handles and propagates errors to its clients.
  • Message contracts: Allow the service to interact directly with messages.

Namespaces and Names

The contract namespace serves the same purpose in WCF as it does in .NET programming: to scope a type of contract and reduce the overall chance for a collision.

C#
[ServiceContract( Namespace = "http://www.MyCompany.com/" )]

By default, the exposed name of the contract will be the name of the interface used. However, you could use an alias for a contract to expose a different name to the clients in the metadata using the Name property of the ServiceContract attribute:

C#
[ServiceContract(Name = "IMyContract")]
interface IMyOtherContract

In a similar manner, the name of the publicly exposed operation defaults to the method name, but you can use the Name property of the OperationContract attribute to alias it to a different publicly exposed name:

C#
[ServiceContract]
interface IMyContract
{
[OperationContract(Name = "SomeOperation")]
void MyMethod(string text);
}

Hosting

Hosting environments make it possible to expose your services to client applications. They facilitate request processing to service operations, but they can also play a critical role in the availability and scalability of your services.

Windows Communication Foundation (WCF) Services can be hosted with Internet Information Services (IIS); with the new Windows Activation Service (WAS) installed with IIS 7.0; or with any managed application process including console, Windows Forms, Windows Presentation Foundation (WPF), or managed Windows service applications. Selecting the right hosting environment for your services is a choice driven largely by deployment requirements related to transport protocol and operating platform.

Today, I will show a small program, just for the very beginner using IIS hosting. Hopefully, in my next article, I will show all the other types of hosting in a very simpler way.

Hope you have VS 2008 or have installed Visual Studio 2005 extensions for .NET Framework 3.0.

A basic application which shows IIS hosting, here we will be creating a service having methods Add and Substract and consume it through an ASP.NET client.

I have used default file names for easy reference.

A Basic WCF Service

SERVICE

File > New > Website > WCF service

See in the right side you have one Service.svc file and also check your App_Code folder where you will be having two files.

  1. IService.cs: This is your contract.
  2. Service.cs: This is the service which will implement IService contract.

Open IService.cs and replace:

C#
[ServiceContract]
public interface IService
{
    [OperationContract]
    string GetData(int value);
    
[OperationContract]
    CompositeType GetDataUsingDataContract(CompositeType composite);
}

By:

C#
[ServiceContract]
public interface IService
{
    [OperationContract]
    double Add(double a, double b);
    
[OperationContract]
    double Substract(double a, double b);
}

Open Service.cs file and replace:

C#
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
{
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
    
if (composite.BoolValue)
    {
       composite.StringValue += "Suffix";
    }
     return composite;
}

By:

C#
public double Add(double a, double b)
{
     return a + b;
}
public double Substract(double a, double b)
{
     return a - b;
}

Check your web.config file whether this line is present or not:

C#
endpoint address="" binding="wsHttpBinding" contract="IService"
  • Address: will be your localhost
  • Binding: This service uses wsHttpBinding binding.
  • Contract: Remember? It's your Contract name which is in IService.cs file.

Now set Service.svc as start page and run the project. If the code is fine, then the project should execute fine.

Copy the URL and keep it somewhere. The URL will be something like this: http://localhost:34935/WCFtest2/Service.svc.

Now we have to create a client for it which will consume this service.

CLIENT

Right click Solution > add > new project > ASP.NET web application.

Now right click your web application and click "Add Service Reference". Paste the service URL which you have copied in the address text box. If not copied, run the project having service.svc file again and copy it.

And click "OK". The service will be added to your project with a name "ServiceReference1" if you have not changed the name.

Now go to the Code behind of your *.aspx page and in page_load event, write this:

C#
ServiceReference1.ServiceClient obj = new ServiceReference1.ServiceClient();
double a = obj.Add(2.5,2.5);
Response.Write(a.ToString());

Set your web application as start project and run the application. It will give you the output as 5.

Points of Interest

It is just a basic representation of WCF service which works just like a web service. Don't stop here. Hopefully, my next article will contain all the different types of hosting we can do in WCF.

Happy coding !!!

License

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