Click here to Skip to main content
6,295,667 members and growing! (13,084 online)
Email Password   helpLost your password?
Database » Database » General     Intermediate

TransactionScope in .NET 1.1

By Alexander Shirshov

Emulate TransactionScope functionality coming in .NET 2.0 with .NET 1.1.
C#, SQL, .NET, WinXP, Win2003, ASP.NET, Visual Studio, COM+, ADO.NET, SQL 2000, SQL 2005, Architect, DBA, Dev
Posted:1 Jun 2005
Views:51,564
Bookmarked:26 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
7 votes for this article.
Popularity: 3.86 Rating: 4.57 out of 5

1

2

3
3 votes, 42.9%
4
4 votes, 57.1%
5

Now: Declarative Database Transactions With ServicedComponent

Developers working with Microsoft SQL Server enjoyed declarative handling of transactions since Windows NT 4.0 days. With the .NET Framework, this usually means we need to inherit a class from ServicedComponent, apply TransactionAttribute to it, and use SetAbort/SetComplete methods to notify the framework if our DB operation succeeded or failed. The framework takes care of the rest.

Simple? Yes, but�

  • ServicedComponent requires you to sign your assemblies, the step considered by many developers as the unnecessary complication.
  • You can�t mix transactional and non-transactional methods in one class, which forces you to split a single logical CustomerService into CustomerReader and CustomerWriter or something like that.

Future: TransactionScope in .NET 2.0

In .NET 2.0, we are going to have the TransactionScope class which solves both problems. Used as braces around a code which must run inside a database transaction and, although not the declarative style anymore, it provides a nice clean model:

using (TransactionScope scope = new TransactionScope())
{
  // open connection

  // perform database operation, which is going to run inside the transaction
// call other method and if the other method creates a TransactionScope object

  // it will share the transaction with the current method


  // All is well:

  Scope.Complete();
}

The Future's Here

OK, the code above looks as good as I�d like it to be, but Whidbey isn�t coming to production machines near me for another year or so. I had to create my own solution using .NET 1.1, and here it is. In fact, the implementation is so embarrassingly simple that I now feel ashamed I didn�t figure it out earlier!

Usage:

using (TransactionScope scope = new TransactionScope())
using (SqlConnection conn = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand(updateSql, conn))
{
  System.Diagnostics.Debug.Assert(
         System.EnterpriseServices.ContextUtil.IsInTransaction);
    
  conn.Open();
    
  int result = cmd.ExecuteNonQuery();

  // We call it success if exactly one record was updated:

  if (result == 1)
  {
    scope.Complete();
  }
}

Here�s the complete class:

// Copyright (c) 2005 Alexander Shirshov

//

// This code is free software; you can redistribute it and/or modify it.

// However, this header must remain intact and unchanged. Additional

// information may be appended after this header. Publications based on

// this code must also include an appropriate reference.

// 

// This code is distributed in the hope that it will be useful, but 

// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 

// or FITNESS FOR A PARTICULAR PURPOSE.


using System;
using System.EnterpriseServices;

namespace Omnitalented.EnterpriseServices
{
  public class TransactionScope : IDisposable
  {
    private bool succeded;

    public TransactionScope() : this(TransactionOption.Required, 
                                TransactionIsolationLevel.Any, 60)
    {
    }

    public TransactionScope(TransactionOption transactionOption) : 
           this(transactionOption, TransactionIsolationLevel.Any, 60)
    {
    }

    public TransactionScope(TransactionOption transactionOption, 
           TransactionIsolationLevel isolationLevel, int timeoutSeconds)
    {
      ServiceConfig cfg = new ServiceConfig();
      cfg.Transaction = transactionOption;
      cfg.IsolationLevel = isolationLevel;
      cfg.TransactionTimeout = timeoutSeconds;
            
      ServiceDomain.Enter(cfg);
    }

    public void Complete()
    {
      succeded = true;
    }

    public void Dispose()
    {
      if (succeded)
      {
        ContextUtil.SetComplete();
      } 
      else
      {
        ContextUtil.SetAbort();
      }
      ServiceDomain.Leave();
    }
  }
}

Please note: The code only works in Windows 2003 Server or Windows XP; this is a requirement for the System.EnterpriseServices.ServiceDomain class.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Alexander Shirshov


Member
Alexander is struggling to write decent software amidst Thailands' many distractions.

You can read whatever he occasionly writes on his blog.
Occupation: Web Developer
Location: Thailand Thailand

Other popular Database articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 17 of 17 (Total in Forum: 17) (Refresh)FirstPrevNext
GeneralName using is not declare PinmemberBMWABCD7:34 23 Jul '08  
GeneralThis vs. .net2.0 TransactionScope + MSDTC Pinmemberbalazs_hideghety10:48 26 Mar '07  
QuestionUsage of Transaction Scope PinmemberVijay Kumar Raja Grandhi0:27 27 Apr '06  
AnswerRe: Usage of Transaction Scope PinmemberDominik5:34 8 Aug '06  
GeneralRe: Usage of Transaction Scope PinmemberDominik6:26 8 Aug '06  
GeneralRe: Usage of Transaction Scope PinmemberVijay Kumar Raja Grandhi0:53 10 Aug '06  
GeneralRe: Usage of Transaction Scope Pinmemberkheongchoon21:18 25 Sep '06  
GeneralRe: Usage of Transaction Scope PinmemberVijay Kumar Raja Grandhi0:22 23 Nov '06  
GeneralRe: Usage of Transaction Scope Pinmemberbalazs_hideghety10:51 26 Mar '07  
GeneralBusiness Layer PinsussAnonymous21:58 1 Sep '05  
GeneralRe: Business Layer PinmemberJoey Chömpff22:00 1 Sep '05  
GeneralRe: Business Layer Pinmemberbalazs_hideghety3:09 24 Jun '07  
GeneralTwo connections? two databases? Pinmemberscubaduba23:23 2 Jun '05  
GeneralRe: Two connections? two databases? PinmemberAlexander Shirshov23:56 2 Jun '05  
GeneralRe: Two connections? two databases? Pinmemberbalazs_hideghety10:53 26 Mar '07  
GeneralRe: Two connections? two databases? Pinmembersanjayjolapra23:54 22 Jun '07  
GeneralRe: Two connections? two databases? Pinmemberbalazs_hideghety3:12 24 Jun '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 1 Jun 2005
Editor: Smitha Vijayan
Copyright 2005 by Alexander Shirshov
Everything else Copyright © CodeProject, 1999-2009
Web16 | Advertise on the Code Project