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

Visual Studio 2008: Windows Communication Foundation

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 26

Visual Studio® 2008:

Windows®
Communication
Foundation
Module 9: Implementing Transactions
• Overview of Transactions in a Service-Oriented Application

• Creating Transactional Service Operations

• Enabling the Flow of Transactions from Client to Service


Lesson: Overview of Transactions in a
Service-Oriented Application
• Transaction Properties

• Coordinating Transactions

• Transaction Context

• Distributed Transactions

• Coordinating Distributed Transactions

• Web Services and Transactions


Transaction Properties

Transactions have ACID properties

Atomic All or nothing

System data must be in a legal state at the


Consistent start and end

Isolated Hide intermediate state from other operations

Durable Results are persistent after success is signaled


Coordinating Transactions
Transaction Two-Phase Transactional
Transaction
Coordinator Commit Resources
Flow
Enlist
Vote?

My vote
Resource
Commit/Abort Manager Message Queue

Enlist
Vote?

My vote
Resource
Commit/Abort Manager Database
Enlist
Vote?

My vote
Resource
Commit/Abort Manager Mainframe
Transaction Context

• Transactional attributes of current thread of


execution (transaction context) must be accessible
• Transaction-aware resource manager uses this
information to enlist in current transaction:
 Store all operations that form part of the same
transaction context and commit or abort them all in one
go

• Transaction context must be propagated through


code as thread executes
• What happens when you leave that execution
space?
Distributed Transactions

Distribution brings challenges for coordinated transactions:


Must to propagate (or "flow") transaction context across
computer boundaries
Must to coordinate commit or abort across computers

Communication failures or delays can hamper 2PC

Alternative is to use a compensating transaction

Undo all the actions you have just performed

Has its own set of interesting problems

WCF and WS-AtomicTransaction protocols use coordinated approach


Coordinating Distributed Transactions
Windows
Distributed Transaction
Coordinator (DTC) Coordinates transactions
between a set of computers
running Windows on a network
DTC on originating
system is the
transaction root
that initiates 2PC

Each DTC collects


votes on its
own system

Can coordinate durable resource managers and volatile


resource managers
Web Services and Transactions
Defines structure of context Defines coordination protocol for
and coordination framework “activities having a short duration and
executed within limited trust domains”

WS-Coordination WS-AtomicTransaction
(WS-COOR) (WS-AT)

Supports both distributed


transactions and distributed
workflow

Between them they enable cross-platform support for


cross-machine transactions.

Windows DTC supports such transactions if WS-AT support


is enabled. The default is native OLE Transactions.
Lesson: Creating Transactional Service Operations
• Selecting a Transaction-Aware Binding

• Setting Transactional Requirements of an Operation

• Defining Isolation and Timeout for an Operation

• Controlling Transactions on Service Operations

• Demonstration: Automatic Transaction Initiation


Selecting a Transaction-Aware Binding
NetTcpBinding
NetNamedPipeBinding
WSHttpBinding
Must select a transaction-aware binding WSDualHttpBinding
WSFederationHttpBinding
Enable flow with transactionFlow property
Not enabled by default
Specify transaction protocol if with WS-AT

<bindings>
<wsHttpBinding>
<binding name = "BankExtranet" transactionFlow = "true"
transactionProtocol="WSAtomicTransactionOctober2004"/>
</wsHttpBinding>
</bindings>

wsHttpBinding wsBinding = new wsHttpBinding();


wsBinding.TransactionFlow = true;
wsBinding.TransactionProtocol =
TransactionProtocol.WSAtomicTransactionOctober2004;
Setting Transactional Requirements of an Operation
Use TransactionalFlow attribute on operation in service
contract to enforce client transaction policy
Possible values:

NotAllowed Client transaction ignored (default)

Allowed Client transaction available in operation if required

Mandatory Exception if called outside transaction scope

[OperationContract]
[TransactionFlow(TransactionFlowOption.Mandatory)]
void Transfer(string sourceAccount,
string targetAccount,
decimal amount);

Programmatic access to transaction context information in


service code through transaction.Current
Defining Isolation and Timeout for an Operation

• Set TransactionIsolationLevel through


ServiceBehavior attribute
• Set TransactionTimeout through ServiceBehavior
attribute:
 Defaults to 60 seconds

[ServiceBehavior(TransactionIsolationLevel=
IsolationLevel.RepeatableRead) ]
public class BankService : IBank
{
... Chaos
} ReadCommitted
ReadUncommitted
RepeatableRead
Serializable
Snapshot
Unspecified
Controlling Transactions on Service Operations
[OperationBehavior(TransactionScopeRequired=true)]
void Transfer(string sourceAccount,
string targetAccount,
decimal amount)
{
...
}

TransactionScopeRequired on OperationBehavior
Must be set to true to propagate an existing transaction

If set to true and no transaction flowed from client,


hosting environment starts one automatically when
the operation is called

Matching TransactionAutoComplete property


Indicates whether to automatically commit/abort at end of operation

Defaults to true
Demonstration: Automatic Transaction Initiation
In this demonstration, you will see how to:
• Apply transactional attributes to control the availability of
transactions in a WCF service operation
• Start a transaction when an operation is invoked
Notes Page Over-flow Slide. Do Not Print Slide.
See Notes pane.
Lesson: Enabling the Flow of Transactions From
Client to Service
• Configuring a Client to Propagate Transactions

• Starting a Transaction on the Client

• Handling Client Transaction Exceptions

• Transactional Behavior of Instances and Sessions

• Demonstration: Transaction Flow From Client to Service


Configuring a Client to Propagate Transactions

Enable transaction flow on binding for client endpoint

This is disabled by default

<client>
<endpoint address="http://localhost:8080/BankService"
binding="wsHttpBinding"
bindingConfiguration="BankServiceWSBinding"
contract="IBank"/>
</client>
<bindings>
<wsHttpBinding>
<binding name="BankServiceWSBinding"
transactionFlow="true"
...
</wsHttpBinding>
</bindings>
Starting a Transaction on the Client
Use System.Transactions.TransactionScope:
• Can set options in constructor if desired
• Call Complete method to try and commit the transaction

IBank service = new BankServiceClient();

using (TransactionScope scope = new TransactionScope())


{

service.Transfer("Customer9879", "Bank0001", 1998.98);


service.AllocateShares("Customer9879", "MSFT", 1942.17);

scope.Complete();
}

Often better to keep transactions on service side by


grouping transactional service operations behind façades
Handling Client Transaction Exceptions
• Any exception in a transaction scope aborts
the transaction:
 Still must to handle exception with try/catch block
• Various sources of transaction-related exceptions:
 For example, not providing a transaction for an operation
on which it is defined as mandatory
• Must match isolation level of service operation:
 Define this on the TransactionOptions of
the TransactionScope
 Operation throws ProtocolException otherwise
Transactional Behavior of Instances and Sessions
Transactions and sessions throw up various complications
If session information is altered by transaction then what happens
on rollback?

Best approach involves:


Persist session state and retrieve it based on a session key
similar to SQL Server session state in IIS

Read session state at start of method and write back at end so that
it becomes part of the transaction

Instance discarded when transaction completes regardless of


instance management settings
Demonstration: Transaction Flow From Client
to Service
In this demonstration, you will see how to start a
transaction in a WCF client and ensure that it flows through
into an operation on a WCF service
Lab: Implementing Transactions for a Service
• Exercise 1: Controlling the flow of a transaction from client
to service
• Exercise 2: Forcing a transaction to be started when a
service operation is called

Logon information

Virtual machine 6461A-LON-DEV-09

User name Student

Password Pa$$w0rd

Estimated time: 40 minutes


Lab Review
• Which form of the solution is more reflective of best
practice? What benefits does it bring over the other
approach?
• Why would a failure in the Patient Letter Service not
actually cause the appointment creation to roll back? How
could you change this?
Module Review and Takeaways
• Review Questions

• Real-World Issues and Scenarios

• Best Practices
Course Evaluation

You might also like