The Baker’s Dozen: A 13-Step Crash Course for Learning Windows Communication Foundation (WCF)

The Baker’s Dozen: A 13-Step Crash Course for Learning Windows Communication Foundation (WCF)

CF is one of the exciting new capabilities in the .NET 3.0 Framework. It provides a unified and uniform programming model for building distributed applications. Those who previously built multiple code bases to deal with Web services and .NET remoting will surely come to appreciate the power of standardization that WCF offers. WCF, like any other new technology, requires research and experimentation to become productive.

This article presents a crash course in the basics of Windows Communication Foundation (WCF). It assumes no prior experience with WCF, and walks you through some basic exercises and steps to show WCF’s capabilities.

Windows Communication Foundation (WCF) is one of the primary components of the .NET 3.0 Framework. WCF provides a uniform and unified programming model for distributed applications, and eliminates the need for multiple code bases to deal with the differences between communication protocols.

The Current Baker’s Dozen Menu
You’ll see a step-by-step guide to building distributed applications with WCF. I’ll minimize the amount of “reading between the lines” that sometimes happens with reference material that makes assumptions about the reader’s knowledge. If you’ve ever built even a simple WCF application, you probably won’t find the content here to be much more than a refresher?it focuses on what someone new to WCF will need for a “crash course.” I’ll walk you through these thirteen steps:

  1. Identify all the required downloads for developing WCF applications.
  2. Identify the requirements for a demo distributed application that this article will build using WCF.
  3. Present an overview of WCF architecture, and how you can use WCF to handle all the requirements of the demo application.
  4. Build your first demo?a self-hosted WCF service in which you build the necessary .NET interfaces for the different layers to communicate (part 1 of 3).
  5. Build the demo .NET server and establish a configuration file to host a WCF service (part 2 of 3).
  6. Build a .NET client piece to access the WCF service (part 3 of 3).
  7. Modify the first demo to use more of the WCF object model with code, instead of configuration files.

The Baker’s Dozen Spotlight:

  1. Build a second demo that builds and hosts a WCF service using IIS, in the same way you’d build and host ASMX files (part 1 of 2).
  2. Host a WCF service using IIS: build the client (part 2 of 2).
  3. Create a WCF XML Web service and establish configurations for non-.NET clients to consume it (part 1 of 3).
  4. Register a WCF XML Web service with IIS (part 2 of 3).
  5. Write code in a non-.NET client to consume the WCF service (part 3 of 3).
  6. Address some security options with WCF.

See the Recommended Reading section at the end of this article where I list several links to articles that you’ll feel more comfortable reading after absorbing this material.

There Are No Bad Questions?
If you’re new to WCF and distributed computing you may wonder how WCF fits in.

Author’s Note: Some .NET developers think that you can use WCF only in a Vista environment, but that’s not true?you also can use it with Windows XP Professional. I built and ran all the sample code using Windows XP Professional.

Distributed computing is an architecture where the various components of an application reside on different computer systems (often called domains). For example, suppose you load SQL Query Analyzer (or SQL Management Studio) from your desktop, and you open a database on your company’s database server. You type a query or run a stored procedure and you get the results. This is a very basic example of distributed computing. You typed the query from your desktop, but the server performed the work and fed the results back to you. So each component of the application performed a portion of the overall task.

Now think about this from an enterprise standpoint?you want the work and processing to execute on the servers (or domains) that make the most sense. A typical distributed application might feature a client module, a Web server, an application server, and a database server. You may want certain processes to execute on certain domains?perhaps to take advantage of specific hardware, to follow certain development guidelines, or because of restrictions or policies, or maybe other reasons. I won’t cover how to architect a distributed application. I make the assumption that you’ve already decided where you want processing to occur.

Developers often use XML Web services or .NET remoting protocols (or both) so that components of distributed applications can communicate and interact. Prior to WCF, developers usually needed to write and maintain different code bases to deal with each protocol. WCF allows developers to work with these protocols using a unified programming model?eliminating the need for separate code bases. You’ll walk through the steps to create simple WCF applications that use both Web services and remoting. By the end of the article, you’ll see how you can use the WCF programming model to write a single code base to deal with all the protocol differences.

I’m Not Using Windows Vista (Yet)
Some .NET developers think that you can only use WCF in a Vista environment. In fact, you also can use it with Windows XP Professional. I built and ran all the sample code using Windows XP Professional.

“I’ve Seen All Good People?”
I want to thank Sam Gentile, Ted Neward, Rick Strahl, and Thom Robbins for helping me with WCF questions that I had while researching this article. In many ways, the steps in this article reflect the learning curve I recently experienced.

Editor’s Note: This article was first published in the May/June 2007 issue of CoDe Magazine, and is reprinted here by permission.

Step 1: Let’s Go Shopping for WCF
To get started, you can find background information at the main Microsoft WCF site. I’ll also list some great online references for WCF at the end of this article.

If you used .NET interfaces and/or .NET Generics prior to WCF, you’re already off to a good start. If you didn’t, now is the time!

You’ll need to download all the necessary WCF components prior to using the examples in this article. Because the download page links are so long, I’ll include them with the sample code that goes with this article.

  1. The Microsoft .NET Framework version 3.0. This version of the .NET Framework contains all the functionality for WCF, as well as Windows Presentation Foundation (WPF) and Windows Workflow Foundation (WF).
  2. The Microsoft Windows SDK for Windows Vista and .NET Framework 3.0 Runtime Components. (These may take a long time to download and install.)
  3. The Visual Studio 2005 Extensions for .NET 3.0 Framework. This allows you to build WCF applications with Visual Studio 2005.
Author’s Note: Although you can use XP Professional, you cannot build WCF applications using Visual Studio 2003.

Step 2: Defining the Requirements for the Demo Application
The demo contains two simple classes: a customer class and a customer order status. The customer class returns the information for a specific customer, and the customer order status class returns basic order information for a specific customer.

You’ll want to access these two classes using each of the following protocols:

  • TCP from a .NET Windows Forms application (similar to .NET remoting).
  • HTTP from both a .NET Windows Forms and a Web Forms application (and be able to switch back and forth using configuration files).
  • HTTP and SOAP from a non-.NET application.

Step 3: An Overview of WCF Architecture
As much as I’d love to jump in with some code right away, you need to understand some concepts first. At the highest level, you can use WCF for the following:

  • Web services
  • .NET to .NET communication (via HTTP, TCP)
  • Distributed transactions
  • WS-* specifications
  • Queued messaging

Essentially, this means you can use the WCF model for a variety of different areas that previously required different code bases.

WCF contains four key components that I’ll define in the next few paragraphs:

  • Contracts
  • Bindings
  • Endpoint definitions
  • Hosting environment

You are probably thinking, “Oh great, contracts?another new term to use!” Well, not exactly. As a teacher of mine used to say (corny joke alert), “It’s one of our old friends, dressed in a Halloween costume.” In this case, the old friend is the .NET interface, which by definition defines a contract that a class implementing the interface must adhere to. Therefore, a WCF contract defines the operations that a service can perform. Step 4 will cover the specifics of building an interface and establishing WCF contracts.

So if you used .NET interfaces and/or .NET Generics prior to WCF, you’re already off to a good start. If you didn’t, now is the time!

Bindings are the communication channels between a WCF service and a client (such as TCP, HTTP, etc.). Table 1 lists the WCF bindings, which I’ll use throughout the code samples in this article.

Table 1: WCF Bindings











Endpoint definitions refer to the URI (Uniform Resource Identifier) addresses for connecting to a WCF service. An endpoint definition consists of the base address, along with the binding and contract information. The configuration files in Step 5 and Step 6 will contain examples of endpoint definitions. WCF allows you to define as many endpoints as necessary?such as a specific endpoint for a .NET client, and another endpoint for a non-.NET client.

Hosting environments refers to the architecture for hosting WCF services. You can host a WCF service in a .NET application or a Windows service. Additionally, you can host your WCF services using IIS, which I’ll cover in Step 9 through Step 11. (Note: At least one of the endpoint definitions must be HTTP.) Finally, you can host a WCF service using the new Windows Activation Service in IIS 7.0.

Here’s a summary of what you’ll see in the next few steps:

  • In Step 4 through Step 6 you’ll learn to build a self-hosted and simple WCF application using configuration files.
  • Step 7 demonstrates how to build the same application without using configuration files. The step will present a little more code to show the WCF object model.
  • In Step 8 you’ll create an IIS-hosted WCF service, and then I’ll show you how to add a WCF service reference to a .NET client that consumes the service (in the same way that you would have added a Web service reference prior to WCF).
  • Steps 9 through 11 describe another IIS-hosted WCF service, this time for consumption by a non-.NET client.

Step 4: Your First Demo, Building the Interface (Part 1 of 3)
Code time! Your first step is to build the interface for the two methods I described back in Step 2 (GetCustomer and GetOrderHistory). Both will receive a customerID integer as a parameter, and both will return an XML string for the results. You’ll construct an interface that establishes the WCF contracts for any clients that consume the service.

TCP remoting in WCF means three words: No more MarshalByRefObject!!!

So do the following:

  1. Fire up Visual Studio 2005 and create a new class library project called DemoInterfaces.
  2. In Solution Explorer, right click on references and add a .NET reference to System.ServiceModel. This is the primary DLL in the .NET 3.0 Framework for WCF. Make sure to add a .NET reference to System.ServiceModel any time you write code using the WCF object model.
  3. Add the code in Listing 1 or Listing 2 (ICustomer.cs or ICustomer.vb).
  4. Build the project, which will create DemoInterfaces.DLL.

The public interface code in Listing 1 and Listing 2 contains two new keyword attributes: ServiceContract and OperationContract.

   [ServiceContract]   public interface ICustomer   {      [OperationContract]      string GetCustomer(int CustomerID);            [OperationContract]      string GetOrderHistory(int CustomerID);   }

The ServiceContact attribute defines the operations that a service can perform, and the OperationContract attribute identifies the exact methods. The .NET CLR translates these interfaces to SOAP types.

You’ll use this interface on both the server that hosts the WCF service and the client that uses it. The interface is your contract (pun intended) between the client and the server.

Step 5: Your First Demo, Building the Business Object and the Server (Part 2 of 3)
Now that you’ve established the interface, the next step is to build the business object that the client side will access, and then write a small server-side process to host the service.

Learn the fundamental WCF terms and security options. Study the entire object model in System.ServiceModel. These will be your vocabulary.

To create the business object, do the following:

  1. Create a new class library project called DemoCustomerBz.
  2. In Solution Explorer, right click on references and add a .NET reference to the DemoInterfaces.DLL that you created when you built the interface project in the previous step.
  3. Add the code in Listing 3 or Listing 4 (CustomerBz.cs or CustomerBz.vb).
  4. Build the project, which will create DemoCustomerBz.DLL.

The only noteworthy aspect of the customer business object (aside from the fact that the methods are merely test methods that return dummy test data) is that the class implements the ICustomer interface from the previous step.

   public class CustomerBz : ICustomer

One of the requirements of this demo application is the ability to access the back-end business object through different communication protocols (e.g., TCP, HTTP). Prior to WCF, developers who used .NET remoting would often derive from System.MarshalByRefObject in conjunction with interfaces. This allowed them to set up the necessary messaging between the client proxy and the remote object.

TCP remoting in WCF means three words: No more MarshalByRefObject! WCF handles that in the endpoint binding definition and the interface; therefore, you no longer need System.MarshalByRefObject, and the back-end class looks like any other class implementing an interface. In other words, this allows you to separate the interface from the implementation.

Next, you can build a small server application to host the service. To do this:

  1. Create a new Windows Forms project called DemoServer.
  2. In Solution Explorer, right click on references and add a .NET reference to both

DemoInterfaces.DLL and DemoCustomerBz.DLL, as well as System.ServiceModel.DLL.

  1. Right click and add a new item as an Application Configuration File (as App.Config), and insert the contents from Listing 5.
  2. In the main form for the Windows Forms application, add two command buttons and a label, and insert the code from Listing 6 or Listing 7 (DemoServer.cs or DemoServer.vb).

The server-side hosting is very simple. The code includes the App.Config reference to the service, which starts with the name of the business class:


App.Config also contains the endpoint address, binding, and contract name. This first example will use basic TCP binding to the localhost port 8228. Note that the contract specifics the interface. (Later in the article you’ll add more endpoint addresses to demonstrate that multiple clients can access different addresses and bindings.)


Finally, the code in the application can open the service by using the ServiceHost class:

   ServiceHost oHost = new ServiceHost(typeof(CustomerBz));   oHost.Open();      // TO CLOSE   oHost.Close();

At this point you’ve created a listener program, a self-hosting application that allows a client application to connect using the specific TCP address, and to use the back-end class CustomerBz that implements the ICustomer interface contract. The next step creates the client application.

Step 6: Your First Demo, Building the Client Piece (Part 3 of 3)
Now you’ll construct a simple .NET application that accesses and uses the service. To do this:

  1. Create a new Windows Forms project called DemoClient.
  2. The client application will utilize the ICustomer interface, as well as the WCF object model. So in Solution Explorer, right click on references and add a .NET reference to DemoInterfaces.DLL as well as System.ServiceModel.DLL.
  3. Right click and add a new item as an Application Configuration File (as App.Config), and insert the contents from Listing 8.
  4. In the main form for the Windows Form application, add two command buttons and a label, and insert the code from Listing 9 or Listing 10.

Notice that the client-side configuration settings for App.Config are almost identical to those on the server-side in the previous tip.


The code also specifies (with the name tag) a variable that you’ll use in the application that relates to this connection information. You could use this if you needed to present multiple communication options to a user.

The code to activate the service on the client side uses the ChannelFactory class, a cornerstone of the client piece. The ChannelFactory is a factory class that creates a communication channel of a specific type for the client to send a message to an endpoint that you specified in your configuration.

   ChannelFactory customersFactory =       new ChannelFactory("Customer");

If that sounds like a mouthful, think of it this way: you’re creating a factory class called customersFactory. It is of type ICustomer (the interface), and inherits all the endpoint information that matches the “Customer” tag.

Note that you haven’t (yet) accessed the WCF service?you’ve created a class from the ChannelFactory that allows you to instantiate a strongly-typed proxy you can use to communicate with the service. The next line creates a strongly-typed proxy (customersProxy) of type ICustomer, using the base ChannelFactory method CreateChannel.

   ICustomer customersProxy =       customersFactory.CreateChannel();

You can then use the proxy customersProxy to access the two methods, GetCustomer and GetOrderHistory.

   string CustomerString =       customersProxy.GetCustomer(1);   string CustomerHistory =       customersProxy.GetOrderHistory(1);

Finally, if you wanted to change the communication binding to use HTTP, or use a different TCP port, you’d only need to modify and distribute the app.config files.


Step 7: Writing Code Instead of Config Files
Step 4 through Step 6 used configuration files to minimize the amount of code you’d need to write. Perhaps more importantly, you can distribute changes via configuration files without having to recompile and redistribute new software modules. However, there may be times when you’ll want to access the WCF object model more directly.

Make sure to add a .NET reference to System.ServiceModel any time you write code using the WCF object model.

Listing 6 and Listing 7 open a ServiceHost object using configuration settings in app.config. If you wanted to write out the code “longhand” you’d do the following:

First, you’d determine the current host address:

   // C# code    IPHostEntry ips = Dns.GetHostEntry(      Dns.GetHostName());   IPAddress _ipAddress = ips.AddressList[0];   string urlService = "net.tcp://" +      _ipAddress.ToString() +       ":8228/MyService";      ' VB.NET    Dim ips As IPHostEntry = Dns.GetHostEntry(      Dns.GetHostName())   Dim _ipAddress As IPAddress = ips.AddressList(0)   Dim urlService As String = "net.tcp://" + _      _ipAddress.ToString() + ":8228/MyService"

Next, you’d create a new instance of a NetTcpBinding object (or WsHttpBinding, or whatever communication binding object you need), and set any required properties:

   // C# code    NetTcpBinding tcpBinding =    new NetTcpBinding();   tcpBinding.Security.Transport.ProtectionLevel =      System.Net.Security. ProtectionLevel.EncryptAndSign;   tcpBinding.Security.Mode = SecurityMode.None;         '  VB.NET code   Dim tcpBinding As New NetTcpBinding()   tcpBinding.Security.Transport.ProtectionLevel =      System.Net.Security.ProtectionLevel.EncryptAndSign;   tcpBinding.Security.Mode = SecurityMode.None;

Finally, create an instance of the ServiceHost object, and use the method AddServicePoint to define the type reference to the service contract (the interface), the binding object, and the address.

   // C# code    ServiceHost host = new ServiceHost(      typeof(ICustomers));   host.AddServiceEndpoint(      typeof(ICustomers), tcpBinding,       urlService);   host.Open();      '  VB.NET code    Dim host As New ServiceHost( _      GetType(ICustomers))   host.AddServiceEndpoint( _      GetType(ICustomers), _      tcpBinding, urlService)   host.Open();
Figure 1. Adding a WCF Service: Select the WCF Service template from the new Web Site dialog.

Step 8: The Baker’s Dozen Spotlight: Building and Hosting a WCF Service Inside IIS (Part 1 of 2)
If you have built ASMX-style Web services, you may be wondering how to accomplish the same thing in WCF: namely, to build a WCF service that uses the interface and business class, and host it in IIS. The steps are at least similar enough that you’ll see some general commonality. In this step, you’ll build the WCF Web service, and in the next step you’ll build a client piece to access it.

First, create a new Web site project, using the WCF Service template (see Figure 1). Call the project WCFService_IISHosted.

Second, right click in Solution Explorer and add .NET references to the two DLLs for the interface and business class libraries that you created in Step 4 and Step 5 (DemoInterfaces.DLL and DemoCustomerBz.DLL). Once you do that, Solution Explorer will look like Figure 2.

Figure 2. Solution Explorer: Here’s what the Solution Explorer in Visual Studio looks like for the IIS-hosted WCF service.

Note that Figure 2 contains a service file called Service.svc. This is similar to the ASMX file you would have used prior to WCF. The contents are as follows:

   <% @ServiceHost Language=C# Debug="true"       Service="MyService"       CodeBehind="~/App_Code/Service.cs" %>

You’ll need to change two things in the service file: the service reference is the CustomerBz.DLL file, and there is no code-behind. (Many online demos feature a simple code-behind file that contains both an interface and the class code, but this example shows how to specify an external DLL).

   <% @ServiceHost Language=C# Debug="true"       Service="DemoCustomerBz.CustomerBz" 

Your next step is to test out the service in a browser. If you run the Web project from within Visual Studio 2005 (or make the folder shareable and run it outside of Visual Studio 2005), you're likely to see a browser screen (see Figure 3) stating that "Metadata publishing is currently disabled." You can enable Metadata publishing by adding the following line to web.config, in the serviceBehavior area:

Figure 3. Metadata Publishing Disabled: If metadata publishing is disabled when you try to load the service in the browser, you'll see this message.
Figure 4. IIS Hosting: The figure shows an IIS-hosted WCF service after enabling metadata publishing.

Now if you try to run the service in the browser, you'll see it correctly (see Figure 4). Note that you cannot actually "run" the service and view test results in the browser, which was never a recommended way to test a service in the first place. The next step will create a simple .NET client to consume this IIS-hosted service.

Step 9: Building a .NET Client to Access an IIS-hosted WCF Service (Part 2 of 2)
Now that you've created the IIS-hosted WCF service, the next step is to build a .NET client to consume the service. In the .NET client, you'll add a service reference to the WCF service, similar to the way you might have added a Web reference prior to WCF.

So create a Windows Forms application, and in Solution Explorer, right click on the References item to add a Service Reference (see Figure 5). Visual Studio 2005 will prompt you for the address of the WCF service (see Figure 6), along with the default name of the local reference to the service. (You can change these if you want, but for this demo, just keep it as localhost.)

Figure 5. Adding a WCF Service Reference: Right click on the References item to add a service reference.
Figure 6. Add Service Reference Dialog: Fill in the fields to add a service reference and a default name.

After you add the service reference, Visual Studio 2005 will do three things:

Figure 7. New WCF Service Reference: Here's how Solution Explorer looks after adding a WCF service reference.
  • Automatically add a reference to System.ServiceModel.
  • Add the binding information into the local app.config file, based on the information from the service.
  • Add an interface proxy to the WCF service, which you'll programmatically access (in the same way you'd access a Web reference proxy).

Figure 7 shows Solution Explorer with these additions.

Finally, you can use the proxy object to consume the WCF service and call the back-end classes. Once again, if you previously consumed ASMX services, this should appear familiar:

   // C# code    localhost.CustomerClient oClient =       new localhost.CustomerClient();   string cResults = oClient.GetOrderHistory(1);      'VB.NET code   Dim oClient As New localhost.CustomerClient()   Dim cResults As String = _      oClient.GetOrderHistory(1)
Figure 8. Svcutil.exe: The figure shows the prompt for the svcutil.exe command-line utility.

One final note: this approach essentially "pulled" the WCF service reference from IIS. In some instances, you may wish to "push" service references out. The Microsoft Windows SDK contains a utility called svcutil.exe (short for ServiceModel MetaData Utility): this utility generates service model code from the service metadata.

Figure 8 shows a command prompt for using svcutil.exe. You specify the full URL for the service and the utility generates two files: the service proxy and an output.config file that you can incorporate into your client application.

Step 10: WCF Services Under IIS for Non-.NET Clients, (Part 1 of 3)?Creating the Service and the Configuration
Here's a complete listing for a modified web.config file for an IIS-hosted service over multiple bindings.

One of the many great things about WCF is that you can define as many endpoints as necessary?such as a specific endpoint for a .NET client, and another endpoint for a non-.NET client.

One of the many great things about WCF is that you can define as many endpoints as necessary, such as a specific endpoint for a .NET client, and another endpoint for a non-.NET client.

Step 11: WCF Services for Non-.NET Clients, (Part 2 of 3)?Registering the Service
Before you consume the service with a non-.NET client, you need to register the service with IIS and ASP.NET 2.0. The .NET 3.0 Framework contains a utility called ServiceModelReg.exe that you can use, as follows:

   -- Location for ServiceModelReg.EXE   -- "WindowsMicrosoft.NETFrameworkv3.0         Windows Communication Foundation"   -- Syntax:   ServiceModelReg.EXE -s:W3SVC/1/ROOT/TestWCFService

ServiceModelReg registers the service and creates the necessary script maps.

Step 12: WCF Services for Non-.NET Clients, (Part 3 of 3) (VFP)
Finally, you can also access the WCF XML Web service using a non-.NET client. Because I was a Visual FoxPro developer in a past life, I'll use VFP to consume the service. Here's a brief code sample:

   -- VFP code to consume a WCF service,    -- in the same way as an ASMX    LOCAL loBasicHttpBinding_IMyService      AS "XML Web Service"   LOCAL loException, lcErrorMsg, loWSHandler   loWSHand = NEWOBJECT("WSHandler",HOME() +       "FFC\_ws3client.vcx")   loBasicHttpBinding = loWSHand.SetupClient(      "http://localhost/WCFDemo/Service.svc?wsdl",      "DemoService", "BasicHttpBinding_IMyService")

If you ever consumed ASMX services in VFP, you'll notice that the code is basically the same!

Step 13: WCF Security Options
With WCF, you are sending SOAP messages over all the supported protocols (TCP, HTTP, etc.) Therefore, you need to implement security (for authentication, encryption, etc.). WCF security is a complete topic in itself (see the Recommended Reading section for more on this topic), which is beyond the scope of this article.

Table 2 lists the main security modes for all the WCF communication bindings.

Table 2: WCF Security Modes








You can specify security settings in the configuration files that you built in previous steps. For example, the following requires that messages must be passed with user credentials:


You can find the entire source code for this article on my Web site. For additional information, check out my blog.

See also  Comparing different methods of testing your Infrastructure-as-Code

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist