introducing system.transactions nigel watson architect advisor [email protected] developer...

49
Introducing Introducing System.Transaction System.Transaction s s Nigel Watson Nigel Watson Architect Advisor Architect Advisor [email protected] [email protected] Developer Platform Strategy Group Developer Platform Strategy Group Microsoft Microsoft DAT214

Post on 21-Dec-2015

219 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

Introducing Introducing System.TransactionsSystem.Transactions

Nigel WatsonNigel WatsonArchitect AdvisorArchitect [email protected]@microsoft.comDeveloper Platform Strategy GroupDeveloper Platform Strategy GroupMicrosoftMicrosoft

DAT214

Page 2: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

Why System.Transactions?Why System.Transactions?

Not one, but two Transaction programming Not one, but two Transaction programming models in .NET 1.1models in .NET 1.1

Both models have disadvantagesBoth models have disadvantagesNeither superior to the other in every respectNeither superior to the other in every respect

.NET 2.0 unifies benefits of both models.NET 2.0 unifies benefits of both modelsA single, unified way to create transactional codeA single, unified way to create transactional code

Minimizing hand crafted codeMinimizing hand crafted code

Separate from hosting environment and instance Separate from hosting environment and instance managementmanagement

Page 3: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

Who cares about transactions, Who cares about transactions, anyway? anyway?

Page 4: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

Transactions in .NET 1.1Transactions in .NET 1.1

Page 5: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

string connectionString = "…"; IDbConnection connection = new SqlConnection(connectionString);connection.Open();IDbCommand command = new SqlCommand();command.Connection = connection;IDbTransaction transaction;transaction = connection.BeginTransaction(); //Enlistingcommand.Transaction = transaction;try{ // Interact with database here transaction.Commit();}catch{ // Oops… transaction.Rollback(); //Abort transaction}finally{ connection.Close();}

Explicit Model in .NET 1.1Explicit Model in .NET 1.1

Page 6: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

Explicit Model in .NET 1.1 Explicit Model in .NET 1.1

DBDB

ClientClient ObjObj TransactionTransaction

Nice and straight-forwardNice and straight-forward

Page 7: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

DBDB

Explicit Model in .NET 1.1 Explicit Model in .NET 1.1

But, breaks with multiple objects…But, breaks with multiple objects…

ClientClient ObjObjTransactionTransaction

ObjObjObjObj

Page 8: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

DBDB

Explicit Model in .NET 1.1 Explicit Model in .NET 1.1

… … and breaks even harder with multiple and breaks even harder with multiple objects and multiple resourcesobjects and multiple resources

DBDB

TransactionTransactionObjObj

ObjObjObjObj

DBDB

ClientClient

Page 9: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

Distributed Transactions Distributed Transactions

Two or more parties or execution Two or more parties or execution contextscontexts

Impractical to manage in your codeImpractical to manage in your code

Need a dedicated 2pc monitorNeed a dedicated 2pc monitor

Managed on Windows by COM+ DTCManaged on Windows by COM+ DTCSystem serviceSystem service

Creates new transactionsCreates new transactions

Propagates transactions across machinesPropagates transactions across machines

Collects resources votesCollects resources votes

Instructs RMs to rollback or commitInstructs RMs to rollback or commit

Page 10: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

Declarative model in .NET 1.1Declarative model in .NET 1.1

To use COM+ DTC from .NET 1.1, you To use COM+ DTC from .NET 1.1, you have two optionshave two options

Code against COM+ directly (via interop)Code against COM+ directly (via interop)

Use System.EnterpriseServicesUse System.EnterpriseServices

using System.EnterpriseServices;

[Transaction]public class MyComponent : ServicedComponent{ [AutoComplete] public void MyMethod() { // Interact with other serviced // components and resource managers }}

Page 11: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

Declarative Model in .NET 1.1Declarative Model in .NET 1.1

ProblemsProblems

Derivation from Derivation from ServicedComponentServicedComponentPerformance penalty for non-distributed Performance penalty for non-distributed transactionstransactions

COM+ hosting modelCOM+ hosting model

No easy way for multiple threads to No easy way for multiple threads to participate in same transactionparticipate in same transaction

Page 12: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

Transactions in .NET 1.1Transactions in .NET 1.1

So…. You are forced to choose:So…. You are forced to choose:Enterprise Services for distributedEnterprise Services for distributed

ADO.NET (maybe) for localADO.NET (maybe) for local

… … and this gets hard-coded into your appsand this gets hard-coded into your apps

Page 13: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

.NET 2.0 Transactions.NET 2.0 Transactions

Page 14: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

System.TransactionsSystem.Transactions

Single, unified development modelSingle, unified development modelSupported by ADO.NET 2.0 Supported by ADO.NET 2.0 Lightweight Transaction Manager (LTM)Lightweight Transaction Manager (LTM)

Manages ‘local’ transactionsManages ‘local’ transactionsSingle durable resource, no remotingSingle durable resource, no remoting

Distributed Transaction Manager Distributed Transaction Manager (OleTx)(OleTx)

Manages distributed transactionsManages distributed transactionsMultiple resources, cross app-domainMultiple resources, cross app-domain

Automatic promotion from local to Automatic promotion from local to distributeddistributed

Page 15: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

TransactionTransaction

TransactionTransaction represents a local or represents a local or distributed transactiondistributed transaction

No Commit on Transaction objectNo Commit on Transaction object

[Serializable]public class Transaction : IDisposable,ISerializable{ public void Rollback(); //Abort the transaction public void Dispose();

//Other members }

Page 16: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

CommittableTransactionCommittableTransaction

CommittableTransactionCommittableTransaction used to used to commit transactioncommit transaction

Allows us to reserve commit for creatorAllows us to reserve commit for creator

Supports Asynchronous commitSupports Asynchronous commit

[Serializable]public sealed class CommittableTransaction : Transaction, IAsyncResult{ public void Commit(); public IAsyncResult BeginCommit(…); public void EndCommit(…);

//Other members}

Page 17: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

Ambient TransactionsAmbient Transactions

Page 18: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

Ambient TransactionAmbient Transaction

Defines ‘ambient’ transactional contextDefines ‘ambient’ transactional context

Transaction.CurrentTransaction.CurrentMight be nullMight be null

Shared on thread via TLSShared on thread via TLS

Can manage ambient transaction Can manage ambient transaction directlydirectly

But better to use But better to use TransactionScope TransactionScope object object

Page 19: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

TransactionScopeTransactionScope

Provides a scoped transaction contextProvides a scoped transaction contextSaves existing ambientSaves existing ambient

Creates Transaction objectCreates Transaction object

Sets Sets Transaction.CurrentTransaction.Current

Complete() memberComplete() memberUsed to vote on transactionUsed to vote on transaction

Sets internal consistency flag (default is false)Sets internal consistency flag (default is false)

Implements IDisposableImplements IDisposableTransaction lifetime defined by scopeTransaction lifetime defined by scope

Fate of transaction rests on consistency flagFate of transaction rests on consistency flag

Page 20: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

TransactionScopeTransactionScopetry{ using( TransactionScope scope = new TransactionScope() ) {

// // Transactional code here…

//scope.Complete();

}}catch{ // // Handle exception // throw;}

Page 21: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

What happens in Dispose()What happens in Dispose()

Consistency flag checkedConsistency flag checkedIf not set, Transaction is abortedIf not set, Transaction is aborted

If set, Transaction attempts to commitIf set, Transaction attempts to commit

A failed commit throws A failed commit throws TransactionAbortedExceptionTransactionAbortedException

Can alert user or log error Can alert user or log error

Usually better to let exception propagate upUsually better to let exception propagate up

No need to abort in No need to abort in catchcatch block block

Original ambient restoredOriginal ambient restored

Page 22: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

Using TransactionScope to Using TransactionScope to make our banking app make our banking app transactional… transactional…

Page 23: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

Transaction Flow ManagementTransaction Flow Management

Page 24: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

Transaction Flow ManagementTransaction Flow Management

Scopes can nest directly, or indirectlyScopes can nest directly, or indirectlyTop-most is called the root scopeTop-most is called the root scope

TransactionScopeOptionTransactionScopeOption used to used to modify default scoping behaviourmodify default scoping behaviour

RequiredRequired

RequiresNewRequiresNew

SuppressSuppress

Page 25: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

More on RequiredMore on Required

When When TransactionScopeTransactionScope joins joins ambient, disposing does not end ambient, disposing does not end transactiontransaction

Ends only when root scope is disposedEnds only when root scope is disposed

Parent and nested scope have distinct Parent and nested scope have distinct consistency bitsconsistency bits

To commit, all scopes in ambient have to be To commit, all scopes in ambient have to be consistentconsistent

Page 26: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

Transaction Flow ManagementTransaction Flow Management

Flow decided based on ambient transaction Flow decided based on ambient transaction and and TransactionScopeOptionTransactionScopeOption

TransactionScopeOptionTransactionScopeOption Ambient Ambient TransactionTransaction The scope will take part inThe scope will take part in

RequiredRequired NoNo New Transaction New Transaction (will be the root)(will be the root)

Requires NewRequires New NoNo New Transaction New Transaction (will be the root)(will be the root)

SuppressSuppress NoNo No TransactionNo Transaction

RequiredRequired YesYes Ambient TransactionAmbient Transaction

Requires NewRequires New YesYes New Transaction New Transaction (will be the root)(will be the root)

SuppressSuppress YesYes No TransactionNo Transaction

Page 27: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

Nested scopes Nested scopes

Page 28: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

Other TransactionScope optionsOther TransactionScope options

TimeoutsTimeoutsDefault is 60 secondsDefault is 60 seconds

After timeout, transaction auto-abortsAfter timeout, transaction auto-aborts

Smallest timeout in nested ambient Smallest timeout in nested ambient transactions usedtransactions used

Use 0 for infinite, but… careful!Use 0 for infinite, but… careful!

Isolation levelIsolation levelDefault is SerializableDefault is Serializable

Departure from this is at own consistency Departure from this is at own consistency risk – make sure you know what you are risk – make sure you know what you are doing…doing…

Page 29: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

PromotionPromotion

Page 30: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

Transaction Manager PromotionTransaction Manager Promotion

Every Every System.TransactionsSystem.Transactions transaction starts as local transaction transaction starts as local transaction

Single object interacts with single Single object interacts with single durable resourcedurable resource

Only requires local transaction Only requires local transaction

Yields best throughput and performanceYields best throughput and performance

Transaction promoted whenTransaction promoted whenEnlisting another durable RM Enlisting another durable RM

Transaction flows to another object in Transaction flows to another object in another app domainanother app domain

Page 31: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

RMs and .NET 2.0RMs and .NET 2.0

Existing RMs cannot participate in a Existing RMs cannot participate in a local transactionlocal transaction

SQL Server 2000SQL Server 2000

OracleOracle

DB2DB2

MSMQ MSMQ

When accessed automatically When accessed automatically promotedpromoted

Even if single resource is involvedEven if single resource is involved

A good reason to switch to SQL2K5 A good reason to switch to SQL2K5

Page 32: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

The magic of promotion The magic of promotion

Page 33: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

TransactionScope benefitsTransactionScope benefits

Transactional and promotableTransactional and promotable

Independent of object modelIndependent of object model

Auto-enlistmentAuto-enlistment

IntuitiveIntuitive

Page 34: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

But, what happens to my But, what happens to my Enterprise Services code?Enterprise Services code?

Page 35: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

Declarative Model in .NET 2.0Declarative Model in .NET 2.0

ES code is same as in .NET 1.1ES code is same as in .NET 1.1

Existing components benefit automatically Existing components benefit automatically

Maintains productivity advantagesMaintains productivity advantages

Supports LTM iff single, local resource.Supports LTM iff single, local resource.

using System.EnterpriseServices; [Transaction] //Uses System.Transactions, gets promotion public class MyComponent : ServicedComponent{ [AutoComplete] public void MyMethod() {...}}

Page 36: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

Enterprise Services Code in 2.0 Enterprise Services Code in 2.0

Page 37: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

ConcurrencyConcurrency

Page 38: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

Concurrency ManagementConcurrency Management

Transactions and concurrency? Transactions and concurrency? Uhhh…Uhhh…

One thread aborts the other commitsOne thread aborts the other commits

Ambient transaction stored in TLSAmbient transaction stored in TLSWill not propagate to worker threadsWill not propagate to worker threads

Solution Solution DependentTransactionDependentTransaction

Page 39: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

Transaction.DependentClone()Transaction.DependentClone()

Creates a Creates a DependentTransaction DependentTransaction of the existing Transactionof the existing Transaction

Parent keeps tabs on clones, which can Parent keeps tabs on clones, which can be passed to other threadsbe passed to other threads

Must create unique clones for each Must create unique clones for each threadthread

cloneOptioncloneOption parameter to parameter to DependentClone()DependentClone()

RollbackIfNotCompleteRollbackIfNotComplete

BlockCommitUntilCompleteBlockCommitUntilComplete

Page 40: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

Concurrent transactionsConcurrent transactions

Page 41: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

Roll your own transactional Roll your own transactional typestypes

Page 42: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

Create your own transactional typesCreate your own transactional types

Any object that implements Any object that implements IEnlistmentNotificationIEnlistmentNotification can enlist in can enlist in transactionstransactionsCall Call Transaction.EnlistVolatile()Transaction.EnlistVolatile() or or Transacation.EnlistDurable()Transacation.EnlistDurable() to be to be notified of important transaction lifecycle notified of important transaction lifecycle eventsevents

Prepare()Prepare()Commit()Commit()Rollback()Rollback()

Consider extending implementation to Consider extending implementation to include include ISinglePhaseNotificationISinglePhaseNotification for for single-phase commit supportsingle-phase commit support

Page 43: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

Transactional int class Transactional int class

Page 44: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

SummarySummary

Existing .NET 1.1 transactional Existing .NET 1.1 transactional approaches may paint you into a cornerapproaches may paint you into a corner

.NET 2.0 introduces new unified .NET 2.0 introduces new unified transactional model that unifies explicit transactional model that unifies explicit and declarative approachesand declarative approaches

Writing reliable code much easier with Writing reliable code much easier with transactionstransactions

Can make pretty much anything Can make pretty much anything transactional in .NET 2.0transactional in .NET 2.0

Page 45: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

We invite you to participate in ourWe invite you to participate in our online evaluationonline evaluation on CommNet,on CommNet,

accessible Friday onlyaccessible Friday only

If you choose to complete the evaluation online, If you choose to complete the evaluation online, there isthere is no need to complete the paper evaluationno need to complete the paper evaluation

Page 46: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214
Page 47: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

Get a 48% Discount on MSDN Get a 48% Discount on MSDN Universal Now!Universal Now! For a limited time purchase a 12 month For a limited time purchase a 12 month

MSDN Universal Subscription for MSDN Universal Subscription for $3565+GST (RRP).$3565+GST (RRP).

You will receive updates as they are You will receive updates as they are released for SQL Server, BizTalk Server, released for SQL Server, BizTalk Server, Visual Studio, Exchange Server and Visual Studio, Exchange Server and Windows Server. Windows Server.

You will also receive early access to beta You will also receive early access to beta products such as Windows Vista and products such as Windows Vista and Office 12.Office 12.

Get in now so that when Visual Studio Get in now so that when Visual Studio Team System ships you will be upgraded Team System ships you will be upgraded at no cost to one of the new top tier at no cost to one of the new top tier subscriptions:subscriptions:

Visual Studio 2005 Team Edition for Visual Studio 2005 Team Edition for Software DevelopersSoftware DevelopersVisual Studio 2005 Team Edition for Visual Studio 2005 Team Edition for Software ArchitectsSoftware ArchitectsVisual Studio 2005 Team Edition for Visual Studio 2005 Team Edition for Software TestersSoftware Testers

For more details and to find your local For more details and to find your local reseller visit: reseller visit: www.microsoft.co.nz/buyMSDNwww.microsoft.co.nz/buyMSDN

Page 48: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

© 2005 Microsoft Corporation. All rights reserved.This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.

Page 49: Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214