Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

WCF Fundamentals

Download as pdf or txt
Download as pdf or txt
You are on page 1of 39

WCF

Fundamentals
By Palash Biswas
WCF Fundamentals Chapter Name

Contents
Chapter 1 Overview of WCF ............................................................................................................................ 3
1.1 What is Windows Communication Foundation? ....................................................................................... 4
1.2 WCF Service Model .................................................................................................................................. 4
Chapter 2 Creating a Simple WCF Service .................................................................................................... 6
2.1 WCF Contracts and its implementation .................................................................................................... 7
2.1.1 Service Contract ............................................................................................................................... 7
2.1.2 Operation Contract ........................................................................................................................... 7
2.1.3 Data Contract.................................................................................................................................... 7
2.1.4 Message Contract ............................................................................................................................ 8
2.1.5 Fault Contract ................................................................................................................................... 8
2.1.6 Examples .......................................................................................................................................... 8
Chapter 3 WCF Bindings ............................................................................................................................... 11
3.1 Choosing a Predefined Binding in WCF ................................................................................................. 12
Chapter 4 Options for Hosting a WCF Service............................................................................................ 13
4.1 Internet Information Server (IIS).............................................................................................................. 14
4.2 Windows Activation Service (WAS) ........................................................................................................ 14
4.3 S elf Hosting ............................................................................................................................................ 14
4.4 Managed Windows Service..................................................................................................................... 15
4.5 Configure Endpoints of Service............................................................................................................... 15
Chapter 5 Creating and Invoking a WCF Client .......................................................................................... 16
5.1 Fundamentals of Creating a WCF Client ................................................................................................ 17
5.2 Creating a Client by Using a Channel Factory........................................................................................ 17
5.3 Asynchronous Invocation in WCF ........................................................................................................... 18
Chapter 6 Customizing WCF with Behaviors .............................................................................................. 19
6.1 Overview of WCF Behaviors ................................................................................................................... 20
Chapter 7 Introduction of WCF Security...................................................................................................... 21
7.1 Security Features of WCF....................................................................................................................... 22
7.2 Security Modes of WCF .......................................................................................................................... 22
Chapter 8 Authentication and Authorization in WCF ................................................................................. 24
Chapter 9 Reliability in WCF Applications .................................................................................................. 26
9.1 Transactions in WCF............................................................................................................................... 27
9.2 Reliable Sessions in WCF....................................................................................................................... 28
Chapter 10 WCF Administration and Diagnostics.................................................................................... 29
10.1 WCF Message Logging ...................................................................................................................... 30
Chapter 11 Security Concerns for Message Logging .............................................................................. 34
11.1 Security Concerns............................................................................................................................... 35
Chapter 12 Ajax and WCF ........................................................................................................................... 36

Kovair Software Inc. 2009 2


WCF Fundamentals Chapter Name

1
Chapter 1 Overview of WCF

Kovair Software Inc. 2009 3


WCF Fundamentals Chapter Name

This chapter will provide an overview of Windows Communication Foundation along with a high-level
explanation of the WCF service model.

1.1 What is Windows Communication


Foundation?
Windows Communication Foundation is Microsoft's next generation technology for developing distributed
applications.

WCF has been built to facilitate the development of service-oriented applications. The communication between
loosely coupled clients and services is based on a model that uses schemas and contracts, rather than classes
and types. Schemas and contracts are independent of programming language, hosting platform, or
implementation. As a result, this model provides many benefits such as maintainability, reusability, and
manageability of your code and your solution. In addition, loosely coupled services tend to model real-world
systems.

WCF can communicate by using Web services, so it can interoperate with other platforms that can use Simple
Object Access Protocol (SOAP), such as Java 2, Enterprise Edition (Java EE).

WCF provides low-level asynchronous operations for passing untyped primitive messages. Higher-level
services are layered on top, including typed messages, secure message exchange, reliable message
exchange, transacted messaging, and queued messaging.

WCF has been designed to integrate and unify existing distributed computing technologies. It is interoperable
with WSE 3.0, System.Messaging, .NET Enterprise Services, and ASMX Web services. This means that, with
little or no change to code, existing applications that are built with these technologies can interoperate with
WCF services.

1.2 WCF Service Model


WCF services expose endpoints that clients and services use to exchange messages. Each endpoint consists
of an address, a binding, and a contract.

The Address identifies where the service is located on the network. The address format is protocol specific.
Addresses can be specified in code or in configuration files. Configuration files are preferable, because they
enable an administrator to configure addresses at deployment time.

The Binding defines how the client needs to communicate with the service. For example, a binding defines the
underlying transport protocol, security requirements, and message encoding.
WCF provides several standard bindings whose behaviors can be modified in configuration files. For example,
BasicHttpBinding exposes an HTTP-based WCF service that encodes SOAP messages in text format. This
binding is used for interoperability. WsHttpBinding adds support for advanced Web service features, such as
transactions and reliable messaging. NetMsmqBinding uses Microsoft Message Queuing, or MSMQ, as the
transport.

The Contract defines what the service can do. WCF specifies attributes that can be used to define contract
types, including those that define service operations, messages, data types, and fault behavior. A service

Kovair Software Inc. 2009 4


WCF Fundamentals Chapter Name

contract defines the operations that are available at the endpoint. A service contract is defined by a .NET
Framework interface that has added WCF attributes. A class, called the service type, implements the interface
to provide the implementation of the service operations

To make your WCF services widely accessible, you can use ASP.NET and Internet Information Services, or IIS,
to host HTTP-based WCF services. In addition, you can use any .NET Framework application to host your WCF
services by using the ServiceHost class. The service can provide metadata about its endpoints to clients in the
form of Web Service Description Language, or WSDL.
Client-side tools can use WSDL, to generate a proxy through which the client communicates with the service.
The proxy contains a client that is capable of invoking the service contract WSDL specifies, and configuration
information provides address and binding information.

Kovair Software Inc. 2009 5


WCF Fundamentals Chapter Name

2
Chapter 2 Creating a Simple WCF
Service

Kovair Software Inc. 2009 6


WCF Fundamentals Chapter Name

This chapter describes the fundamental principles of the implementation of WCF services, including WCF
contract types and hosting options. The lesson also describes the process of creating and configuring a basic
service.

2.1 WCF Contracts and its implementation


WCF contracts define the behavior of WCF services. They are created in code by service developers and are
exposed to clients in the service metadata. The five types of contracts are described below.

2.1.1 Service Contract


A service contract defines the operations that a service supports and maps to a portType in Web Service
Description Language (WSDL). Service contracts are implemented as .NET Framework interfaces that are
annotated with the ServiceContract attribute.

[ServiceContract]
public interface IMyContract

{ ...}

2.1.2 Operation Contract


Operation contracts define the individual operations that a service supports and map to operations in WSDL.
Operations are defined by adding methods to a Service Contract interface that is annotated with the
OperationContract attribute.

[ServiceContract]
public interface IMyContract

{ ...}
[OperationContract]
void SomeOperation();

2.1.3 Data Contract


Data contracts define how complex types are serialized when they are used in WCF service operations. They
are defined by applying the DataContract and DataMember attributes to classes, felds and properties.

Kovair Software Inc. 2009 7


WCF Fundamentals Chapter Name

[DataContract]
public class SomeType
{
[DataMember]
public int ID;
}

2.1.4 Message Contract


Message contracts describe the entire SOAP message format. They can use data contracts and serializable
types to emit schema for complex types, and they also make it possible to control the SOAP message headers
and body explicitly, by using a single type. Message contracts provide a simple method to add custom SOAP
headers to incoming and outgoing messages.

[MessageContract]
public class MyRequest
{
[MessageHeader]
public string field1;
[MessageBody]
public string field2;

2.1.5 Fault Contract


A WCF service reports errors by using Fault objects. Fault contracts document the errors that WCF code is
likely to produce, and WCF maps Fault objects to SOAP faults. Note that the type specified in the FaultContract
does not have to be an exception, although it often will be.

[OperationContract]
[FaultContract(typeof(DivideByZeroException))]
void SomeMethod();

A Fault is generated by throwing a FaultException:

throw new FaultException<DivideByZeroException>(someException);

2.1.6 Examples
2.1.6.1 A Service Contract Definition
The following code example shows how to define a WCF service contract by using a .NET Framework
interface. The ServiceContract attribute is applied to the interface, and each of the methods defined in the
interface has the OperationContract attribute applied to it. Note that any methods that are not marked with
OperationContract are not visible to clients.

[ServiceContract]
public interface IOrderService
{

Kovair Software Inc. 2009 8


WCF Fundamentals Chapter Name

[OperationContract]
void CreateOrder(int orderNumber);

[OperationContract]
void AddItemToOrder(int orderNumber, Item itm);

[OperationContract]
Order GetOrderDetails(int orderNumber);
}

2.1.6.2 Service Contract Implementation


The following code example shows how to implement a WCF service contract by using a .NET Framework
class that implements a service contract interface. Note that the implementing class does not require any
special attributes.

public class OrderService : IOrderService


{
void CreateOrder(int orderNumber)
{
// implementation details
}

void AddItemToOrder(int orderNumber, Item itm)


{
// implementation details
}
Order GetOrderDetails(int orderNumber)
{
// implementation details
}
}

2.1.6.3 Data Contract Implementation


The following code example shows how to implement a WCF data contract. The DataContract attribute is used
to define a data contract class and DataMember attributes define the class members that take part in the
contract.

[DataContract]
public class Order
{

Kovair Software Inc. 2009 9


WCF Fundamentals Chapter Name

[DataMember]
public int OrderNumber;
[DataMember]
public String ClientName;
...
}

Kovair Software Inc. 2009 10


WCF Fundamentals Chapter Name

3
Chapter 3 WCF Bindings

Kovair Software Inc. 2009 11


WCF Fundamentals Chapter Name

WCF Bindings

A WCF binding is an object that specifies how to connect to the endpoint of a WCF service, and each endpoint
must have a binding associated with it. WCF ships with a number of predefined bindings that cover most
common scenarios, although it is also possible to create custom bindings.

A binding contains the following three categories of information:

1. Protocol information, such as the security mechanism that is being used, and the reliable messaging and
transaction settings.
2. Information about the underlying transport protocol to use, such as TCP or HTTP.
3. Information about the message encoding, for example, Text or XML, Binary, or Message Transmission
Optimization Mechanism (MTOM).

Bindings contain a collection of binding elements, such as SecurityBindingElement and TcpTransportElement,


which define a communication stack, and the operation of the stack depends on the order in which the binding
elements were added to the collection.

Binding information can be complex, and not all options may be compatible. For this reason, WCF provides a
set of predefined combinations of binding elements that are appropriate for many common scenarios. For
example, BasicHttpBinding enables basic Web service communication by using text or HTML, with
WSHttpBinding also supporting many of the WS-* standards. NetMsmqBinding uses queuing to communicate
between WCF applications, and MsmqIntegrationBinding integrates WCF and existing MSMQ applications.

3.1 Choosing a Predefined Binding in WCF


Binding Used For

BasicHttpBinding Basic Web service communication. No security by default.

WSHttpBinding Web services with WS-* support. Supports transactions.

WSDualHttpBinding Web services with duplex contract and transaction support.

WSFederationHttpBinding Web services with federated security. Supports transactions

MsmqIntegrationBinding Communication directly with MSMQ applications. Supports transactions


Communication between WCF applications by using queuing. Supports
NetMsmqBinding
transactions.
Communication between WCF applications on same computer. Supports
NetNamedPipeBinding
duplex contracts and transactions
Communication between computers across peer-to-peer services. Supports
NetPeerTcpBinding
duplex contracts.
Communication between WCF applications across computers. Supports
NetTcpBinding
duplex contracts and transactions.

Kovair Software Inc. 2009 12


WCF Fundamentals Chapter Name

4
Chapter 4 Options for Hosting a WCF
Service

Kovair Software Inc. 2009 13


WCF Fundamentals Chapter Name

WCF is flexible because its services can be hosted in different types of applications. The following table lists
several common scenarios for hosting WCF services.

4.1 Internet Information Server (IIS)


WCF services can be hosted within Internet Information Services, which provides a number of advantages if the
service uses HTTP as its transport protocol. There is no requirement to write hosting code as part of the
application and IIS automatically activates the service code as required.

Services also benefit from IIS features such as management of process lifetime and automatic application
restart after configuration changes.

Services can be run within IIS by creating a .svc file, which contains the service code, and a configuration file,
which contains binding information, and then saving them in an IIS virtual directory.

4.2 Windows Activation Service (WAS)


Windows Activation Service is the new process activation mechanism that is a feature of IIS 7.0. IIS 7.0 is a
part of Microsoft Windows Vista, the Microsoft Windows Server 2008.

WAS builds on the existing IIS 6.0 process and hosting models, but is no longer dependent on HTTP.

Although IIS 7.0 uses WAS over HTTP, WCF can use WAS to provide message-based activation over other
protocols, such as TCP and named pipes. This helps WCF applications to take advantage of WAS features,
such as process recycling, rapid fail protection, and the common configuration system, which were previously
available only to HTTP-based applications.

4.3 S elf Hosting


WCF services can be hosted inside any .NET managed application, such as console applications and Windows
Forms or Windows Presentation Foundation (WPF) graphical applications.

A developer creates a class that implements a WCF service contract interface, and specifies binding
information in the application configuration file. The application code can then use an instance of
System.ServiceModel.ServiceHost to make the service available at a particular Uniform Resource Identifier
(baseAddress in the following code example).

ServiceHost myHost = new ServiceHost(typeof(MyService), baseAddress);

The service is started by calling the Open method on the host:

myHost.Open();

Kovair Software Inc. 2009 14


WCF Fundamentals Chapter Name

4.4 Managed Windows Service


A WCF service can be registered as a Windows Service, so that it is under control of the Windows Service
Control Manager (SCM). This is suitable for long-running WCF services that are hosted outside of IIS in a
secure environment and are not message-activated. The WCF service benefits from the features of Windows
Services, such as automatic start at start time and control by the SCM.

To host a WCF service in this way, the application must be written as a Managed Windows Service by inheriting
from System.ServiceProcess.ServiceBase. It must also implement a WCF service contract interface and then
create and open a ServiceHost to manage the WCF service.

4.5 Configure Endpoints of Service


WCF service Endpoints can be configured in code or by using configuration files. If you are hosting a service in
IIS, you use the web.config file, but you use the application configuration file for any other application.

Each service must have an endpoint defined. An endpoint consists of an address that shows where the
endpoint is located, a binding that specifies communication information, and a service contract that identifies
the methods that the service supports.

An endpoint address contains a URI as well as other optional properties, such as an identity, WSDL elements,
and headers. The optional properties can be used for tasks, such as routing incoming messages or deciding
where to send a reply.

To define an endpoint in code, use the AddEndpoint method on the ServiceHost object to pass in an address, a
binding object, and a service contract in the form of an interface.

Uri echoUri = new Uri("http://localhost/MathService/Ep1");


WSHttpBinding binding = new WSHttpBinding();
ServiceHost.AddEndpoint(typeof(IMath), binding, echoUri);

To set up endpoints in configuration files, define <endpoint> elements within a parent <service> element inside
the <system.ServiceModel> section of your configuration file.

<endpoint address="http://localhost/MathService/Ep1" binding="wsHttpBinding"


contract="IMath"/>

Kovair Software Inc. 2009 15


WCF Fundamentals Chapter Name

5
Chapter 5 Creating and Invoking a WCF
Client

Kovair Software Inc. 2009 16


WCF Fundamentals Chapter Name

This lesson describes the options for creating a client to a service, including two methods for creating clients, by
using proxies and channel factories. It also describes how clients can invoke operations asynchronously, and
how duplex contracts allow a service to call back to a client.

5.1 Fundamentals of Creating a WCF Client


Like almost all other distributed technologies, clients use proxies to access WCF services. Proxies can be
created in one of two ways: at design time by using the svcutil.exe command line tool or dynamically at runtime
by using a ChannelFactory.

The svcutil.exe command line tool can create a proxy and configuration file from WCF service metadata. The
proxy has no reference to the service implementation, but does reference the contract that is exposed by the
service. The configuration file can be used to provide the address and the binding. Note that each proxy
instance points at exactly one endpoint, and the endpoint is provided to the proxy at construction time.

The service is accessed by creating a proxy object and then by calling service operations. Calling Open locks
the settings of the proxy, the channel is opened on the first call, and closed when Close is called, or the proxy is
disposed.

The proxy class implements IDisposable, so in C# a using statement can be used to control the lifetime of the
proxy. The constructor argument refers to the endpoint to be used by this proxy:

using (TestProxy tp = new TestProxy("default"))


{
// use tp to call service
}

5.2 Creating a Client by Using a Channel Factory


You can also use a ChannelFactory object to create a client, as described below

Create a ChannelFactory object by specifying the address, binding details, and contract details. The contract is
used to parameterize the factory class, as shown in the following code:

ChannelFactory<IGreetingService> ch = new ChannelFactory<IGreetingService>(new


BasicHttpBinding(), new
EndpointAddress("http://localhost/MyGreetingService/EndPoint1"));

You can now create a channel, which starts in the Created state; which means that the channel can be
configured but it cannot used to send messages.

Kovair Software Inc. 2009 17


WCF Fundamentals Chapter Name

To send messages you must open the channel. This changes the state of the channel from Created to Opened.
At this point, you can send messages but you cannot configure the channel.

When you have finished, you call Close, whch allows any unfinished work to complete before closing the
channel.

ch.Open();
IGreetingService Service = ch.CreateChannel();
Service.Greeting("Palash");
ch.Close();

5.3 Asynchronous Invocation in WCF


All communication to this point has been synchronous, but it is also possible to call services asynchronously, so
that the client does not block while it is waiting for a response. Both services and clients can use asynchronous
calls, but they are mostly initiated from the client side.

Note: Calling an operation asynchronously is independent of how the operation is implemented. A synchronous
method can be called asynchronously, and an asynchronous method can be called synchronously.

Asynchronous invocation follows the .NET Async pattern in which a synchronous operation is broken down into
Begin and End operations. The Begin operation starts the process and returns immediately, and the End
operation queries for the result.

The client calls the Begin operation by passing any required parameters, a callback function, and a state object.
The callback function is called when the operation finishes. The state object can be any object you want to pass
to the callback function and in WCF it is usually a reference to the proxy:

IAsyncResult iar = proxy.BeginAdd(i1, i2, MyCallback, proxy);

This function returns immediately and provides an IAsyncResult that the caller can use to check the state of the
operation. The callback function is executed when the service operation completes, and the callback function
calls the matching End method:

static void MyCallback(IAsyncResult iar)


{
double val = ((AddProxy)iar.AsyncState).EndAdd(iar);
}

Kovair Software Inc. 2009 18


WCF Fundamentals Chapter Name

6
Chapter 6 Customizing WCF with
Behaviors

Kovair Software Inc. 2009 19


WCF Fundamentals Chapter Name

WCF behaviors provide a powerful way to customize the behavior of WCF services and clients. This lesson
describes the main features of WCF behaviors, and tells you how to configure them.

6.1 Overview of WCF Behaviors


Behaviors enable you to modify how service and clients operate. They can be applied at many places in WCF:
client channels, services, endpoints, contracts, and operations. Behaviors are purely local, so they have no
effect on contracts or messages and do not have to be compatible with both clients and services.

Behaviors may be code-only, or may also use configuration settings. For example, instancing behavior
determines how many instances are created in response to messages, and is specified in code:

[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
public class MyService : ISomeContract

Throttling allows you to set limits on access to a service, such as the number of connections or pending calls.
You configure throttling in the configuration file:

<throttling maxConcurrentCalls = "12" maxConnections = "34" maxInstances = "56" />

Developers can also retrieve the throttling settings at runtime, and modify them before opening the service.
There are a large number of predefined service and client behaviors in areas such as:
Service operation, such as concurrency, instancing, and throttling.
Error handling. Security, such as impersonation, authorization, and auditing.
Transactions, such as AutoEnlist, AutoComplete, Timeout, and Isolation.
Metadata.
Developers can create custom behaviors by using IServiceBehavior and IEndpointBehavior. Any class that
implements these interfaces can be used as a behavior and applied as an attribute or in a configuration file.

Kovair Software Inc. 2009 20


WCF Fundamentals Chapter Name

7
Chapter 7 Introduction of WCF Security

Kovair Software Inc. 2009 21


WCF Fundamentals Chapter Name

This lesson provides an overview of WCF security and introduces the high-level features of the WCF security
model. This lesson also provides a demonstration of how to configure message-based security.

7.1 Security Features of WCF


As a service provider, you need to know who is accessing your service and you need to control the level of
access that each client has to the service. You may also need to protect messages that are in transit from
eavesdropping and tampering.

WCF provides comprehensive security features in three main areas: transfer security, authentication and
authorization of clients, and auditing.

Transfer security supports two main mechanisms that you can use to protect messages. Transport mode uses
features of the underlying transport protocol, such as Secure Socket Layer, or SSL, to protect the channel.
Message mode uses WS-Security and other specifications to encrypt and sign the message. Transport mode is
efficient and well-understood, but it is only useful for point-to-point communication. Message mode is less
efficient, but it can be used to ensure that the message is protected on the network, through intermediary
nodes, and in persistent stores.

By default, WCF enables authentication and authorization, which is based on credentials and claims. A
credential provides proof of identity. It can also provide additional claims about the client. For example, an
X.509 certificate can contain a number of claims about a user, including company name and e-mail address. A
commonly used credential is the combination of a user name and password, and the user name on its own
provides a claim. Other credential types that WCF supports include Kerberos tokens and Security Assertion
Markup Language tokens.

WCF uses claims for authorization. Claims are extracted from credentials and used to provide sophisticated
access control. You can still use .NET Framework role-based authorization, but claims-based authorization
subsumes this model and provides greater flexibility. It enables authorization decisions to be based on more
than the authenticated callers identity or the roles to which that identity belongs.

Administrators must also be able to audit access to services. By default, WCF security events are written to the
Windows event log, so that administrators can see who has accessed a particular service. You can configure
auditing in code or in the service configuration file.
My NotesSecurity Features of WCF.

7.2 Security Modes of WCF


Many WCF services will require secure communication, where it is necessary to authenticate the sender of a
message, and to ensure that messages have not been read or tampered with by unauthorized third parties.
WCF can provide authentication, privacy, and integrity for messages by using two mechanisms.

Transport mode, which uses the security features of a transport layer such as HTTPS. This mode has
performance benefits due to the optimized nature of the underlying protocols, but it has a restricted set of
credential or claim types. This mode also only works between two transport endpoints.

Message mode, which protects the message itself by using a protocol such as WS-Security. Credential
information is embedded within the message so that this mode can support a richer set of claim types at the
expense of performance. This mode provides end-to-end security for the message.

Kovair Software Inc. 2009 22


WCF Fundamentals Chapter Name

WCF also supports a mixed mode, where integrity and privacy are provided by the transport, while
authentication is handled by using credentials in the message. This can give the best balance of performance
and flexibility.

You can specify the security for a binding by setting its SecurityMode property. By default, the BasicHttpBinding
has no security configured. Other HTTP bindings use WS-Security, and TCP and Named Pipe bindings use
Windows security.

Kovair Software Inc. 2009 23


WCF Fundamentals Chapter Name

8
Chapter 8 Authentication and
Authorization in WCF

Kovair Software Inc. 2009 24


WCF Fundamentals Chapter Name

WCF can establish that the sender of a message is who they claim to be, a process known as authentication,
and control access to resources based on identity, a process known as authorization. The following table
describes how an application can use message credentials and transport credentials, and how you can
implement authorization.

Message Credentials

An application that uses message mode can use the following credential types:

None (anonymous client)


Windows (Kerberos tokens)
Username tokens
X.509 certificates
Custom tokens, such as SAML tokens issued by a STS
Note that WCF enforces that the transport is secured when using user name credentials. WCF also prevents
you from using the username for encryption or to generate signatures.

You can configure the security of a binding by using the SecurityMode property. There are a number of
predefined combinations, such as HttpAuthentication and WSSecurityOverTcp

Transport Credentials

A transport may support more than one method for obtaining authentication information. For example,
HttpAuthentication supports a number of schemes including the following:

Anonymous
Basic
Digest
NT LAN Manager (NTLM)
Kerberos protocol
Certificate
Authorization
You can use the .NET PrincipalPermission attribute to restrict access to an operation based on name, role, or
authentication status. For example, the following code allows access to any caller who is a member of the
Administrators group:

[PrincipalPermission(SecurityAction.Demand, Role="Builtin\\Administrators")]
public void MyOperation()

{
...
}

Kovair Software Inc. 2009 25


WCF Fundamentals Chapter Name

9
Chapter 9 Reliability in WCF
Applications

Kovair Software Inc. 2009 26


WCF Fundamentals Chapter Name

WCF has several features that can be used to implement highly reliable messaging, independent of the
transport over which messages are sent. This lesson covers the reliability features of WCF, namely
transactions, queuing, and reliable sessions.

9.1 Transactions in WCF


Overview

A transaction treats a group of operations as an atomic unit, so either all succeed or all fail. WCF supports two
types of transactions: shared transactions and transacted messaging.

WCF supports two transaction protocols:

OleTransaction protocol. Used for transaction control between WCF applications.


WS-AtomicTransaction protocol. Enables WCF applications to flow transactions to interoperable applications,
such as Web services that have been built by using third-party technology. The ability to flow transactions
across services, even if they are on different platforms, is extremely powerful.

Client Side

Clients use a TransactionScope object to group operations into transactions:

using (TransactionScope sc = new TransactionScope())


{
service1.submitRequest(rq1);
service2.submitRequest(rq2);
sc.Complete();
}

As well as specifying transaction requirements, the client can control the isolation level and timeout for the
transaction by using a TransactionOptions object:

TransactionOptions top = new TransactionOptions();


top.IsolationLevel = IsolationLevel.ReadCommitted;
using (TransactionScope sc = new
TransactionScope(TransactionScopeOption.RequiresNew, top)) ...

Server Side

The ServiceBehavior attribute enables you to configure the service as a whole for transaction time-outs,
isolation level, and whether transactions complete when a session closes. The OperationBehavior attribute

Kovair Software Inc. 2009 27


WCF Fundamentals Chapter Name

helps you to control whether a transaction is required for an operation, and whether transactions complete if no
exception is thrown.

Configuring Transaction Flow

Transaction flow is governed by the following three factors:

TransactionFlow attributes applied to methods, which specify whether a transaction is required, allowed, or not
allowed.
TransactionFlow binding properties, which specify whether the binding supports transactions.
TransactionFlowProtocol binding properties, which specify whether to use the OleTransaction or WS-
AtomicTransaction protocol.
Developers use the TransactionFlow attribute to specify how their methods take part in transactions;
TransactionFlow binding and TransactionFlowProtocol binding properties enable administrators to specify
policy at deployment time.

9.2 Reliable Sessions in WCF


A reliable session provides session-based delivery for WCF messages, regardless of the number or type of
transport intermediaries between two endpoints. A reliable session provides the same reliability for SOAP
messages as TCP does for IP packets, but the reliability is provided at the SOAP message level, which
provides end-to-end reliability rather than the point-to-point reliability that is provided by TCP.

Reliable sessions handle lost or duplicated messages. Messages are delivered exactly once, and can optionally
be delivered in order. If a message cannot be delivered, the sender is informed.

Because reliable sessions can cope with transport disconnections and failures in SOAP or other intermediate
transports, they can provide benefits such as connection verification, connection maintenance, flow control (by
adapting the sending rate to the receiver) and congestion control (by adapting the sending rate to network load
levels).

They are enabled by default for theWsDualHttp, NetNamedPipeandMsmqIntegrationbindings, and can be


enabled for theNetTcp, WsHttpandWsHttpFederationbindings. Custom bindings can easily be configured to use
reliable sessions by adding areliableSessionelement to the binding description, and optionally by setting the
ordered attribute.

Kovair Software Inc. 2009 28


WCF Fundamentals Chapter Name

10
Chapter 10 WCF Administration and
Diagnostics

Kovair Software Inc. 2009 29


WCF Fundamentals Chapter Name

Windows Communication Foundation (WCF) provides a rich set of functionalities that can help you monitor the
different stages of an applications life. For example, you can use configuration to set up services and clients at
deployment. WCF includes a large set of performance counters to help you gauge your application's
performance. WCF also exposes inspection data of a service at runtime through a WCF Windows Management
Instrumentation (WMI) provider. When the application experiences a failure or starts acting improperly, you can
use the Event Log to see if anything significant has occurred. You can also use Message Logging and Tracing
to see what events are happening end-to-end in your application. These features assist both developers and IT
professionals to troubleshoot an WCF application when it is not behaving correctly.

10.1 WCF Message Logging


Windows Communication Foundation (WCF) provides the capability to log incoming and outgoing messages for
off line access. Message logging enables you to see what the message and message body looks like. This type
of logging is particularly helpful in letting you know what arguments were passed in and how the receiving
endpoint saw the arguments expressed as XML. In addition, logging the message as it was received allows you
to diagnose malformed messages as well as to see how the message arrived. You can also examine the
security tokens used, parts encrypted and signed, and parts left intact.

Configuring Message Logging

This topic describes how you can configure message logging for different scenarios.

Enabling Message Logging

Windows Communication Foundation (WCF) does not log messages by default. To activate message logging,
you must add a trace listener to the System.ServiceModel.MessageLogging trace source, and set attributes for
the <messagelogging> element in the configuration file.

The following is an example of enabling logging and specifying additional options.

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

<system.serviceModel>
<diagnostics>
<messageLogging
logEntireMessage="true"
logMalformedMessages="false"
logMessagesAtServiceLevel="true"
logMessagesAtTransportLevel="false"
maxMessagesToLog="3000"
maxSizeOfMessageToLog="2000"/>

Kovair Software Inc. 2009 30


WCF Fundamentals Chapter Name

</diagnostics>
</system.serviceModel>

You can use add to specify the name and type of the listener you want to use. In our example configuration, we
named the Listener "messages" and add the standard .NET Framework trace listener
(System.Diagnostics.XmlWriterTraceListener) as the type we want to use. If you use
System.Diagnostics.XmlWriterTraceListener, you must specify the output file location and name in the
configuration file. This is done by setting initializeData to the name of the log file. Otherwise, the system throws
an exception. You can also implement a custom listener that emits logs to a default file.

Caution:

Because message logging consumes disk space, you should limit the number of messages that are written to
disk for a particular service. When the message limit is reached, a trace at the Information level is produced and
all message logging activities stop.

The logging level, as well as the additional options, are discussed in the Logging Level and Options
section.

The switchValue attribute of a source is only valid for tracing. If you specify a switchValue attribute for the
System.ServiceModel.MessageLogging trace source as follows, it has no effect.

<source name="System.ServiceModel.MessageLogging" switchValue="Verbose">


If you want to disable the trace source, you should use the logMessagesAtServiceLevel,
logMalformedMessages, and logMessagesAtTransportLevel attributes of the messageLogging element
instead. You should set all these attributes to false. This can be done by using the configuration file in the
previous code example, through the Configuration Editor UI interface (SvcConfigEditor.exe).

Kovair Software Inc. 2009 31


WCF Fundamentals Chapter Name

Logging Levels and Options

For incoming messages, logging happens immediately after the message is formed, immediately before the
message gets to user code in the service level.

For outgoing messages, logging happens immediately after the message leaves user code, and immediately
before the message goes on the wire.

WCF logs messages at two different levels, service and transport. Malformed messages are also logged. The
three categories are independent from each other and can be activated separately in configuration.

You can control the logging level by setting the logMessagesAtServiceLevel, logMalformedMessages, and
logMessagesAtTransportLevel attributes of the messageLogging element.

Service Level

Messages logged at this layer are about to enter (on receiving) or leave (on sending) user code. If filters have
been defined, only messages that match the filters are logged. Otherwise, all messages at the service level are
logged. Infrastructure messages (transactions, peer channel, and security) are also logged at this level, except
for Reliable Messaging messages. On streamed messages, only the headers are logged. In addition, secure
messages are logged decrypted at this level.

Transport Level

Messages logged at this layer are ready to be encoded or decoded for or after transportation on the wire. If
filters have been defined, only messages that match the filters are logged. Otherwise, all messages at the
transport layer are logged. All infrastructure messages are logged at this layer, including reliable messaging
messages. On streamed messages, only the headers are logged. In addition, secure messages are logged as
encrypted at this level, except if a secure transport such as HTTPS is used.

Malformed Level

Malformed messages are messages that are rejected by the WCF stack at any stage of processing. Malformed
messages are logged as-is: encrypted if they are so, with non-proper XML, etc.

Kovair Software Inc. 2009 32


WCF Fundamentals Chapter Name

Other Options

In addition to the logging levels, the user can specify the following options:

Log Entire Message (logEntireMessage attribute): This value specifies whether the entire message (message
header and body) is logged. The default value is false, meaning that only the header is logged. This setting
affects service and transport message logging levels.

Max messages to log (maxMessagesToLog attribute): This value specifies the maximum number of messages
to log. All messages (service, transport, and malformed messages) are counted towards this quota. When the
quota is reached, a trace is emitted and no additional message is logged. The default value is 10000.

Max size of message to log (maxSizeOfMessageToLog attribute): This value specifies the maximum size of
messages to log in bytes. Messages that exceed the size limit are not logged, and no other activity is performed
for that message. This setting affects all trace levels.. The default value for service level and transport level
messages is 256K, while the default value for malformed messages is 4K.

If no trace listener is defined in the configuration file, no logging output is generated regardless of the specified
logging level.

Kovair Software Inc. 2009 33


WCF Fundamentals Chapter Name

11
Chapter 11 Security Concerns for
Message Logging

Kovair Software Inc. 2009 34


WCF Fundamentals Chapter Name

This topic describes how you can protect sensitive data from being exposed in message logs, as well as events
generated by message logging.

11.1 Security Concerns


Logging Sensitive Information

Windows Communication Foundation (WCF) does not modify any data in application-specific headers and
body. WCF also does not track personal information in application-specific headers or body data.

When message logging is enabled, personal information in application-specific headers, such as, a query
string; and body information, such as, a credit card number, can become visible in the logs. The application
deployer is responsible for enforcing access control on the configuration and log files. If you do not want this
kind of information to be visible, you should disable logging, or filter out part of the data if you want to share the
logs.

The following tips can help you to prevent the content of a log file from being exposed unintentionally:

1. Ensure that the log files are protected by Access Control Lists (ACL) both in Web-host and self-host
scenarios.

2. Choose a file extension that cannot be easily served using a Web request. For example, the .xml file
extension is not a safe choice. You can check the Internet Information Services (IIS) administration
guide to see a list of extensions that can be served.

3. Specify an absolute path for the log file location, which should be outside of the Web host vroot public
directory to prevent it from being accessed by an external party using a Web browser.

Kovair Software Inc. 2009 35


WCF Fundamentals Chapter Name

12
Chapter 12 Ajax and WCF

Kovair Software Inc. 2009 36


WCF Fundamentals Chapter Name

We will be looking at how we can use AJAX to implement a WCF Service, so that it's methods are available to
client-side JavaScript. This is an extremely powerful tool, as we are able to access the WCF Service almost
instantaneously, without posting back a page or waiting several seconds. In this example, we will create a basic
ASPX page with a HTML form that will make use of JavaScript calls to the WCF Service we will create.

Define a DataContract

[DataContract(Name = "TestResult", Namespace = "KovairPage")]


public class TestResult
{
private int number;
[DataMember(Name="Number",Order=0)]
public int Number
{
set { number = value; }
get { return number; }
}
}

Define A Service Contract

[ServiceContract(Namespace="KovairPage")]

public interface IService


{
[OperationContract]
TestResult Add(int Num1,int Num2);
}

Kovair Software Inc. 2009 37


WCF Fundamentals Chapter Name

Implement the Service Contract

[ServiceBehavior(Namespace="KovairPage")]
public class Service : IService
{
public TestResult Add(int Num1, int Num2)
{
try
{
TestResult tr = new TestResult();
tr.Number = Num1 + Num2;
return tr;
}
catch (Exception exc)
{
throw exc;
}

}
}

Add This Xml to Web.config(Inside Configuration Element)

<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="WcfWithAjax.EndPointBehavior">
<enableWebScript/>
</behavior>
</endpointBehaviors>

</behaviors>
<services>
<service name="WcfWithAjax.Service">
<endpoint address="" binding="webHttpBinding"
contract="WcfWithAjax.IService"
behaviorConfiguration="WcfWithAjax.EndPointBehavior" >
</endpoint>
</service>
</services>
</system.serviceModel>

In Above Configuration XML You can see the Binding name webHttpBinding . In case of Ajax youo must have
to use this binding. Another think is endPointBehavior,you must have to use <enableWebScript/> for enabling
the Ajax scripts.

Access this WCF From Javascripts

Add Script Manager

<asp:ScriptManager ID="ScriptManager" runat="server">


<Services>

Kovair Software Inc. 2009 38


WCF Fundamentals Chapter Name

<asp:ServiceReference Path="Service.svc" />


</Services>
</asp:ScriptManager>

Call WCF From Javascript

function CallWcf()
{
var proxy = new KovairPage.IService();
proxy.Add(10, 20, onSuccess, onFail, null);
return false;
}
function onSuccess(result,context,method)
{
alert(result.Number);
}
function onFail(result,context,method)
{
alert("Error");
}

Kovair Software Inc. 2009 39

You might also like