WCf-Transactions Notes

Embed Size (px)

Citation preview

  • 8/7/2019 WCf-Transactions Notes

    1/2

    TRANSACTIONS IN WCF

    The TransactionIsolationLevel property determines how the database management system (SQLServer in the exercises in this book) lets concurrent transactions overlap. In a typical system,multipleconcurrentusers access the database at the same time. However, this can lead toproblems when twousers trytomodifythe same data atthe same time,orwhenone usertries to query data that anotheruseris modifying. Youmust ensure thatconcurrentusers cannotinterfere adverselywith each othertheymust be isolated. Typically,whenever a usermodifies, inserts,ordeletes data during a transaction, thedatabase management system locks the affected data until the transactioncompletes. If the transactioncommits, the database management systemmakes the changes permanent. If an erroroccurs and thetransaction rolls back, the database management system cancels the changes. TheTransactionIsolationLevelproperty specifies howthe locks applied during a data-modificationtransactionaffectothertransactions attempting to access the same data.

    TheTransactionIsolationLevel property can take one of several values. The most common isolationlevels are: IsolationLevel.ReadUncommitted This isolation level enables the transaction to read data thatanothertransaction has modified and locked, butnotyetcommitted. This isolation level provides the mostconcurrency; however, there is the riskof the user being presented with dirty data thatmightchangeunexpectedlyifthe modifying transactionrolls backthe changes ratherthancommitting them. IsolationLevel.ReadCommittedThis isolation level prevents the transaction from reading data thatanother transaction has modified, butnotyetcommitted. The reading transactionwill be forced towaituntil the modified data is unlocked. Although this isolation level prevents read access to dirty data,it doesnot guarantee consistency; if the transaction reads the same data twice, there is the possibility thatanothertransactionmight have modified the data in betweenreads,thus the reading transactionwould bepresented with two differentversions ofthe data. IsolationLevel.RepeatableReadThis isolation level is similar to the ReadCommitted isolation level,but itcauses the transactionreading the data to lockthis data until the reading transactionfinishes (theReadCommitted isolation level does notcause a transaction to lock data that it reads). The transactioncanthen safelyread the same data as manytimes as itwants withoutthe data being changed by anothertransactionuntil this transaction has completed. This isolation level therefore provides more consistency,atthe costofreduced concurrency. IsolationLevel.SerializableThis isolation level takes the RepeatableReadisolation level one stagefurther. When using the RepeatableRead isolation level, data read by a transaction cannot change.However, it is possible for a transaction to execute the same query twice and obtain different results ifanother transaction inserts data that matches the query criteria: new rows suddenly appear. TheSerializable isolation level prevents this inconsistency fromoccurring by restricting the rows thatotherconcurrent transactions can add to the database. This isolation level provides the greatest level ofconsistency, butthe degree ofconcurrencycan be significantlyreduced.

    Unless you have a good reasontochoose otherwise,use the IsolationLevel.RepeatableReadisolation level.

    Changes to implement Transactions in WCF:

    Locate the Service Behaviorattribute thatprecedes the ServiceImplclass. Add the followingTransactionIsolationLevelproperty (shownin bold)tothis attribute:

    [Service Behavior (InstanceContextMode = InstanceContextMode.PerSession,TransactionIsolationLevel=IsolationLevel.RepeatableRead)]

    public class ShoppingCartServiceImpl : IShoppingCartService{...

    }

    Inthe ShoppingCartServiceImplclass, add the following OperationBehaviorattribute totheAddItemToCartmethod:

    [OperationBehavior(TransactionScopeRequired=true, transactionAutoComplete=false)]public bool AddItemToCart(string productNumber){...

    }

  • 8/7/2019 WCf-Transactions Notes

    2/2

    TransactionScopeRequiredproperty :ofthe OperationBehaviorattribute totrue forces the operationto execute as partofa transaction; eitherthe client applicationmustinitiate the transaction (youwill seehowto dothis shortly)orthe WCF runtime will automaticallycreate a newtransactionwhenthisoperationruns.The TransactionAutoCompleteproperty specifies what happens tothe transactionwhenthe operationfinishes. Ifyou setthis propertytotrue,the transaction automaticallycommits and makes all its changespermanent. Setting this propertytofalse keeps the transaction active;the changes are notcommittedyet. The defaultvalue forthis propertyis true. Inthe case oftheAddItemToCartmethod,you dontwanttocommitchanges and finish the transactionuntil the userhas checked out and paid forthegoods, sothe code sets this propertytofalse.

    Add the TransactionFlowattributes (shownin bold inthe following code)to all the method definitionsinthe IShoppingCartService interface, just afterthe OperationContractattribute:

    publicinterface IShoppingCartInterface{

    [OperationContract(Name = "AddItemToCart", IsInitiating = true)][TransactionFlow(TransactionFlowOption.Mandatory)]public bool AddItemToCart(string productNumber)

    }

    Specifying a parameterofTransactionFlowOption.Mandatoryindicates thatthe client applicationmustcreate a transaction before calling this operation and must send the details ofthis transaction as partofthe SOAP message headerwheninvoking the operation. The othervalues youcan specify areTransactionFlowOption.Allowed,which will use a transactioncreated bythe clientifone exists (the WCFruntime will create a newtransactionifnot), and TransactionFlowOption.NotAllowed,which causes theWCF runtime to disregard anyclienttransaction and always create a newone.The defaultvalue is TransactionFlowOption.NotAllowed.

    NoteNot all bindings allowyoutoflowtransactions fromclient applications into a service. Thebindings that donot supporttransactions include BasicHttpBinding,NetMsmqBinding,NetPeer,TcpBinding, and WebHttpBinding.