Andy's observations as he continues to attempt to know all that is .NET...

Friday, January 18, 2008

Ensure local transaction snippet

Whilst teaching developmentors enet 3 class this week I had an idea for a new snippet. It came to me whilst teaching the deck on System.Transactions, I was in the middle of demonstrating to them how you need to be really careful not to cause a transaction to be promoted to the DTC ( See Previous Blog Article ). Two strategies I suggest are


 

  1. Stop the DTC, net stop MSDTC
  2. Add an Debug.Assert statement inside your TransactionScope block to ensure the current transaction is not a distributed transaction, by checking that the DistributedIdentifier is an empty GUID.


 

The first option is reasonable if you never need the DTC, but if you do have bits of code that does need the DTC its clearly not an option. The second approach is a bit tedious ut if you use a snippet, then its not all that bad. Below is the snippet code..


 


 

<CodeSnippet
Format="1.0.0"
xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">

<Header>

<Title>Local Transaction</Title>

<Author>Andrew Clymer</Author>

<Shortcut>lscope</Shortcut>

<Description>Creates a transaction scope and ensures at the end of the block that the transaction is only a local transaction </Description>

<SnippetTypes>

<SnippetType>SurroundsWith</SnippetType>

<SnippetType>Expansion</SnippetType>

</SnippetTypes>

</Header>

<Snippet>

<Declarations>

<Literal>

<ID>scope</ID>

<Default>scope</Default>

</Literal>

</Declarations>

<Code
Language="CSharp">

<![CDATA[

using (TransactionScope $scope$ = new TransactionScope())

{


 

$selected$

$end$


 


 

Debug.Assert(Transaction.Current.TransactionInformation.DistributedIdentifier == Guid.Empty,

"Unexpected!! Transaction is now distributed");

}


]]>

</Code>

</Snippet>

</CodeSnippet>

No comments:

About Me

My photo
Im a freelance consultant for .NET based technology. My last real job, was at Cisco System were I was a lead architect for Cisco's identity solutions. I arrived at Cisco via aquisition and prior to that worked in small startups. The startup culture is what appeals to me, and thats why I finally left Cisco after seven years.....I now filll my time through a combination of consultancy and teaching for Developmentor...and working on insane startups that nobody with an ounce of sense would look twice at...