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

WCF for Beginners

Rate me:
Please Sign up or sign in to vote.
4.56/5 (49 votes)
19 Sep 2008CPOL6 min read 126.8K   83   23
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)


Written By
Software Developer (Senior) Sapient Corporation
India India
Holding a MCA degree, trying to be a small part of this big IT world.

Listen to others if they correct me, I am not an expert.

Comments and Discussions

 
PraisePraise Pin
Member 1053830117-Jan-18 1:34
Member 1053830117-Jan-18 1:34 
GeneralGood Job Pin
Alireza_13621-Aug-16 13:50
Alireza_13621-Aug-16 13:50 
GeneralMy vote 5 Pin
jason.m@msn.com13-Mar-16 21:53
jason.m@msn.com13-Mar-16 21:53 
GeneralVote of 5 Pin
Beginner Luck2-Feb-16 19:04
professionalBeginner Luck2-Feb-16 19:04 
PraiseMy Vote of 5 Pin
VR Karthikeyan21-Jan-16 23:45
professionalVR Karthikeyan21-Jan-16 23:45 
Excellent article for beginners, Thank you Wink | ;)
VR Karthikeyan
Software Engineer (Senior)
Foresquare Technologies

Questiongood job Pin
Member 47447510-Nov-15 6:20
Member 47447510-Nov-15 6:20 
GeneralMy vote of 2 Pin
mohamadsafa26-Jun-14 5:13
mohamadsafa26-Jun-14 5:13 
GeneralMy vote of 5 Pin
Dileep Mada20-Mar-13 23:43
professionalDileep Mada20-Mar-13 23:43 
GeneralMy vote of 5 Pin
programmerdon23-Jan-13 8:04
programmerdon23-Jan-13 8:04 
QuestionGreat Job! Pin
programmerdon23-Jan-13 8:03
programmerdon23-Jan-13 8:03 
QuestionNice Pin
vasanthamateti6-Sep-12 22:11
vasanthamateti6-Sep-12 22:11 
QuestionGreat Pin
bala_03cvc5-Aug-12 23:39
bala_03cvc5-Aug-12 23:39 
GeneralMy vote of 5 Pin
subhadeep.a.mitra12-Jul-12 9:54
subhadeep.a.mitra12-Jul-12 9:54 
Questionmy vote of 5 Pin
.NetStars25-Apr-12 1:14
.NetStars25-Apr-12 1:14 
QuestionVery Useful Artticle to beginner... Pin
sabarimalai26-Mar-12 18:21
sabarimalai26-Mar-12 18:21 
GeneralThsnks for such a wonderful article about WCF Pin
Tinoy Jameson Malayil27-Feb-12 0:13
Tinoy Jameson Malayil27-Feb-12 0:13 
GeneralMy vote of 5 Pin
ramakrishnankt8-Jul-11 0:49
ramakrishnankt8-Jul-11 0:49 
Questionerror when running the code Pin
Rounak Hasan5-Jul-11 2:09
Rounak Hasan5-Jul-11 2:09 
AnswerRe: error when running the code Pin
Rounak Hasan5-Jul-11 2:32
Rounak Hasan5-Jul-11 2:32 
GeneralMy vote of 5 Pin
KrishnaReddy M7-Feb-11 20:46
KrishnaReddy M7-Feb-11 20:46 
GeneralMy vote of 5 Pin
yohandole20-Dec-10 16:55
yohandole20-Dec-10 16:55 
Generalthank Pin
nguyentanthuc30-Aug-10 16:26
nguyentanthuc30-Aug-10 16:26 
Generalplain simple Pin
arbel kfir3-May-09 10:27
arbel kfir3-May-09 10:27 

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.