Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

WCF: From a Beginner's perspective & a Tutorial

4.81/5 (105 votes)
5 Apr 2013CPOL19 min read 274.7K   5.8K  
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.

Need For WCF

Next question wobbling the mind would be why WCF, what's the need for it? Well yeah it's the most probable query after a little initial understanding. Prior to WCF, there were a handful of technologies doing tasks of 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) :

Image 1

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 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. Data Types in the message.
  2. Locations of the operations, or where the methods are defined
  3. Protocol information and serialization format
  4. Message exchange patterns(whether the behavior of the message is either one-way, duplex or request/reply type)
  • Policy and Binding: Specify important information such as security, protocol.

Let's switch over to the Service Runtime layer:

Service Runtime layer specifies and manages different behaviors of the service that occur during the service operation. Behaviors of the service or Service Behaviors as they can be fondly called, are basically objects that modify and control the run time characteristics of WCF. Below is a list of Service Behaviors managed by the Service Runtime layer:

  • Throttling Behavior: Determines the number of processed messages, which varies according to the demand of the service.
  • Error Behavior: Specifies what kind of action to be taken when any of the messages give error during runtime.
  • Metadata Behavior: Specifies whether metadata is available across the network.
  • Instance Behavior: Specifies the number of service instances that are available to process a message.
  • Message Inspection: Inspects a message totally or partly during runtime.
  • Transaction Behavior: Enables the transaction operation, which rollbacks the transaction if any process fails during runtime.
  • Dispatch Behavior: Determines the handling and processing of a message.
  • Concurrency Behavior: Specifies whether the messages are processed sequentially or concurrently.
  • Parameter Filtering: Filters the message headers & executes preset actions based on the filter of the message headers.

Let's discuss stuffs about the Messaging Layer:

Messaging Layer is responsible for the pattern of exchanges and its format. It's composed of the following components and channels:

  • WS-Security Channel: Enables message security by implementing the WS-Security specifications. Extensive coverage on WS Security can be found out here: http://msdn.microsoft.com/en-us/library/ms977327.aspx
  • WS Reliable Messaging Channel: Guarantees delivery of messages.
  • Encoders: Provides the number of encoders for messages, such as Binary, XML, Text, MTOM.
  • HTTP Channel: States that HTTP is used to deliver messages.
  • TCP Channel: States that TCP is used to deliver messages.
  • Transaction Flow Channel: Governs transacted message patterns.
  • Named Pipe Channel: Enables Inter Process Communication.
  • MSMQ Channel: Enables services to operate with MSMQ.

Let's move on to Hosting and Application Layer:

This layer provides a number of options in which a service can be activated and hosted. Hosting can be of 2 types: self hosting, hosting on external agents, such as IIS. Various options provided by this layer are as follows:

  • 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
  • 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 BasicHttpSecurityMode needs to be configured. Have a look at the below code on how to configure the host of the basicHttpBinding.
XML
<?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>

Let's discuss about Contracts as in C of ABC's of WCF:

Contracts: Agreements between the client and services. 3 basic contracts are:

  • Service Contracts: Defines the methods of the service.
  • Data Contract: Defines the data types used by the service methods.
  • Message Contract: Ability to control the message headers during the creation of the message.

The second feature of WCF is Improved Transport Layer: Unlike .ASMX web services, WCF services use a numerous protocols for communication between a client and the service. It uses HTTP, TCP, HTTPS, Named pipes. Hence, improved transport facility.

Queuing Support: WCF supports queuing, which allows messages to be stored in a queue and then sent in a timely manner, thus giving a consistent state of communication.

Improved Transactional Support: WCF incorporates improved transactional support, which says if any process fails during service runtime, the transaction doesn't commit, it rollbacks.

Improved Security: Authentication plays a big role in WCF, also WCF ensures that during transit, order of the messages ain't altered.

Hosting support on various environments: WCF allows hosting of services in a number of environments, such as Windows NT Services, Windows Forms, Console Apps, IIS, Windows Activation Services(WAS). IIS provides added advantages such as automatic start and stopping of the service.

AJAX Integration and JSON Support: WCF supports ASP.NET AJAX and JSON data format, which allows WCF services to expose operations to AJAX clients. JSON is a data format used to carry data exchange 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.

Using the Code

We will first code a simple WCF service and test it via inbuilt WCF test client.

  1. Open Visual Studio 2008 and click on File> New> Project.

    Image 2

  2. Create a new Blank Solution to start with.We will add projects later in the next step.

    Image 3

    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.

    Image 4

  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.

    Image 5

  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.

    Image 6

  6. Now, right click the WCF service library and add a new class file, name it as MyService.cs

    Image 7

  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 a class called as Maths and define 2 properties over there.

    Individual members of the Data contract class need to be exposed as data members. The namespace System.Runtime.Serialization needs to be added for data contract to come alive.Then, we will have to define our service contract, which ensures what operations are exposed by the service. Add an interface, call it as IMaths and add individual methods inside it which will accept the Data contract class as argument to work upon. Service contract will come alive via inclusion of System.ServiceModel namespace. Next comes the actual implementation of the service, extend the MyService class to implement the interface and its operations. Define the functionalities of the operations as you desire. In the below code, normal arithmetic operations are defined in the MyService class. Build the solution, it should compile without any error.

C#
using System;
<pre>using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.ServiceModel;
namespace MyServiceLibrary
{
    [DataContract]
    public class Maths
    {
       
        [DataMember]
        public int Number1 { get; set; }
        [DataMember]
        public int Number2 { get; set; }
    }
    [ServiceContract]
    public interface IMaths
    {
        [OperationContract]
         int Addition(Maths obj1);
        [OperationContract]
         int Subtraction(Maths obj2);
        [OperationContract]
         int Multiplication(Maths obj3);
        [OperationContract]
         int Division(Maths obj4);
    }
    class MyService:IMaths
    {
        #region IMaths Members
        public int Addition(Maths obj1)
        {
            return (obj1.Number1 + obj1.Number2);
        }
        public int Subtraction(Maths obj2)
        {
            return (obj2.Number1 - obj2.Number2);
        }
        public int Multiplication(Maths obj3)
        {
            return (obj3.Number1 * obj3.Number2);
        }
        public int Division(Maths obj4)
        {
            return (obj4.Number1 / obj4.Number2);
        }
        #endregion
    }
}
  1. 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.
  2. 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.

    Image 8

  3. 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.

    Image 9

  4. 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.

    Image 10

  5. 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:

    Image 11

  6. Give some random values and click on Invoke button, the service will return a response based upon the functionality of the operation as below:

    Image 12

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.

    Image 13

  2. A dialog box will open, select WCF service, give the location where you want to store it.

    Image 14

  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.

    Image 15

  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 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.

    Image 16

  5. On clicking the URL inside the page, you'll be redirected to the Web Services Description Language (WSDL) page:

    Image 17

  6. Let's view the skeleton of the Service.svc file:
    XML
    <%@ ServiceHost Language="C#" Debug="true" Service="Service" CodeBehind="~/App_Code/Service.cs" %>

    The element Service shown as bold in the above piece of code refers to the Service class 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.

  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:
C#
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]

public int Number2

{

get { return number2; }

set { number2 = value; }

}

}

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 ServiceContract called as IMathInterface which exposes 2 operations to the client.

  1. Have a look at the MathService.cs file:
C#
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 MathService class inherits the IMathService interface and provides the implementation of the operations exposed by the service.

  1. 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:

    Image 18

    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..

  2. Right click on the solution and click on Add>New Project as shown below:

    Image 19

  3. 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.

    Image 20

  4. 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.

    Image 21

  5. 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.

    Image 22

    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:
C#
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();

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 obj and 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 mathobj will be able to access the properties of the Math class. 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.

  1. 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'.

    Image 23

  2. Now debug the application and if everything's correct, then the console app would work without any errors, shown as below:

    Image 24

    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.

  3. Click on localhost service under service references and click on 'Show All Files'.

    Image 25

  4. A list of files will be evident as shown below:

    Image 26

  5. 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.

    Image 27

  6. 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 MathServiceClient has 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.

Image 28

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 DataContract or a ServiceContract and 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:

Image 29

Same applies when you are trying to refactor the Interface.

A zipped folder has been added which has the source codes referenced in this article. It has 2 folders basically, MyFirstServiceSolution(WCF service library coded from scratch) and WCF_WebService(having a WCF service and a console app). Do make use of that.

I would like to give credit to MSDN and the Black Book of C# and ASP.NET from where I have referenced certain definitions and stuffs.

Sequel to this article can be found at : http://www.codeproject.com/Articles/570036/WCF-From-a-Beginners-perspective-and-a-tutorial-Se. It helps the readers to consume a WCF service in an ASP.NET website and to create an AJAX enabled WCF service. View it and enjoy coding WCF services.

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)