Buy this Book
Print Book $44.99 PDF $30.99 Read it Now!
Print Book £31.99
Add to UK Cart
Reprint Licensing

Learning WCF
Learning WCF A Hands-on Guide

By Michele Leroux Bustamante
Book Price: $44.99 USD
£31.99 GBP
PDF Price: $30.99

Cover | Table of Contents


Table of Contents

Chapter 1: Hello Indigo
Windows Communication Foundation (WCF), formerly code-named "Indigo," is a new distributed messaging platform released with Windows Vista as part of the .NET Framework 3.0. The .NET Framework 3.0, formerly code-named "WinFX," includes four pillars: Windows Presentation Foundation (WPF), Windows Workflow Foundation (WF), Windows Communication Foundation (WCF), and Windows CardSpace. As illustrates, .NET 3.0 relies on the .NET Framework 2.0 (.NET 2.0) and is supported on Windows XP, Windows Vista, Windows Server 2003, and Windows "Longhorn" Server platforms.
Figure 1-1: Platform support for WCF
Why release yet another technology for distributed messaging? Unlike its predecessors, WCF is a truly service-oriented, loosely coupled, and interoperable platform. It simplifies service-oriented system design by removing the design dependencies that traditionally exist between how you access business functionality and the actual implementation of that business functionality. WCF promotes loose coupling not only between services and the functionality they expose, but also for choice of protocol, message encoding formats, and hosting environment. For example, services can be accessed over a variety of supported protocols, including named pipes, TCP, HTTP, and MSMQ. WCF also supports all of the core and emerging web service standards, which makes it a highly interoperable platform. Messages can always be represented in a format consistent with a set of well-adopted standards to communicate with other platforms.
Besides these modern characteristics, what's even more interesting is that you can now choose a single communication stack to gain access to the system services necessary to build a distributed system. WCF unifies the disparate programming paradigms you have previously used on the Windows platform to achieve similar goals—namely .NET Remoting, ASP.NET Web Services (ASMX), and Enterprise Services. WCF provides all of the plumbing for security, transactions, and reliable messaging over any protocol. Only Enterprise Services came close to providing all of these features in a single stack, but your component design was coupled to the technology and limited to TCP communication (thus, not interoperable).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Service Oriented Architecture
What is Service Oriented Architecture (SOA)? There have been so many interpretations of this throughout the years that it seems important to establish a common understanding before I discuss WCF as an SOA platform. The Organization for the Advancement of Structured Information Standards, better known as OASIS (), provides this official definition in its Reference Model for Service Oriented Architecture:
Service Oriented Architecture (SOA) is a paradigm for organizing and utilizing distributed capabilities that may be under the control of different ownership domains.
You can find the OASIS SOA Reference Model documentation at .
You might add to this definition by stating that SOA relies on the ability to access chunks of business functionality, potentially owned by different applications, departments, companies, or industries. Notice that this description does not specify the mechanism through which those chunks of functionality are accessed. In fact, the term "service" isn't even mentioned, although it is implied.
The road to SOA has been a progressive one—driven by the need to improve how developers build complex enterprise systems. The principals behind enterprise system design are far-reaching: from object-oriented programming to component-oriented programming to service-orientation. All three approaches share the common goal of encapsulation and reuse. With object-oriented programming, classes encapsulate functionality and provide code-reuse. To share classes between distinct applications or binaries, however, you have to copy the code, as shown in .
Figure 1-2: Duplicating types between components
Component-oriented programming introduces the concept of sharing binaries that encapsulate reusable classes. Initially, this was limited to the same machine until distribution was made possible with technologies like COM and DCOM, CORBA, and later Enterprise Java Beans (EJBs) and .NET Remoting. Although these technologies accomplish distribution in different ways the result is the same—binary components are activated over process and machine boundaries (see ).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
WCF Services
WCF services are the new distributed boundary in an enterprise application—with an emphasis on SOA. In the past, you had to deliberate between Enterprise Services, .NET Remoting, or ASMX to distribute and reuse functionality, WCF provides you with a single programming model to satisfy the needs of any equivalent distribution scenario. With WCF, you can cross process, machine, and corporate boundaries over any number of protocols; you can expose interoperable web services; and you can support queued messaging scenarios. I'll take you through a few examples where WCF is deployed in lieu of earlier technologies.
illustrates an intranet scenario where a WCF service is invoked within an application domain over TCP protocol. In this scenario, the client needed to reach remote services and authenticate with Windows credentials, and didn't require interoperability. As such, the service is accessible over TCP using binary serialization for better performance, and supports traditional Windows authentication using NTLM or Kerberos. In the past, this may have been achieved using Enterprise Services (or possibly .NET Remoting although security features are not built-in).
Figure 1-11: Deploying WCF services on the intranet
illustrates an Internet scenario where multiple web services are exposed—one supporting legacy protocols (Basic Profile), another supporting more recent protocols (WS*). With WCF, a single service can be defined and exposed over multiple endpoints to support this scenario.
Figure 1-12: WCF services exposed on the Internet
In you can see WCF implemented at several tiers—behind the firewall to support an ASP.NET application, and outside the firewall for smart client applications. Again, the same service can be exposed over multiple protocols without duplicating effort or switching technologies.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Fundamental WCF Concepts
At its core, WCF is a development platform for service-oriented applications. As I mentioned earlier, WCF is part of the .NET Framework 3.0, which comprises a set of new assemblies that rely on the .NET Framework 2.0. System.ServiceModel is the assembly that contains core functionality for WCF, which explains why the WCF platform is often called the service model. Any project that exposes or consumes WCF services must reference the System.ServiceModel assembly, and possibly other supporting assemblies.
Before you can begin to do interesting things with the service model, it helps to understand the core features that make it possible to create, host, and consume services. In this section, I will briefly summarize some of the concepts that will be elaborated on in this chapter, to help you on your way.
All enterprise applications at some point must make remote calls across process and machine boundaries. This is handled by sending messages between applications. The format of the message is what determines an application's ability to communicate with other applications. Remote procedure calls (RPC) and XML messaging formats are two common ways for applications to communicate.
RPC calls are used to communicate with objects (components) across boundaries—for example, calls from a client application to a remote object living in another process. RPC calls are marshaled by converting them to messages and sending them over a transport protocol such as TCP. When the message reaches its destination, it is un-marshaled and converted into a stack frame that invokes the object. This is all usually handled transparently through a client proxy and stub at the destination. Both proxy and stub know how to construct and deconstruct messages. This process is known as serialization and deserialization.
illustrates the serialization and deserialization process (often just called serialization) from a high level. As I mentioned, the transport carries a message according to the agreed-upon format of both the client and remote application. As far as the client is concerned, it is usually working with a proxy that looks like the remote object. When a method is invoked at the client, the proxy invokes underlying plumbing of the technology (for example, Enterprise Services or .NET Remoting) to serialize the outgoing message. The remote application usually listens for messages on a particular port, and as they arrive, deserializes those messages (using the same technology) to build a stack frame and invoke the appropriate method on the remote object. The method return is likewise serialized by the underlying plumbing and returned to the client, at which time the plumbing deserializes the message and constructs a stack frame for the response. RPC communication like this comes in many flavors, and each flavor is generally not compatible with another—that's why RPC is not interoperable.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating a New Service from Scratch
You're about to be introduced to the WCF service. This lab isn't your typical "Hello World"—it's "Hello Indigo"! In this lab, you will learn how to build a new WCF service and in the process learn the minimum requirements of service development and consumption. Here's a short list of things you'll accomplish:
  • Create a new service contract and service implementation
  • Programmatically configure a service host, its endpoints, and bindings
  • Create a client application and open a client channel proxy to invoke the service
Now, before you start thinking "been there, done that," this simple lab will be slightly different because I'm going to give you some practical design tips that ensure configurability and appropriate decoupling of service, host, and client. In addition, I'll be diving deeper into basic concepts such as services, service contracts, endpoints, bindings, ServiceHost, and channels.
In this first lab, you will create a new solution with three projects: a service, a host, and a client. When you run the service host, you'll expose a single service endpoint. The client application will access service operations through that endpoint. You'll host the service in a console application and invoke the service using a manually constructed proxy. This lab will teach you the basic requirements for creating, hosting, and consuming a service with WCF.

Section 1.4.1.1: Creating a new service

The first thing you will do is create a new service contract with a single operation and implement this contract on a new service type.
  1. In this lab, everything begins from scratch, so you'll start by creating a new Visual Studio solution. Open a new instance of Visual Studio 2005. Select File → New → Project, and from the New Project dialog, create a new Blank Solution in the <YourLearningWCFPath>\Labs\Chapter1 directory. Name the solution ServiceFromScratch. Click OK to create the empty solution.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Generating a Service and Client Proxy
In the previous lab, you created a service and client from scratch without leveraging the tools available to WCF developers. Although this helps you to understand the raw requirements for sending messages between clients and services, in reality, developers need tools to be productive. This time around, I'll show you how to use several such tools that help you to generate services, access metadata, create configuration settings, and generate proxies. Specifically, you'll use the following:
  • Visual Studio service templates
  • Service Configuration Editor
  • ServiceModel Metadata Utility (SvcUtil)
The primary goal of the lab in this section will be to improve your productivity for building clients and services, but several other concepts will be discussed in the process. To begin with, you'll use declarative configuration settings instead of code to configure the service host and client. To enable proxy generation, you'll access service metadata, which involves enabling a service behavior. In addition, you'll learn more about service configuration settings for base addresses, endpoints, bindings and behaviors.
After you complete the lab, I'll spend some time discussing these concepts.
In this lab, you will generate service code using two approaches: by adding a service to an existing host and by generating a new service library, both using Visual Studio templates. To configure service endpoint for the host, this time you'll use the Service Configuration Editor. To generate client proxies and related configuration you'll use the ServiceModel Metadata Utility (SvcUtil). Both of these tools are available through the Solution Explorer in Visual Studio.
Visual Studio extensions for WCF will be part of the next release of Visual Studio, code-named "Orcas." As such, the user interfaces and features of these extensions may change from the time of this writing.

Section 1.5.1.1: Using the WCF Service template

Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Hosting a Service in IIS
How messages reach a service endpoint is a matter of protocols and hosting. IIS can host services over HTTP protocol, the Windows Activation Service (WAS) can support others such as TCP and named pipes, and self-hosting can support many protocols and includes several deployment options such as console or Windows Forms applications and Windows services. Selecting a hosting environment has nothing to do with service implementation, but everything to do with service deployment and overall system design.
This lab will show you how to host an existing service type as part of a web site hosted in IIS. In the process, I'll also be illustrating other extended concepts such as:
  • The WCF Service web site template
  • Message-based activation
  • Additional metadata behavior settings
  • Exporting service descriptions
  • Consuming service description documents to generate client code
As always, after the lab I'll describe some of these features in greater detail.
For this lab, you will work with an existing solution that contains a completed service library and shell client application. Using Visual Studio templates, you'll create a new IIS web site project that contains a service and modify it to host a preexisting service. To consume the service, you'll generate a client proxy from static service documentation exported using SvcUtil.

Section 1.6.1.1: Creating a WCF Service web site

The first thing to do is create a WCF-enabled web site using the WCF Service template, which is new to WCF. When services are added to a web site, the supplied sample service is accompanied by a .svc file, the web server endpoint.
  1. Open the startup solution for the lab, located at <YourLearningWCFPath>\Labs\Chapter1\IISHostedService\IISHostedService.sln. This solution contains a copy of the HelloIndigo project from earlier labs and a shell client application.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Exposing Multiple Service Endpoints
So far in this chapter, I have shown you different ways to create services, how to expose a service endpoint and metadata exchange endpoint, how to generate client proxies, how to work with metadata, and how to configure service behaviors. In this section, I'll place the emphasis on endpoints, binding configuration, and allocation of assemblies for a more complex solution.
WCF includes a number of standard bindings that allow you to quickly configure a service for a particular set of protocols. Clients must use compatible protocols when they communicate with each endpoint. Services can expose multiple endpoints for the same service contract in order to expose functionality over different protocols. For example, a service may be called by internal clients over TCP, but by external clients over HTTP. In addition to supporting different protocols, internal and external clients may not have access to the same service contracts. Some operations may be allowed only by clients within the domain, while others are publicly available to remote clients on the Internet.
In this lab you will configure multiple endpoints for a service to support different endpoint and binding configurations. In the process you'll explore the following concepts:
  • Hosting multiple services
  • Configuring multiple endpoints for a service
  • Accessing a service from a Windows client application
  • Initializing proxies from multiple endpoint and binding configurations
  • Comparing proxy generation to sharing types between services and clients
In this lab, you'll modify an existing solution to implement a service contract and an administrative contract on two distinct services. You'll then host each service in the same host process, a console application. An internal client presumed to be behind the firewall will consume each service using network protocols such as TCP and named pipes. This client will have access to service operations exposed by the service contract and administrative contract. An external client, presumed to be accessing the service over the Internet will have access only to operations exposed by the service contract over HTTP. The internal client will share class libraries to access service contracts, while the external client will use traditional methods for generating service proxies.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Summary
This chapter covered a lot of ground, beginning with a look at the purpose of WCF, the problems it solves and its alignment with SOA, through discussion of the fundamentals developers should know before they begin working with WCF. I also touched on the overall architecture of WCF, though this is covered in greater detail in . Through hands-on practice and discussion you should be comfortable now with the following concepts:
  • Defining service contracts and services
  • Hosting services in a console application or in IIS
  • Exposing endpoints for a service using various standard bindings
  • Working with Visual Studio templates and WCF tools to improve productivity
  • Working with service metadata and configuring related service behaviors
  • Generating proxies to invoke services
Of course, the next step is to start diving into the details of service contracts, bindings, and hosting. In addition, you'll need to learn more about service behaviors and messaging protocols that handle instancing, throttling, reliability, security and exception handling.
Since service contracts are central to defining the messages exchanged between clients and services, the next chapter will focus on this subject. In , I'll explain how to approach service contract design, how to work with complex types and how to control serialization on many levels. In the process of reading , you'll further solidify your knowledge of the fundamental concepts touched on in this chapter.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Contracts
In , you were introduced to fundamental WCF concepts, including how to create and consume a service, how to host a service and expose endpoints where it can be reached by clients, how to support metadata exchange so that clients can generate service contracts, and how to work with client proxies to invoke service operations. In , you also learned the importance of service metadata, which is shared with clients through a WSDL document. Service metadata includes all of the necessary information for a client to invoke service operations, including:
  • The address where messages should be sent
  • The protocols supported by the service, including transport protocol, message encoding format, and other messaging protocols
  • A list of service operations and the required information to be passed to or returned from those operations
The service contract is the hub of this metadata—defining a set of operations, parameters, and return values. Each service contract represents a group of logically related operations that are exposed through endpoints. Endpoints describe the address where messages can be sent to reach those operations and the other required protocols to process those messages. Services may implement one or more service contracts, and thus may have different logical groupings of operations, but all of this is still ultimately included in the WSDL document.
As discussed in , clients communicate with services by exchanging messages that are serialized on the wire and deserialized into CLR types at each end. In the simplest scenario, client and service developers work only with objects, and all the serialization magic happens somewhere down below in the plumbing. WCF provides this plumbing. WSDL describes the protocols required to reach the service, clients use proxies to communicate with the service, and messages just happen. There are times, however, when developers must exercise more control over service contract design over message serialization and over the choice of protocols. For these scenarios, it helps to understand the options available.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Messaging Protocols
Regardless of the transport protocol (TCP, named pipes, MSMQ, or HTTP), messages are represented by the runtime in the same way, as a Message type from the System.ServiceModel.Channels namespace. The Message type is essentially a runtime representation of a SOAP message. When serialized, the wire format of the message complies with SOAP 1.1 or 1.2 depending on the binding configuration for the endpoint.
The Message type also holds addressing headers, consistent with the WS-Addressing standard. These are serialized with the message if the binding supports addressing. When the service model processes messages, other standards may also come into play to add features such as security and reliability. The service model supplies channels for many of the emerging protocols, usually referred to as WS* (pronounced WS-Star). Through bindings (discussed in ), you can enable features that use these protocols. In short, WCF relies on standards to serialize messages; here I'll provide you with an overview in this chapter of the core standards that will be elaborated on throughout this book.
Keep in mind that you will rarely need to worry about the details of messaging protocols because WCF implements them in the plumbing of the service model.
SOAP was introduced in 1999—a short specification that finally made it possible to standardize how messages are exchanged on the wire, using XML at its core to support interoperability. A SOAP message contains message headers and a message body. The basic XML structure for a SOAP message contains a root Envelope element with two child elements: an optional Header element and a required Body element as follows:
<Envelope>
  <Header>
    <!-- message headers -->
  </Header>

  <Body>
    <!-- message body elements -->
  </Body>
</Envelope>
The message body is required. It contains data custom to an application. For example, when a client invokes a service operation, a request message is sent containing the data required by the operation. For each parameter, a separate XML element is provided within the message body. These elements are ultimately deserialized into the appropriate associated CLR types. If the operation returns a value, or if there are any
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Service Description
While messaging protocols are responsible for message serialization formats, there must be a way to capture the protocols required to communicate between clients and services. In , you worked with WSDL documents, which describe the requirements of a service, including the operations associated with each endpoint and the protocols used by each endpoint. In this section, I'll discuss the relationship between the service description, message exchange patterns, and WSDL.
Services may implement one or more endpoints, each possibly supporting a different set of operations, messaging protocols, message encoding formats, and transport protocols. Collectively, this information about a service is part of the service metadata, as I discussed in . This can also be referred to as the service description. In fact, WCF represents this information at runtime as a ServiceDescription type from the System.ServiceModel namespace.
The ServiceDescription type is a runtime representation of all service endpoints and their associated service contracts, the binding configuration that describes protocol support, and local behaviors that affect how the service model processes messages. It is the ServiceDescription type that is used to generate the WSDL document, and it also supports dynamic metadata exchange so that clients can discover at runtime what protocols are required to invoke service operations. Recall from that SvcUtil is used to generate proxies for clients by consuming a WSDL document or using dynamic metadata exchange, which is based on WS-MetadataExchange protocol (see ).
Figure 2-1: SvcUtil can generate proxies from a WSDL document or by using dynamic metadata exchange
SOAP protocol defines the basic requirements to allow platforms to process SOAP messages, extracting headers and body elements to perform work. Obviously, to understand the header and body elements, the platform also needs to know the format of those elements. That's where WSDL comes in.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
WCF Contracts and Serialization
So far I've talked about the standards behind it all, but in fact WCF hides most of this from the developer by providing a programming interface for designing service contracts and controlling the message format. Application messaging requirements are described by contracts in WCF. There are three types of formal contracts that clients and services rely on to control messaging. The service contract describes the operations exposed by a particular service endpoint. Each operation, through parameters and return types, defines the format of request and response messages. A data contract describes how a complex type is serialized as part of a message. Data contracts are the preferred way to include complex types in a service contract. A message contract provides control over the format of the entire SOAP message, including support for custom message headers and individual body elements that can be described by data contracts.
By default, message serialization is handled by the DataContractSerializer. This is a new serializer introduced with WCF that requires all types to opt-in their exact requirements for serialization—in compliance with SOA tenets. The DataContractSerializer can serialize data contracts, message contracts, and other serializable types such as those marked with the SerializableAttribute or those that inherit IXmlSerializable (see ). It is also possible to tell WCF to use the XmlSerializer that ASP.NET web services use (useful only in rare cases). The XmlSerializer provides much less control over serialization in that all public members are serialized. I'll discuss these and other serialization concepts later in this chapter.
Figure 2-2: The DataContractSerializer can serialize message contracts, data contracts, and other serializable types
As you complete the labs in this chapter, you will practice working with service contracts, data contracts, message contracts, other serializable types, and raw messages. Throughout, I'll provide you with practical design tips, discuss approaches in contract versioning, and teach you how to override default serialization behaviors.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Service Contracts
A service contract describes the operations supported by a service, the message exchange pattern they use, and the format of each message. The service contract is also the main driver for generating a service description. A valid WCF service implements at least one service contract. The following attributes play an important role in defining service contracts: ServiceContractAttribute, OperationContractAttribute, and MessageParameterAttribute. Collectively, these attributes provide control over the way messages are formatted.
In this section, the first thing you'll do is complete a lab that exercises each of these attributes. Following the lab, I'll summarize the features of each of these attributes and their roles in service contract design. In the process, I'll also cover other related concepts such as:
  • How service contracts map to WSDL elements
  • Service contract design
  • Operations signatures and messages
  • Versioning scenarios
In this lab, you will begin with an existing solution that includes three projects: a service, a host, and a client. The solution includes a working implementation of a very simple service contract, and you will edit this implementation to exercise more control over the service contract to control the resulting service description. In the process, you'll also test service contract version tolerance.

Section 2.4.1.1: Exploring service contract compatibility

In the first part of this lab, you'll modify an existing service contract to use an explicit contract name and namespace while testing compatibility between proxy and service as changes are made.
  1. Start by opening the solution for this lab: <YourLearningWCFPath>\Labs\Chapter2\ServiceContracts\ServiceContracts.sln.
  2. Test the solution first to see that it works. Compile the solution and run the Host project followed by the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Data Contracts
A data contract describes how CLR types map to XSD schema definitions. Data contracts are the preferred way to enable serialization of complex types included in operation signatures as parameters or return values. You create a data contract by applying theDataContractAttribute to a type. To include members in serialization, you decorate them with the DataMemberAttribute; this is an opt-in process that has nothing to do with visibility of members (public, protected, private). By default, serialization is handled by the DataContractSerializer, a new serializer for WCF that succeeds the XmlSerializer used for earlier technologies such as ASMX.
In this section, you will become acquainted with the key features of data contracts and common serialization practices, including the following:
  • How to apply data contract attributes to exercise control over type serialization
  • Version tolerance and data contract versioning techniques
  • Implementing IExtensibleDataObject to support version tolerance
  • How to work with polymorphic types in the service contract
  • How enumerations, arrays, and collections are serialized
First you'll complete a lab that illustrates many of these scenarios, and then I'll explain the related attributes and features in greater detail.
For this lab you will modify a preexisting type, turning it into a data contract so that it can be included in the service contract. Using the DataContractAttribute and the DataMemberAttribute, you will control type serialization through the DataContractSerializer. You'll also test data contract version tolerance and implement the IExtensibleData interface in support of versioning.

Section 2.5.1.1: Creating a data contract

In this part of the lab, you'll turn a complex type into a data contract so that it can be included in a service contract, and then take a look at the XSD schema produced for the type in the WSDL document.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Message Contracts
When you define a service contract, you traditionally describe a set of operations that may include a parameter list and a return value. Each operation is ultimately linked to a request, a response message, or both in the service description, depending on the message exchange pattern for the operation. A message contract is a more formal way to describe operation messages. It gives you more granular control over the actual structure of the message (the SOAP envelope), which can be important for the web service savvy. You can use message contracts as the only parameter and as the return type for any operation, in lieu of a parameter list or return value-comprising data contracts or serializabletypes.
Data contracts are still very important to the message contract. In fact, message contracts internally describe what would have been a parameter list or return value. The value added by message contracts is in their ability to exercise greater control over how message headers and message body elements are serialized. The following attributes will be introduced in this section as I show you how to work with message contracts: MessageContractAttribute, MessageHeaderAttribute, and MessageBodyMemberAttribute.
In this lab, you will modify an existing service contract that uses traditional operation signatures and replace that approach with message contracts. A new message contract type will be created for each message. Each message contract will encapsulate the parameters or return values applicable to the message. In addition, you'll learn how to create a custom message header.

Section 2.6.1.1: Creating message contracts

  1. Open the startup solution for this lab, located in <YourLearningWCFPath>\Labs\ Chapter2\ MessageContracts\MessageContracts.sln.
  2. Take a look at the existing service contract first. Go to the GigManager project and open GigManagerService.cs. The operations in the service contract look like this:
    [OperationContract]
    void SaveGig(LinkItem item);
    
    [OperationContract]
    LinkItem GetGig( );
    
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Approaches to Serialization
At this point in the chapter, you have learned how to create a service contract, expose complex types as data contracts, and create message contracts for greater control over message format. These are the serialization staples for WCF services. In a perfect situation, when you go about designing your services, you can create data contracts representative of the types used by service operations; you'll let the service description be generated from the service contract and these data contract types; and you won't ever have to look at XML. But things aren't always that simple.
Despite the fact that data contracts are the preferred format for exposing complex types in the service contract, there are times when other approaches to serialization may be necessary. Here are some scenarios you may need to consider:
  • Exposing preexisting types that implement the SerializableAttribute and ISerializable
  • Conforming messages to a specific XSD schema
  • Mapping incoming messages to existing types that are not serializable or that don't match a predefined schema
In this section, I'll discuss other serialization concepts and explain practical approaches to these scenarios.
Although the focus has been on data contracts thus far, the following types can all be serialized through the DataContractSerializer:
  • Data contracts are complex types decorated with the DataContractAttribute or the CollectionDataContractAttribute.
  • Serializable types are types decorated with the SerializableAttribute that optionally implement the ISerializable interface for custom serialization, and types that implement IXmlSerializable.
  • Message contracts are complex types decorated with the MessageContractAttribute and containing only data contracts or serializable types as header and body members.
Any of these types can be included in a service contract, but your choice of serializer may affect the resulting message format.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Message Type
There are a number of scenarios where you may need to get your hands on raw messages that pass between client and service. The service model provides you with a Message type with direct access to message headers, message body elements, and other properties associated with a SOAP message. Untyped messages like this make it possible to develop generic service operations that do not do the work of serialization and deserialization; instead, they act as a pass-through for messages. Web service intermediaries and content-based routers are examples of service endpoints that can accept any message while still inspecting appropriate message headers or content and forwarding to the rightful recipient.
In this section, I'll introduce you to several advanced concepts related to the use of untyped messages including:
  • Defining a service contract that works with untyped messages
  • Using the Message type to create and process messages
  • Encapsulating functionality by inheriting Message
  • Working with the MessageHeader type
For this lab, you will convert an existing service to work with raw messages. In the process you'll learn how to create messages from scratch, how to process incoming untyped messages, and how to work with the serialization process between messages and CLR types. The purpose of this lab is to illustrate several aspects of raw message serialization, using the Message type. Later in this section of the chapter, I'll discuss some more practical uses for working with raw messages as well.

Section 2.8.1.1: Using untyped messages in the service contract

In the first part of this lab you'll open a preexisting solution that uses message contracts and data contracts at the client and service. You're going to change the service to expose operations that use untyped messages.
  1. First, open the startup solution for this lab located in <YourLearningWCFPath>\Labs\Chapter2\RawMessages\RawMessages.sln
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Summary
This chapter focused on contracts and serialization to provide you with the tools you need to design service contracts and where applicable, exercise greater control over serialization. You learned about classic code-first approaches to building a service description, which means relying on service contracts, data contracts, message contracts and other serializable types to produce WSDL. You also learned some techniques that can be applied to contract-first scenarios, where the WSDL or XSD schema is provided up front and your service must conform. Namely, using IXmlSerializable you can respect preexisting XSD schema while still building a service contract to frame the operations available at an endpoint.
Things you should take away from this chapter include the following recommendations:
  • Where possible, try to use code-first approaches, which will improve your productivity in designing services.
  • Develop a consistent set of naming conventions that you apply across all of your services, including those for the target namespace, the schema namespace, and operation and parameter names.
  • Decide whether you will use strict or non-strict approaches to versioning and follow the guidelines I have provided for achieving those results.
  • Use message contracts if you need custom headers.
  • Consider IXmlSerializable for situations where the XSD schema has been provided in advance, for example by standards organizations in your industry.
Now that you have learned almost all there is to know about contracts, it's time to dive in and discuss the various bindings provided by the service model to control how the communication channel is built. The next chapter will focus on how to work with the standard bindings and how to customize those bindings to meet the needs of some typical application scenarios. You'll learn how to build intranet services, Internet web services, and control message-encoding formats, and how to configure callbacks. You'll also learn how to build custom bindings when the standard bindings aren't meeting the needs of your scenario.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Bindings
So far in this book, you have learned how to create and consume services; how to design and implement service contracts; how to host services and configure service endpoints; and learned various ways to generate proxies for clients to invoke service operations. In the process, you have worked with a few of the standard bindings such as NetTcpBinding and BasicHttpBinding to establish communication channels between clients and services. Although I've shown you how to select a binding for a service endpoint, and I've discussed how bindings determine the protocols used to communicate, I haven't begun to show you scope of what bindings can do. In this chapter, I'll focus on bindings, explaining how to choose from the different standard bindings, how to customize them to meet your deployment needs, and how to create custom bindings to address special situations where the standard bindings don't satisfy your requirements. In the process, you'll learn how to work with web service bindings and connection-oriented bindings, how to implement two-way communication scenarios, and how to handle large messages.
Every service endpoint is associated with a particular binding. A binding is a runtime type that derives from the common base type Binding. Bindings describe the transport protocol, message-encoding format and other messaging protocols for the communication channel. In this section, I'm going to introduce you to each of the standard bindings, explain the features provided by the service model for bindings, and explain how binding configuration builds the communication channel.
In , I showed you how to configure an endpoint and its associated binding in two ways:
  • Declaratively, using service model configuration settings
  • Programmatically, by adding endpoints to the ServiceHost
Declaratively, you set the binding property for each service or client <endpoint> by referring to it by its configuration name, as shown here:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
How Bindings Work
Every service endpoint is associated with a particular binding. A binding is a runtime type that derives from the common base type Binding. Bindings describe the transport protocol, message-encoding format and other messaging protocols for the communication channel. In this section, I'm going to introduce you to each of the standard bindings, explain the features provided by the service model for bindings, and explain how binding configuration builds the communication channel.
In , I showed you how to configure an endpoint and its associated binding in two ways:
  • Declaratively, using service model configuration settings
  • Programmatically, by adding endpoints to the ServiceHost
Declaratively, you set the binding property for each service or client <endpoint> by referring to it by its configuration name, as shown here:
// service endpoint
<endpoint address="HelloIndigoService" binding="basicHttpBinding"
contract="Host.IHelloIndigoService" />

// client endpoint
<endpoint address="http://localhost:8000/HelloIndigo/HelloIndigoService"
binding="basicHttpBinding" contract="Client.localhost.IHelloIndigoService" />
Programmatically, you construct a binding instance and associate it with endpoints added to the ServiceHost or client proxy. In either case, you create an instance of the desired binding by its CLR type, for example:
BasicHttpBinding basicBinding = new BasicHttpBinding(  );
NetTcpBinding tcpBinding = new NetTcpBinding(  );
Each binding is represented at runtime by its CLR type, but when you set the binding property for declarative configuration you refer to the binding by its configuration name.
I'm making the distinction between the CLR type name and configuration name so that you can relate them as you read this book. In the book, I will usually refer to bindings in a discussion by the proper CLR type name, even while describing a declarative example that uses the configuration name.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Web Service Bindings
Web services make it easy to expose system functionality to remote clients. For one, web services are typically exposed over HTTP or HTTPS through ports that administrators allow to be open. More importantly, web services provide an interoperable way to communicate using standards such as SOAP, WSDL, and XML, making them the ideal conduit for communication between trading partners, independent systems, and heterogeneous environments.
Several of the standard WCF bindings can be used to expose web services, including BasicHttpBinding, WSHttpBinding, WSDualHttpBinding, and WSFederationHttpBinding. BasicHttpBinding supports SOAP 1.1 by default, whereas the other three bindings default to SOAP 1.2 with support for WS-Addressing among other protocols.
This section will focus on the fundamental web service bindings, BasicHttpBindng and WSHttpBinding. The first thing you'll do is complete a lab that exercises each binding. After the lab, I'll explain the following concepts:
  • Binding features and their applicability to these bindings
  • Scenarios in which each binding is appropriate
  • MessageVersion settings
  • Serialization differences for SOAP 1.1 and SOAP 1.2
  • Alternatives for exposing a single service over two bindings
In this lab, you'll exposed web service endpoints for a service that lets users upload photos and save a record of each upload to a database. You'll provide endpoints for SOAP 1.1 and SOAP 1.2 with WS-Addressing in order to support clients using web service platforms with different capabilities.

Section 3.2.1.1: Exposing multiple web service endpoints

The first thing you will do in this lab is open an existing solution and expose endpoints for an existing service using BasicHttpBinding and WSHttpBinding. You'll see how to configure multiple .svc endpoints in a web host.
  1. Open the startup solution for this lab at
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Connection-Oriented Bindings
Connection-oriented transports such as named pipes and TCP are ideal for crossing process and machine boundaries, and yield greater performance and reliability than HTTP transport. Named pipes support reliable and sequential data transfer (FIFO) via memory-mapped files. Communications may be handled over one-way pipes (caller writes, receiver reads), or half-duplex (both caller and receiver read and write to the pipe—just not at once). TCP sockets, on the other hand, provide endpoints through which caller and receiver communicate, as a full-duplex implementation (two-way).
WCF provides standard bindings for both of these protocols. NetNamedPipeBinding wraps communication over named pipes, and limits that communication to the same machine for security reasons (you can be certain your named pipe endpoints cannot be called remotely). NetTcpBinding enables TCP socket communication for RPC and streaming scenarios. In this section, I'll show you how to work with NetNamedPipeBinding and NetTcpBindng endpoints and discuss scenarios in which each binding is most applicable. You'll complete a lab first to put them to use, and then I'll dig into the details.
NetPeerTcpBinding is also based on the TCP protocol, offering peer-to-peer communications. This binding has implications beyond WCF and is too broad to cover in this book.
In this lab, you will turn a two-tier web application into an n-tier, service-oriented application by wrapping business functionality into a WCF service and consuming it from the application. At first, you'll invoke the service using named pipes, and then simulate distributing the same functionality across machines with TCP sockets. To achieve this, you'll use NetNamedPipeBinding and NetTcpBinding.

Section 3.3.1.1: Setting up the lab

In this section, you'll do some preliminary work before starting the lab. You'll examine the state of the application as it currently exists, and you'll verify that the application can communicate properly with the database.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
One-Way and Duplex Communication
A message exchange pattern describes the way messages are sent between applications. There are three classic message exchange patterns: request-reply, one-way, and duplex (callbacks). illustrates these patterns. So far in this book, I have focused on examples that use the classic request-reply pattern, that is, service operations that receive parameters and return values synchronously while clients wait for the response. There are cases where clients want to send messages and do not need a response—that is, the operation performs a function that can succeed or fail and the client either does not care, or does not care right away. In other cases, communication may be initiated at the other end of a communication channel—for example, a service sending unsolicited messages to a client application. This type of communication implies two-way communication between client and service, and it requires the support of a binding that can support duplex communications.
Figure 3-7: Message exchange patterns
One-way operations are useful because once the message reaches the receiving end, the client connection is released so that the client can continue doing other work. Furthermore, they won't be affected if a problem occurs at the other end, since no exceptions are reported. One-way messages are also known as asynchronous messages.
Duplex or two-way operations play a key role in applications that send notifications, issue events, or implement some form of publish-subscribe pattern.
In this section, I'll explain how to implement one-way operations and duplex patterns while also discussing the following concepts:
  • How to implement message exchange patterns with WCF
  • Scenarios for one-way operations and duplex communications
  • WSDualHttpBinding features
  • Supporting callbacks
  • Concurrency issues for the service and client
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Large Message Transfers
Content preview·Buy PDF of this chapter|