views:

1219

answers:

3

In my web application I've to keep audit of the user actions. So whenever user takes an action I update the object on which action is taken and keep audit trail of that action.

Now If I first modify the object and then update audit trail but the audit trail fails then what?

Obviously I need to roll-back changes to modified object. I can use Sql-Transactions in simple application, but I'm using Subsonic to talk to db. How I can handle the situation?

+5  A: 

Something like:

Using ts As New System.Transactions.TransactionScope()
  Using sharedConnectionScope As New SubSonic.SharedDbConnectionScope()

' Do your individual saves here

' If all OK
      ts.Complete()

   End Using
End Using
I can confirm TransactionScope works correctly with SubSonic, and does rollback transactions correctly.
RandomNoob
Thanks @kevinw and @bnkdev. I'm using C# so I'll post the code in C# also so it can be readily used by others. Also wouldn't you put the individual saves or actions inside try/catch so it is easier to know if all Ok or not?
TheVillageIdiot
+4  A: 

The answer given by @Kevinw is perfectly okay. I'm posting this just as translation of his answer to C# code. I'm not using comments as it will not format code :) Also I'm using try/catch to know if transaction should complete or be rolled back.

using (System.Transactions.TransactionScope ts = new TransactionScope())
{
    using (SharedDbConnectionScope scs = new SharedDbConnectionScope())
    {
        try
        {
            //do your stuff like saving multiple objects etc. here 

            //everything should be completed nicely before you reach this
            //line if not throw exception and don't reach to line below
            ts.Complete();
        }
        catch (Exception ex)
        {
            //Do stuff with exception or throw it to caller
        }
    }
}
TheVillageIdiot
+1  A: 

Nope. If I put the shareddbconnectionscope outside the changes are visibles in the database before ts.Complete(). Putting it inside blocks the server until the oporation is done.

Apocatastasis