Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows...

45
http://www.mini.pw.edu.pl/~mossakow Krzysztof Mossakowski .NET Programming Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication Foundation, Addison-Wesley, 2008 J. Smith, Inside Microsoft Windows Communication Foundation, MS Press, 2007 J. Sharp, Microsoft Windows Communication Foundation Step by Step, MS Press, 2007 C. McMurtry, Windows Communication Foundation Unleashed, Sams, 2007 S. Klein, Professional WCF Programming, Wiley Publishing, 2007 MSDN

Transcript of Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows...

Page 1: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

.NET Programming

Windows Communication Foundation

WCF

S. Resnick et al., Essential Windows Communication Foundation, Addison-Wesley, 2008J. Smith, Inside Microsoft Windows Communication Foundation, MS Press, 2007J. Sharp, Microsoft Windows Communication Foundation Step by Step, MS Press, 2007C. McMurtry, Windows Communication Foundation Unleashed, Sams, 2007S. Klein, Professional WCF Programming, Wiley Publishing, 2007MSDN

Page 2: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

2Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Contents

Overview

Contracts

Channels

Bindings

Behaviours

Serialization and encoding

Hosting

Page 3: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

3Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

WCF Introduction

WCF is the easiest way to produce and consume services on the Microsoft platform

Developers can focus on their applications rather than on communication protocols

WCF is agnostic to protocol and message format

WCF has a built-in model for hosting, so services can reside within IIS or in Managed Services on Windows

WCF supports various message exchange patterns, such as request-response, one-way, and duplex

Page 4: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

4Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

WCF Basics

A WCF service is composed of endpoints, and each endpoint has address, binding, and contract

Services also have behaviours that describe their operating semantics, such as threading and concurrency

Services can be hosted in any operating system process

e.g.: console application, Windows service, IIS server

Clients communicate with services exclusively through messages

For developer productivity, Visual Studio provides tools for building client side proxy classes to represent server operations

Inside the proxy class, WCF serializes the parameters as XML and sends the XML message to the proper service endpoint address

Page 5: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

5Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

WCF Programming Lifecycle

1. Define the service contract

A service contract specifies the signature of a service, the data it exchanges, and other contractually required data

2. Implement the contract

Create the class that implements the contract

Specify custom behaviours that the runtime should have

3. Configure the service by specifying endpoint information and other behaviour information

4. Host the service

5. Build a client application

Page 6: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

6Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Implementing a WCF Service[ServiceContract]

public interface IMyFirstService {

[OperationContract]

int GetNumberWords(string s);

}

public class MyFirstService : IMyFirstService {

public int GetNumberWords(string s) {

return s.Split(

new char[] { ' ', ';', ',', '.', '?' },

StringSplitOptions.RemoveEmptyEntries).Length;

}

}

const string serviceURL = "http://localhost:1234/MyFirstService";

ServiceHost serviceHost = new ServiceHost(

typeof(MyFirstService), new Uri(serviceURL));

serviceHost.AddServiceEndpoint(

typeof(IMyFirstService), new BasicHttpBinding(), "");

serviceHost.Open();

// the service is running now

serviceHost.Close();

Page 7: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

7Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Implementing a WCF Client

[ServiceContract]

public interface IMyFirstService {

[OperationContract]

int GetNumberWords(string s);

}

const string serviceURL = "http://localhost:1234/MyFirstService";

ChannelFactory<IMyFirstService> channelFactory =

new ChannelFactory<IMyFirstService>(

new BasicHttpBinding(),

new EndpointAddress(serviceURL));

IMyFirstService myFirstService = channelFactory.CreateChannel();

string s = "Sample text for testing";

int numberWords = myFirstService.GetNumberWords(s);

Page 8: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

8Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Configuring a WCF Service's Host

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<system.serviceModel>

<services>

<service name="SecondService.MySecondService">

<host>

<baseAddresses>

<add baseAddress=

"http://localhost:1235/MySecondService"/>

</baseAddresses>

</host>

<endpoint address=""

binding="basicHttpBinding"

contract="SecondService.IMySecondService" />

</service>

</services>

</system.serviceModel>

</configuration>

ServiceHost serviceHost = new ServiceHost(typeof(MySecondService));

serviceHost.Open();

// the service is running now

serviceHost.Close();

Page 9: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

9Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Configuring MEX Endpoint<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<system.serviceModel>

<services>

<service name="SecondService.MySecondService"

behaviorConfiguration="mySecondServiceBehavior">

<host>

<baseAddresses>

<add baseAddress=

"http://localhost:1235/MySecondService"/>

</baseAddresses>

</host>

<endpoint address="" binding="basicHttpBinding"

contract="SecondService.IMySecondService" />

<endpoint address="mex" binding="mexHttpBinding"

contract="IMetadataExchange" />

</service>

</services>

<behaviors>

<serviceBehaviors>

<behavior name="mySecondServiceBehavior">

<serviceMetadata httpGetEnabled="true"/>

</behavior>

</serviceBehaviors>

</behaviors>

</system.serviceModel>

</configuration>

Page 10: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

10Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Configuring a WCF Client<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<system.serviceModel>

<bindings>

<basicHttpBinding>

<binding name="BasicHttpBinding_IMySecondService" [...] >

<readerQuotas [...] />

<security mode="None">

<transport [...] />

<message [...] />

</security>

</binding>

</basicHttpBinding>

</bindings>

<client>

<endpoint address="http://localhost:1235/MySecondService"

binding="basicHttpBinding"

bindingConfiguration="BasicHttpBinding_IMySecondService"

contract="ServiceReference1.IMySecondService"

name="BasicHttpBinding_IMySecondService" />

</client>

</system.serviceModel>

</configuration>MySecondServiceClient client =

new MySecondServiceClient();

int numberWords = client.GetNumberWords(

"Sample text for testing");

Page 11: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

11Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Contracts

A contract is a description of the messages that are passed to and from service endpoints

Type of contracts in WCF:

Service contracts describing the functional operations implemented by the service

they map the class methods of a .NET type to WSDLservices, port types, and operations

Data contracts describing data structures that are used by the service to communicate with clients

they map CLR types to XML Schema Definitions (XSD) and defines how they are serialized and deserialized

Message contracts providing precise control over the SOAP headers and bodies

they map CLR types to SOAP messages

Page 12: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

12Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

WSDL for WCF

To make contracts interoperable with the widest range of systems, they are expressed in Web Service Description Language (WSDL)

There is a mapping between CLR types and WSDL:

1. When writing service code, WCF-defined attributes are used

ServiceContract, OperationContract, FaultContract, MessageContract, and DataContract

2. When writing client code, the service is queried to learn the contract details and to generate a proxy class

Visual Studio or svcutil.exe

3. When a client calls a method on a service interface, WCF serializes the CLR types and method calls into XML and sends the message over the wire according to the binding and encoding scheme agreed upon in the WSDL

Page 13: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

13Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Types of Operations

Request-response

Synchronous

Asynchronous

One-Way

The client just need acknowledgement of successful delivery, it does not need an actual response from the service

[OperationContract(IsOneWay = true)]

Duplex

Bidirectional communication – the service can initialize it

Both the service and the client need an address, binding, and contract defining

<endpoint binding="wsDualHttpBinding" ... />

Page 14: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

14Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Data Contracts

Representation of WCF service's application data:

inside – simple an complex .NET CLR types

outside – XML Schema Definitions (XSD)

WCF data contracts provide a mapping function between .NET CLR and XSD types, using attributes:

DataContract indicates which classes should be represented

DataMember indicates which class members should be included in the external representation

Page 15: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

15Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Data Contract Example[DataContract]

public class CompositeType {

[DataMember]

public bool Flag { get; set; }

[DataMember]

public string Text { get; set; }

[DataMember]

public DateTime Date { get; set; }

}

<?xml version="1.0" encoding="utf-8"?>

<xs:schema [...]>

<xs:complexType name="CompositeType">

<xs:sequence>

<xs:element minOccurs="0" name="Date" type="xs:dateTime" />

<xs:element minOccurs="0" name="Flag" type="xs:boolean" />

<xs:element minOccurs="0" name="Text" nillable="true"

type="xs:string" />

</xs:sequence>

</xs:complexType>

<xs:element name="CompositeType" nillable="true"

type="tns:CompositeType" />

</xs:schema>

Page 16: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

16Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Data Contract Serialization

At runtime, the DataContractSerializer class serializes objects to XML using the rules defined by the DataContract and DataMember attributes

The following types can be serialized:

Marked with the DataContract and DataMember attributes

Marked with the CollectionDataContract attribute

Implementing the IXmlSerializable interface

Marked with the Serializable attribute whose members are not marked with NonSerialized

Marked with Serializable and implementing ISerializable

CLR built-in primitive types (e.g. int32, string)

Bytes array, DateTime, TimeSpan, Guid, Uri, XmlQualifiedName, XmlElement, XmlNode

Arrays and collections (e.g. List<T>, Dictionary<K,V>, Hashtable)

Enumerations

Page 17: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

17Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Changes in Data Contracts

Nonbreaking changes:

Adding new nonrequired data members

Removing existing nonrequired data members

Breaking changes:

Change the name or namespace of a data contract

Rename an existing data member that was previously required

Add a new data member with a name that has been used previously

Change the data type of an existing data member

Add new members with IsRequired=true on DataMemberAttribute

Remove existing members with IsRequired=true on DataMemberAttribute

Page 18: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

18Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Message Contracts

Message contracts describe the structure of SOAP messages sent to and from a service

They enable to inspect and control most of the details in the SOAP header and body

Using message contracts gives complete control over the sent SOAP message

There is a direct access to the SOAP headers and bodies

To use message contracts, use the MessageContractattribute instead of DataContract

The MessageContract attribute defines the structure of SOAP messages

Typed messages use MessageHeader and MessageBodyMember attributes to describe the structure of the SOAP header and body

Page 19: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

19Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Message Contract Example[MessageContract]

public class HelloResponseMessage

{

[MessageBodyMember(Name = "ResponseToGreeting",

Namespace = "http://www.examples.com")]

public string Response { get; set; }

[MessageHeader(Name = "OutOfBandData",

Namespace = "http://www.examples.com",

MustUnderstand = true)]

public string ExtraValues { get; set; }

}

<s:Envelope>

<s:Header>

<a:Action s:mustUnderstand="1">

http://HelloResponseMessage/Action

</a:Action>

<h:OutOfBandData s:mustUnderstand="1" xmlns:h="http://www.examples.com">

Served by object 13804354.

</h:OutOfBandData>

</s:Header>

<s:Body>

<HelloResponseMessage xmlns="Microsoft.WCF.Documentation">

<ResponseToGreeting xmlns="http://www.examples.com">

Service received: Hello.

</ResponseToGreeting>

</HelloResponseMessage>

</s:Body>

</s:Envelope>

Page 20: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

20Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Untyped Messages

Untyped operation contracts enable the client and service to pass virtually any content in the SOAP body

As long as the content can be encoded by the binding stack being used for communication

The Message class (the System.ServiceModel.Channelnamespace) can be used to create, read, and write messages

Page 21: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

21Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Channels

Channels are responsible for preparing and delivering messages in a consistent way

They are defined for transports, protocols, and message interception

There are two types of channels:

Transport channels are responsible for transporting message using a transport protocol

supported directly: HTTP, TCP, MSMQ, peer-to-peer, named pipes

3rd parties: SMTP, FTP, UDP, WebSphere MQ, SQL Service Broker

Protocol channels (layered channels) are responsible for implementing wire-level protocols by transforming and modifying messages

Page 22: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

22Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Bindings

Bindings represent wire-level agreements between a client and a server

Each binding specifies the transport, encoding, and protocols involved in the communication

Page 23: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

23Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Selecting a Binding

S. Resnick et al., Essential Windows Communication Foundation, Addison-Wesley, 2008

Page 24: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

24Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Using Bindings in Various Scenarios

Local machine communication between .NET applications

netNamedPipeBinding

Cross-machine communication between .NET applications

netTcpBinding (can be optimized for the better performance)

Communication using basic web services

basicHttpBinding (support for Web services based on the WS-I Basic Profile 1.1)

Communication using advanced web services

wsHttpBinding (support for the WS-* specifications)

wsDualHttpBinding (wsHttpBinding + support for duplex communication)

ws2007HttpBinding (similar to wsHttpBinding, but with support for latest WS-* standards)

Page 25: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

25Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Custom and User-Defined Bindings

Custom bindings

They can be created using either code or configuration

Objects of the CustomBinding class can be used

User-defined bindings

They can be created by inheriting from the Binding class

Also, the BindingElementExtensionElement class can be used as a base custom binding extensions

Page 26: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

26Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Behaviours

Behaviours are WCF classes that affect runtime operation

They are invoked as the WCF runtime starts on the client and server and as messages flow

They are an important extensibility point for customizations

There are 3 types of behaviours:

Service behaviours run at the service level and have access to all of the endpoints

useful for authorization and auditing

Endpoint behaviours are scoped to the service endpoint

useful for inspecting and logging

Operation behaviours are scoped at the operation level

useful for manipulating serialization, transaction flow, and parameter handling for a service operation

Page 27: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

27Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Concurrency and Instancing

The ConcurrencyMode service behaviour is used to control thread concurrency within a service instance:

Single – one thread at a time can access the service class

Reentrant – one thread at a time, but it can leave the class and come back later to continue

Multiple – the service instance is multi-threaded, no synchronization guarantees are made

The InstanceContextMode service behaviour is used to control instancing:

Single – implements a singleton

PerCall – one instance of the service class per incoming request

PerSession [default] – one instance per client session

Page 28: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

28Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Exporting and Publishing Metadata

Metadata is exposed from a service throught a Metadata Exchange (MEX) endpoint

Like any other endpoint, a MEX endpoint can be added to a service either through configuration or through code

<system.serviceModel>

<services>

<service name="SecondService.MySecondService"

behaviorConfiguration="mySecondServiceBehavior">

[...]

<endpoint address="mex"

binding="mexHttpBinding"

contract="IMetadataExchange" />

</service>

</services>

<behaviors>

<serviceBehaviors>

<behavior name="mySecondServiceBehavior">

<serviceMetadata httpGetEnabled="true"/>

</behavior>

</serviceBehaviors>

</behaviors>

</system.serviceModel>

Page 29: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

29Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Transactions

WCF supports short-running transactions

It does this by leveraging .NET and Windows infrastructure for transactions running in a Microsoft-only environment and by leveraging WS-* standards transactions that span platforms

By default, operations execute without a transaction. To use a transaction:[OperationBehavior(TransactionScoreRequired=true)]

Commiting a transaction depends on settings:

[OperationBehavior(TransactionAutoComplete=true)] –automatically commits a transaction at the end of the operation

[OperationBehavior(TransactionAutoComplete=false)] –needs calling OperationContext.current.SetTransactionComplete before returning from the method to commit a transaction

Page 30: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

30Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Web Service Atomic Transactions (WS-AT)

To use flowing transactions:

Service contracts must require sessions:SessionMode.Required

The binding must support sessions.

Operation behaviour must require a transaction scope:TransactionScopeRequired=true

Operation contracts must allow transaction information to flow in the header of messages:TransactionFlowOption.Allowed

The binding must enable transaction flow so that the channel can put transaction information into the SOAP header:TransactionFlow=true

The party that initiates the transaction (usually the client), must use a transaction scope when calling the service operations

Page 31: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

31Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Security Behaviours

ServiceCredentials – useful for accessing client security information

Impersonation – enables impersonation from the client to the service

ServiceAuthorization – used to authorize the caller to access the service or operation

It can be used to set an AuthorizationManager that is responsible for determining whether to grant access to the service

ServiceSecurityAudit – determines what, if any, information is automatically logged with each service request

Page 32: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

33Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Serialization and Encoding

Serialization in WCF is a process of converting an object graph into an XML Information Set (XML Infoset)

The System.ServiceMode.Channels.Message class is a representation of an XML Infoset

XML Infoset has no restriction to use a text format (as the XML standard), thus WCF can represent messages in different formats

Encoding is a process of converting a WCF message into an array of bytes

5 types of encoding formats are supported: binary, text, Message Transmission Optimization Mechanism, JavaScript Object Notation, and Plain-Old-XML (POX)

Page 33: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

34Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Available Serialization Mechanisms

DataContractSerializer – the default serializer

It maps CLR types to types defined in XSD

NetDataContractSerializer – supports type fidelity by adding additional information for CLR type information and reference preservation

It should be used within the confines of a single application

XmlSerializer – already built in to .NET 2.0

It can be used to help convert ASP.NET Web Services to WCF

It offers the most controls over the serialized XML output and custom serialization

DataContractJsonSerializer – supports the use of JavaScript Object Notation

Very useful for ASP.NET AJAX and Silverlight clients

Page 34: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

35Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Streaming Data

The transferMode attribute of the netTcpBinding can be used to turn on streaming of data:

Buffer [the default], Streamed, StreamedResponse, StreamedRequest

<system.serviceModel>

<services>

<service name="ThirdService">

<endpoint address=""

bindingConfiguration="EnableStreaming"

contract="WCFTest.IThirdService" />

</service>

</services>

<bindings>

<netTcpBinding>

<binding name="EnableStreaming"

transferMode="Streamed" />

</netTcpBinding>

</bindings>

</system.serviceModel>

Page 35: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

36Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Hosting

A service host is an operating system process responsible for the lifetime and context of a WCF service

It is responsible for starting and stopping the WCF service and providing some basic management functions for controlling it

A WCF service can be hosted by:

Windows Process Activation Services (WAS)

Internet Information Services (IIS)

Windows Service (a.k.a. NT Service)

Managed Application

Regardless of the hosting environment, the WCF programming model doesn’t change

Page 36: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

37Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Hosting in WAS

Windows Process Activation Service is a component introduced in IIS 7.0 that manages application pool configuration and worker processes instead of the WWW process

This enables the same configuration for both HTTP and non-HTTP sites to be used

The WAS process model generalizes the IIS 6.0 process model for the HTTP server by removing the dependency on HTTP

Hosting WCF services in WAS allows to use both HTTP and non-HTTP protocols, such as Net.TCP

This hosting environment supports message-based activation and offers the ability to host a large number of applications on a given machine

Page 37: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

38Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Hosting in IIS

Versions of IIS supporting WCF hosting:

IIS 5.1 on Windows XP SP2

IIS 6.0 on Windows Server 2003

improved scalability, reliability, and application isolation

HTTP only

IIS 7.0 on Windows Vista and Windows Server 2008

it uses WAS to allow activation and network communication over protocols other than HTTP

Benefits:

Services manageable like any other IIS application

Process activation, health management, and recycling capabilities

Shared hosting model where multiple applications reside in a common worker process for improved server density and scalability

Dynamic compilation, which simplifies development and deployment of hosted services

Page 38: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

39Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Hosting in Windows Service

Windows services are suited to applications that must live in a long-running executable and do not display any form of user interface

They can be configured to start automatically when the computer starts

Hosting WCF services inside of a Windows service application is one option for building robust, long-running, WCF applications

Page 39: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

40Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Hosting in Managed Application

WCF services can be hosted in any .NET Framework application

Self-hosting services is the most flexible hosting option because it requires the least infrastructure to deploy

It is also the least robust hosting option, because managed applications do not provide the advanced hosting and management features of other hosting options in WCF

To create a self-hosted service, create and open an instance of the ServiceHost, which starts a service listening for messages

Page 40: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

41Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Hosting WCF Services – Summary

Hosting Common Scenarios Key Benefits and Limitations

Managed Application("Self-Hosted")

• Console applications used during development.• Rich WinForm and WPF client applications accessing services.

• Flexible.• Easy to deploy.• Not an enterprise solution for services.

Windows Services (NT services)

• A long-running WCF service hosted outside of IIS.

• Service process lifetime controlled by the operating system, not message-activated. • Supported by all versions of Windows.• Secure environment.

IIS 5.1, IIS 6.0• Running a WCF service side-by-side with ASP.NET content on the Internet using the HTTP protocol.

• Process recycling. • Idle shutdown.• Process health monitoring. • Message-based activation. • HTTP only.

Windows Process Activation Service (WAS)

• Running a WCF service without installing IIS on the Internet using various transport protocols.

• IIS is not required.• Process recycling. • Idle shutdown.• Process health monitoring. • Message-based activation.• Works with HTTP, TCP, named pipes, MSMQ.

IIS 7.0

• Running a WCF service with ASP.NET content.• Running a WCF service on the Internet using various transport protocols.

• WAS benefits. • Integrated with ASP.NET and IIS content.

Page 41: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

42Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

WCF Exception Handling

WCF makes the assumption that exceptions indicate a serious issue in the service’s capability to continue communications with the client

In case of an unhandled exception, WCF faults the service channel – any existing sessions are destroyed

If a session is part of the service call, the client channel will no longer be useful, and the client-side proxy will need to be re-created for the client to continue calling the service

All .NET specific exceptions are serialized to the common data schema described by SOAP

Page 42: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

43Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Tracing<system.diagnostics>

<sources>

<source name="System.ServiceModel"

propagateActivity="true"

switchValue="Warning,ActivityTracing">

<listeners>

<add type="System.Diagnostics.DefaultTraceListener"

name="Default">

<filter type=""/>

</add>

<add initializeData="Trace.log"

type="System.Diagnostics.XmlWriterTraceListener"

name="tracelog"

traceOutputOptions="Timestamp" >

<filter type=""/>

</add>

</listeners>

</source>

</sources>

</system.diagnostics>

<E2ETraceEvent xmlns="http://schemas.microsoft.com/2004/06/E2ETraceEvent">

<System xmlns="http://schemas.microsoft.com/2004/06/windows/eventlog/system">

<EventID>131085</EventID>

<Type>3</Type>

<SubType Name="Start">0</SubType>

<Level>255</Level>

<TimeCreated SystemTime="2008-12-15T13:17:59.8865527Z" />

<Source Name="System.ServiceModel" />

<Correlation ActivityID="{c2b0bd6d-0348-43fe-b389-82d0803fb8ac}" />

<Execution ProcessName="WinFormsClient" ProcessID="14180" ThreadID="1" />

<Channel/>

<Computer>KMOSSAKOWSKI</Computer>

</System>

<ApplicationData>

<TraceData>

<DataItem>

<TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent

<TraceIdentifier>

Page 43: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

44Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Message Logging<system.diagnostics>

<sources>

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

<listeners>

<add name="messages"

type="System.Diagnostics.TextWriterTraceListener"

initializeData="Messages.log" />

</listeners>

</source>

</sources>

</system.diagnostics>

<system.serviceModel>

<diagnostics>

<messageLogging logEntireMessage="true"

logMessagesAtServiceLevel="true" />

</diagnostics>

</system.serviceModel>

System.ServiceModel.MessageLogging Information: 0 :

<MessageLogTraceRecord Time="2008-12-15T14:35:46.2835527+01:00"

<s:Envelope xmlns:a=http://www.w3.org/2005/08/addressing

<s:Header>

<a:Action s:mustUnderstand="1">IThirdService/GetThirdType</a:Action>

<a:MessageID>urn:uuid:6f9f4bed-1946-40c3-bb84-9a06bb4fdc27</a:MessageID>

<ActivityId CorrelationId="98029069-9b50-4648-9e5e-3e0e4c348aa8"

<a:ReplyTo>

<a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>

</a:ReplyTo>

</s:Header>

<s:Body>

<GetThirdType xmlns="http://tempuri.org/">

<s>t1</s>

</GetThirdType>

</s:Body>

</s:Envelope>

</MessageLogTraceRecord>

Page 44: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

45Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Service Trace Viewer

Available in Microsoft Windows SDK

wcf_hosting.src.zip

Page 45: Windows Communication Foundation WCFpages.mini.pw.edu.pl/.../awp/lecture_slides/WCF.pdf · Windows Communication Foundation WCF S. Resnick et al., Essential Windows Communication

46Windows Communication Foundation

http://www.mini.pw.edu.pl/~mossakowKrzysztof Mossakowski

Service Configuration Editor