services and windows communication foundation - wcfapm/tdin/docs/08wcf_conftr.pdf · iis hosting...

26
Services and Windows Communication Foundation - WCF Configuration Use 2010@FEUP WCF Services 1

Upload: others

Post on 21-May-2020

11 views

Category:

Documents


0 download

TRANSCRIPT

Services and

Windows Communication

Foundation - WCF

Configuration

Use

2010@FEUP WCF Services 1

IIS Hosting

Very similar to a XML Web Service (ASMX file)

Its a resource in an IIS web application

IIS can host services with Bindings that use HTTP as the

transport protocol

In the Web Application directory (URL) we put a service

descriptor as a file named <ServiceName>.svc

The service configuration elements are specified in Web.config

inside a section called <system.serviceModel>

The service compiled code should be present in the subdirectory

‘bin’ (in the form of a .dll)

Service descriptor example

Service.svc:

<%@ ServiceHost Service="WCFIISService.WCFIISTest" %>

Class implementing the service

22010@FEUP WCF Services

Creation in Visual Studio

Create a project

Visual C# New Web Site WCF Service

After writing code and configuration publish it in a local

or remote IIS creating there a new Web Application

The service address will be:

• http://<machine>/<Web App URL>/<Service>.svc

Create new Web Application

32010@FEUP WCF Services

Instance Management

It’s possible to specify how the instances of the class

that implements the service are created

Single – Just one instance will handle all the client calls

(Singleton mode)

Per call – One different instance is created to handle each client

call, deactivated when the call returns

Per session – Session creation is allowed, where one service

instance will handle all the calls from the same proxy (in a client)

The instantiation mode is specified in an attribute called

[ServiceBehavior] that can be applied to the service implementation

[ServiceContract]

interface IMyService { … }

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single]

public class MyService : IMyService { … }

It can be:Single

PerCall

PerSession

42010@FEUP WCF Services

Session Creation (1)

By default WCF services use the PerSession mode

The Binding must allow sessions (wsHttp…, Tcp, Pipe, Queues)

By default, a session starts in the client 1st call and ends when

the proxy is closed

Requirement for a Binding with sessions

The parameter SessionMode from attribute [ServiceContract]

specifies if the Binding requires, allows or does not allow

sessions

[ServiceContract(SessionMode = SessionMode.Allowed)]

interface IMyService { … }

public class MyService : IMyService { … }

Required

Allowed (default)

NotAllowed

52010@FEUP WCF Services

Sessions (2)

By default any call of any method starts a session

We can specify the methods that start a session and the

methods that end the session

Parameters IsIniciating and IsTerminating of [OperationContract]

• By default IsInitiating is true and IsTerminating is false

[ServiceContract(SessionMode = SessionMode.Required)]

interface IBasketSession {

[OperationContract(IsInitiating = true)]

void InitBasket(string user);

[OperationContract(IsInitiating = false]

AddItem(int itnr);

[OperationContract(IsInitiating = false, IsTerminating = true)]

void CheckOut();

}

public class BasketSession : IBasketSession { … }

62010@FEUP WCF Services

Concurrency

By default only one thread can run inside each instance

This can impair performance for services in Single mode or even

in sessions

It’s possible to allow more threads to run and simultaneous calls

from the clients

Some hosts or Bindings can limit the maximum number of

threads and/or instances

The concurrency mode is specified in the attribute

[ServiceBehavior] applied to the service implementation

[ServiceContract]

interface IMyService { … }

[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple]

public class MyService : IMyService { … }

Can be:Single (default)

Reentrant

Multiple

Possible synchronization issues and consistency should be treated in the implementation

72010@FEUP WCF Services

Service Invocation Patterns

WCF Services support three invocation patterns

The default pattern – Request / reply

The one way pattern (or call and forget)

The dual pattern also called duplex

ServiceClient

Request

Reply

ServiceClient

Request

ServiceClientRequest

Request

Reply

Reply

82010@FEUP WCF Services

One-way Operations

The methods defined in a contract can be configured as

one-way

This configuration is specified using the parameter IsOneWay in

the attribute [OperationContract]

The one-way operation cannot return any value (must be void)

In the client this kind of invocation returns immediately

But, if exceptions do occur in the service, the client will also

experience them

[ServiceContract]

interface IMyService {

[OperationContract(IsOneWay = true)]

void MyOneWayMethod(string parameter);

}

public class MyService : IMyService { … }

92010@FEUP WCF Services

Duplex Operations

Only a few Bindings support this kind of operations

In HTTP only wsDualHttpBinding supports them, as well as the

Tcp and the Pipe bindings

Some situations need sessions

The service contract must define also the client operations

It must use the parameter CallbackContract of [ServiceContract]

[ServiceContract(CallbackContract = typeof(ISomeCallbackContract))]

interface IMyService {

[OperationContract]

void DoSomething( ); }

interface ISomeCallbackContract {

[OperationContract]

void OnCallback( ); }

public class MyService : IMyService { … }

102010@FEUP WCF Services

The Duplex Client

The client must implement the callback contract in some

class and build the proxy specifying this implementation

class

class ClientContract : IMyServiceCallback {

public void OnCallback() { … }

}

public class Client {

IMyServiceCallback callback = new ClientContract();

InstanceContext context = new InstanceContext(callback);

MyServiceClient proxy = new MyServiceClient(context);

proxy.DoSomething();

proxy.Close();

}

calls to the service

can be made here

112010@FEUP WCF Services

Duplex Operations Invocation (1)

Invocation outside the service methods

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]

class MyService : IMyService {

static IMyContractCallback m_callback = null;

public void DoSomething( ) {

IMyContractCallback callback = OperationContext.Current.

GetCallbackChannel<IMyContractCallback>( );

m_callback = callback;

}

public static void CallClient( ) {

if (m_callback != null)

m_callback.OnCallback; // problem if the client has gone

}

}

122010@FEUP WCF Services

Duplex Operations Invocation (2)

Invocation in a service method

There is no problem if the callback is one-way, but there will be a

reentrant thread in other modes

[ServiceContract(CallbackContract = typeof(IMyContractCallback))]

interface IMyService {

[OperationContract]

void DoSomething( );

}

interface ISomeCallbackContract {

[OperationContract]

void OnCallback( );

}

[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Reentrant)]

class MyService : IMyService {

public void DoSomething( ) {

IMyContractCallback callback = OperationContext.Current.

GetCallbackChannel<IMyContractCallback>( );

callback.OnCallback( );

}

}

132010@FEUP WCF Services

Transactions

WCF services support the propagation of client initiated

distributed transactions to their methods

Also a service method can initiate a transaction and

propagate it to other methods that it calls

Root

Transaction Controller

Transactional

resource

Transactional

resource

Transactional

resource

Dependent

Transaction Controller

Dependent

Transaction Controller

Dependent

Transaction Controller

Dependent

Transaction Controller

142010@FEUP WCF Services

Conditions for Transaction Flow (1)

The Binding must have transaction flow allowed

Only a few kinds of Binding support transaction flow

This global permission is done in the configuration file

• It’s easier to use the tool SvcConfigEditor.exe

<bindings>

<netTcpBinding>

<binding name="TcpBinding" transactionFlow="true">

<security mode="None" />

</binding>

</netTcpBinding>

</bindings>

<endpoint address=“…" binding="netTcpBinding" bindingConfiguration="TcpBinding"

name="TcpOps" contract=“…" />

152010@FEUP WCF Services

Conditions for Transaction Flow (2)

Each service method should specify its option for

transaction flow

This specification uses an attribute in the contract

[TransactionFlow]

[ServiceContract]

interface IMyContract {

[OperationContract]

[TransactionFlow(TransactionFlowOption.Allowed)]

void MyMethod( );

}

NotAllowed (default)

Allowed

Mandatory

The one-way methods cannot be used in transactions

162010@FEUP WCF Services

Conditions for Transaction Flow (3)

For a method to participate or to create a transaction it

also needs

Include the parameter TransactionScopeRequired of the

[OperationBehavior] attribute in the method implementation

[ServiceContract]

interface IMyContract {

[OperationContract]

[TransactionFlow(TransactionFlowOption.Allowed)]

void MyMethod( );

}

class MyService : IMyContract {

[OperationBehavior(TransactionScopeRequired = true)]

public void MyMethod( ) {

}

}

172010@FEUP WCF Services

Transaction Flow - Example

182010@FEUP WCF Services

Transaction Flow

Transaction modes as the product of binding, contract, and behavior

Binding transaction flow TransactionFlowOption TransactionScopeRequired Transaction mode

False Allowed False None

False Allowed True Service

False NotAllowed False None

False NotAllowed True Service

True Allowed False None

True Allowed True Client/Service

True Mandatory False None

True Mandatory True Client

Service – Tr. initiated in the service Client – Tr. initiated in the client and transmitted

to the service Client/Service – Tr. can be initiated in the client and transmitted or, if not,

it will be initiated in the service

192010@FEUP WCF Services

Transaction End and Vote

A service method that executes inside a transaction will

automatically include the transactional resources’ operations in the

transaction

At the method return it should be capable of communicating

success/failure to its caller and execute the commit/rollback if it is

not the transaction root

Success/failure communication can be automatic or explicit and is controlled by

the parameter TransactionAutoComplete of [OperationBehavior]

[OperationBehavior(TransactionScopeRequired = true,

TransactionAutoComplete = true)]

public void MyMethod( ) {

try {

...

} catch {

/* Some local handling here */

throw;

}

}

(default)

202010@FEUP WCF Services

Vote or Explicit Transaction End

We can specify an explicit termination/vote

It requires a session in order to work

The automatic mode is always preferable

[OperationBehavior(TransactionScopeRequired = true,

TransactionAutoComplete = false)]

public void MyMethod( ) {

try {

/* Do transactional work here, then: */

OperationContext.Current.SetTransactionComplete( );

} catch {

/* Do some error handling then */

throw;

}

}

212010@FEUP WCF Services

Isolation Levels and Timeouts

The [ServiceBehavior] attribute also contains

The parameter TransactionIsolationLevel

The parameter TransactionTimeout

[ServiceBehavior(TransactionIsolationLevel = IsolationLevel.Serializable,

TransactionTimeout = “00:00:30”)]

class MyService : IMyContract {

}

default = 1 min.

ReadUncommitted

ReadCommitted

RepeatableRead

Serializable

Unspecified (default)

222010@FEUP WCF Services

The Isolation level can be:

Initiate a Transaction in the Client

The client can initiate a transaction and propagate it to

the service methods

try {

using (TransactionScope scope = new TransactionScope( )) {

/* Perform transactional work here */

/* Call services */

//No errors - commit transaction

scope.Complete( );

}

} catch {

//Some exception took place

Trace.WriteLine("Cannot complete transaction");

}

232010@FEUP WCF Services

Queued Services

The netMsmqBinding binding allows the connection

between clients and services using queues in a

transparent way

242010@FEUP WCF Services

Contract and Configuration

Only one-way methods are allowed

The MSMQ queue to use must already exist

//////////////////////// Service Side ///////////////////////////

[ServiceContract]

interface IMyContract {

[OperationContract(IsOneWay = true)]

void MyMethod( );

}

class MyService : IMyContract {

public void MyMethod( ) {...}

}

//////////////////////// Client Side ///////////////////////////

MyContractClient proxy = new MyContractClient( );

proxy.MyMethod( );

proxy.Close( );

<endpoint

address = "net.msmq://localhost/private/MyServiceQueue"

binding = "netMsmqBinding" ...

/>

252010@FEUP WCF Services

Queued Services and Transactions

Transactions cannot be transmitted through the queue

But the queue write and retrieve operations can be

included in different transactions using transactional

queues

262010@FEUP WCF Services