Geeks With Blogs
NIEM Guy - NIEM, XML, and .NET Piecing it all together

I have a situation where I want to use a transaction to keep track of a particular message process in order to roll back various parts if there is a failure.  The service operation is listening on a queue using the NetMSMQBinding and the operation is marked with the transaction properties of the OperationBehavior like so:
<OperationBehavior(TransactionAutoComplete:=True,TransactionScopeRequired:=True)> Public Sub SendHello( ...

Using the above attribute enables the operation for transaction support.  The next trick is to grab the ambient transaction.  Doing this requires pulling in the System.Transactions namespace.

Dim ambientTransaction as System.Transactions.Transaction = System.Transactions.Transaction.Current

Once you have the ambient transaction you can pass that to your LINQ data context using the data context's Connection.EnlistTransaction method.

myDataContext.Connection.EnlistTransaction(ambientTransaction)

Note: Enlisting the transaction will require you to open and close your connection.  The code block worked for me.  I tested by throwing an exception after this block and my database insert (usp_InsertHello is a stored procedure) did not commit.

Using myDataContext as new HelloWorldDataContext

  myDataContext.Connection.EnlistTransaction(ambientTransaction)
  myDataContext.Connection.Open
  myDataContext.usp_InsertHello(helloText)
  myDataContext.Connection.Close

End Using

Many objects have an enlist transaction method that you can pass your transaction to.  The obvious benefit is that now all of the calls required for processing of the message will be handled in the scope of this transaction and if the method runs to completion all changes are committed - data operations are saved and the message is removed from the queue.  In the event of a failure the whole operation is rolled back and the message is returned to the queue. 

For a poison message strategy just putting back at the top of the queue is not ideal; this is just an example of how transactions can be used across multiple calls in the context of an operation.

Technorati Tags: ,,,
Posted on Wednesday, May 28, 2008 9:23 PM | Back to top


Comments on this post: Passing a Transaction from a WCF Operation to a LINQ Data Context

# re: Passing a Transaction from a WCF Operation to a LINQ Data Context
Requesting Gravatar...
hi
pls help me for passing a transaction from a wcf operation to a linq datacontext
Left by hasan on Mar 02, 2009 8:51 AM

Your comment:
 (will show your gravatar)


Copyright © niemguy | Powered by: GeeksWithBlogs.net