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...
Using the XmlSerializer for Custom Serialization
The DataContractSerializer is the preferred serialization mechanism in WCF. However, at times you might want to go beyond the default serialization. One option to change the serialization is to work with the XmlSerializer. There are many reasons to use the XmlSerializer, including the capability to implement custom serialization, sharing of types, and support for legacy Web services. As with the DataContractSerializer, the XmlSerializer is an integral part of WCF. This section looks at the...
wsHttpBinding
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 RequestResponse 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...
Persisting Workflow State on the Server
The state of a long-running workflow is stored within the WorkflowRuntime class. As events trigger activities within the workflow, the WorkflowRuntime executes those activities. When a workflow is idle and waiting for an event, the WorkflowRuntime can persist the workflow state to external storage to free system resources such as memory and CPU. More importantly, when the WorkflowRuntime is shut down, the state of all active workflows must be written to external storage, or the workflow...
Message Filters
By default, all messages appropriate for the level specified in the lt messageLogging gt configuration element are logged. However, to reduce the overhead associated with logging and to decrease the size of log files, you might want to include only messages that match a set of rules you configure. Messagefilters are XPath expressions that must be satisfied before a message will be logged. Messages that do not match the XPath queries are excluded, except for malformed messages, which are not...
Versioning Data Contracts
Change is inevitable. 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...
TIP Client Notifications
It is common for applications to maintain a reference to a client proxy. In these situations it is important to use the state transitions events to be notified when the client proxy enters the Faulted state and eventually the Closed state so that communication between client and server can be maintained. The ICommunicationObject interface is typically used by casting an existing communication object to the interface to gain access to the methods and events that the ICommunicationObject exposes....
Transports
The following is a list of transport channels and their associated binding classes, binding extensions, and their XML configuration element. Each of these represents a different transport channel that can be used in a custom binding. The transports available are TCP, HTTP, named pipes, HTTP with SSL TLS encryption, MSMQ, and Peer Networking. Transport channel based on the TCP protocol Transport channel based on the Named Pipe protocol Transport channel based on the HTTP protocol Transport...
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...
RoleBased Authorization Using Role Providers
ASP.NET role-based authorization allows developers to perform authorization checks based on roles. It also uses a provider model, which abstracts the details of user role storage from the application's code. There are several provider models in ASP.NET for roles, including the SqlRoleProvider, WindowsTokenRoleProvider, and AuthorizationStoreRoleProvider. Because we are assuming an Internet-facing application, we will examine how to use the SqlRoleProvider to perform authorization checks. There...
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....
Implementing a Message Inspector for Service Endpoint Behavior
Listing 5.23 implements a logging behavior by printing out every message sent and received by an endpoint. The code shows a message inspector called from an endpoint behavior. This also shows how the endpoint behavior is manually added to the service description in a custom hosted service. TIP Implementing Custom Behavior for Tracing In practice, if you're implementing a message inspector for diagnostic purposes, see Chapter 10, Exception Handling, for tracing techniques. The class...
Chris Bowen
Upper Saddle River, NJ Boston Indianapolis San Francisco New York Toronto Montreal London Munich Paris Madrid Cape Town Sydney Tokyo Singapore Mexico City Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals. The authors and publisher have taken care in the...
Transport UpgradesHelpers
The following list of binding elements includes upgrades or helpers to transports. WCF allows bindings that use stream-oriented protocols such as TCP and named pipes to support stream-based transport upgrades. For example, the SslStreamSecurityBindingElement provides support for channel security using an SSL stream. Peer name resolution using the PNRP protocol Channel security using an SSL stream Windows Stream Security Used to specify Windows stream security settings The following lists...
ws2007HttpBinding
.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 netNamedPipeBinding 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...
netTcpBinding
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...
Vw
verbose tracing options, 381 versioning data contracts, 72-74 WAS Windows Process Activation Service , service hosting, 288-291 WebScriptServiceHost class, 530 WebScriptServiceHostFactory class, 530-531 Web services, 131. See also advanced Web services communication, basicHttpBinding binding, 132-135 hosting, 512-514 WebGet attribute, 514 WebInvoke attribute, 514-515 WebOperationContext class, 523-529 WebMessageEncoder, 284-285 WebOperationContext class, 523-529 WebScriptServiceHost class, 530...
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 wsHttpBinding
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...
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 OneWay Operations and FaultContracts
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...
OneWay 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...
Performance Counters
Three sets of WCF-related performance counters are installed with the .NET Framework 3.0. In Performance Monitor, you can see these counters under ServiceModelService, ServiceModelEndpoint, and ServiceModelOperation. You can choose to enable these for your application via configuration, shown in Listing 9.7. Listing 9.7 Enabling Performance Counter Updates lt diagnostics lt messageLogging logMalformedMessages true gt lt diagnostics gt lt system.serviceModel gt lt configuration gt Enable...
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....
Configuration in appconfig
As with most WCF services, information on endpoints and security and behavioral settings are stored in the app.config or web.config files. When Visual Studio created the project using the Sequential Workflow Service template, it included an app.config file. But because the template included in the IWorkflowl and Workflowl interface and class and the example shown in this section use IStockService and StockService, these names need to be adjusted in the app.config. The updated WCF settings in...
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...








