Professional Documents
Culture Documents
CPOL
This article tries to dig in as to what is WCF, how to code WCF services
Introduction
Well, a month ago i wrote an article on ASP.NET Web Services, which can be found here
http://www.codeproject.com/Articles/524983/Web-Services-From-a-beginners-perspective, I received a
comment that .ASMX Web Services are seldom used now, which is pretty correct to an extent. Hence, I have
decided to pen down an article covering WCF, how to code WCF services and stuffs.
Let's start with the article without much delay.
Well, WCF stands for Windows Communication Foundation, it was first shipped with .NET 3.0 framework
along with WPF, Windows CardSpace and WorkFlow Foundation.
From a beginner's perspective, what does actually WCF mean? Let's break the abbreviation into single
entities and try to debug. It consists of 3 words, a)Windows b)Communication c)Foundation.
A beginner would glance at the words and would think, well it is something which deals with Windows
platform, which is used to communicate and connect applications. Hmm, well he/she ain't wrong on the first
strike...
A definition which comes to mind may be summed up as: WCF is a kind of technology, which is used to
develop and deploy services on Windows platform. Different books have different set of words to describe
WCF, but the gist is almost the same which points to development and deployment of services on Windows
Platform.
MSDN says, WCF is a framework to build service-oriented applications. So basically WCF revolves around
developing applications which are greatly dependent upon services.
1/26
4/17/2015
communication between a client and a server, they had their pros and cons. For instance:
.ASMX Web Services allowed stuffs to be accessed from any platform.
MSMQ allowed queuing of messages, so that communication between a client and server is possible
even when the server was disconnected.
.NET Remoting service allowed transfer of data between a client and server on Windows OS.
So if a developer had to develop an architecture having all the above functionalities, he had to learn the
above technologies, which was a cumbersome task. Hence WCF was introduced by Microsoft to overcome
these shortcomings. Basically WCF unified the above technologies into a single programming model for the
ease of developing service oriented architecture.
I hope that the readers have got an initial understanding of WCF by now, let's move on.
WCF Architecture
Below is the image of WCF Architecture (courtesy: Google Images) :
WCF has a multi-layered architecture namely Contracts layer, Service Runtime Layer, Messaging
Layer and Activation and Hosting Layer. I'll try to explain major architectural stuffs in a simple language.
Contracts Layer
In a layman's terms, a contract may be seen as a kind of agreement between 2 or more parties, over some
goods or services. The contract will define what kind of services need to be offered, how they need to be
offered, details about the place etc. Similar is the case with WCF Contracts Layer. It's an agreement
between 2 machines defining the terms and conditions for the messages to be exchanged. Let's
have a look at the individual items of the Contracts Layer.
Data Contract: Agreement between a service and a client on the data that has to be exchanged.
Also defines what data structures and parameters to be used by services in order to interact with the
http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print
2/26
4/17/2015
client.
Message Contract: Provides control over the SOAP messages that are produced and consumed by
WCF. It also provides direct access to message header & body to alter the SOAP message as per
the requirement.Usually developers don't pay much heed to message contracts in normal scenarios,
but there arises a need for message contracts and their use when interoperability is important or
security needs to be maintained at the message level.
Service Contract: Defines the kind of operations supported by the service. It also exposes certain
information to the client such as:
1.
2.
3.
4.
3/26
4/17/2015
Windows Activation Services: Enables WCF applications to automatically activate, when deployed
on a system running WAS.
.EXE: WCF services can also be run as executable files.
Windows Services: WCF services can also be run as Windows services.
COM+: WCF services can also be run as COM+ app.
After a discussion about the architecture, let's move on to the features of WCF, which is an important
domain as well.
Features of WCF
Features of WCF can be described as follows:
Endpoint Support
Improved Transport Layer
Queuing Support
Improved Transactional process
Improved Security
Hosting Support on various environments
AJAX Integration and JSON Support
Let's start with a brief discussion about each of them
Endpoint Support: An endpoint is basically a resource or an entity in the network to which messages can
be sent. Endpoints are responsible for the communication between a client and the service. Elements of
endpoints are:
Addresses to locate the service
Bindings to communicate with the service
Contracts to specify the functionalities to be performed while communicating with the service.
Endpoint behaviors to specify the runtime behavior of the service endpoint.
These Addresses, Bindings and Contracts are normally referred to as ABC's of WCF.
Let's discuss a bit about these ABC's.
Addresses: In order to send a message to a service, you would need its address. An address in WCF
would consist of the following items:
Scheme: Basically the transport protocol used.
Machine: Full Domain Name of the machine.
Port: Defines the port number where the service is running.
Path: Path of the service.
Example can be written as:
scheme://domain_name:port/path
http://localhost:8080/services/MyFirstService
In the above example, a service is locally hosted with HTTP being the transport protocol and 8080 being the
port used, path being services/MyFirstService.
Bindings: Facilitate the communication between the client and the service. Specify the communication
protocol used to access the service. Below is the list of pre-defined binding elements:
basicHttpBinding
wsHttpBinding
wsDualHttpBinding
http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print
4/26
4/17/2015
wsFederationHttpBinding
netTcpBinding
netNamedPipeBinding
netMsmqBinding
msmqIntegrationBinding
netPeerTcpBinding
Well I would discuss a little about one of the bindings and details on the use and implementation of others
can be searched easily on MSDN and even on CP...
basicHttpBinding: This type of binding is used by the WCF services to configure and expose those
end points that are able to communicate with .ASMX Web Services and clients. Transport protocol used is
HTTP, while message encoder used is Text/XML. Security is disabled by default in this, to enable the
security BasicHttpSecurityModeneeds to be configured. Have a look at the below code on how to
configure the host of the basicHttpBinding.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<services>
<service name="MyFirstService">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8080/MyFirstservice"/>
</baseAddresses>
</host>
<endpoint address="" binding="basicHttpBinding" contract="MyFirstService">
</endpoint>
</service>
</services>
</system.serviceModel>
</configuration>
5/26
4/17/2015
between AJAX enabled services and their clients. Let's start with the coding part now.
Background
There ain't any pre-requisites as such, just the presence of Visual Studio 2008 client is enough.
2. Create a new Blank Solution to start with.We will add projects later in the next step.
Give the name of the solution as MyFirstServiceSolution and the location where you want to store the
codes.
3. A solution will be created by VS, then right-click the solution explorer Add> New project.
http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print
6/26
4/17/2015
4. After clicking on Add>New project, a dialog box will open with few options. Select WCF service
library, provide the name as MyServiceLibrary, location as desired and click on OK.
5. A new WCF service library will be added to the solution, which will have 2 default class files namely,
Service1.cs and IService1.cs, providing default implementation of the WCF Service library. Since we
will configure the library on our own, so delete both these class files.
http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print
7/26
4/17/2015
6. Now, right click the WCF service library and add a new class file, name it as MyService.cs
7. Open MyService.cs, initially it will just have a class called MyService. We need to define what kind
of data the service needs to expose. Primitive datatypes such as int, string, float don't need to be
exposed as data contract, they are pretty much understood by the .NET engine, whereas user
defined data types such as class, enumerations need to be exposed as data contracts. Hence define
http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print
8/26
4/17/2015
9/26
4/17/2015
}
}
8. Next, we need to configure the App.Config file. First of all, we need to change the service name to
point to MyServiceLibrary.MyService, intially it would have pointed to
MyServiceLibrary.Service1, but since we have deleted Service1.cs and have included
MyService.cs, we need to alter the service node in the config file.
9. Next we need to configure the endpoints. Change the contract name to point to
MyServiceLibrary.IMaths. Here, I have configured 2 different endpoints to make the service
talk via 2 means. Have used wsHttpbinding and basicHttpBinding. Have changed the base
address to a simpler path.
10. Well, when you try to debug the WCF service after making all the changes, it might give you an
Access Denied exception as below, saying the base address can not be reached. Debug your WCF
service in Administrator mode, then it will work.
http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print
10/26
4/17/2015
11. Let's now debug the service and see how it works. press F5, then a WCF test client will be launched
as below. The .NET engine looks for the base address and pings it to get the metadata of the service
and eventually gives us all the operations which were exposed by the service.
12. It shows the same operations twice, coz we have added 2 different bindings to use. Double click any
of the operations and then you can give the values of the parameters and invoke the service. The
service in turn will return the response. Let's invoke the Addition operation as below:
http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print
11/26
4/17/2015
13. Give some random values and click on Invoke button, the service will return a response based upon
the functionality of the operation as below:
In the above example, we saw the creation of a WCF service library from scratch, which involves creating
just a single class and implementing everything in that, though it's not actually mandatory to implement
everything in the same class.It was just for demonstration.
Next we will see how to call and consume a WCF service from a client. Let's start.
1. Open your Visual Studio once again and click on New>WebSite as below.
http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print
12/26
4/17/2015
2. A dialog box will open, select WCF service, give the location where you want to store it.
3. The template will add up a WCF service project in the solution, having 2 class files IService.cs,
Service.cs and a Service.svc file.
4. Service.svc file is helpful when we want to host the service within the IIS. Service.cs and IService.cs
classes will provide some default implementation of the service. For the time being, leave them as it
is. Build the solution, set the Service.svc file as Start Page and debug it. You will see that the
http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print
13/26
4/17/2015
ASP.NET Development server browses over to a URL and sends back a Service implementation
something like below. It implies that the service has been created and is up and running.
5. On clicking the URL inside the page, you'll be redirected to the Web Services Description
Language (WSDL) page:
The element Service shown as bold in the above piece of code refers to the Serviceclass present
in theService.cs file, which is further stored under App_Code folder.
Above was just an intro to the WCF service and its features, let's start to code a WCF service and try
to consume it in a console application.
http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print
14/26
4/17/2015
7. Rename the IService.cs, Service.cs files to something appropriate like IMathService.cs and
MathService.cs. Accordingly you'll have to alter the names within the Service.svc and web.config file.
Have a look at the below code for IMathService.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
// NOTE: If you change the interface name "IService" here, you must also update the reference
to "IService" in Web.config.
[ServiceContract]
public interface IMathService
{
[OperationContract]
int Addition(Math obj1);
[OperationContract]
int Subtraction(Math obj2);
// TODO: Add your service operations here
}
// Use a data contract as illustrated in the sample below to add composite types to service
operations.
[DataContract]
public class Math
{
int number1, number2;
[DataMember]
public int Number1
{
get { return number1; }
set { number1 = value; }
}
[DataMember]
http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print
15/26
4/17/2015
Here in the code, we have a class as Math which is a DataContract since it acts as a user-defined data
type. It has 2 members and 2 properties defining the numbers. Then we have a ServiceContractcalled
as IMathInterfacewhich exposes 2 operations to the client.
8. Have a look at the MathService.cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
// NOTE: If you change the class name "Service" here, you must also update the reference to
"Service" in Web.config and in the associated .svc file.
public class MathService : IMathService
{
#region IMathService Members
public int Addition(Math obj1)
{
return (obj1.Number1 + obj1.Number2);
}
public int Subtraction(Math obj2)
{
return (obj2.Number1 - obj2.Number2);
}
#endregion
}
The MathServiceclass inherits the IMathServiceinterface and provides the implementation of the
operations exposed by the service.
http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print
16/26
4/17/2015
9. Build the solution, set Service.svc as Start Page and debug. It should work without any errors
and you'll see the Service page in the browser as below:
It shows as to how we can use this WCF service in a client application. Let's now try to code a
console application to consume this service. Stay Tuned..
10. Right click on the solution and click on Add>New Project as shown below:
11. A dialog box will be opened, select Console Application from the list of templates, store this
application inside the same solution in which the above service is kept and give a name for
the application as DemoClient.
http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print
17/26
4/17/2015
12. A Console Application project will be added to the solution, now we need to refer the WCF service in
this application. Right click on References>Add Service Reference.
13. This will open a Add Service Reference window. We need to search the WCF service to add, give
its URL in the Address textbox and hit Go. The service will be evident and its services and operations
will be listed.
http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print
18/26
4/17/2015
Give the namespace as localhost, since it is the domain name(providing domain name is the
convention) and hit OK. The service reference will be added to the Console Application project.
Now open the program.cs file of the Console app and start coding as shown below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DemoClient
{
class Program
{
static void Main(string[] args)
{
localhost.MathServiceClient obj = new DemoClient.localhost.MathServiceClient();
localhost.Math mathobj = new DemoClient.localhost.Math();
http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print
19/26
4/17/2015
mathobj.Number1 = 10;
mathobj.Number2 = 5;
Console.WriteLine("Addition continues..");
Console.WriteLine(obj.Addition(mathobj));
Console.WriteLine("Subtraction continues..");
Console.WriteLine(obj.Subtraction(mathobj));
Console.ReadLine();
}
}
}
I will explain the above code. We haven't done anything special, we have just created an object of the
MathService client as objand have tried to access the operations which were exposed in the WCF service.
Since the operations of the WCF service accept an argument of type Math class, we have to make an
object of the Math class, shown above as mathobj. This mathobjwill be able to access the properties of
the Mathclass. Then we have given some values to the properties and have just called the individual
operations Addition()and Subtraction() as exposed by the WCF service.
14. Now, we need to debug our console application to see whether the implementation is successful or
not. Well, right-click on the console app name in the solution and set as 'Startup Project'.
15. Now debug the application and if everything's correct, then the console app would work without any
errors, shown as below:
http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print
20/26
4/17/2015
Hence, we have been pretty successful in creating a WCF service and consuming it via a client, a
console application in this case.
I want to emphasize as to what happens when a service reference is added to an
application, what's the internal mechanism and stuffs. Let's see.
16. Click on localhost service under service references and click on 'Show All Files'.
http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print
21/26
4/17/2015
18. Click on Reference.cs under Reference.svcmap classification, which will contain the mappings,
serialization and proxy class stuffs. For ex: In the below image we can see that a partial class named
as Math has been created, in which the DataMembers are serialized, it implies that the user-defined
data type, Math class in our WCF service is serialized when the service is consumed by a client and
then it's referenced.
http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print
22/26
4/17/2015
19. Have a glance at the below image too, implementation of the operations has been created, which
means that we will have to code the same way if we have to consume these operations in our client
application. Also, we can see that a proxy class named as MathServiceClienthas been created,
we just need to instantiate the proxy class in our main method and then we're good enough to use
the operations which have been exposed by the WCF service.
http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print
23/26
4/17/2015
Gist is that, when we add a service reference to a client application, Visual Studio looks at the WSDL file of
the service, downloads it and prepares similar methods and functions inside Reference.cs file. Post that we
just need to refer these methods and functions in our main application.
I guess I have reached the end of the article for now. I have discussed:
What is WCF, its architecture, its features, uses.
How to create a WCF Service Library and test it via WCF Test Client, from scratch.
How to create a WCF Service and consume it in a client application.
In the next part of the article, I would like to deal with how to consume a WCF service in an ASP.NET Web
application and how to write WCF Services with ASP.NET AJAX (This article will come soon)...
Points Of Interest
Well, I learnt a lot while writing this very article.
A tip which I want to share with our readers is that when you are declaring a DataContractor a
ServiceContractand these terms don't highlight (show error), probably because we haven't included
the required namespaces, we can do Ctrl+Dot key to implement the namespaces rather than by explicitly
typing. Have a look below:
http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print
24/26
4/17/2015
History
Version 1.0 of WCF article completed on 25th, March 2013.
License
This article, along with any associated source code and files, is licensed under The Code Project Open
License (CPOL)
Share
About the Author
http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print
25/26
4/17/2015
Anurag Sinha V
Systems Engineer
India
An electronics engineer landed in the crazy .NET world...
Selectai limba
http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print
26/26