Windows Dev Center

WCF Development

From a developer's perspective, Windows Communication Foundation is a set of .NET Framework 3.0 managed classes, primarily located in the System.ServiceModel and child namespaces. These classes and associated tools are used to build the messaging infrastructure for a distributed application.

Distributed solutions are typically designed using a top-down approach. A high-level design is created that clearly identifies each network node, its role (client, service, or both), and the contract offered or used by each node. Each node would then be further analyzed to produce component and object designs. Each service exposes one or more endpoints. Each endpoint exposes a contract, which is a collection of operations that represent message exchanges. Services publish metadata that describes the endpoints exposed by the service. Tools can consume this metadata to generate code that makes it easy for clients to consume the endpoints.

For more detailed information, see "Windows Communication Foundation" in the Windows SDK.

Services and Clients

A WCF Service is a program that exposes a collection of Endpoints. Each Endpoint is a portal for communicating with the world.

A Client is a program that exchanges messages with one or more Endpoints. A Client may also expose an Endpoint to receive Messages from a Service in a duplex message exchange pattern.

The following sections describe these fundamentals in more detail.

Endpoints

A Service Endpoint has an Address, a Binding, and a Contract.

The Endpoint's Address is a network address where the Endpoint resides. The EndpointAddress class represents a WCF Endpoint Address.

The Endpoint's Binding specifies how the Endpoint communicates with the world, including transport protocols (for example, TCP and HTTP), encoding (for example, text and binary), and security requirements (for example, SSL and SOAP message security). The Binding class represents a WCF Binding.

The Endpoint's Contract specifies what the Endpoint communicates and is essentially a collection of messages organized in operations that have basic Message Exchange Patterns (MEPs) such as one-way, duplex, and request/reply. The ContractDescription class represents a WCF Contract.

The ServiceEndpoint class represents an Endpoint and has an EndpointAddress, a Binding, and a ContractDescription corresponding to the Endpoint's Address, Binding, and Contract respectively (see Figure 1).

Bb756905.WCFD_YS01(en-us,MSDN.10).gif
NoteNote

Figure 1 Each Service's Endpoint contains an EndpointAddress, a Binding and a Contract represented by ContractDescription.

EndpointAddress

An EndpointAddress is basically a URI, an Identity, and a collection of optional headers as shown in Figure 2.

An Endpoint’s security identity is normally its URI; however, in advanced scenarios the identity can be explicitly set independent of the URI using the Identity address property.

The optional headers are used to provide additional addressing information beyond the Endpoint's URI. For example, address headers are useful for differentiating between multiple Endpoints that share the same address URI.

Bb756905.WCFD_YS02(en-us,MSDN.10).gif
NoteNote

Figure 2 EndpointAddress contains a URI and AddressProperties which contains an Identity and a collection of AddressHeaders.

Bindings

A Binding has a name and namespace and a collection of composable binding elements (Figure 3). The Binding's name and namespace uniquely identify it in the service's metadata. Each binding element describes an aspect of how the Endpoint communicates with the world.

Bb756905.WCFD_YS03(en-us,MSDN.10).gif

Figure 4 shows a binding element collection containing three binding elements. The presence of each binding element describes part of the how of communicating with the Endpoint. The TcpTransportBindingElement indicates that the Endpoint will communicate with the world using TCP as the transport protocol. ReliableSessionBindingElement indicates that the Endpoint uses reliable messaging to provide message delivery assurances. SecurityBindingElement indicates that the Endpoint uses SOAP message security. Each binding element usually has properties that further describe the specifics of the how of communicating with the Endpoint. For example, the ReliableSessionBindingElement has an Assurances property that specifies the required message delivery assurances, such as none, at least once, at most once, or exactly once.

The order and types of binding elements in Bindings are significant. The collection of binding elements is used to build a communications stack ordered according to the order of binding elements in the binding elements collection. The last binding element to be added to the collection corresponds to the bottom component of the communications stack while the first one corresponds to the top component. Incoming messages flow through the stack from the bottom upwards while outgoing messages flow from the top downwards. Therefore, the order of binding elements in the collection directly affects the order in which communications stack components process messages. Note that WCF provides a set of pre-defined bindings that can be used in the majority of scenarios instead of defining custom bindings.

Bb756905.WCFD_YS04(en-us,MSDN.10).gif
NoteNote

Figure 4 An example Binding with three binding elements.

Although eight standard bindings are provided that can be used for many common scenarios, custom bindings can be readily defined. Microsoft-specific bindings have a "Net" prefix (for example, NetMsmqBinding). Bindings that adhere to the WS-* protocols have the string "WS" in the beginning of their name. BasicHttpBinding adheres to the Basic Profile 1.1 specification.

For more information on standard bindings, see "Predefined Bindings" in the Windows SDK.

The following table describes some common standard bindings:

Binding Name

Characteristics

Suitability

BasicHttpBinding

HTTP or HTTPS, text encoding, simplex and request-reply message exchange patterns.

Synchronous connection to Web services that conform to the WS-Basic Profile specification.

WSHttpBinding

HTTP or HTTPS, text or MTOM encoding, security, sessions, reliability, transactions, simplex, and request-reply.

Synchronous connection to endpoints that conform to the Web Services (WS-*) Specifications protocols.

WSDualHttpBinding

HTTP, text or MTOM encoding, security, sessions, reliability, transactions, and all three message exchange patterns.

Similar to BasicHttpBinding except it does not support HTTPS. It does support asynchronous (duplex) messaging.

NetNamedPipeBinding

Named pipe transport, binary encoding, security, sessions, reliability, transactions, and all three message exchange patterns.

Synchronous or asynchronous connection to other .NET Framework nodes on the same computer.

NetMsmqBinding

Message Queuing transport, text encoding, security, sessions, reliability, transactions, and simplex and duplex message exchange patterns.

Synchronous or asynchronous connection to other Windows computers that support queued messages.

Contracts

A WCF Contract is a collection of Operations that specifies what the Endpoint communicates to the outside world. Each operation is a simple message exchange (for example, one-way or request/reply message exchange).

The ContractDescription class is used to describe WCF Contracts and their operations. Within a ContractDescription, each Contract operation has a corresponding OperationDescription that describes aspects of the operation such as whether the operation is one-way or request/reply. Each OperationDescription also describes the messages that make up the operation using a collection of MessageDescriptions.

A ContractDescription is usually created from an interface or class that defines the Contract using WCF's programming model. This type is annotated with ServiceContractAttribute, and its methods that correspond to Endpoint Operations are annotated with OperationContractAttribute. You can also build a ContractDescription by hand without starting with a CLR type annotated with attributes.

A duplex Contract defines two logical sets of operations: A set that the Service exposes for the Client to call and a set that the Client exposes for the Service to call. The programming model for defining a duplex Contract is to split each set in a separate type (each type must be a class or an interface) and annotate the contract that represents the service’s operations with ServiceContractAttribute, referencing the contract that defines the client (or callback) operations. ContractDescription contains a reference to each of the types, thereby grouping them into one duplex Contract.

Similar to Bindings, each Contract has a Name and Namespace that uniquely identify it in the Service's metadata.

Each Contract also has a collection of ContractBehaviors, which are modules that modify or extend the contract’s behavior. The next section covers behaviors in more detail.

Bb756905.WCFD_YS05(en-us,MSDN.10).gif
NoteNote

Figure 5 ContractDescription class describes a WCF Contract.

Behaviors

Behaviors are types that modify or extend Service or Client functionality. For example, the metadata behavior, implemented by ServiceMetadataBehavior, controls whether the Service publishes metadata. Similarly, the security behavior controls impersonation and authorization while the transactions behavior controls enlisting in, and auto completing transactions.

Behaviors also participate in the process of building the channel and can modify that channel based on user-specified settings and/or other aspects of the Service or Channel.

A Service Behavior is a type that implements IServiceBehavior and applies to Services.  Similarly, a Channel Behavior is a type that implements IChannelBehavior and applies to Client Channels.

Developing with the Service Model

Most developers will access the functionality of Windows Communication Foundation primarily through its service model. This model relies heavily on declarative programming to identify many of the different messaging entities (for example, contracts and behaviors) by annotating .NET Framework classes with Windows Communication Foundation attributes.

Solutions minimally require a small amount of procedural code and optional configuration file entries. The latter are typically managed by the administrator of the solution.

The service model supports two approaches to working with messages:

  • Typed service — message contents are bound to .NET Framework objects and intrinsic types, much like method parameters and return values. The associated .NET Framework types must be serializable or have an associated data contract.

  • Untyped service — messages are handled as raw SOAP (XML) messages. Untyped services use the Message class to directly specify the XML content of the SOAP messages.

The base messaging layer provides the finest level of control over message contents and processing.

For a typed service, there are two basic design and implementation approaches used:

  • Code-first — Service interfaces are written using a supporting CLR language, such as C# or Visual Basic .NET, and then declarative programming is used to specify capabilities and message formats.

  • WSDL-first — XML Schema and Web Services Description Language (WSDL) documents that describe the service are created first, then a tool, such as Svcutil.exe, is used to generate implementation classes. (Alternately, classes can also be generated from a running service that publishes a metadata exchange (MEX) endpoint by using Svcutil.)

In both approaches, completion of the implementation requires some procedural code and optionally the creation of a configuration file. Assuming a consistent set of requirements, these two approaches can produce equivalent implementations.

The rest of this document will examine a service model approach using typed services and a code-first approach.

Creating a WCF Solution

Much of the work in implementing a solution in this manner is devoted to mapping service-oriented concepts and features to the corresponding object-oriented features, often by specifying attributes in the form of contracts and behaviors. There are three fundamental components that a developer must create in order to create a basic Windows Communication Foundation system:

  • Hosting code that interfaces with the hosting solution chosen, for example IIS or WAS. Typically this represents just a few lines of code that can be easily changed to suit a new host. The cleanest and most flexible approach is to separate the hosting code and the main server logic into separate assemblies. In most circumstances, a configuration file will be created for the service (Web.config or App.config depending on the host). The SvcConfigEditor tool can be used to create and modify this file. For more information, see "Hosting a Service" in the Windows SDK.

  • The WCF contract and its implementation. The contract is a .NET Framework interface that has ServiceContractAttribute applied to it. Each published operation on the contract is a method that has the OperationContractAttribute applied to it. The runtime behaviors of the service and its operations can optionally be specified through the ServiceBehaviorAttribute and OperationBehaviorAttribute attributes.The contract implementation, also known as a Service Type, is a .NET Framework class that implements the contract. Using the typed service approach, parameters and returned types are defined by data contracts by using the DataContractAttribute and DataMemberAttribute attributes.

  • At least one WCF client that exercises the functionality of the service. Typically the base code for the client proxy is created with the Svcutil tool, which will automatically create a properly-attributed class. This class represents the service interface and contains methods that represent operations, which appear to the client code as local calls. As with services, a configuration file is also often supplied for the client.

Beyond service structure, there are many more aspects that have to be considered when implementing a robust WCF system (for example, fault handling, message pattern, concurrency, and transaction support, auditing, and logging).

For more information about building a WCF solution, see Windows Communication Foundation In-Depth.

Exception and Fault Handling

Windows Communication Foundation clients and services use the standard .NET Framework exception handling mechanism internally. In addition to the standard set of exceptions in the .NET Framework, a new set of exceptions (for example, CommunicationException) can be thrown during processing on the client or service. Exceptions are handled locally, within the client or service where they originate. For more information about .NET Framework exceptions, see "Handling and Throwing Exceptions" in the Windows SDK.

Faults are used to selectively convey exception information from the service back to the client. Best practice recommends that faults created by service model programmer should be used to convey business logic failures instead of implementation details. Inside a method, a fault is represented by the FaultException<> class. (There also exists a non-generic FaultException class for creating undifferentiated faults.) When an instance of this class is thrown, it creates a SOAP fault message which is sent to the invoking client.

At the client, the SOAP fault message is translated back into the corresponding FaultException instance for the client to process, similar to a local exception. However, to properly differentiate between different fault types, a fault contract must be shared between the client and service as part of the service contract. This is accomplished through the FaultContractAttribute, which is applied to the operation that can report the associated fault. The fault contract specifies how a SOAP fault message is converted into a client exception. If a fault contract does not exist for a reported fault, the fault is converted into a FaultException object on the client.

Faults rely on SOAP response messages. They cannot be delivered to the client if simplex (one-way) messaging is being used.

Services can exert greater control over the fault generation and reporting process through the IErrorHandler interface. For more information, see "Extending Control over Error Handling and Reporting" in the Windows SDK.

Support for Message Exchange Patterns

Windows Communication Foundation provides support for the following message exchange patterns:

  • Simplex — one-way invocation, no response. This is the most basic message exchange pattern that is a good fit for operations that don't return a value (void return value in C#). To mark an operation as simplex, the OperationContractAttribute that annotates the associated method has its IsOneWay property set to true. When set, a SOAP response message will not be generated by the service when this operation is invoked (although the underlying transport protocol may initiate lower-level acknowledgement messages). For more information, see "How To: Create a One-Way Contract" in the Windows SDK.

  • Request/reply — one way invocation with response. The operation invocation is sent from the client to the service as one SOAP message and the reply, containing the return value, is sent back from the service to the client as a separate SOAP message. This pattern is well-suited for typical remote method call schemes.

    NoteNote

    Even methods that don't return a value will receive a reply message containing no data.

  • Duplex — two-way invocation. This pattern differs in that it enables the client and service to independently exchange messages over the same connection. It adds the concept of a callback contract, which is a separate service contract that defines the operations that the service can invoke on the client. The duplex pattern is specified by initializing the CallbackContract property of the ServiceContractAttribute to the interface that declares the associated callback contract. The methods in this interface must be annotated with the OperationContractAttribute (just like a standard contract), but these methods are implemented in a class in the client. This duplex pattern is suited for event notification schemes and multiple asynchronous return values. For more information, see "How To: Create a Duplex Contract" in the Windows SDK.

NoteNote

Some bindings limit support to a subset of these three. For example, BasicHttpBinding supports only the simplex and request/reply patterns.

Events and Asynchronous Operations

Windows Communication Foundation does not directly support .NET Framework events between the service and the client; however, service event information can be passed back to the client through standard message passing (duplex message exchange), using either synchronous or asynchronous operations. The latter is typically preferred because it is non-blocking.

Asynchronous operations are also used in situations where the requested operation takes a long time to complete and the client can perform other processing while it is waiting for a reply. Windows Communication Foundation supports asynchronous operations through two different mechanisms:

  • At the messaging level, one-way (simplex) message passing enables the service or client to send a message and continue processing immediately, without waiting for a reply. For more information about one-way message passing, see Support for Message Exchange Patterns topic above.

  • At the operation level, WCF supports the standard .NET Framework asynchronous design pattern. For more information, see "Asynchronous Programming Using Delegates" in the Windows SDK.

From a .NET Framework asynchronous design pattern perspective, a single synchronous duplex operation is equivalent to a pair of asynchronous simplex operations. This equivalence means that each side of a communication can either view it as one or the other (or both in different places). In fact, there is a direct conversion between the declarations of a synchronous duplex version and its equivalent asynchronous simplex pair. The declaration:

[OperationContract]
returnType Foo(<parameterList>);

is equivalent to:

[OperationContact(AsyncPattern=true )]
IAsyncResult BeginFoo(<parameterList>, AsyncCallback callback, object state);
returnType EndFoo(IAsyncResult result);

Although asynchronous versions of these operations can be manually generated, they can be automatically generated using the Service Model Metadata Utility Tool (SvcUtil.exe) by supplying the /async option.

Configuration Files

Although hard-coding the capabilities and characteristics of Windows Communication Foundation services and clients can be useful during the prototyping phase, deployed solutions generally need more flexibility, allowing solution administrators to change service characteristics such as addresses, bindings, security requirements, service behavior, tracing, and logging. Support is provided for configuration files for both clients and services through the System.ServiceModel.Configuration namespace, which is primarily used to create, read, and modify configuration files.

The following procedure is used to create and use configuration files:

  1. Create a base configuration file for the associated client or service. This is typically accomplished through one of the following approaches:

    • Use the Service Metadata Utility Tool (SvcUtil.exe) with the /config:filename switch to create the configuration file from the associated client or service assembly. This tool has other uses (for example, editing existing configuration files and merging two existing configuration files). For more information about this tool, see the "Service Metadata Utility Tool" (SvcUtil.exe) in the Windows SDK.

    • Manually create a new configuration file from a template or an existing configuration file. For example, a new configuration file can be added in Microsoft Visual Studio through the command:

      Project > Add New Item > Application Configuration File

      NoteNote

      By convention, configuration files for Web-based applications are named Web.config. When Visual Studio adds a new configuration file for other types of applications into a project, the name of this file is set to app.config. As part of the build process, this configuration file is copied to the output directory and renamed to app-name.exe.config.

    Windows Communication Foundation configuration files are XML-based and have the following general format. Each element has a name attribute so that it can be referenced from other parts of the configuration file and also from the associated component.

Server configuration file

Client configuration file

<?xml ?><configuration>
    <system.serviceModel>
        <services>
            <service>
            </service>
        </services>
        <bindings>
        </bindings>
        <behaviors>
        </behaviors>

    </system.serviceModel>
</configuration>
<?xml ?><configuration>
    <system.serviceModel>
        <client>
        </client>
        <bindings>
        </bindings>
        <behaviors>
        </behaviors>

    </system.serviceModel>
</configuration>
  1. Edit the configuration file (either with a text editor or with the SvcConfigEditor tool) to specify the characteristics required for development or deployment. For a concrete example, see Windows Communication Foundation In-Depth. If required, add the configuration file to the development project. For example, in Visual Studio, use the command Project > Add Existing Item.

  2. The configuration file settings can be used by the application in several general ways:

    • Separate elements can be referenced within imperative code. Where a hard-coded value would be used, instead reference the appropriate element from this configuration file. All of the appropriate methods have overloaded versions that take the string denoting the element's configuration name. For example:

      CustomBinding binding = new CustomBinding("PnsBinding1");
      
    • When the elements within the configuration file properly reference each other, the infrastructure will properly link them together during a call. For example, when the endpoint entry properly references a binding, then the following code will successfully create the service proxy on the client:

      IProperNamesService proxy = ChannelFactory.CreateChannel<IProperNamesService>("PnsEndPoint"); 
      
  3. Administrators, users, or even the solution itself can modify the configuration files (for example, manually editing the configuration file, graphically though the SvcConfigEditor tool, or through some utility created by the developer) to suit the current deployment of the solution. Care must be taken to avoid haphazard or malicious modification of these configuration files in order not to disable the solution.

For more information, see "Configuring Windows Communication Foundation Applications" and "Windows Communication Foundation Configuration Schema" in the Windows SDK.

Security

In this discussion, an entity is any person, computer, or application that possesses credentials and can potentially use computer resources. A resource is a computer-based file, database, service, or operation that can be accessed by an entity. Clients and services are entities, and service operations also represent resources. Windows Communication Foundation provides the following security capabilities during runtime:

  • Secure message exchanges between entities — ensures that a message is sent only between intended parties, arrives whole and unmodified, and cannot be read by unauthorized entities. The identities are identified using credentials to enable each party to authenticate the other. A credential contains a number of claims about the entity to prove their identity.

  • Secure access to resources by entities — only those entities authorized to use resources are allowed to do so. Authorization is achieved through identifying claims in the message (for example, my username is Alice or this x509 certificate has a subject name of "MySecureApplication"). Checking the list of claims sent in a message enables authorization checks. Mapping one set of claims to another set enables new credentials to be issued.

  • Record of activity — messages can be selectively logged and resource requests can be audited.

The following features support these security capabilities:

Feature

Description

WCF-supported

Identity and authentication

Reliably identifies an entity (client or service) using credentials.

  • Anonymous (none).

  • Windows security tokens.

  • X.509 certificates.

  • Username and password.

  • SAML (Security Assertion Markup Language)

Authorization

Defines what resources an entity is allowed to access and at what level they can be used.

  • Claim checking in the message.

  • ASP.NET Role Provider.

  • Windows Access Control Lists (ACL).

Integrity

Messages cannot have their contents modified without the receiving entity knowing.

  • XML Digital signatures.

Confidentiality

Untrusted entities cannot read the message.

  • Encryption either of the message or at the transport.

Non-repudiation

Parties to message exchanges cannot deny their actions.

  • Logging and auditing of messages.

These security features are combined to provide security capabilities. For example, identity, authorization, and non-repudiation are used to record the activities of clients. For more information about security considerations, see "Windows Communication Foundation Security" in the Windows SDK.

Securing Messages

When securing messages between entities using the standard bindings, there are two main decision points: whether to secure at the transport or message level (or both), and the type of credentials to use for both the client and the service.

Windows Communication Foundation secures messages during transmission in the following ways:

  • Transport security is available through the HTTPS over HTTP and SSL protocol over TCP. Both of these transport security protocols have the advantages of being widely deployed and supported, and having good data throughput rates.

  • SOAP message security is implemented through the WS-Security protocol, which has the advantage of providing end-to-end security through intermediaries, and flexible and rich credential support (including point of origin information).

  • Securing at both the transport and message. This scenario is a mixture of providing encryption at the transport level and integrity (signing) at the message level, thereby providing the best of both in applicable scenarios.

Different standard bindings have different security choices. Bindings that are specific to Windows-only solutions (for example, NetNamedPipeBinding) only use Windows security. The standard interoperable bindings BasicHttpBinding and WSHttpBinding support HTTPS transport security and WS-Security message content security.

All the bindings that support security have an overloaded constructor that takes a security mode enumeration parameter, SecurityMode which can have the following values:

SecurityMode value

Description

None

No security.

Message

The security capabilities are enforced at the SOAP message content level

Transport

The security capabilities are enforced at the transport level (authenticated occurs at the transport level).

TransportWithMessageCredential

Confidentiality (encryption) is secured at the transport and client is authenticated at the message level. For example a username and password are sent as clear text in the message, which is encrypted over HTTPS

The second main decision point in securing a message is how to provide the credentials for authentication and these are also binding dependent. The example below shows how to set a service X509 certificate onto an endpoint that uses a basicHttpBinding. The service certificate is set by specify the ServiceCredentialBehavior which indicates where to find the certificate named "ServerCert" which is used to encrypted and authenticate the message to the service from the client.

    <system.serviceModel>
      <client>
        <endpoint       address="http://localhost/MessageMutualCertificateService/service.svc"
            bindingConfiguration="SecureStockQuoteServiceBinding"
            binding="basicHttpBinding"
            contract="IStockService"
      behaviourConfiguration="ServiceCredentialBehavior"
            name="SecureStockQuoteService">
       <bindings>
          <binding name="SecureStockQuoteServiceBinding">
            <security mode="Message">
              <message clientCredentialType="Certificate"/>
              </security>
          </binding>
        </basicHttpBinding>
      </bindings>
      <behaviors>
<behavior name=" ServiceCredentialBehavior">
   <clientCredentials>
<serviceCertificate x509FindType="FindBySubjectDistinguishedName" findValue="cn=ServerCert" />
   </clientCredentials>
        </behavior>
      </behaviors>
    </system.serviceModel>

The credential types that can be supplied to the binding to authenticate the client and the service are None (anonymous), Certificate, Windows, UserName, and IssuedToken (SAML).

Securing Resources (Authorization)

Windows Communication Foundation is designed for extensible authorization in a wide range of scenarios. The authorization is a claims-based model that provides facilities for defining access controls for resources in a distributed system, enforcing such access controls, and mapping sets of claims to other sets of claims. A typical scenario for this is messages sent to a web service. The access control requirements of the web service use identity, roles, or groups. The message sender is mapped to a set of roles or groups. Role or group information is used to perform access checks.

One way this is set in WCF is via the PrincipalPermissionMode. This attribute supports the following parameters:

Parameter

Description

None

Indicates that CurrentPrincipal is not set. PrincipalPermission cannot be used.

UseWindowsGroups

Indicates that Thread.CurrentPrincipal is populated with a WindowsPrincipal based on the user credentials of the incoming message. PrincipalPermission can be used with User and/or Role specification.

UseAspNetRoles

Indicates that Thread.CurrentPrincipal is populated with an IPrincipal based on ASP.NET role information (an appropriate Role Provider must be configured for the service). PrincipalPermission can be used with User and/or Role specification.

Custom

Indicates that a custom IAuthorizationPolicy implementation is used to populate Thread.CurrentPrincipal. IAuthorizationPolicy is an interface that enables you to check a ClaimSet class and provides the most flexible form of Authentication

Client Impersonation at the Service

When using a Windows security the service operations can run using the identity and privileges of the invoking client. The following steps enable client impersonation:

  • In the service implementation class, for every operation that will enable impersonation, modify the OperationBehaviorAttribute annotation to set the Impersonate parameter to true.

  • On the client side, use the SetSspiSettings method of the ChannelSecurityCredentials class to set the appropriate impersonation level. This method uses the TokenImpersonationLevel enumeration to specify impersonation level. The following code demonstrates:

    IProperNamesService proxy =
        ChannelFactory.CreateChannel<IProperNamesService>(uri, binding);
    proxy.ChannelFactory.Security.SetSspiSettings(
        TokenImpersonationLevel.Impersonation);
    

Alternately, individual service operations can impersonate clients by using the standard .NET Framework impersonation mechanisms provided by the System.Security.Principal.Identity class. For example, the following line impersonates the current client:

ServiceSecurityContext.Current.WindowsIdentity.Impersonate();

Auditing

After a service is deployed, it is often vital from a management and security standpoint to obtain usage information, especially when failures or security violation attempts occur. For more information about auditing in Windows, see "Auditing Security Events" in Microsoft TechNet. Similar to Windows Security, the ServiceSecurityAuditBehavior class controls audits for a service through its public properties.

Property

Description

AuditLogLocation

An enumeration that specifies the log file. The values can be Default, Application, or Security.

MessageAuthenticationAuditLevel

An AuditLevel that specifies which types of message authentication events are audited. The choices are None, Failure, Success, and SuccessOrFailure.

ServiceAuthorizationAuditLevel

An AuditLevel that specifies which types of service authorization events are audited. The choices are None, Failure, Success, and SuccessOrFailure.

SuppressAuditFailure

A Boolean that specifies what occurs to the client request when auditing fails (for example, because the event log is full). The default value of true indicates that failures are ignored and the client request is processed normally.

If the AuditLogLocation property is not specified, then the default log file chosen depends on the operating system:

  • If the operating system (Windows Vista® and Windows 2003 Server) supports the security event log, and the service thread has proper privileges (SeSecurityPrivilege), then the record will be written to the security event log.

  • Earlier versions of Windows (for example, XP SP 2 (and earlier) and Windows 2000) will write to the general application log file.

The event log files can be viewed with the Event Viewer tool (Eventvwr.msc), which is a Microsoft Management Console (MMC) snap-in.

Auditing is enabled and configured by adding a serviceSecurityAudit element as a behavior to the services configuration file. This is demonstrated by the following code:

<system.serviceModel>
   <behaviors>
      <behavior>
         <serviceSecurityAudit
            auditLogLocation = Application
            suppressAuditFailure = true  
            authorizationAccessCheck = Failure  
            messageAuthenticationAuditLevel = SuccessOrFailure /> 
      </behavior>
   </behaviors>
</system.serviceModel>

For more information about auditing in Windows Communication Foundation, see "Auditing Security Events" in the Windows SDK.

Reliable Sessions

Windows Communication Foundation supports the reliable delivery of messages between two endpoints through the WS-Reliable Messaging protocol. Reliable messaging sessions provide two guarantees:

  • Exactly-once delivery of a message.

  • Optionally, ordered delivery of messages.

These services are guaranteed even for messages sent across SOAP or transport intermediaries (for example, routers, bridges, firewalls, and NATs).

A reliable session is created through a very simple procedure:

  • Select one of the bindings that support it (for example, WSHttpBinding, WsDualHttpBinding, or NetTcpBinding).

  • Set the ReliableSession property of the binding to true.

  • If ordered delivery is also required, also set the OrderedSession property to true.

Reliable sessions can also be specified by setting the Sessions property of the ServiceContractAttribute to true. However, if the service is run with bindings that do not support reliable sessions or if this capability has not been enabled, then an InvalidOperationException will occur. Some forms of communication (for example, duplex services using the CallbackContract property) require a session to be established in order to communicate independently between a particular service and client instance.

For more information about using reliable sessions, see "Creating Reliable Sessions" in the Windows SDK.

Queues

Windows Communication Foundation supports reliable delivery of messages between two endpoints, even when the two WCF endpoints are not running at the same time, through MSMQ. This increased isolation between the communicating WCF endpoints ensures overall high availability of the application. The queue support in WCF provides:

  • Exactly-once delivery of a message or no assurances delivery of a message.

  • Grouping messages in a session with optional ordering.

  • Transacted send to queue and receive from queue of messages.

  • Storing messages in a volatile or a durable queue.

  • Per-application dead lettering.

  • Poison Message Handling.

WCF provides 2 queued bindings:

  • NetMsmqBinding for use to communicate between two WCF endpoints.

  • MsmqIntegrationBinding for use to communication between a WCF endpoint and an existing MSMQ application.

A service that requires queued delivery can specify a QueuedDeliveryRequirement attribute in the service contract set to Allowed, NotAllowed, or Required. If Required is specified, then the service must be run with a binding that supports queued messaging.

For more information about queued communication support, see "Queues in Windows Communication Foundation" in the Windows SDK.

Transactions

The Windows Communication Foundation transaction feature supports:

  • The ability to automatically create local transactions for a service operation.

  • The ability to flow a transaction between 2 WCF endpoints

  • The ability to flow to and receive transactions from other WS-AT systems

  • The ability to use a transaction to read or write channels that are backed by a Resource Manager such as a queue. MSMQ uses this feature to read and write to queues.

Support for transactions in WCF is built upon existing .NET Framework support for transactions in the System.Transactions namespace. For more information, see "Transaction Processing" in the Windows SDK.

WCF supports interoperable distributed transactions through the following standard specifications:

  • WS-Coordination to propagate transactions between web service endpoints.

  • WS-AtomicTransaction (WS-AT) to coordinate transaction outcomes between transaction managers.

Windows Communication Foundation can use these specifications to flow transactions across multiple databases or services, including third-party Web services that support this framework. WS-AT support is integrated into the Microsoft Distributed Transaction Coordinator (MSDTC).

At the service model level, basic support for transactions can be added to a system through the following steps. (Note that some basic bindings, for example BasicHttpBinding, do not support transactions.)

  1. Modify the service behavior to indicate which operations require the use of local transactions by using the TransactionScopeRequired property on the OperationBehaviorAttribute.

  2. Modify the service contract to indicate which operations support or require incoming distributed transactions by applying the TransactionFlowAttribute to the corresponding service methods. This attribute can be initialized to TransactionFlowOption.NotAllowed, Allowed, or Mandatory.

  3. Code the client to create and manage transactions using the standard System.Transactions namespace members. For example, one common method of using transactions is represented by the following code:

    Using (TransactionScope tx = new TransactionScope())
    {
        // do work, including WCF operations
        tx.Complete();
    }
    

In addition to this basic mechanism, transaction support can be modified at the service and operation level through the ServiceBehaviorAttribute and OperationBehaviorAttribute, respectively. The following properties can be set for the entire service.

Property

Description

TransactionAutoCompleteOnSessionClose

Specifies whether an incomplete transaction is automatically completed when a session is closed. If this property is false, incomplete transactions will be rolled back when a session is closed. The default is false.

ReleaseServiceInstanceOnTransactionComplete

Specifies whether the underlying service instance is released when a transaction completes. The default is true.

TransactionIsolationLevel

Specifies the isolation level used to create new transactions created at the service. If this property is specified, incoming transactions must have the same isolation level as the specified value. The default is IsolationLevel.Unspecified, which creates new transactions with IsolationLevel.Serializable and allows incoming transactions with any isolation level.

TransactionTimeout

Specifies the time period within which a new transaction created at the service must complete or else it will be rolled back. The default is the System.Transactions default.

The following OperationBehaviorAttribute properties can be set for individual operations.

TransactionScopeRequired

Specifies whether a method must execute within a transaction scope. The transaction may be local to the service, or distributed if the TransactionFlowAttribute was enabled on the method.

TransactionAutoComplete

Specifies whether the transaction in which the method executes is automatically completed if no unhandled exceptions occur.

For more information about these properties, see "ServiceModel Transaction Attributes" in the Windows SDK.

A transaction completes when one of the following occurs:

  • An auto-complete operation returns. An auto-complete operation is marked by setting the associated TransactionAutoComplete property of OperationBehaviorAttribute equal to true.

  • The service calls the SetTransactionComplete method of the associated OperationContext.

  • A client closes a session associated with an active transaction and the TransactionAutoCompleteOnSessionClose property is enabled.

  • A transaction will roll back when one of the following occurs:

  • The service operation throws an exception.

  • The current transaction is explicitly rolled back.

  • The transaction times out.

A resource manager enlisted on the transaction votes to roll back. There are many additional issues and options concerning transactions that should be considered before implementing a transaction-based system. For more information, see "Using Windows Communication Foundation Transactions" in the Windows SDK.

Message Logging and Tracing

Windows Communication Foundation uses the .NET Framework for logging, tracing, and auditing, although it adds its own schema for configuration file elements. Although their uses can overlap, tracing is commonly used to aid debugging during application development. Logging is commonly used to troubleshoot deployed solutions. Auditing is used to monitor a stable deployed solution.

For more information about general WCF support, see "Windows Communication Foundation Administration and Diagnostics" in the Windows SDK.

For more information about .NET Framework support for tracing, see "Tracing" and "Instrumenting Applications" in the Windows SDK.

For more information about .NET Framework support for logging, see "Logging Application, Server, and Security Events" in the Windows SDK.

Message Logs

A message log is a file that contains an entry for each message sent or received, including transport, service model, malformed, fault, and WS-* messages. Message logging is configured by adding the System.ServiceModel.MessageLogging trace source and a trace source listener in the <system.diagnostics> section, and the <messageLogging> options element in the <diagnostics> section under <system.serviceModel> in the application's configuration file (client or/and server). The message's capture process can be modified through the properties of the MessageLoggingElement class as follows:

Property

Description

LogEntireMessage

A Boolean that determines whether the whole message is logged. The default is false.

LogMalformedMessages

A Boolean that determines whether malformed messages are logged. The default is false.

LogMessagesAtServiceLevel

A Boolean that determines whether service-level messages are logged. The default is false.

LogMessagesAtTransportLevel

A Boolean that determines whether transport-level messages are logged. The default is false.

MaxMessagesToLog

An Int32 value that sets an upper limit on the number of messages to log.

MaxSizeOfMessageToLog

An Int32 value that sets an upper limit on the length of each message that is logged. Longer messages are truncated.

Filters

A collection of XPath filters to use to screen the transport-level messages. If LogMessagesAtTransportLevel is set to false, this property is ignored.

By default, message logging is off. To enable message logging, the trace listener behavior (including the location of the log files) must be specified in the application's configuration files. The following code sample demonstrates a configuration file diagnostics sections that specify message logging for the example service. In addition to enabling message logging, it also enables performance counters for the service in the <diagnostics> section. For more information about using performance data, see "Introduction to Monitoring Performance Thresholds" in the Windows SDK.

<system.diagnostics>
  <sources>
   <source name="System.ServiceModel.MessageLogging">
      <listeners> 
          <add name="messages"
           type="System.Diagnostics.XmlWriterTraceListener"
           initializeData="C:\logs\messages.e2e"/>
      </listeners>
   </source>
  </sources>
</system.serviceModel>

<system.serviceModel>
...
   <diagnostics performanceCountersEnabled="true">
      <messageLogging 
          logEntireMessage="true"
          maxMessagesToLog="300" 
          logMessagesAtServiceLevel="true"
          logMessagesAtTransportLevel="true"
          logMalformedMessages="true">
         <filters>
            <add xmlns:soap="http://www.w3.org/2003/05/soap-envelope">/
                               soap:Envelope</add>
         </filters>
      </messageLogging>
   </diagnostics>
</system.serviceModel>

Tracing

A very detailed and extensive record of standard and custom occurrences and conditions can be generated for a Windows Communication Foundation solution by enabling end-to-end tracing. Standard tracing records the calls to proxies, operation calls and returns, transport protocol processing, and helper actions. Tracing relies on the System.Diagnostics namespace and is also configured in the <system.diagnostics> section of the application's configuration files. To receive trace data, a trace listener for the trace source needs to be created by inserting the following XML section into the application's configuration file, as described above for the System.ServiceModel.MessageLogging trace source:

<system.diagnostics>
    <sources>
      <source name="myTraceSource" 
              switchValue="Verbose, ActivityTracing" >
            <listeners>
            <add name="xml"
                    type="System.Diagnostics.XmlWriterTraceListener"
                    initializeData="C:\logs\ServiceTraces.e2e" />
            </listeners>
        </source>
    </sources>
    <trace autoflush="true" />
</system.diagnostics>

If ActivityTracing is set, activity boundaries and transfers between activities are emitted as traces. Activities are logical units of work (for example, a request/response) and group traces related to the same unit of work. Transfers are correlations between activities.

The System.ServiceModel is a pre-defined trace source to view all traces emitted in WCF. If propagateActivity="true" is specified in the ServiceModel trace source, WCF propagates activity ids across endpoints for end-to-end correlation.

    <sources>
        <source name="System.ServiceModel" switchValue="Verbose, 
                                           ActivityTracing" 
                                           propagateActivity="true">
            <listeners>
            <add name="xml"
                    type="System.Diagnostics.XmlWriterTraceListener"
                    initializeData="C:\logs\ServiceTraces.e2e" />
            </listeners>
        </source>
    </sources>

Depending on the trace level, traces are produced at different detail levels. All traces created by a particular listener appear in the same file.

The Trace Viewer Tool (SvcTraceViewer.exe) is provided for inspecting trace log files. This GUI utility gives a wealth of information on each log file, the trace sets in it, and each individual trace record. (Currently, the tool supports files with the "e2e" extension.)

When using Tracing and Message Logging, Personally Identifiable Information may be logged, in particular when logging application-specific data. For more information, see "Windows Communication Foundation Administration and Diagnostics" in the Windows SDK.

For more information about message logging and tracing, see the "Tracing and Logging Example", "Windows Communication Foundation Configuration Schema", and "Trace and Debug Settings Schema" in the Windows SDK.

Community Additions

Show:
© 2015 Microsoft