11

I am trying to write a file to disk as well as insert data into a database via a stored procedure all within an atomic transaction. i.e. If any one of these 2 operations fails (either the file cannot be written to disk or the stored procedure fails) I'd like to do nothing and simply throw an exception back to the caller.

Any suggestions on how to best to tackle this atomic transaction for a file write and a database insert?

Additional Info: I am using C# .NET with a stored procedure into MS SQL Server but general solutions not necessarily tailored to these technologies are fine too.

UPDATE: After reviewing all the answers below and researching others, I wrote this post about how to solve this problem using 3 different approaches.

1
  • When you mean 'Transaction' do you mean in 1 Routine or do you physically mean SQL Database Transaction where you have a rollback? Feb 24, 2011 at 21:11

5 Answers 5

7

You need to use the new TxF, the Transacted NTFS introduced in Vista, Windows 7 and Windows Server 2008. This is a good introductory article: Enhance Your Apps With File System Transactions. It contains a small managed sample of enrolling a file operation into a system transaction:

// IKernelTransaction COM Interface
[Guid("79427A2B-F895-40e0-BE79-B57DC82ED231")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IKernelTransaction
{
    int GetHandle(out IntPtr pHandle);
}

[DllImport(KERNEL32, 
   EntryPoint = "CreateFileTransacted",
   CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern SafeFileHandle CreateFileTransacted(
   [In] string lpFileName,
   [In] NativeMethods.FileAccess dwDesiredAccess,
   [In] NativeMethods.FileShare dwShareMode,
   [In] IntPtr lpSecurityAttributes,
   [In] NativeMethods.FileMode dwCreationDisposition,
   [In] int dwFlagsAndAttributes,
   [In] IntPtr hTemplateFile,
   [In] KtmTransactionHandle hTransaction,
   [In] IntPtr pusMiniVersion,
   [In] IntPtr pExtendedParameter);

....

using (TransactionScope scope = new TransactionScope())
{
   // Grab Kernel level transaction handle
   IDtcTransaction dtcTransaction = 
      TransactionInterop.GetDtcTransaction(managedTransaction);
   IKernelTransaction ktmInterface = (IKernelTransaction)dtcTransaction;

   IntPtr ktmTxHandle;
   ktmInterface.GetHandle(out ktmTxHandle);

   // Grab transacted file handle
   SafeFileHandle hFile = NativeMethods.CreateFileTransacted(
      path, internalAccess, internalShare, IntPtr.Zero,
      internalMode, 0, IntPtr.Zero, ktmTxHandle,
      IntPtr.Zero, IntPtr.Zero);

   ... // Work with file (e.g. passing hFile to StreamWriter constructor)

   // Close handles
}

You'll need to enroll your SQL operation in the same transaction, which will occur automatically under a TransactionScope. But I highly recommend you override the default TransactionScope options to use ReadCommitted isolation level:

using (TransactionScope scope = new TransactionScope(
     TransactionScope.Required, 
     new TransactionOptions 
         { IsolationLevel = IsolationLEvel.ReadCommitted}))
{
...
}

W/o this you'll get the default Serializable isolation level which is way way overkill for most cases.

1
5

This question and answer seems to be part of the answer. It involves Transactional NTFS. SLaks links to a .NET managed wrapper for Transactional NTFS hosted on MSDN.

You could try using a TransactionScope.

4
  • Wouldn't a file still be present (if the WriteToDisk was first) even if the transaction failed? Never used this before (and it looks cool) but it doesn't seem to have any magic regarding non-database things that may happen in the block, just that the transaction wouldn't be committed if an exception occurred. Feb 24, 2011 at 21:17
  • 1
    Transactional NTFS would roll back the file ;) it has magic as it uses the DTC as needed to store rollback information.
    – TomTom
    Feb 24, 2011 at 21:30
  • Awesome. I will have to check it out. We just went to a slew of modern servers so I may actually be able to use it! Feb 24, 2011 at 21:38
  • Wihtout transactional NTFS you could use a CRM (Compensating Resource Manager) to clean up the file after restart.
    – TomTom
    Oct 5, 2012 at 17:29
1

You can leverage System.Transactions namespace

The System.Transactions namespace contains classes that allow you to write your own transactional application and resource manager. Specifically, you can create and participate in a transaction (local or distributed) with one or multiple participants.

For more details refer MSDN documentation: http://msdn.microsoft.com/en-us/library/system.transactions.aspx

1

For something this simple, I would just (psudocode)

try
{
//write file

//commit to DB

}
catch(IOException ioe)
{
// no need to worry about sql as it hasn't happened yet
// throw new exception
}
catch(SqlException sqle)
{
// delete file
// throw exception
}
4
  • 3
    But potentially faulty, if the delete can't happen for some reason (e.g. another process locked the file, or you don't want the app to have delete priviliges). Not likely, but not totally safe. Why wouldn't you do the database part first, which can be absolutely rolled back with no fuss? Feb 24, 2011 at 21:26
  • 2
    -1. Shows pretty exactly how normal programmers are ignorant regarding transactions.
    – TomTom
    Feb 24, 2011 at 21:30
  • @TomTom what's your suggestion then? Oct 5, 2012 at 13:25
  • Use the System.Transaction namespace, implementa CRM (Compensating Ressource Manager for the file update. Distributed Transactions 101 - for beginners ;) All supported by the .NET framework.
    – TomTom
    Oct 5, 2012 at 17:29
0

Maybe I don't quite get the difficulty here but seems pretty straightforward... pseudocode:

public void DoStuff()
{
      bool itWorked=false;
      StartTransaction();
      itWorked = RunStoredProcedure();
      itWorked = itWorked && WriteFile();
      if (!itWorked) {
          RollbackTransaction();
          throw new Exception("It didn't work");
      } else {
          CommitTransaction();
      }
}

You could do it the other way around but then you'd have to delete the file after, putting the DB attempt first makes it easiest to undo the first operation.

edit... i just realized that this could be shortened by a few lines, the bool isn't necessary... leaving the original for clarity:

public void DoStuff()
{
      StartTransaction();
      if (!(RunStoredProcedure() && WriteFile())) {
          RollbackTransaction();
          throw new Exception("It didn't work");
      } else {
          CommitTransaction();
      }
}

Love short circuits.

2
  • There are many things that could go wrong here. You can't be sure the file was REALLY written (and something bad in a similar way happened some months ago in Linux, where configurations files were written but not correctly flushed), the Commit could fail and you would have to delete the file (and the delete could fail)...
    – xanatos
    Feb 24, 2011 at 21:29
  • 1
    The assumption is that WriteFile() returns true only if the file was actually written. I don't know any other way one could operate, i mean, if it was not REALLY written and you didn't have any way to find that out, then where are you? I guess if you can't depend with a suitable level of confidence on either one or the other then the only solution is to hardcode the "undo" part of this, but those steps, too, could fail, you're not really any better off. If there's an unsuitable degree of confidence in either then you'd have to try everything, and if it didn't work out, email someone. Feb 24, 2011 at 21:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.