47
COM+ Transactions COM+ Transactions Writing Components In Visual Writing Components In Visual Basic Basic ® Brian A. Randell Brian A. Randell DevelopMentor DevelopMentor 1-304 1-304

COM+ Transactions Writing Components In Visual Basic ® Brian A. Randell DevelopMentor 1-304

Embed Size (px)

Citation preview

COM+ TransactionsCOM+ TransactionsWriting Components In Visual BasicWriting Components In Visual Basic®®

Brian A. RandellBrian A. RandellDevelopMentorDevelopMentor

1-3041-304

developmentormentor Hands-on training for hardcore Hands-on training for hardcore

developersdevelopers Guerrilla training courses:Guerrilla training courses:

Guerrilla VB & Guerrilla COM (C++)Guerrilla VB & Guerrilla COM (C++) COM courses with banker’s hours:COM courses with banker’s hours:

Essential COM+ for VB programmersEssential COM+ for VB programmers Essential COM+ for C++ programmersEssential COM+ for C++ programmers

Lots of other Lots of other courses too!courses too!

AgendaAgenda

OLTP ConceptsOLTP Concepts The ACID rules, isolation & lockingThe ACID rules, isolation & locking Writing transactionsWriting transactions

Distributed TransactionsDistributed Transactions Transaction managers & the 2-phase Transaction managers & the 2-phase

commit protocolcommit protocol COM+ TransactionsCOM+ Transactions

Creating objects inside a transactionCreating objects inside a transaction Controlling a distributed transaction’s Controlling a distributed transaction’s

outcomeoutcome

Transaction FundamentalsTransaction Fundamentals

Most business applications use data in Most business applications use data in some waysome way Some apps are concerned with querying & Some apps are concerned with querying &

analyzing dataanalyzing data Other apps are primarily concerned with Other apps are primarily concerned with

modifying datamodifying data Apps that modify data and have many Apps that modify data and have many

users are commonly referred to as users are commonly referred to as on-line transaction processing (OLTP) on-line transaction processing (OLTP) systemssystems

What Is A Transaction?What Is A Transaction?

Imagine an application that Imagine an application that processes purchase ordersprocesses purchase orders Each order requires 3 database Each order requires 3 database

modificationsmodifications1)1) Order quantity must be deducted from inventoryOrder quantity must be deducted from inventory

2)2) Purchase price must be charged to customerPurchase price must be charged to customer

3)3) Order record must be inserted in Orders table Order record must be inserted in Orders table

These three modifications make up These three modifications make up one transaction (TX)one transaction (TX) These modifications represent a These modifications represent a

single unit of worksingle unit of work

The ACID RulesThe ACID Rules

A transaction must meet 4 basic A transaction must meet 4 basic requirementsrequirements

It must be It must be atomicatomic A transaction must be an all-or-nothing A transaction must be an all-or-nothing

propositionpropositioneverything must be successfully written everything must be successfully written or nothing should be writtenor nothing should be written

It must be It must be consistentconsistent The data used by an application is never The data used by an application is never

left in an invalid state after a transaction left in an invalid state after a transaction has completedhas completed

The ACID RulesThe ACID Rules

It must be It must be isolatedisolated The uncommitted changes of one user are The uncommitted changes of one user are

never seen by another user. Systems that never seen by another user. Systems that run concurrent transactions require run concurrent transactions require blockingblocking

It must be It must be durabledurable Once a transaction has committed, the Once a transaction has committed, the

data source has stored all changes in data source has stored all changes in persistent storage and these changes can persistent storage and these changes can be recovered in the event of a system be recovered in the event of a system failurefailure

Isolation & LockingIsolation & Locking

A transaction has one of two outcomesA transaction has one of two outcomes Successful transactions are committedSuccessful transactions are committed Unsuccessful transactions are abortedUnsuccessful transactions are aborted

Isolation is required during a Isolation is required during a transactionstransactions Uncommitted changes might be rolled backUncommitted changes might be rolled back Reading uncommitted changes can lead to Reading uncommitted changes can lead to

inconsistent datainconsistent data TX2 cannot see the uncommitted changes TX2 cannot see the uncommitted changes

of other TX1of other TX1

Potential Concurrency ProblemsPotential Concurrency Problems

Naïve concurrent execution of Naïve concurrent execution of transactions would yield the following transactions would yield the following problems:problems: Lost UpdatesLost Updates Dirty ReadsDirty Reads Unrepeatable ReadsUnrepeatable Reads PhantomsPhantoms

Properly isolated transactions do not Properly isolated transactions do not exhibit any of these problemsexhibit any of these problems

Degrees Of IsolationDegrees Of Isolation

Whether or not these problems occur Whether or not these problems occur depends on a transaction’s depends on a transaction’s degree of degree of isolationisolation

Common NameCommon Name

11 2200 33DegreeDegree

Read Read UncommittedUncommitted

Read Read CommittedCommittedChaosChaos SerializableSerializable

AKAAKA BrowseBrowse Cursor Cursor StabilityStability IsolatedIsolated

NoNoYesYes NoNo

YesYesYesYes NoNo

Lost Updates?Lost Updates? NoNo

Dirty Reads?Dirty Reads? NoNo

Unrepeatable Reads?Unrepeatable Reads? YesYes YesYesYesYes NoNo

Phantoms?Phantoms? YesYes YesYes YesYes NoNo

2.9992.999

RepeatableRepeatableReadRead

NoNo

NoNo

NoNo

YesYes

Isolation & LockingIsolation & Locking

Isolation is provided by a lock managerIsolation is provided by a lock manager A data source such as DBMS provides a A data source such as DBMS provides a

lock managerlock manager Uncommitted changes are isolated with Uncommitted changes are isolated with

write lockswrite locks write locks are also known as exclusive lockswrite locks are also known as exclusive locks

Additional consistency is provided Additional consistency is provided through read locksthrough read locks read locks are also known as shared locksread locks are also known as shared locks

Locks are placed on data itemsLocks are placed on data items Could be a file, a table, a page or a recordCould be a file, a table, a page or a record

Locking BasicsLocking Basics Many concurrent systems use locks to Many concurrent systems use locks to

implement isolation levelsimplement isolation levels Model relies on two types of locks to avoid Model relies on two types of locks to avoid

“problems” but allow maximum concurrency“problems” but allow maximum concurrency Read (shared) locks allow multiple Read (shared) locks allow multiple

transactions to read a piece of state transactions to read a piece of state concurrentlyconcurrently

Write (exclusive) locks allow exactly one Write (exclusive) locks allow exactly one transaction to write to a piece of statetransaction to write to a piece of state Requires that no read locks are outstandingRequires that no read locks are outstanding Classic Win32 synchronization primitives (e.g., Classic Win32 synchronization primitives (e.g.,

Mutex, Critical Section) are write locksMutex, Critical Section) are write locks

Lock Managers & BlockingLock Managers & Blocking

Write locks block all other locksWrite locks block all other locks One transaction blocks all other One transaction blocks all other

transactionstransactions Read locks only block write locksRead locks only block write locks

Many transactions can read the same data Many transactions can read the same data item at the same timeitem at the same time

Here’s how it worksHere’s how it works

Attempt Read LockAttempt Read Lock

Attempt Write LockAttempt Write Lock

Read Lock HeldRead Lock Held Write Lock HeldWrite Lock HeldNo Lock HeldNo Lock Held

Lock GrantedLock Granted Lock GrantedLock Granted Request BlockedRequest Blocked

Lock GrantedLock Granted Request BlockedRequest Blocked Request BlockedRequest Blocked

Isolation LevelsIsolation Levels How long are locks held?How long are locks held?

Write locks are always held until the end Write locks are always held until the end of the transactionof the transaction

Read locks might or might not be held Read locks might or might not be held until the end of the transactionuntil the end of the transaction

The isolation level adjusts the duration The isolation level adjusts the duration and behavior of read locksand behavior of read locks Higher isolation provides better Higher isolation provides better

consistencyconsistency Lower isolation provides better Lower isolation provides better

concurrencyconcurrency

Adjusting Isolation LevelsAdjusting Isolation Levels

Occasionally useful to loosen isolation Occasionally useful to loosen isolation requirements to increase overall requirements to increase overall system throughputsystem throughput Must tolerate one or more problems!!Must tolerate one or more problems!!

Adjustment of isolation levels is not Adjustment of isolation levels is not always possiblealways possible Some data managers don’t allow itSome data managers don’t allow it

As we’ll see, COM+ has a specific As we’ll see, COM+ has a specific setting in mind!setting in mind!

Running Local TransactionsRunning Local Transactions

Local transactions are managed by a Local transactions are managed by a DBMS’s transaction managerDBMS’s transaction manager The transaction manager works together The transaction manager works together

with the lock managerwith the lock manager How do you run a local transaction?How do you run a local transaction?

You write explicit commands to start, You write explicit commands to start, commit and rollback the transactioncommit and rollback the transaction

Transaction logic is usually embedded in Transaction logic is usually embedded in a SQL batch or a stored procedurea SQL batch or a stored procedure

Running Local TransactionsRunning Local Transactions

DBMSDBMSSQLSERVR.EXESQLSERVR.EXECOM+ ApplicationCOM+ Application

ActivityActivity

ADOADOConnConn

VB VB ObjectObject

ActivityActivity

ADOADOConnConn

VB VB ObjectObject

ActivityActivity

ADOADOConnConn

VB VB ObjectObject

Client 1Client 1

Client 2Client 2

Client NClient N

Transaction Transaction ManagerManager

LockLockManagerManager

DataData

Programming Local Tx’s #1Programming Local Tx’s #1

This examples uses an ADO This examples uses an ADO connectionconnection ADO connection object provides ADO connection object provides

transaction controltransaction control This technique can be used with any This technique can be used with any

ODBC or OLE-DB data source that ODBC or OLE-DB data source that supports transactionssupports transactions

Controlling transactions from an ADO Controlling transactions from an ADO connection can be expensive due to the connection can be expensive due to the need to use use extra round trips to DBMS need to use use extra round trips to DBMS to start/commit/abortto start/commit/abort

ADO ExampleADO Example

Dim conn As ConnectionDim conn As ConnectionSet conn = New ConnectionSet conn = New Connectionconn.Open "DSN=Market;UID=sa;PWD="conn.Open "DSN=Market;UID=sa;PWD="conn.IsolationLevel = adXactSerializableconn.IsolationLevel = adXactSerializableconn.BeginTransconn.BeginTrans ' SQL statements omitted for clarity' SQL statements omitted for clarity conn.Execute SQL_DecrementInventoryconn.Execute SQL_DecrementInventory conn.Execute SQL_ChargeCustomerconn.Execute SQL_ChargeCustomer conn.Execute SQL_AddOrderconn.Execute SQL_AddOrderconn.CommitTransconn.CommitTrans

Programming Local Tx’s #2Programming Local Tx’s #2

Control the transaction using SQLControl the transaction using SQL SQL logic is embedded into a SQL batch SQL logic is embedded into a SQL batch

or stored procedureor stored procedure Isolation level can be adjusted on a Isolation level can be adjusted on a

statement-by-statement statement-by-statement basis using hintsbasis using hints

This approach usually requires SQL that This approach usually requires SQL that is specific to a particular DBMSis specific to a particular DBMS

Writing fast OLTP code works across Writing fast OLTP code works across DBMS’s is usually impossibleDBMS’s is usually impossible

T-SQL ExampleT-SQL Example

-- set isolation level to serializable-- set isolation level to serializableSET TRANSACTION ISOLATION LEVEL SERIALIZABLESET TRANSACTION ISOLATION LEVEL SERIALIZABLE-- run transaction to purchase a product-- run transaction to purchase a productBEGIN TRANSACTIONBEGIN TRANSACTION -- decrement product quantity from inventory-- decrement product quantity from inventory UPDATE Products UPDATE Products SET Quantity = Quantity - 1SET Quantity = Quantity - 1 WHERE Product = 'Dog'WHERE Product = 'Dog' -- charge price to customer account-- charge price to customer account UPDATE Customers UPDATE Customers SET AccountBalance = AccountBalance + 20SET AccountBalance = AccountBalance + 20 WHERE Customer = 'Bob'WHERE Customer = 'Bob' -- add order record-- add order record INSERT Orders(Customer, Product, Quantity, Price)INSERT Orders(Customer, Product, Quantity, Price) VALUES('Bob', 'Dog', 1, 20)VALUES('Bob', 'Dog', 1, 20)COMMIT TRANSACTIONCOMMIT TRANSACTION

Distributed TransactionsDistributed Transactions

Local transactions only work when all Local transactions only work when all the data lives in one placethe data lives in one place For example, all the data lives in a single For example, all the data lives in a single

DBMSDBMS The transaction manager inside the DBMS The transaction manager inside the DBMS

enforces ACID rulesenforces ACID rules What if the data lives in multiple data What if the data lives in multiple data

sources?sources? The problem is much more difficultThe problem is much more difficult Commit/Abort logic must be coordinated Commit/Abort logic must be coordinated

across multiple data sourcesacross multiple data sources

2-Phase Commit Protocol2-Phase Commit Protocol

Many vendors offer products that solve Many vendors offer products that solve the problems of distributed the problems of distributed transactions in the same waytransactions in the same way

CICS from IBM, TUXEDO from BEA CICS from IBM, TUXEDO from BEA System and COM+ from Microsoft all System and COM+ from Microsoft all use similar high-level architecturesuse similar high-level architectures

Architecture uses an abstraction called Architecture uses an abstraction called the transaction manager and a protocol the transaction manager and a protocol called called 2-phase commit2-phase commit

The Microsoft DTCThe Microsoft DTC

The DTC is the Distributed Transaction The DTC is the Distributed Transaction CoordinatorCoordinator It is Microsoft's transaction managerIt is Microsoft's transaction manager

It coordinates distributed transactions It coordinates distributed transactions and enforces the ACID rulesand enforces the ACID rules

It executes the 2-phase commit It executes the 2-phase commit protocolprotocol

Originally released as a part Originally released as a part of SQL Serverof SQL Server Now an integrated part of MTS & COM+Now an integrated part of MTS & COM+

Computer 3Computer 3

RM3 - ORACLERM3 - ORACLE

Participating DTCParticipating DTC

Computer 2Computer 2

RM2 -SQL ServerRM2 -SQL Server

Participating DTCParticipating DTC

Computer 1Computer 1

The Coordinating DTC The Coordinating DTC

RM1 - RM1 - MSMQMSMQ

A Distributed TransactionA Distributed Transaction

DataData

DataData

Your Tx COM+ ApplicationYour Tx COM+ Application

QueueQueue

RM ProxyRM Proxy

RM ProxyRM ProxyRM ProxyRM Proxy

COM+ TransactionsCOM+ Transactions

COM+ transactions make your COM+ transactions make your life much easierlife much easier COM+ provides a programming model COM+ provides a programming model

with declarative transactionswith declarative transactions COM+ transaction represents a set of COM objectsCOM+ transaction represents a set of COM objects

You create your objects inside an COM+ You create your objects inside an COM+ transactiontransaction

Your objects establish and enlist Your objects establish and enlist connections to resource managersconnections to resource managers

Your objects read and write data inside Your objects read and write data inside the scope of a DTC transactionthe scope of a DTC transaction

COM+ TransactionsCOM+ Transactions

What’s different about this model?What’s different about this model? You never explicitly start a transactionYou never explicitly start a transaction You never explicitly commit a transactionYou never explicitly commit a transaction You never explicitly abort a transactionYou never explicitly abort a transaction

So how does it work?So how does it work? A COM+ transaction is a friendly wrapper A COM+ transaction is a friendly wrapper

around a DTC transactionaround a DTC transaction

A Tale Of Two TransactionsA Tale Of Two Transactions

There are really two transactionsThere are really two transactions MTS/COM+ creates a MTS/COM+ creates a logical transaction logical transaction when an object is when an object is

created from a component marked created from a component marked Requires Requires or or Requires NewRequires New MTS/COM+ creates a MTS/COM+ creates a physical transactionphysical transaction by calling to DTC by calling to DTC

transaction dispenser and invoking transaction dispenser and invoking BeginTransactionBeginTransaction MTS delays start of DTC transaction until object activation timeMTS delays start of DTC transaction until object activation time COM+ further delays start of DTC transaction until first COM+ further delays start of DTC transaction until first

"interesting" call"interesting" call DTC transaction is created with isolation level of DTC transaction is created with isolation level of serializableserializable DTC transaction has a default time out interval of DTC transaction has a default time out interval of 60 seconds60 seconds

The MTS/COM+ runtime controls the physical DTC The MTS/COM+ runtime controls the physical DTC transactiontransaction MTS/COM+ calls Commit or Abort when the root object is MTS/COM+ calls Commit or Abort when the root object is

deactivateddeactivated You can change things in the logical transaction to affect what You can change things in the logical transaction to affect what

goes on with the physical transactiongoes on with the physical transaction

Creating Objects In A TransactionCreating Objects In A Transaction

A transaction must exist within the scope of an activityA transaction must exist within the scope of an activity This eliminates problems with concurrency and reentrancyThis eliminates problems with concurrency and reentrancy Secondary objects should be created with CreateInstance in Secondary objects should be created with CreateInstance in

MTSMTS Secondary objects should be created with CreateObject in Secondary objects should be created with CreateObject in

COM+COM+ Every configured component has a Transaction Support Every configured component has a Transaction Support

propertyproperty Configured components can be marked as...Configured components can be marked as...

Requires a transaction: inherits transaction of creator, COM+ Requires a transaction: inherits transaction of creator, COM+ creates one if necessary creates one if necessary

Requires a new transaction: never inherits transaction of Requires a new transaction: never inherits transaction of creator, COM+ always creates onecreator, COM+ always creates one

Supports transactions: inherits transaction of creator if present, Supports transactions: inherits transaction of creator if present, otherwise runs withoutotherwise runs without

Does not support transactions: never inherits transaction of Does not support transactions: never inherits transaction of creator, always runs withoutcreator, always runs without

' root object is set to: Requires Transaction' root object is set to: Requires Transaction' this code assumes COM+ as opposed to MTS' this code assumes COM+ as opposed to MTSPublic Sub CreateOtherObjects()Public Sub CreateOtherObjects() Dim Joe As CJoe, Brian As CBrianDim Joe As CJoe, Brian As CBrian Dim Jason As CJason, Ted As CTedDim Jason As CJason, Ted As CTed Set Joe = Set Joe = CreateObject("MyDll.CJoe")CreateObject("MyDll.CJoe") Set Brian = Set Brian = CreateObject("MyDll.CBrian")CreateObject("MyDll.CBrian") Set Jason = Set Jason = CreateObject("MyDll.CJason")CreateObject("MyDll.CJason") Set Ted = Set Ted = CreateObject("MyDll.CTed")CreateObject("MyDll.CTed")End SubEnd Sub

CJoe: CJoe: Requires Requires CBrian: CBrian: Requires newRequires newCJason: CJason: supportssupportsCTed: CTed: does not supportdoes not support

Creating Secondary ObjectsCreating Secondary Objects

Creating Secondary ObjectsCreating Secondary Objects

COM+ RuntimeCOM+ Runtime

Transaction 1Transaction 1

TedTed

ClientClient

Transaction 2Transaction 2

RootRoot

JasonJasonJoeJoe

BrianBrian

Activity boundaryActivity boundary

COM+ TransactionCOM+ Transaction

DoomedDoomed FALSEFALSE

Commit/Abort BehaviorCommit/Abort Behavior

When the root object is deactivated…When the root object is deactivated… The MTS/COM+ runtime calls either Commit or AbortThe MTS/COM+ runtime calls either Commit or Abort There are 3 flags you need to know aboutThere are 3 flags you need to know about

Context AContext A

HappyHappy TRUETRUE

DoneDone FALSEFALSE

RootRootObjectObject

COM+COM+ProxyProxy

ClientClient

Controlling A Declarative Controlling A Declarative TransactionTransaction The ObjectContext interface allows objects to voteThe ObjectContext interface allows objects to vote

Any object that dies unhappy will doom transaction to failureAny object that dies unhappy will doom transaction to failure An secondary object which doesn't vote gives passive An secondary object which doesn't vote gives passive

consent to commit changesconsent to commit changes Root object MUST call SetComplete to commit changesRoot object MUST call SetComplete to commit changes

Important methods in the ObjectContext interfaceImportant methods in the ObjectContext interface DisableCommitDisableCommit:: object is saying "I'm unhappy but I’m not object is saying "I'm unhappy but I’m not

done - someone could still make me happy."done - someone could still make me happy." EnableCommitEnableCommit:: object is saying "I'm happy but I’m not done. object is saying "I'm happy but I’m not done.

Someone could still change my mind."Someone could still change my mind." SetCompleteSetComplete:: object is saying "I'm happy and I’m done. I am object is saying "I'm happy and I’m done. I am

now ready to be deactivated."now ready to be deactivated." SetAbortSetAbort:: object is saying "I'm unhappy and I’m done. I will object is saying "I'm unhappy and I’m done. I will

now deactivate and doom transaction"now deactivate and doom transaction"

The IContextState InterfaceThe IContextState Interface ObjectContext methods set both DONE bit and HAPPY ObjectContext methods set both DONE bit and HAPPY

bitbit SetComplete, SetAbort, DisableCommit, EnableCommitSetComplete, SetAbort, DisableCommit, EnableCommit

COM+ introduces the IConstextState interfaceCOM+ introduces the IConstextState interface SetMyTransactionVoteSetMyTransactionVote GetMyTransactionVoteGetMyTransactionVote SetDeactivateOnReturnSetDeactivateOnReturn GetDeactivateOnReturnGetDeactivateOnReturn

How does IContextState differ from ObjectContextHow does IContextState differ from ObjectContext You can read the value of the done bit and the happy bitYou can read the value of the done bit and the happy bit The methods raise errors if the object isn't in a transactionThe methods raise errors if the object isn't in a transaction

Should you use IContextState instead of ObjectContextShould you use IContextState instead of ObjectContext No real need – unless you want to read the happy or done bitNo real need – unless you want to read the happy or done bit

Multi-Object Transaction IssuesMulti-Object Transaction Issues

Creating secondary objects in a transactionCreating secondary objects in a transaction Each transaction has a Each transaction has a root object root object

the root is created by a base client in the simplest scenariothe root is created by a base client in the simplest scenario All objects in a transaction must share the same activityAll objects in a transaction must share the same activity

This eliminates issues with concurrency and synchronizationThis eliminates issues with concurrency and synchronization Transaction Support property must be set properlyTransaction Support property must be set properly In COM+, the root should create secondary objects by calling In COM+, the root should create secondary objects by calling

CreateObjectCreateObject In MTS, the root should create secondary objects by calling In MTS, the root should create secondary objects by calling

CreateInstanceCreateInstance Remember the Remember the New New operator can get you into trouble on either operator can get you into trouble on either

platformplatform Secondary objects usually connect to RM to access dataSecondary objects usually connect to RM to access data

MTS/COM+ automatically enlists connections in current MTS/COM+ automatically enlists connections in current transaction when made to a valid resource manager (RM) through transaction when made to a valid resource manager (RM) through a RM proxya RM proxy

Each secondary object gets to vote on the transaction's outcomeEach secondary object gets to vote on the transaction's outcome

How Does Voting Work?How Does Voting Work? Any object can prevent the transaction from Any object can prevent the transaction from

committingcommitting If If a secondary object is deactivated in an unhappy statea secondary object is deactivated in an unhappy state

ThenThen MTS/COM+ sets the transaction's doomed flag to true MTS/COM+ sets the transaction's doomed flag to true Setting the doomed flag to true is irreversibleSetting the doomed flag to true is irreversible

COM+ TransactionCOM+ TransactionDoomedDoomed True/False True/False

ClientClient

SecondarySecondaryObject 1Object 1

SecondarySecondaryObject 2Object 2

SecondarySecondaryObject 3Object 3

RootRootObjectObject

proxyproxyHappyHappy DoneDone

proxyproxyHappyHappy DoneDone

proxyproxyHappyHappy DoneDone

proxyproxyHappyHappy DoneDone

Writing Commit/Abort LogicWriting Commit/Abort Logic Each transaction must have a root objectEach transaction must have a root object

This usually defines the client's entry point into the packageThis usually defines the client's entry point into the package Root should always call Root should always call SetComplete SetComplete or or SetAbort SetAbort to release txto release tx

Secondary objects can also vote in transaction outcomeSecondary objects can also vote in transaction outcome If any secondary object can vote to rollback the transactionIf any secondary object can vote to rollback the transaction MTS/COM+ sets doomed flag to true when deactivating an MTS/COM+ sets doomed flag to true when deactivating an

unhappy objectunhappy object

Root must somehow discover transaction is doomedRoot must somehow discover transaction is doomed No way for root to discover this through ObjectContext interfaceNo way for root to discover this through ObjectContext interface Calling Calling SetCompleteSetComplete in root after a secondary object has set the in root after a secondary object has set the

doomed flag will result in a runtime errordoomed flag will result in a runtime error An attempt to activate an object in a doomed transaction results An attempt to activate an object in a doomed transaction results

in an errorin an error Secondary objects should raise errors when voting to rollbackSecondary objects should raise errors when voting to rollback

Watch Out When Calling Watch Out When Calling SetAbort In COM+SetAbort In COM+ There's an ugly bug in COM+ that isn’t in MTSThere's an ugly bug in COM+ that isn’t in MTS

Secondary objects should not raise an error after setting the Secondary objects should not raise an error after setting the done bitdone bit

The bug steps on the error message and the root gets the The bug steps on the error message and the root gets the infamous error message infamous error message "method '~' of object '~' failed""method '~' of object '~' failed"

This bug breaks MTS code when you move your application This bug breaks MTS code when you move your application to Win2Kto Win2K

The bug will be fixed in Win2K service pack1The bug will be fixed in Win2K service pack1 Here's a workaround until the bug is fixedHere's a workaround until the bug is fixed

Secondary objects should avoid calling SetAbort before Secondary objects should avoid calling SetAbort before raising an errorraising an error

Secondary objects should call SetMyTransactionVote or Secondary objects should call SetMyTransactionVote or DisableCommit instead – DisableCommit instead – just don’t set the done bit to truejust don’t set the done bit to true

What are the worst things about is this bug a problemWhat are the worst things about is this bug a problem MTS code will break when run under COM+MTS code will break when run under COM+ You can’t really create a component that can act as either the You can’t really create a component that can act as either the

root or as a secondary objectroot or as a secondary object

Remote Computer 2Remote Computer 2

ORACLE (RM2)ORACLE (RM2)

Participating DTCParticipating DTC

Remote Computer 1Remote Computer 1

SQL Server (RM1)SQL Server (RM1)

Participating DTCParticipating DTC

COM+ ComputerCOM+ Computer

Coordinating DTCCoordinating DTC

COM+ ApplicationCOM+ Application

COM+ RuntimeCOM+ Runtime

User’s ComputerUser’s Computer

Base ClientBase Client

COM+ TransactionCOM+ Transaction

DataData

DataData

DTC Proxy LayerDTC Proxy Layer

RootRoot

SecondarySecondary

SecondarySecondary

Enlisting Resource Enlisting Resource ManagersManagers

Going StatelessGoing Stateless Transactional objects typically die after each method Transactional objects typically die after each method

callcall Calling Calling SetComplete SetComplete or or SetAbortSetAbort on ObjectContext tells on ObjectContext tells

MTS/COM+ that the object's work is done and it can be MTS/COM+ that the object's work is done and it can be deactivated (i.e. destroyed)deactivated (i.e. destroyed)

Object destruction occurs in interception layer in method post-Object destruction occurs in interception layer in method post-processingprocessing

MTS/COM+ hides object destruction from clientsMTS/COM+ hides object destruction from clients The client holds a persistent connection to system-supplied The client holds a persistent connection to system-supplied

proxyproxy MTS/COM+ uses just-in-time activation to create a new object MTS/COM+ uses just-in-time activation to create a new object

for each method called from the clientfor each method called from the client How does this affect the way you program?How does this affect the way you program?

It helps you to release your transactions ASAPIt helps you to release your transactions ASAP It discards state acquired from RMs before locks are releasedIt discards state acquired from RMs before locks are released

this is required to enforce the ACID rulesthis is required to enforce the ACID rules This can make design more difficult because objects cannot This can make design more difficult because objects cannot

hold statehold state

Stateless Versus Stateful Stateless Versus Stateful ComponentsComponents Statelessness is a strange side-effect of declarative Statelessness is a strange side-effect of declarative

transactionstransactions You must design around the assumption that state is lost on You must design around the assumption that state is lost on

every method call to a transactional objectevery method call to a transactional object Many misinformed authorities have suggested that the point of Many misinformed authorities have suggested that the point of

calling SetComplete is aggressive memory reclamation (calling SetComplete is aggressive memory reclamation (this is this is totally untruetotally untrue))

Deactivation and JIT reactivation is only for transactional Deactivation and JIT reactivation is only for transactional objects and poolable objects (objects and poolable objects (there is no reason to set the done there is no reason to set the done bit in any other casebit in any other case))

Objects that need transactions can hold stateObjects that need transactions can hold state Many designs require that state is held across method callsMany designs require that state is held across method calls

losing state implies that object must be recreated & reinitialized on a per call losing state implies that object must be recreated & reinitialized on a per call basisbasis

Many advantages of MTS/COM+ apply to non-transactional Many advantages of MTS/COM+ apply to non-transactional objects as wellobjects as wellstateful objects benefit from thread pooling, COM+ security, stateful objects benefit from thread pooling, COM+ security, configuration mgmt, etc.configuration mgmt, etc.

Consider Using The Lower Consider Using The Lower Design ApproachDesign Approach It’s often advantageous to place a a It’s often advantageous to place a a

non-transactional object between a non-transactional object between a transactional object and the clienttransactional object and the client Client can hold server-side state and still Client can hold server-side state and still

run declarative transactionsrun declarative transactions Non-transaction object can shield client Non-transaction object can shield client

from errors thrown by the DTCfrom errors thrown by the DTC

Consider Using The Lower Consider Using The Lower Design ApproachDesign Approach

Client Application 1Client Application 1

COM+ ApplicationCOM+ Application

RootRootObjectObject

Happy BitHappy Bit TRUETRUE

Context AContext A

StubStub

Done BitDone Bit TRUETRUE

ProxyProxyClientClient

Client Application 2Client Application 2 Context BContext B

StubStubProxyProxy

ClientClient RootRootObjectObject

Happy BitHappy Bit TRUETRUE

Context CContext C

Done BitDone Bit TRUETRUE

Non-TXNon-TXObjectObject

ProxyProxy

When Should You Use When Should You Use Transactions?Transactions? You should use transactions only when you need to You should use transactions only when you need to

enforce the ACID rulesenforce the ACID rules They're expensive and reduce scalability when used They're expensive and reduce scalability when used

unnecessarily unnecessarily Only run transactions when you need acquire locks across a set Only run transactions when you need acquire locks across a set

of operationsof operations You don’t need an explicit transaction for an individual SQL You don’t need an explicit transaction for an individual SQL

statementstatementthe DBMS runs each SQL statement as an individual transaction automaticallythe DBMS runs each SQL statement as an individual transaction automatically

How do you decide between local and distributed How do you decide between local and distributed transactions?transactions? Local transaction are always faster (no DTC & fewer roundtrips)Local transaction are always faster (no DTC & fewer roundtrips) Distributed transactions are required when your data lives in Distributed transactions are required when your data lives in

many RMsmany RMs Distributed transaction can make your designs and Distributed transaction can make your designs and

programming easierprogramming easierbut they do so at the expense of response times and overall system throughputbut they do so at the expense of response times and overall system throughput

SummarySummary OLTP ConceptsOLTP Concepts

The ACID rulesThe ACID rules Isolation and lockingIsolation and locking Writing local transactionsWriting local transactions

Distributed TransactionsDistributed Transactions The transaction manager and two phase commitThe transaction manager and two phase commit The Distributed Transaction CoordinatorThe Distributed Transaction Coordinator Writing distributed transactionsWriting distributed transactions

MTS/COM+ TransactionsMTS/COM+ Transactions Creating objects inside a transactionCreating objects inside a transaction Controlling the transactions outcomeControlling the transactions outcome