
Pro CSharp 2008 And The .NET 3.5 Platform [eng]
.pdf
872 CHAPTER 25 ■ INTRODUCING WINDOWS COMMUNICATION FOUNDATION
At this point, your browser should launch, showing you the directory contents. Once you click the HelloWorld.asmx file, you will see each “web method” exposed from this endpoint. At this point, you can click the HelloWorld link to invoke the method via HTTP. Once you do, the browser will display the return value encoded as XML:
<?xml version="1.0" encoding="utf-8" ?> <string xmlns="http://tempuri.org/">
Hello World </string>
Simple stuff, huh? Even better, when you wish to generate a client-side proxy file that can be used to invoke web methods, you can make use of the wsdl.exe command-line tool or Visual Studio’s Add Service Reference option under the Project menu. These same tools can be used to generate a client-side *.config file, which contains various configuration settings for the proxy (such as the web service endpoint) in a declarative manner.
This proxy code will hide the details of manually working with HTTP connections and the translation of XML data back into .NET data types. Assuming you have generated a proxy for this simple web service (there is no need to do so here), the client application is able to invoke the web method in a painfully simple manner, for example:
static void Main(string[] args)
{
//The proxy type contains code to read the *.config file
//to resolve the location of the web service.
HelloWebServiceProxy proxy = new HelloWebServiceProxy(); Console.WriteLine(proxy.HelloWorld());
}
■Note Previous editions of this text included an entire chapter devoted to the topic of .NET XML web services. With the release of WCF, however, I have decided not to include this chapter in this edition. This chapter on .NET XML web services (titled “Understanding XML Web Services”) can be obtained free of charge from the Apress website (http://www.apress.com) by those who have purchased this text.
While it is still perfectly possible to build this “traditional” flavor of XML web service under
.NET 3.5, most new service projects will benefit from instead making use of the WCF templates. As you will see, you have many HTTP-based bindings to choose from, which allow you to essentially build a web service without selecting a specific “web service” project template.
■Source Code The HelloWorldWebService project is located under the Chapter 25 subdirectory.
Web Service Standards
A major problem that web services faced early on was the fact that all of the big industry players (Microsoft, IBM, and Sun Microsystems) created web service implementations that were not 100 percent compatible with other web service implementations. Obviously, this was an issue, given that the whole point of web services was to achieve a very high degree of interoperability across platforms and operating systems!
In order to ensure the interoperability of web services, groups such as the World Wide Web Consortium (W3C; http://www.w3.org) and the Web Services Interoperability Organization (WS-I; http://www.ws-i.org) began to author several specifications that laid out the details of how a

CHAPTER 25 ■ INTRODUCING WINDOWS COMMUNICATION FOUNDATION |
873 |
software vendor (again, such as IBM, Microsoft, or Sun Microsystems) should build web service– centric software libraries to ensure compatibility.
Collectively all of these specifications are given the blanket name WS-* and cover the issues of security, attachments, the description of web services (via the Web Service Description Language, or WSDL), policies, SOAP formats, and a slew of other important details.
As you may know, Microsoft’s implementation of most of these standards (for both managed and unmanaged code) is embodied in the Web Services Enhancements (WSE) 3.0 toolkit, which can be downloaded free of charge from the supporting website: http://msdn2.microsoft.com/en-us/ webservices.
When you are building WCF service applications, you will not need to make direct use of the assemblies that are part of the WSE 3.0 toolkit. Rather, if you build a WCF service that makes use of an HTTP-based binding, these same WS-* specifications will be given to you out of the box (exactly which ones will be based on the binding you choose).
Named Pipes, Sockets, and P2P
As if choosing among DCOM, .NET remoting, web services, COM+, and MSMQ was not challenging enough, the list of distributed APIs continues. Programmers can also make use of additional interprocess communication APIs such as named pipes, sockets, and peer-to-peer (P2P) services. These lower-level APIs typically provide better performance (especially for machines on the same LAN); however, using these APIs becomes more complex (if not impossible) for outward-facing applications.
If you are building a distributed system involving a set of applications running on the same physical machine, you can make use of the named pipes API via the System.IO.Pipes namespace (which is new to .NET 3.5). This approach can provide the absolute fastest way to push data between applications on the same machine.
As well, if you are building an application that requires absolute control over how network access is obtained and maintained, sockets and P2P functionality can be achieved under the .NET platform using the System.Net.Sockets and System.Net.PeerToPeer namespaces, respectively.
The Role of WCF
As I am sure you already figured out from the previous few pages, the wide array of distributed technologies makes it very difficult to pick the right tool for the job. This is further complicated by the fact that several of these technologies overlap in the services they provide (most notably in the areas of transactions and security).
Even when a .NET developer has selected what appear to be the “correct” technologies for the task at hand, building, maintaining, and configuring such an application is complex at best. Each API has its own programming model, its own unique set of configuration utilities, and so forth.
Because of this, prior to .NET 3.0, it was very difficult to “plug and play” distributed APIs without authoring a considerable amount of custom infrastructure. For example, if you build your system using the .NET remoting APIs, and you later decide that XML web services are a more appropriate solution, you need to reengineer your code base.
WCF is a distributed computing toolkit introduced with .NET 3.0 that integrates these previous independent distributed technologies into a streamlined API represented primarily via the System. ServiceModel namespace. Using WCF, you are able to expose services to callers using a wide variety of techniques. For example, if you are building an in-house application where all connected machines are Windows based, you can make use of various TCP protocols to ensure the fastest possible performance. This same service can also be exposed using the XML web service–based protocol to allow external callers to leverage its functionality regardless of the programming language or operating system.

874 CHAPTER 25 ■ INTRODUCING WINDOWS COMMUNICATION FOUNDATION
Given the fact that WCF allows you to pick the correct protocol for the job (using a common programming model), you will find that it becomes quite easy to plug and play the underlying plumbing of your distributed application. In most cases, you can do so without being required to recompile or redeploy the client/service software, as the grungy details are often relegated to application configuration files (much like the older .NET remoting APIs).
An Overview of WCF Features
Interoperability and integration of diverse APIs are only two (very important) aspects of WCF. In addition, WCF provides a rich software fabric that complements the remoting technologies it exposes. Consider the following list of major WCF features:
•Support for strongly typed as well as untyped messages. This approach allows .NET applications to share custom types efficiently, while software created using other platforms (such as J2EE) can consume streams of loosely typed XML.
•Support for several bindings (raw HTTP, TCP, MSMQ, and named pipes) to allow you to choose the most appropriate plumbing to transport message data to and fro.
•Support for the latest and greatest web service specifications (WS-*).
•A fully integrated security model encompassing both native Win32/.NET security protocols and numerous neutral security techniques built upon web service standards.
•Support for sessionlike state management techniques, as well as support for one-way stateless messages.
As impressive as this list of features may be, it really only scratches the surface of the functionality WCF provides. WCF also offers tracing and logging facilities, performance counters, a publish and subscribe event model, and transactional support, among other features.
An Overview of Service-Oriented Architecture
Yet another benefit of WCF is that it is based on the design principles established by service-oriented architecture (SOA). To be sure, SOA is a major buzzword in the industry, and like most buzzwords, SOA can be defined in numerous ways. Simply put, SOA is a way to design a distributed system where several autonomous services work in conjunction by passing messages across boundaries (either networked machines or simply two processes on the same machine) using well-defined interfaces.
In the world of WCF, these “well-defined interfaces” are typically created using actual CLR interface types (see Chapter 9). In a more general sense, however, the interface of a service simply describes the set of members that may be invoked by external callers.
When WCF was designed, the WCF team did so by observing four tenets of SOA design principles. While these tenets are typically honored automatically simply by building a WCF application, understanding these four cardinal design rules of SOA can help put WCF in further perspective. The sections that follow provide a brief overview of each tenet.
Tenet 1: Boundaries Are Explicit
This tenet reiterates the fact that the functionality of a WCF service is expressed using well-defined interfaces (e.g., descriptions of each member, its parameters, and its return values). The only way that an external caller is able to communicate with a WCF service is via the interface, and the external caller remains blissfully unaware of the underlying implementation details.

CHAPTER 25 ■ INTRODUCING WINDOWS COMMUNICATION FOUNDATION |
875 |
Tenet 2: Services Are Autonomous
When speaking of services as “autonomous” entities, we are referring to the fact that a given WCF service is (as much as possible) an island unto itself. An autonomous service should be independent with regard to version issues, deployment issues, and installation issues. To help promote this tenet, we yet again fall back on a key aspect of interface-based programming. Once an interface is in production, it should never be changed (or you will risk breaking existing clients). When you need to extend the functionality of your WCF service, simply author new interfaces that model the desired functionality.
Tenet 3: Services Communicate via Contract, Not Implementation
The third tenet is yet another byproduct of interface-based programming in that the implementation details of a WCF service (which language it was written in, how it gets its work accomplished, etc.) are of no concern to the external caller. WCF clients interact with services solely through their exposed public interfaces. Furthermore, if the members of a service interface expose custom complex types, they need to be fully detailed as a data contract to ensure all callers can map the content into a particular data structure.
Tenet 4: Service Compatibility Is Based on Policy
Because CLR interfaces provide strongly typed contracts for all WCF clients (and may also be used to generate a related WSDL document based on your choice of binding), it is important to point out that interfaces/WSDL alone is not expressive enough to detail aspects of what the service is capable of doing. Given this, SOA allows us to define “policies” that further qualify the semantics of the service (e.g., the expected security requirements used to talk to the service). Using these policies, we are able to basically separate the low-level syntactic description of our service (the exposed interfaces) from the semantic details of how they work and how they need to be invoked.
WCF: The Bottom Line
Hopefully this little history lesson has illustrated that WCF is the preferred approach for building distributed applications under .NET 3.0 and higher. Whether you are attempting to build an inhouse application using TCP protocols, are moving data between programs on the same machine using named pipes, or are exposing data to the world at large using web service protocols, WCF is the recommended API to do so.
This is not to say you cannot use the original .NET distributed-centric namespaces (System.Runtime.Remoting, System.Messaging, System.EnterpriseServices, System.Web.Services, etc.) in new development efforts. In fact, in some cases (specifically if you need to build COM+ objects), you will be required to do so. In any case, if you have used these APIs in previous projects, you will find learning WCF straightforward. Like the technologies that preceded it, WCF makes considerable use of XML-based configuration files, .NET attributes, and proxy generation utilities.
With this introductory foundation behind us, we can now turn to the topic of actually building WCF applications. Again, do understand that full coverage of WCF would require a entire book, as each of the supported services (MSMQ, COM+, P2P, named pipes, etc.) could easily be a chapter unto itself. Here, you will learn the overall process of building WCF programs using both TCPand HTTP-based (e.g., web service) protocols. This should put you in a good position for future study as you see fit.

876 CHAPTER 25 ■ INTRODUCING WINDOWS COMMUNICATION FOUNDATION
Investigating the Core WCF Assemblies
As you would expect, the programming fabric of WCF is represented by a set of .NET assemblies installed into the GAC. Table 25-1 describes the overall role of the core WCF assemblies you will need to make use of in just about any WCF application.
Table 25-1. Core WCF Assemblies
Assembly |
Meaning in Life |
System.Runtime.Serialization.dll |
Defines namespaces and types that can be used for |
|
serializing and deserializing objects within the WCF |
|
framework |
System.ServiceModel.dll |
The core assembly that contains the types used to build any |
|
sort of WCF application |
|
|
These two assemblies define a number of new namespaces and types. While you should consult the .NET Framework 3.5 SDK documentation for complete details, Table 25-2 documents the roles of some of the important namespaces to be aware of.
Table 25-2. Core WCF Namespaces
Namespace |
Meaning in Life |
System.Runtime.Serialization |
Defines numerous types used to control how data is |
|
serialized and deserialized within the WCF framework |
System.ServiceModel |
The primary WCF namespace that defines binding and |
|
hosting types, as well as basic security and transactional |
|
types |
System.ServiceModel.Configuration |
Defines numerous types that provide programmatic |
|
access to WCF configuration files |
System.ServiceModel.Description |
Defines types that provide an object model to the |
|
addresses, bindings, and contracts defined within WCF |
|
configuration files |
System.ServiceModel.MsmqIntegration |
Contains types to integrate with the MSMQ service |
System.ServiceModel.Security |
Defines numerous types to control aspects of the WCF |
|
security layers |
|
|
A BRIEF WORD REGARDING CARDSPACE
In addition to System.ServiceModel.dll and System.Runtime.Serialization.dll, WCF provides a third WCF assembly named System.IdentityModel.dll. Here you will find a number of additional namespaces and types that support the WCF CardSpace API. This technology allows you to establish and manage digital identities within a WCF application. Essentially, the CardSpace API provides a unified programming model to account for various security-related details for WCF applications, such as caller identity, user authentication/authorization services, and whatnot.
We will not examine CardSpace further in this edition of the text, so be sure to consult the .NET Framework 3.5 SDK documentation if you are interested in learning more.

CHAPTER 25 ■ INTRODUCING WINDOWS COMMUNICATION FOUNDATION |
877 |
The Visual Studio WCF Project Templates
As will be explained in more detail later in this chapter, a WCF application is typically represented by three interrelated assemblies, one of which is a *.dll that contains the types that external callers can communicate with (in other words, the WCF service itself). When you wish to build a WCF service, it is perfectly permissible to select a standard Class Library project template (see Chapter 15) as a starting point and manually reference the WCF assemblies.
Alternatively, you can create a new WCF service by selecting the WCF Service Library project template of Visual Studio 2008 (see Figure 25-2). This project type automatically sets references to the required WCF assemblies; however, it also generates a good deal of “starter code,” which you will more likely than not simply delete.
Figure 25-2. The Visual Studio 2008 WCF Service Library project template
One benefit of selecting the WCF Service Library project template is that it also supplies you with an App.config file, which may seem strange since we are building a .NET *.dll, not a .NET *.exe. This file, however, is very useful in that when you debug or run your WCF Service Library project, the Visual Studio IDE will automatically launch the WCF Test Client application. This program (WcfTestClient.exe) will read the settings in the App.config file in order to host your service for testing purposes. You’ll learn more about the WCF Test Client later in this chapter.
■Note The App.config file of the WCF Service Library project is also useful in that it shows you the bare-bones settings used to configure a WCF host application. In fact, you can copy and paste much of this code into your host’s actual configuration file.

878 CHAPTER 25 ■ INTRODUCING WINDOWS COMMUNICATION FOUNDATION
In addition to the basic WCF Service Library template, the WCF project category of the New Project dialog box defines two WCF library projects that integrate Windows Workflow Foundation functionality into a WCF service as well as a template to build an RSS library (all of which are also seen in Figure 25-2). The next chapter will introduce you to the Windows Workflow Foundation, so I’ll ignore these particular WCF project templates for the time being (and I’ll leave it to the interested reader to dig into the RSS feed project template).
The WCF Service Website Project Template
Truth be told, there is yet another Visual Studio 2008 WCF-centric project template that you will find in the New Web Site dialog box, activated via the File New Web Site menu option (see Figure 25-3).
Figure 25-3. The Visual Studio 2008 web-based WCF Service project template
This WCF Service project template is useful when you know from the outset that your WCF service will make use of web service–based protocols rather than, for example, named pipes. This option can automatically create a new Internet Information Services (IIS) virtual directory to contain your WCF program files, create a proper Web.config file to expose the service via HTTP, and author the necessary *.svc file (more about *.svc files later in this chapter). In this light, the webbased WCF Service project is simply a time-saver, as the IDE will automatically set up the required IIS infrastructure.
In contrast, if you build a new WCF service using the WCF Service Library option, you have the ability to host the service in a variety of ways (custom host, Windows service, manually built IIS virtual directory, etc.). This option is more appropriate when you wish to build a custom host for your WCF service.

CHAPTER 25 ■ INTRODUCING WINDOWS COMMUNICATION FOUNDATION |
879 |
The Basic Composition of a WCF Application
When you are building a WCF distributed system, you will typically do so by creating three interrelated assemblies:
•The WCF Service assembly: This *.dll contains the classes and interfaces that represent the overall functionality you are exposing to external callers.
•The WCF Service host: This software module is the entity that hosts your WCF service assembly.
•The WCF client: This is the application that accesses the service’s functionality through an intervening proxy.
As mentioned, the WCF service assembly is a .NET class library that contains a number of WCF contracts and their implementations. The one key difference is that the interface contracts are adorned with various attributes that control data type representation, how the WCF runtime interacts with the exposed types, and so forth.
The second assembly, the WCF host, can literally be any .NET executable. As you will see in this chapter, WCF was set up in such a way that services can be easily exposed from any type of application (Windows Forms, a Windows service, WPF applications, etc.). When you are building a custom host, you will make use of the ServiceHost type and a related *.config file, which contains details regarding the server-side plumbing you wish to make use of. However, if you are using IIS as the host for your WCF service, there is no need to programmatically build a custom host, as IIS will make use of the ServiceHost type behind the scenes.
■Note It is also possible to host a WCF service using the Vista-specific Windows Activation Service (WAS). Consult the .NET Framework 3.5 SDK documentation for details.
The final assembly represents the client that is making calls into the WCF service. As you might expect, this client could be any type of .NET application. Similar to the host, client applications also typically make use of a client-side *.config file that defines the client-side plumbing.
Figure 25-4 illustrates (from a very high level) the relationship between these three interrelated WCF assemblies. As you would assume, behind the scenes are several lower-level details used to represent the required plumbing (factories, channels, listeners, etc.). These low-level details are most often hidden from view; however, they can be extended or customized if required. Thankfully, in most cases, the default plumbing will fit the bill.
Figure 25-4. A high-level look at a typical WCF application
It is also worth pointing out that the use of a server-side or client-side *.config file is technically optional. If you wish, you can hard-code the host (as well as the client) to specify the necessary

880CHAPTER 25 ■ INTRODUCING WINDOWS COMMUNICATION FOUNDATION
plumbing (endpoints, binding, addresses, etc.). The obvious problem with this approach is that if you need to change the plumbing details, you will be required to recode, recompile, and redeploy a number of assemblies. Using a *.config file keeps your code base much more flexible, as changing the plumbing is as simple as updating the file’s content and restarting the application.
The ABCs of WCF
Hosts and clients communicate with each other by agreeing on the ABCs, a friendly mnemonic for remembering the core building blocks of a WCF application, specifically address, binding, and contract.
•Address: The location of the service. In code, this is represented with a System.Uri type; however, the value is typically stored in *.config files.
•Binding: WCF ships with a number of different bindings that specify network protocols, encoding mechanisms, and the transport layer.
•Contract: A description of each method exposed from the WCF service.
Do understand that the ABC abbreviation does not imply that a developer must define the address first, followed by binding, and ending with the contract. In many cases, a WCF developer begins by defining a contract for the service, followed by establishing an address and bindings (but any order will do, so long as each aspect is accounted for). Before we build our first WCF application, here is a more detailed walk-through of the ABCs.
Understanding WCF Contracts
The notion of a contract is the key to building a WCF service. While not mandatory, the vast majority of your WCF applications will begin by defining a set of .NET interface types that are used to represent the set of members a given WCF type will support. Specifically, interfaces that represent a WCF contract are termed service contracts. The classes (or structures) that implement them are termed service types.
WCF service contracts are adorned with various attributes, the most common of which are defined in the System.ServiceModel namespace. When the members of a service contract contain only simple data types (such as numerical data, Booleans, and string data) you can build a complete WCF service using nothing more than the [ServiceContract] and [OperationContract] attributes.
However, if your members expose custom types, you will need to make use of types in the
System.Runtime.Serialization namespace (see Figure 25-5) of the System.Runtime.Serialization. dll assembly. Here you will find additional attributes (such as [DataMember] and [DataContract]) to fine-tune the process of defining your interface types.
Strictly speaking, you are not required to use CLR interfaces to define a WCF contract. Many of these same attributes can be applied on public members of a public class (or structure). However, given the many benefits of interface-based programming (polymorphism, elegant versioning, etc.), it is safe to consider using CLR interfaces to describe a WCF contract as a best practice.

CHAPTER 25 ■ INTRODUCING WINDOWS COMMUNICATION FOUNDATION |
881 |
Figure 25-5. System.Runtime.Serialization defines a number of attributes used when building WCF data contracts.
Understanding WCF Bindings
Once a contract (or a set of contracts) has been defined and implemented within your service library, the next logical step is to build a hosting agent for the WCF service itself. As mentioned, you have a variety of possible hosts to choose from, all of which must specify the bindings used by remote callers to gain access to the service type’s functionality.
Choosing a set of bindings is one area that makes WCF development quite different from .NET remoting and/or XML web service development in that WCF ships with a number of binding choices, each of which is tailored to a specific need. If none of the out-of-the-box bindings fits the bill, it is possible to create your own by extending the CustomBinding type (something we will not do in this chapter). Simply put, a WCF binding can specify the following characteristics:
•The contracts implemented by the service
•The transport layer used to move data (HTTP, MSMQ, named pipes, TCP)
•The channels used by the transport (one-way, request-reply, duplex)
•The encoding mechanism used to deal with the data itself (XML, binary, etc.)
•Any supported web service protocols (if permitted by the binding) such as WS-Security, WSTransactions, WS-Reliability, and so on
Let’s take a look at our choices.
HTTP-Based Bindings
The BasicHttpBinding, WSHttpBinding, WSDualHttpBinding, and WSFederationHttpBinding options are geared toward exposing contract types via XML web service protocols. Clearly, if you require the furthest reach possible for your service (multiple operating systems and multiple programming architectures), these are the bindings to focus on, because all of these binding types encode data based on XML representation and use HTTP on the wire.