Article Author: Poornachandra Sarang
Introduction
In the last couple of years, SOA (Service Oriented Architecture) has become a buzz word in the industry, and the state-of-the-art programming model has gradually changed from object oriented to service oriented. Each service in an SOA-based project uses an object oriented model to provide the services. Many technologies were developed to implement SOA, Microsoft itself provided several models such as remoting, ASMX, messaging, .NET enterprise servers, etc to implement SOA. These different technologies led to confusion and difficulties in coding for interoperability. A new programming model was desired that would unify all these existing technologies and that’s where WCF was born. WCF defines a unified programming model for building service oriented applications. It combines several features offered by the earlier models such as attributed coding, declarative transaction support, pluggable transports, pluggable Interceptors, etc. all into a single unified model.
In this article, you will learn the WCF architecture and several benefits offered by it. You will also learn how to create a service and a client based on the WCF Framework.
System Requirements
To develop and run the applications described in this article, you will need Visual Studio 2005 Beta2 installed on your machine. At the time of this publication, Microsoft has recently released the final version of Visual Studio 2005. However, the RC1 and September CTP versions of WinFX still support only the VS2005 Beta2 and Visual Studio Express Beta2 release, hence I’ve kept with Visual Studio Beta 2 in this article.
You will also need the Microsoft WinFX SDK RC1 installed on your machine. Both these applications can be downloaded from Microsoft site from the links section.
Installing and Compiling the Sample Code
To run the sample WCF Service and Client you will need to download the source code from ASPToday and unzip it into a folder.
To run WCF Service:
- The Visual Studio Solution for the WCF Service can be found under the folder IndigoService
- Open the solution in VS 2005
- Build the solution
- Run the solution
- A Console window opens with a message that indicates that the service is running. The service may be terminated by pressing ENTER key
- Keep the service running for testing the client
To run WCP Client:
- The Visual Studio Solution for the WCF Client can be found under the folder IndigoClient
- Open the solution in a separate instance of VS 2005
- Build the solution
- Run the solution
- The console window displays the client output
What is WCF?
WCF is a framework to build distributed, message oriented applications such as those based on SOA. It is basically a communication infrastructure for creating distributed applications. The communication infrastructure is built around the web services architecture and is built on top of web services protocols.
Web Services Architecture
The web services architecture consists of a service that exposes its interface using standard web protocols – SOAP and WSDL. A remote client uses the service using these standard web protocols. The service exposes its interface in WSDL and the client after understanding this interface consumes the service using the standard SOAP request/response mechanism. The SOAP request/response architecture is shown in Figure 1.

Figure 1. SOAP request/response mechanism in web services architecture
WCF Architecture
WCF is a set of .NET technologies for building and running connected systems. It is based on messaging between various components. The messages are SOAP request and response as illustrated in Figure 1above. The WCF services thus created are interoperable as they are based on standard protocols for communication.
Using the WCF framework, you create a service and a client that consumes the service. The service exposes its interface to the outside world using WSDL and the client invokes the service by sending a SOAP request message. The service returns a SOAP response to the client. In the WCF programming model, these underlying messaging operations have been totally abstracted from the developer, as you will see it shortly.
When the messages are transmitted between the components, they need to be secured and the message transmission and reception must be reliable. Also, the messages may be transacted depending on the application need. To support this, several web services standards such as WS-Security , WS-Reliable Messaging , WS-Coordination , WS-Transaction (Currently called WS-AtomicTransaction and WS-BusinessActivity ), etc. have been developed in the web services architecture. The WCF architecture provides all these services to the developer transparently with the help of a configurable deployment. WCF defines message contracts, end points and service definitions, all of which can be configured easily with the help of deployment descriptors. The ease of configuring these parameters makes WCF attractive to use.
WCF Client/Server Development
In WCF, client/server development has been simplified by using attributed coding. The developer creates a service using component technology (object-oriented programming techniques). The class methods which need to be exposed to the outside world are simply attributed with a framework provided attribute. The framework generates WSDL based on these attributed methods. This WSDL is published for the client use. You may notice this is very similar to the ASMX Web Services model.
Using the published WSDL, a framework provided utility creates a proxy to the service for the client to use. The client simply instantiates this class and invokes the methods on the proxy. The underlying code in the proxy converts the method call into a SOAP request and dispatches it to the service. The service response, which is essentially a SOAP response, is interpreted by the client proxy and the results in native form are returned to the client. In short, the marshalling and unmarshalling between the binary method call and SOAP request/response is done transparently to the user.
Creating a WCF Service
Visual Studio 2005 provides a wizard for creating a WCF service. We will use the skeleton generated by this wizard to develop our own service. Like the traditional way of learning a new language, our first service will be a HelloService . Our service will contain one business method called SayHello() that accepts a string argument and returns a greeting to the caller.
To create the service, open Visual Studio and select File → New → Web Site menu option. This opens up the screen shown in Figure 2:

Figure 2. WCF Service Creation Wizard
This figure has been reduced in size to fit in the text. To view the full image Click here
Select the desired location (say c:HelloService ) and language ( Visual C# ) for creating the service. In this article, we will use C# for creating both the service and the client. When you click the OK button, the wizard generates the project and all the necessary files for a sample service that can be compiled and run directly. However, we will be making changes to the wizard-generated source files to implement our own service methods. Open the service.cs file and make the following changes to it.
- Change the interface name from IMyService to IHelloService :
public interface IHelloService
The IHelloService interface declares the service methods that we wish to expose as a web service. The service class declared later will inherit this interface and provide implementation for the various business methods declared in this interface.
- Change the method signature of MyOperation1() in the interface to the following signature:
string SayHello(string myValue1);
We will expose this method as a WCF web service. The method takes a single parameter of type string and returns a string response to the caller. As discussed previously, when the server receives a request for the invocation of this method, it receives a SOAP request. The underlying runtime converts the SOAP request to a binary method call. Similarly, when the response is generated for the client, the runtime converts this binary response into a SOAP response. These conversions and the marshalling/unmarshalling of parameters remain transparent to the developer.
Next, you will make modifications to the service implementation class.
- Rename the wizard-generated MyService class to HelloService and make following modifications in the class implementation code:
public class HelloService : IHelloService
{ public string SayHello(string myValue1) { return "Hello: " + myValue1; }
}
The HelloService class implements the IHelloService interface and provides the implementation for the SayHello() method. The SayHello() method accepts a string parameter and returns a string result to the caller.
Next, we need to modify the service.svc file
- Modify the service.svc file to the code shown here:
<%@ Service Language="C#" CodeBehind="~/App_Code/Service.cs" Class="HelloService" %>
The wizard registers a .svc file with IIS as executables. Later on, when you run the service by typing the URL for the service in your browser, IIS will run this service.svc file. The CodeBehind attribute defines the name of the .cs file (in this case service.cs ) that contains the service implementation. The Class attribute specifies the class name that provides the implementation for the service methods.
- Modify web.config file
The web.config file defines the application configuration. Modify the serviceType and contractType attribute values as shown in the listing below:
<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"> <system.serviceModel> <services> <service serviceType="HelloService"> <endpoint contractType="IHelloService" bindingSectionName="wsProfileBinding"/> </service> </services> </system.serviceModel> <system.web> <compilation debug="true"/> </system.web>
</configuration>
The partial document structure for the configuration file is shown below:
<system.ServiceModel>
<services>
<service>
<endpoint/>
</service>
</services>
</system.ServiceModel>
The system.ServiceModel element declares various services. The services are listed under the <services> tag. Each service is described in the <service> element. In the case of our example, we set the serviceType attribute to HelloService . This is our service implementation class. We set the contractType attribute to IHelloService . This is our service interface that declares the various service methods exposed as web service methods.
In the wizard-generated web.config file the bindingSectionName attribute has been set to wsProfileBinding . The bindings define the communication mechanism to the web service endpoint. WCF provides several pre-defined bindings. The wsProfileBinding is one such pre-defined binding. I’ll discuss bindings in more detail later in the article.
Running the WCF Service
Once you make the necessary code modifications as described in the previous section, you are ready to run the service. Simply build and run the project. If the build is successful, Visual Studio will start the browser and run the service from the browser window. The screenshot in Figure 3 shows the output window.

Figure 3. Output window of a running WCF Service
This figure has been reduced in size to fit in the text. To view the full image Click here
The service shown in Figure 3 listens on port 1233 . This port is randomly selected by the wizard at the time of service creation. When you create the service on your machine, your service will likely listen on a different port.
The web browser opens the service.svc file at the specified URL. The ASP.NET runtime under IIS executes the . svc file and instantiates the HelloService class defined in it. The structure of the service.svc file was discussed previously.
After the service starts, you can examine the exposed interface by opening the WSDL document in the browser window. The WSDL is opened in the browser by appending the string ?wsdl to the service URL and opening it in the browser. The screen output that displays the WSDL for our HelloService is shown in Figure 4.

Figure 4. WSDL document for HelloService
This figure has been reduced in size to fit in the text. To view the full image Click here
As can be seen in Figure 4, the WSDL contains the message formats for both the input and output messages and the definition of the operations; in this case, it is the SayHello() operation. In WCF development, very rarely you will need to examine WSDL. The utility discussed under the client development uses this WSDL to create a server proxy. The client uses the proxy to invoke the service.
Our next step is to write the client application that consumes the HelloService service.
Creating the WCF Client
To create a client that uses the HelloService , you will first create a proxy class to our HelloService . Next, you will create a console application that uses this proxy class to use the service.
Creating a Proxy
The client needs a proxy to the server. You create the proxy using the provided svcutil.exe utility. The svcutil.exe is executed using the following command at the command prompt:
svcutil.exe http://localhost:1233/HelloService/Service.svc?wsdl
Figure 5 shows the output of running the svcutil.exe utility.

Figure 5. Output of the svcutil.exe
The svcutil.exe utility creates two files – the .cs file that contains the proxy to the service and the output.config file that contains the configuration information for the client application. You will need to rename this configuration file to app.config as the client application uses this default name.
Creating the Client Application
Using the wizard, create a Console Application within Visual Studio. Next you will need to add following files to your project:
- tempuri.org.cs – the proxy class (Note: You may rename this file to any other name of your choice)
- app.config – application configuration
- a reference to the System.ServiceModel dll
Lastly, modify the default program.cs file to the code shown below:
using System;
using System.Collections.Generic;
using System.Text;
namespace HelloClient
{ class Program { static void Main(string[] args) { HelloServiceProxy proxy = new HelloServiceProxy(); string result = proxy.SayHello("John"); System.Console.WriteLine("The Hello service returned ‘"result"’"); proxy.Close(); System.Console.ReadLine(); } }
}
In the Main() method, we instantiate the proxy class ( HelloServiceProxy ) and invoke the SayHello() method on the created instance. The program prints the output of the method on the console. At the end of the Main() method, we close the proxy object.
From this code, you can see the ease of client development. Remember the invocation of the SayHello() method creates a SOAP request. This SOAP request creation is taken care of by the underlying WCF runtime. The client developer doesn’t need to not know XML and SOAP to use the remote web service.
Running the Client
Once the above files have been added to the project, build it and run the application. You may run the application through the IDE or from the command prompt. The output should be similar to that depicted in Figure 6.

Figure 6. Client application output
An Alternate Way to Create and Host a Service
In the previous section, we used the Visual Studio wizard to create a WCF service. In this section, you will learn to create a WCF service without using the wizard. To create a service, you need to complete the following steps:
- Define a service interface
- Provide an implementation class for the service
- Create a console application to launch the service
These steps are described in detail in the following sections:
Defining a Service Interface
The service interface contains the methods which you want to expose as a web service. We will create an interface called IGreeting that declares a method called SayHello() . The interface definition is given in the code listing below:
[ServiceContract]
interface IGreeting
{ [OperationContract(IsOneWay = false)] string SayHello(string strName);
}
The method SayHello() is declared with the attribute OperationContract . This makes it a web method that may be invoked using a SOAP request. The attribute also declares this method as IsOneWay = false . This indicates that the method is supposed to return a response to the caller. The response will be a SOAP response.
The interface IGreeting itself is declared with the attribute ServiceContract . This marks the entire interface as a web service containing web methods attributed using the OperationContract attribute.
Providing an Implementation Class for the Service
The implementation of web methods is done in the class called Greeting . This class is declared as internal , although this is not necessary. The Greeting class implements the various methods declared in the IGreeting interface.
internal class Greeting : IGreeting
{ public string SayHello(string strName) { return "Hello from Indigo, " + strName; }
}
Creating a Console Application to Host the Service
To launch the service, we use the ServiceHost class. The console application code is shown below:
class HelloIndigoService
{ static void Main(string[] args) { Uri url = new Uri("http://localhost:2005"); ServiceHost<Greeting> host = new ServiceHost<Greeting>(url); BasicProfileBinding binding = new BasicProfileBinding(); host.AddEndpoint(typeof(IGreeting), binding, "/Greeting"); host.Open(); Console.WriteLine("Press ENTER to terminate!"); Console.ReadLine(); host.Close(); Console.WriteLine("Service shutting down."); }
Note that there are few changes in September CTP version of WinFX. If you have downloaded the September CTP, refer to its documentation for minor changes that may be required in the code.
In the Main() method, first you should create an instance of Uri at which our service will be listening. Our service will run at the URL localhost:2005 . Note that you may specify any desired port for your service that you want. Next you should instantiate the ServiceHost class with the created URL. You also need to add the binding information and the endpoint to the host. For this you can instantiate the BasicProfileBinding class to create the binding for your service. The WCF framework provides several other binding classes which are discussed later in the article. You can now add the endpoint to the host by calling its AddEndpoint() method. The AddEndpoint() method receives the service interface as its first parameter, the binding object as its second parameter and a string as its third parameter that adds a unique identifier to our service URL. After adding the endpoint information, you can open the service by calling the Open() method on the host . You can keep the console application in running state by calling the ReadLine() method of Console class. Thus, the service will keep on running until the time the user presses the Enter key to terminate the process. When this happens, you can close the host object.
Once the service starts running, you may obtain its WSDL by typing the following URL in your web browser: http://localhost:2005/Greeting?wsdl
WCF Benefits
One of the greatest benefits that you must have noticed from the above client/server development is the ease of development that WCF offers for developing SOA-based applications. The set of .NET classes provided in the WCF framework totally abstracts the underlying web service architecture from the developer. Though this comes as an immediate visible benefit to the developer, the purpose of WCF framework is very much beyond this simple immediate benefit. WCF offers several real benefits to the developer. The next few sections discuss some of the important benefits of using the WCF framework.
Ease of Development
As seen from the HelloService example, WCF provides an easy way to create a server, publish its interface and also to write a client that consumes this service.
Service Development
Let us examine the service interface of our HelloService . The interface is shown in the listing below:
[ServiceContract()]
public interface IHelloService
{ [OperationContract] string SayHello(string myValue1);
}
The interface is attributed using ServiceContract attribute. Any interface that you wish to expose as a web service, you will need to add this attribute to it. The interface declares one or more methods in it. The method that is to be exposed as a service method is attributed using the attribute OperationContract . Only the methods that have this attribute will be exposed as web service methods that may be invoked using a SOAP request. The other methods that do not have this attribute will be treated as normal methods and cannot be invoked using a SOAP request.
Publishing the Service
A web service is published by creating a WSDL document and making it available for the client to use. Opening the service URL after appending ?wsdl to it, creates and displays the WSDL in the browser window. The location of WSDL may be published in a public UDDI registry, the client then searches the registry for the desired service and obtains its WSDL from the provided location. Based on this WSDL, the client may create a proxy to the service or programmatically generate a SOAP request to invoke the service. Note that since the service is exposed as a web service, you may write a client in any language and based on any technology other than .NET and yet consume the service as desired.
Writing the Client
The client needs to create and send a SOAP request to use the remote web service. The framework provided svcutil.exe creates a proxy to the server using the published WSDL. The client simply instantiates this proxy class and invokes the methods on it. The runtime generates a SOAP request for the invoked method and dispatches it to the server. The server response is interpreted by the proxy and response in native form is returned to the client. The developer of the client application does not need to know anything about XML or SOAP to use the services.
Flexibility in Communication Mechanism Selection
WCF provides lot of flexibility in the selection of the communication mechanism between the client and the server. The communication mechanism is decided by the bindings which are specified in the application configuration files. In our HelloService example, the wsProfileBinding was specified in the web.config file. The wsProfileBinding specifies a secure, reliable and interoperable binding.
In general, the binding specifies how to connect to the endpoint and defines the following:
- The protocol stack
- The transport
- The encoding
The protocol stack determines whether the transport is secured and reliable. The transport determines the transport protocol such as TCP, HTTP, etc. The encoding determines the wire encoding such as Text/XML, Binary, etc.
WCF provides several predefined bindings such as BasicProfileBinding , WsProfileBinding , NetProfileTcpBinding , NetProfileMsmqBinding , etc. Each type of binding provides distinct features. The developer selects the appropriate binding depending on the application needs. For example, if you wish to communicate to the existing MSMQ application, you will use NetProfileMsmqBinding . If you want a secure, reliable, optimized binding suitable for cross-machine communication you will use NetProfileTcpBinding and so on. To use any desired binding, you simple need to instantiate the desired binding class and use its reference in the AddEndPoint() method as shown in the code snippet below:
BasicProfileBinding binding = new WsProfileBinding ();
host.AddEndpoint(typeof(IGreeting), binding, "/Greeting");
To cover the in-depth purpose of each binding is beyond the scope of the current article and will be covered in a future article.
Other Benefits of WCF
WCF offers several other benefits in creating applications based on the web services architecture. For example, you may easily create a client using the Duplex binding that allows the invoked web service to call back on the client. Both calls, from client to server and server to client would be based on web services standards. Like this, WCF provides many other features to implement a configurable security, a transaction support for interoperable web services, etc. These topics are beyond the scope of this article but there are links available in the links section for additional information.
Conclusion
WCF is Microsoft’s new framework for building and running connected systems. WCF unifies several existing technologies into a new model for developing distributed systems based on SOA. WCF provides several .NET classes to create both client and server applications. The client/server communicates with each other using web services standards. The SOAP request/response mechanism has been totally abstracted from the developer. The developer simply uses attributed coding to accomplish the task.
The article demonstrates the ease of client/server creation with the help of a simple example. WCF provides easy customization of the applications using application configuration files. The application configuration file allows you to select the endpoint for the service, the transport that is used for accessing the service, the security privileges to invoke the service and also supports several different types of encoding. The article has discussed some of these benefits offered by WCF. Future articles will discuss the several binding configurations, their implementations and use in practical scenarios and also several other features of WCF architecture.

