WCF Fundamentals
WCF Fundamentals
WCF Fundamentals
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
1
Chapter 1 Overview of WCF
This chapter will provide an overview of Windows Communication Foundation along with a high-level
explanation of the WCF service model.
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.
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
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.
2
Chapter 2 Creating a Simple WCF
Service
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.
[ServiceContract]
public interface IMyContract
{ ...}
[ServiceContract]
public interface IMyContract
{ ...}
[OperationContract]
void SomeOperation();
[DataContract]
public class SomeType
{
[DataMember]
public int ID;
}
[MessageContract]
public class MyRequest
{
[MessageHeader]
public string field1;
[MessageBody]
public string field2;
[OperationContract]
[FaultContract(typeof(DivideByZeroException))]
void SomeMethod();
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
{
[OperationContract]
void CreateOrder(int orderNumber);
[OperationContract]
void AddItemToOrder(int orderNumber, Item itm);
[OperationContract]
Order GetOrderDetails(int orderNumber);
}
[DataContract]
public class Order
{
[DataMember]
public int OrderNumber;
[DataMember]
public String ClientName;
...
}
3
Chapter 3 WCF Bindings
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.
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).
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.
4
Chapter 4 Options for Hosting a WCF
Service
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.
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.
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.
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).
myHost.Open();
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.
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.
To set up endpoints in configuration files, define <endpoint> elements within a parent <service> element inside
the <system.ServiceModel> section of your configuration file.
5
Chapter 5 Creating and Invoking a WCF
Client
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.
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:
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:
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.
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();
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:
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:
6
Chapter 6 Customizing WCF with
Behaviors
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.
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:
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.
7
Chapter 7 Introduction of WCF Security
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.
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.
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.
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.
8
Chapter 8 Authentication and
Authorization in WCF
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:
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()
{
...
}
9
Chapter 9 Reliability in WCF
Applications
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.
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.
Client Side
As well as specifying transaction requirements, the client can control the isolation level and timeout for the
transaction by using a TransactionOptions object:
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
helps you to control whether a transaction is required for an operation, and whether transactions complete if no
exception is thrown.
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.
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).
10
Chapter 10 WCF Administration and
Diagnostics
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.
This topic describes how you can configure message logging for different scenarios.
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.
<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"/>
</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.
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.
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.
11
Chapter 11 Security Concerns for
Message Logging
This topic describes how you can protect sensitive data from being exposed in message logs, as well as events
generated by message logging.
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.
12
Chapter 12 Ajax and WCF
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
[ServiceContract(Namespace="KovairPage")]
[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;
}
}
}
<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.
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");
}