Click here to Skip to main content
Click here to Skip to main content
Go to top

WCF for Beginners

, 19 Sep 2008
Rate this:
Please Sign up or sign in to vote.
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.

[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:

[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:

[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:

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

By:

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

Open Service.cs file and replace:

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:

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:

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:

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)

Share

About the Author

Suraj Rai
Software Developer (Senior) Sapient Corporation
India India
Holding a MCA degree, trying to be a small part of this big IT world. Started my career in the year of 2005.
 
Listen to others if they correct me, I am not an expert.

Comments and Discussions

 
GeneralMy vote of 2 Pinmembermohamadsafa26-Jun-14 5:13 
GeneralMy vote of 5 PinmemberDileep Mada20-Mar-13 23:43 
GeneralMy vote of 5 Pinmemberprogrammerdon23-Jan-13 8:04 
QuestionGreat Job! Pinmemberprogrammerdon23-Jan-13 8:03 
QuestionNice Pinmembervasanthamateti6-Sep-12 22:11 
QuestionGreat Pinmemberbala_03cvc5-Aug-12 23:39 
GeneralMy vote of 5 Pingroupwidestination12-Jul-12 9:54 
Questionmy vote of 5 Pinmember.NetStars25-Apr-12 1:14 
QuestionVery Useful Artticle to beginner... Pinmembersabarimalai26-Mar-12 18:21 
GeneralThsnks for such a wonderful article about WCF PinmemberJameson M Tinoy27-Feb-12 0:13 
GeneralMy vote of 5 Pinmemberramakrishnankt8-Jul-11 0:49 
Questionerror when running the code Pinmemberhasan.rounak5-Jul-11 2:09 
It is first article I read about WCF.It has helped me a lot.Thanks..I have done the same described here.The WCF service is running fine.But when I am running the whole solution it is showing "The remote server returned an unexpected response: (407) Proxy Authentication Required."Can you pls help me what type of error is this.
AnswerRe: error when running the code Pinmemberhasan.rounak5-Jul-11 2:32 
GeneralMy vote of 5 PinmemberMember 37916757-Feb-11 20:46 
GeneralMy vote of 5 Pinmemberyohandole20-Dec-10 16:55 
Generalthank Pinmembernguyentanthuc30-Aug-10 16:26 
Generalplain simple Pinmemberarbel kfir3-May-09 10:27 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140916.1 | Last Updated 19 Sep 2008
Article Copyright 2008 by Suraj Rai
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid