Defining XML Schema for a NET Class

The DataContract attribute, defined in System.Runtime.Serialization, indicates that a class should be exposed as an XSD in the WSDL that represents the service. If a class doesn't have the DataContract attribute, it will not be present in the WSDL. By default, the name of the XML Schema is the same as the name of the class and the target namespace of the schema is concatenated with the .NET namespace of the class. Both of these can be overridden. You may want to override them to control the...

Generating Client Proxy Class and Configuration Files

If you are modifying an existing client that already had ASMX proxies, you should use Add Web Reference. Listing 1.13 shows the client code that uses a proxy generated by Add Web Reference to call a service operation. Listing 1.13 Client Code Using Add Web Reference Proxy to Access an ASMX Service new ASMXReference. StockService ()) double p proxy.GetPrice(msft) p) proxy.Close() Listing 1.14 shows a configuration file that was generated by Visual Studio from Add Web Reference. Notice that the...

Communication Using Basic Web Services

Web services are the foundation for interoperable communication among heterogeneous systems. For example, services built on Java-based platforms such as IBM Websphere or BEA WebLogic must communicate seamlessly with clients and services built on .NET. And services built on .NET must communicate seamlessly with clients or services built on Java-based platforms. Prior to WCF, ASP.NET Web Services (ASMX) and Web Service Enhancements (WSE) provided this capability on the .NET platform. With .NET...

Impersonating Users

By default, WCF services access local and remote resources using the credentials under which the service host is executing. It is up to the service to authenticate callers to verify who they are, then perform authorization checks to ensure that they can access other resources (which would be accessed as the host identity). When running services that receive Windows credentials, we have another option called impersonation. Impersonation is the process by which an alternative credential is used...

Hosting a Service in IIS

In IIS 6, available on Windows 2003 and Windows XP SP2, application pools were introduced as a runtime container for hosted applications. This enabled control over startup and shutdown, and identity and recycling services on a per-process basis. It naturally provided process isolation across applications, which led to greater reliability. Overall process management was handled by the application pool architecture. In IIS7, available on Windows Vista and Windows Server 2008, process management...

Resolving Peers Using PNRP

PNRP is a distributed name resolution protocol that enables publication and discovery of P2P resource information. WCF uses PNRP to resolve peer nodes in a mesh network. This allows for participants in a peer mesh to discover other participants so that they can communicate with one another. This protocol has been available for some time either as an optional download to Windows XP or as a part of Windows XP SP2. Windows Vista now includes PNRP v2.0 out of the box when you enable IPv6 support....

One Way Operations

The one-way message exchange pattern is useful when a client needs to send information to a service but doesn't receive a response. With this pattern, the client just needs acknowledgement of successful delivery it does not need an actual response from the service. Sometimes the one-way pattern is erroneously called fire-and-forget. In reality, it's fire and acknowledge because the caller receives an acknowledgement that the message was successfully committed to the communication channel. WCF...

Praise for Essential Windows Communication Foundation

Resnick, Crane, and Bowen have surveyed the essence of Microsoft's Web services platform. Whether this is the first time or the fifty-first time you're using WCF, you'll learn something new by reading this book. Nicholas Allen, Program Manager, Web Services, Microsoft As developers, we are constantly called upon to be 'instant experts' in many areas. When the time comes for you to begin working with distributed systems development and messaging in the new Microsoft .NET 3.x world, you find...

Controlling the Number of Concurrent Instances

By default, WCF hosts will spin up as many instances as possible to process incoming requests. If the instancing and concurrency behavior of a service contract is not specified, WCF will create a service instance for each incoming request and will allocate threads as needed to respond to requests. Overall this is a good approach to performance and scalability because the server will scale with the capacity of the hardware. Figure 5.5 Output from session-aware service Figure 5.5 Output from...

Text Versus Binary Encoding

Prior to WCF, you had a number of choices for building distributed applications. Two of those options were .NET Remoting and ASP.NET Web Services. .NET Remoting was great for communicating between .NET applications because it optimized the transmission of data using binary encoding. This offered better performance than ASP.NET Web Services, which leveraged text encoding for interoperability. Text encoding was acceptable for ASP.NET Web Services because it allowed for interoperability across...

Contracts

In the world of atoms and money, a contract is a binding agreement between two or more parties that specifies the supply of goods or services for a known price. In the world of bits and services, a contract has a similar function It's an agreement between two or more parties that specifies the messages that can be exchanged and the terms and conditions of those messages. A contract is a description of the messages that are passed to and from service endpoints. Each endpoint is defined by the...

Registering Names Using PNRP

WCF can use PNRP to discover other participants on a mesh network. In its implementation, the WCF peer channel abstracts away the use of PNRP so an application does not need to work with PNRP directly. However, some peer application might like to publish and resolve identifiers peer names themselves outside of the WCF peer channel. Unfortunately, prior to .NET Framework 3.5 there was no way from managed code to register PNRP names. A new namespace called System.Net.Peer was added in .NET...

Channel Factoryo

Two classes refer to channel factories within WCF ChannelFactory and ChannelFactory lt gt . They might seem similar, but they are actually separate classes that do different things. The ChannelFactory lt gt class is used in advanced situations where multiple clients need to be created. Essentially it works with a given ChannelFactory, but it does not have any responsibilities for creating a channel stack. The ChannelFactory lt gt class is used by defining the class with a specific...

Implementing a WCF Service

This section describes how to implement a simple service with WCF. By simple, we'll assume HTTP as the wire protocol, and we'll assume a text-based representation of an XML document on the wire. For security, we'll assume it's handled somehow in the application. We'll assume a synchronous request-reply conversation and that our service supports just one operation, which takes a string as input and returns a double as output. In later chapters, we'll vary all these assumptions, but for now,...

Hosting a Service in Windows Process Activation Services

Windows Process Activation Services WAS is the hosting infrastructure built into Vista and Windows Server 2008. Features previously available only in IIS, such as process activation, recycling, and identity management, have been moved into WAS and made available to protocols other than HTTP. WAS enables you to host services in a robust environment that doesn't rely on the HTTP protocol. The HTTP protocol is widely deployed and understood, but there are cases when it's not the best option. For...

Comparing WCF Serialization Options

There are many ways to use serialization objects using WCF. Determining which mechanism to use for serialization depends on a number of factors. These include whether you want to share types or contracts, support existing .NET types, preserve references, and more. The default serialization mechanism for WCF is the DataContractSerializer. This class can be found in the System.Runtime.Serialization namespace. The DataContractSerializer is built to support the sharing of contracts based on XSD...

Duplex Operations

Request-response communication is the most prevalent message-exchange pattern between a client and the service. Communication is initiated on the client, the client sends a request message to the service, and then the service sends a response message back to the client. If the response is expected quickly, this can be implemented synchronously, so the client application blocks waiting for the response. If a delay is expected between the request and the response, a request-response pattern can...

Client Authentication

A client authenticates with a service by presenting a set of claims that the service trusts. The claims can be in any format, as long as both the client and the service understand the format and trust its source. If the client and service share a secret, such as a username and password, as long as the client sends over a valid credentials, the service trusts that the client is who it says it is. This is the mechanism for basic authentication with HTTP. In a Windows-only environment where the...

All About the URI

Most everyone should be familiar with URIs because this is how people browse the Web today. People access resources, such as HTML pages, via URIs typed into the address bar of their browsers. Browsers can access a variety of resources using URIs, including images, videos, data, applications, and more. Accessing of resources via a URI is also one of the principles behind the REST architectural style. Table 13.1 shows several examples of resources on the Web that can be accessed in this manner....

Serialization Versus Encoding

There are important differences between serialization and encoding in WCF. The terms serialization and encoding have slightly different meanings in the WCF world when compared with other distributed computing technologies such as ASP.NET Web services and COM . Serialization is the term often used to describe the process of converting an object graph into an array of bytes. This is a very useful feature for representing the state of an object. Serialization can be used to persist an object's...

Transactional Operations Within a Service

Transactional service operations succeed or fail as a unit. They are initiated by one party, which assumes that the result will be consistent, whether the operation succeeds or fails. Figure 5.9 depicts pseudo code of this behavior. The client opens a connection to the service and calls its Transfer method. Transfer executes a debit, a credit, and then marks the transaction complete. The client is uninvolved in the transactional semantics. withdraw From, Amt deposit To, Amt commit Figure 5.9...

WsHttp Binding

Support for WS- is included throughout the WCF framework. The wsHttpBinding binding is an example of this support. This binding provides interoperable communication across heterogeneous platforms as well as advanced infrastructure level protocols, such as security, reliable messaging, and transactions. The wsHttpBinding binding is the default binding in .NET Framework 3.0 whenever you need interoperable communication based on Web services. The following code shows the addressing formats for the...

Exposing a Parameter Inspector for Service Operation Behavior as an Attribute

Listing 5.24 implements a behavior for validating parameters against regular expressions. It can be applied to any operation and enables the developer to define a regular expression and an error message to return if the parameter is invalid. The code shows a parameter inspector called from an operation behavior and shows the operation behavior implementing an attribute. It also shows how the operation behavior is added to the service description by referencing the attribute in the service...

Creating and Consuming Strongly Typed Faults

As we just described, a basic FaultException does not provide a type-specific way to create robust try catch finally error-handling logic on the client side. To enable that kind of handling on the client, consider using the generic-based FaultException lt gt class. FaultException lt gt accepts a type that defines the structure of exception data being serialized. This could be any type that can be serialized for transmission, but for the client to have strongly typed access to that type, it must...

Asynchronous Request Response Operations

Good design minimizes situations in which the user must wait for one task to complete before initiating the next task. For instance, when an e-mail client is downloading new messages, you can still read or delete messages already downloaded. Or while a Web browser is downloading images referenced on a Web page, you can still scroll the page or navigate elsewhere. This form of multitasking within the client program is accomplished through an asynchronous design pattern. In WCF, request-response...

Implementing a Client for a WCF Service

WCF provides a rich API for clients to use when communicating with a service. The API, implemented by System.ServiceModel, takes care of serializing types to XML and sending a message from the client to the service. You can either program directly to that API, or you can use tools to generate a proxy class and configuration file. In this section, we will first demonstrate how to call a service directly in code, and then we'll do the same using tools. The former approach involves less code and...

Versioning Data Contracts

Businesses change, technologies change, laws change, and so do software contracts. In the face of software changes, a solid ver-sioning strategy is essential. Care must be taken up front to plan for inevitable changes and to preserve backward compatibility with existing clients. The most common need for data contract versioning is when members are added to an existing data contract. By following the nonbreaking changes described in this section, you can freely do this...

Untyped Messages

In some scenarios, you may not know the structure of messages passed between a client and service at design time. For instance, intelligence might be built in to the messages themselves, such as routing and service operations that are determined at runtime. Or a layer of software or hardware might be between the client and service that manipulates SOAP messages and requires special data formats. For these cases, untyped operation contracts can be very useful. Untyped operation contracts enable...

NOTE Impersonation via Code

It is also possible to invoke impersonation manually through code. The Windowsldentity exposed via ServiceSecurityContext.Current features an Impersonate method that can be invoked to activate impersonation. Ensure you have first verified that the Windowsldentity is not null before attempting the call. Next, the client in cases where full impersonation or delegation is necessary must explicitly designate that it supports impersonation. This can be done via configuration or code. For...

Section Examples Introduction

The examples in this section are modeled to reflect having WCF-based services and callers communicating over a LAN behind a corporate firewall. We follow the basic model of having a contract implementation class library, host console application SampleHost , and client console application ClientConsole . The topology is shown in Figure 8.2, where the client, host, and other resources such as the database are all behind a corporate firewall separating communications from the open Internet....

Ws2007Http Binding

.NET Framework 3.5 introduces a new binding for Web service interoperability called the ws2007HttpBinding binding. This binding is similar to the wsHttpBinding binding except that it supports the latest WS- standards available for messaging, security, reliable messaging, and transactions. Table 4.8 lists the new WS- standards that are supported by the ws2007HttpBinding binding. Table 4.8 WS- Specifications Supported by the ws2007HttpBinding Binding Table 4.8 WS- Specifications Supported by the...

Exposing a Service Behavior Through Configuration

Listing 5.25 implements a behavior for validating that a software license key is installed in the service configuration. If it is not present or if it is invalid, the service will not start. It shows an endpoint behavior that validates configuration information as the service runtime is built. It also shows a behavior extension that is called as the service runtime is being built and how that extension adds the behavior to the service runtime. The result is that a custom behavior is used in the...

Tip Wcf Restricts the netNamed PipeBinding Binding to Local Machine Communication

Although it is possible to use named pipes to communicate across a network, WCF restricts the use to local machine communication. This means that the netNamedPipeBinding binding and any other binding based on the namedPipeTransport binding element can be used to ensure that your service is not available across a network. This is accomplished using two mechanisms. First, the Network Security Identifier SID S-1-5-2 is denied access to the named pipe. Second, the name of the named pipe is randomly...

Communication Using Queued Services

Connected applications are applications that require both the client and the server to be running at the same time and reachable over a network. Disconnected applications are ones in which the client can function without connectivity to the server, but not all features are available in that mode. Disconnected applications must cache data locally, must communicate in some asynchronous manner, and must persist any messages so they can be delivered when connectivity is reestablished. Persisted...

NetTcp Binding

The netTcpBinding binding is designed to support communication between .NET applications that are deployed on separate machines across a network, including communication across intranets and the Internet. We refer to this type of communication as cross-machine communication. In this situation there is no need for interoperability because both applications are built on .NET. This gives us a great deal of flexibility when communicating across the network. Because no interoperability requirement...

Multiple Contracts and Endpoints in a Service

A service is defined as a collection of endpoints. Each endpoint has an address, binding, and contract. The contract is what exposes the endpoint capabilities. The address is simply where those application or service capabilities live on the network, and the binding is how to access them. There is a one many relationship between endpoints and contracts. An endpoint can have only one contract, but a contract can be referenced by many endpoints. And although an endpoint can specify only one...

Authenticating with wsHttp Binding

The wsHttpBinding uses message-level security. It uses the WS-Security protocol to send the encrypted messages between client and service over the HTTP transport channel. You do not need to configure HTTP.SYS or IIS to support SSL, because WS-Security enables secure communication on any protocol. Because of this, the service endpoint and its MEX sibling can be on the same port, making secure IIS hosting very simple. A potential disadvantage of wsHttpBinding is that because it uses port 80...

Calling a WCF Service from WF

WF activities are the building block of workflow programs. Each activity typically performs one task, such as calling a method on a class, calling a Web service, or invoking another program. WF ships with a few built-in activities, and developers can create their own activities by inheriting from one of the activity base classes. There are at least four ways to invoke a service from WF use the Send activity, write a custom activity, use the InvokeWebService activity, or use the Code activity....

Sending Binary Data Using MTOM Encoding

The textMessageEncoding encoder converts messages into text-based XML. This is great for interoperability, but it is not efficient at transmitting large chunks of binary data. MTOM is used to send large amounts of binary data as raw bytes in interoperable scenarios. As mentioned previously, MTOM refers to Message Transmission Optimization Mechanism. This is standard for optimizing the binary data by sending the binary data as attachments to the SOAP message. This means that binary data can be...

Authorization Using AzMan

Windows Authorization Manager AzMan is a system that provides centralized and therefore easier to maintain role-based authorization services to applications, including WCF, based on policies defined in authorization stores. AzMan features an MMC-based utility for managing both the authorization stores and related access levels. The runtime of Authorization Manager is independent of the physical authorization stores, which may be based on SQL Server, Active Directory, ADAM, or XML, depending on...

Exporting and Publishing Metadata Service Behavior

The ABCs of a service its addresses, bindings, and contracts are represented in metadata so that potential clients know where, how, and what to communicate. This information is collectively referred to as service metadata. The metadata service behavior is the first behavior that most developers encounter, because it's referenced in the configuration files generated by Visual Studio 2008 when you create WCF project. This behavior works in concert with a metadata endpoint to make metadata...

Creating Clients from Metadata

The MetadataResolver class allows for binding information to be retrieved programmatically rather than using configuration. This means that clients can be created dynamically without the need for specifying a configuration file. This is useful if you want to deploy clients and then later change the configuration of the service. Listing A.1 shows an example of how to use the MetadataResolver class to point to a known metadata endpoint. The Resolve method on the MetadataResolver class is used to...

Behaviors

Behaviors are WCF classes that affect runtime operation. Behaviors are invoked as the WCF runtime starts on the client and server and as messages flow between the two. Because behaviors run at these critical times, they are used to implement many built-in features in the WCF. They are also an important extensibility point for customizations. For example, ServiceHost is responsible for defining the instancing and concurrency aspects of a server, in addition to dispatching messages to the proper...

NOTE One Way Operations and Fault Contracts

As mentioned earlier, one-way operations do not return messages to callers, so there is no direct mechanism for returning faults. Because faults are not returned, an InvalidOperationException will be thrown at service load time if you decorate any one-way operations with a FaultContract. Throwing a FaultExceptiono with a Defined FaultContract Having indicated to WCF that the ApproveInvoice operation may throw an exception that serializes data within the TrackedFault data contract, we need only...

Enabling Message Logging

Like tracing, message logging is based on System.Diagnostics and is disabled by default. It can be enabled first by adding a trace listener for example, XMLWriterTraceListener to process messages from the System. ServiceModel.MessageLogging trace source. Listing 9.3 shows our SelfHost application, configured for message logging. Listing 9.3 Enabling Message Logging in Configuration lt system.serviceModel gt lt services gt lt behaviors gt lt diagnostics gt lt messageLogging logEntireMessage true...

One Way Communication Pattern

In the one-way communication pattern, messages are sent in only one direction, from the client to the server. One-way communication is common when the sender does not need an informational response back right away the sender just needs an acknowledgement that the message was sent. After the message is sent, that is the end of the communication exchange. The two interfaces used to facilitate one-way communication are the IOutputChannel and the IInputChannel interface. Figure 3.2 shows how...

Creating a Custom Binding

There will be times when the preconfigured bindings do not meet the requirements of your service. Common scenarios include custom security and additional transports, which are not supported by WCF. One example is the lack of support for the UDP protocol within WCF. Support for the UDP protocol exists as a sample in the Windows SDK. For these situations WCF provides the capability to create custom bindings. Custom bindings can be created using either code or configuration. A custom binding is...

Flowing Transactions Across Operations

When working with distributed systems, transactions sometimes must span service boundaries. For instance, if one service managed customer information and another service managed orders, and a user wanted to place an order and ship the product to a new address, the system would need to invoke operations on each service. If the transaction completed, the user would expect that both systems were properly updated. If infrastructure supports an atomic transactional protocol, the services can be...

Using Forms Authentication

All the approaches so far show how services can be accessed over the Internet from a Windows-based application. Figure 8.8 shows a Web application that accesses services over the Internet from the browser. We will now consider how Web applications can access WCF services securely using a Web-centric approach. This means that we want to use standard HTTP approaches for securely accessing our services. This includes using HTTP cookies for authentication and SSL for encryption. SSL for encryption...

Communicating Exception Details

In the earlier example, we called a service that raised an unhandled exception to the service layer, and the client received the minimal information shown in Figure 10.1. By default, WCF relays this message, rather than details about an exception, to a caller to prevent exposure of sensitive details about the system's implementation or infrastructure. ServiceDebugBehavior has an IncludeExceptionDetaillnFaults property that can be used to enable transmission of exception details to the client....

Duplex Communication

Duplex communication uses two one-way channel shapes combined into a third interface called IDuplexChannel, as shown in Figure 3.3. The advantage of duplex communication over one-way or request-reply is that messages can be sent from either the client or the server. An example of duplex communication is an event notification system. A server will send events to a client that receives events. The client provides an endpoint on which the server can send messages to the client. The server will...

Sharing Ports Between Services

Internet Information Services 6.0 IIS and later provides a way to share ports across multiple processes. The actually mechanism that is responsible for sharing ports is the new HTTP service http.sys . This is a kernel-mode service that does connection management for both IIS and self-hosted WCF services. This approach works well for services that use the HTTP transport protocol and is transparent across hosting environments. WCF provides the Net.Tcp Port Sharing Service Windows Service to...

Using a Send Activity

The Send activity is one of the built-in activities with Visual Studio 2008. Its purpose is to use a WCF proxy to call a Web service. The design environment supports the common properties that need to be configured to call a Web service, including endpoint information. The property sheet and designer is also used to bind WF variables to the service operation parameters. In addition, the activity can override the URI address of the service. Before accessing the Web service, the project must...

Names of Operations Types Actions and Namespaces in WSDL

WCF generates the externally exposed service artifacts based on the internally named classes and attributes defined in the source code of the service. These artifacts are exposed through the MEX endpoint of the service and typically consumed as WSDL by a client at design time. On the client side, the WSDL is then used to write code that builds the proper message format through which it communicates with the service. So the names you choose for classes, methods, and parameters can potentially...

Implementing a Custom Peer Resolver

The peer transport channel allows developers to implement their own peer resolutions by specifying a custom peer resolver. There are many reasons to implement your own custom peer resolver rather than using the default PNRP resolver. PNRP requires the use of IPv6 and needs an additional download for Windows XP SP2 and Vista clients to work together. In these situations a custom peer resolver can be used to leverage an existing IPv4 infrastructure and to ease deployment. There are many examples...

Contents

Preface xxvii Acknowledgments xxxiii Writing a WCF Service Entirely in Code 7 Writing a Service with Code and Configuration Files 10 Exposing the Metadata Exchange MEX Endpoint 14 Implementing a Client for a WCF Service 18 Writing a WCF Client Entirely in Code 18 Writing a Client with Code and Configuration 19 Hosting a Service in IIS in Three Steps 24 Implementing a WCF Client for an ASMX Service 27 Generating Client Proxy Class and Configuration Files 28 Synchronous Request-Response...

WsDual HttpBinding

The wsDualHttpBinding binding is similar to the wsHttpBinding binding, with additional support for duplex communication and lack of support for transport-level security. Duplex communication is accomplished through two shape-changing binding elements the OneWayBindingElement and CompositeDuplexBindingElement binding elements. The CompositeDu-plexBindingElement binding element layers a duplex communication channel on top of two one-way channels. The wsDualHttpBinding binding uses the...

Roundtrip Serialization Using lExtensible DataObject

Data contract versioning is an important aspect of service orientation of support service-oriented architectures over time. Over time, it is likely that new versions of new services are created that have new versions of the same data contracts, just with additional information. Rather than recompiling all previous clients and services that were built using the older data contracts versions, you would hope that they would gracefully degrade to sharing the data they have in common. This is...

Sample Application

We will now examine each of the preconfigured bindings available in WCF. To demonstrate each binding we will use a sample application based on stock quotes. The sample asks for quotes based on a ticker symbol and returns the stock price. The intent is to expose and consume the same service over different bindings and take note of any changes in code or configuration. Listing 4.4 shows the stock quote service. Listing 4.4 StockQuoteService Service public interface IStockQuoteService public class...

Configuring HTTP Connections

Disable Keep Alives

The HTTP 1.1 specification includes a feature called HTTP Keep-Alives. HTTP Keep-Alives allow for HTTP connections to be persisted connections between clients and servers. This allows clients to keep connections open so that they can be reused for subsequent requests. To limit the resources used by a single client, the HTTP 1.1 specification specifies a maximum of two connections per server from an application. By default, HTTP clients in the .NET Framework use HTTP 1.1 Keep-Alives including...

Limiting the Number of Hops for a Message

Peer networks based on message flooding typically provide a way to limit the distance a message travels with the network. The distance a message travels is often referred to as the number of hops it makes when traveling on the network. The number of hops is determined by counting the number of times a message is sent between neighbors. For those familiar with socket programming, this is similar to the Time-to-Live TTL setting on the TCP protocol, which specifies the maximum number of routers a...

Bindings

As covered in Chapter 3, Channels, a channel stack is a layered communication stack that is made up of one or more channels that process messages. Bindings are preconfigured channel stacks. They represent wire-level agreements between a client and a server. Each binding specifies the transport, encoding, and protocols involved in the communication. WCF encapsulates the configuration for the various communication scenarios using bindings. The most common communication scenarios, such as Web...

Using SOAP Headers with Untyped Messages

Whether you're working with typed or untyped messages, you may want to pass information in the SOAP header in addition to the SOAP body. A common need is to pass session or context information along with a message. So, rather than creating additional wrapper messages, the SOAP header is a convenient and well-understood mechanism of passing that information. If you're using typed messages, WCF explicitly supports this through the MessageHeader attribute as demonstrated in Listing 2.28. If using...

Preserving References and Cyclical References

Two important issues exist regarding references and serialization preserving references and cyclical references. Both of these issues are addressed through reference preservation. Reference preservation may help significantly when you are trying to optimize the amount of data that gets serialized or when sharing type information between client and server. Reference preservation allows for the same data to be referred to more than once in a data contract without duplicating the data. This is a...

Configuring TCP Connections

Visual Studio 2008 Visual Designers

Unlike HTTP connections, WCF does not leverage classes in the .NET Framework to manage TCP connection lifetime. Instead, WCF uses a connection pool to cache connections. The connection pool can be managed using the ConnectionPoolSettings property of the TcpTransportBindingElement binding element. The ConnectionPoolSettings property returns an instance of the TcpConnectionPoolSettings class. This class has three properties that help manage connections in the connection pool IdleTimeout,...

Directional Messaging Using Custom Binding

A common mistake when working with the peer transport channel is to assume that it supports directed communication over a peer mesh. Directional messaging means that a message can be sent to a particular node in a peer mesh by propagating it across a peer mesh to its destination that is, routing . This is not possible using the peer transport channel. This limits the types of peer applications that can be built, because all messaging assumes that messages will be sent to every node. However,...

Publishing Metadata Endpoints

We have already discussed metadata in Chapter 1, Basics. This discussion gave an introduction to exposing the configuration of services using metadata. However, it did not go into details on how the metadata is exposed. Later on we introduced the concept of bindings in Chapter 4, Bindings, but limited the discussion to those bindings meant to expose services we did not focus on metadata bindings. WCF provides four additional bindings mexHttpBinding, mexHttpsBinding, mexTcpBinding, and the...

Comparing Binding Performance and Scalability

Developers need to know about the performance and scalability characteristics of bindings. Performance and scalability are important when you are working with real-world applications where service-level agreements and user experience matters. Users will complain about an application that performs poorly. Applications that do not scale usually mean that business objectives are not being met. We have provided a simple performance comparison of four bindings available in WCF. The operation under...

Managing Service Exceptions with Fault Exception

The first example demonstrated the effect of allowing an unhandled exception to rise through the service implementation layers to the service host. Notice that in Figure 10.1, the type of exception returned to the caller is FaultException. This is a base Exception-derived type used in WCF to integrate with the SOAP fault specification. By default, exceptions that reach the service host that are not derived from FaultException are considered indications of a potentially fatal condition. The...

Local Machine Communication Between NET Applications

Interprocess, or cross-process, communication refers to communication between two separate processes running on the same machine. Intra-process, or in-process, communication refers to communication between two software components running within one process. Together these types of communication make up what we refer to as local-machine communication a.k.a. on-machine communication Application domains a.k.a. app-domains are a mechanism in .NET for further partitioning a Windows process to...

Enabling ASMX Features in an IISHosted Service

Prior to WCF, ASMX was a common approach to Web services in ASP.NET. It provided excellent support for the common Web service requirements and offered robust extensibility via the ASP.NET HTTP pipeline. With WCF, services are designed to be transport independent and agnostic to their hosting model. So WCF services cannot rely on an implementation within the HTTP pipeline, such as HTTP.SYS. Like ASMX, WCF also provides a robust extensibility model. But rather than using the HTTP pipeline, it...

Operation Contract and Channel Shapes

Channels use channel shapes to implement the various types of message exchange patterns that they support. For example, a transport channel based on TCP would implement the IlnputChannel and IOutputChannel because these transports are inherently one-way. Other transports based on other protocols such as TCP may implement multiple channel shapes. Developers do not work with channel shapes directly. Instead, WCF chooses the channel shape based on the OperationContract of a service. Table 3.1...