Managed Kernel Transaction Manager – Pt 2.

In my previous posting on using the Kernel Transaction Manager here, I mentioned that I would do a follow up explaining how to ensure that your code behaves on systems that don’t have the KTM present. In other words, how do you ensure that your code runs under pre Vista operating systems? Well, it turns out that this is both very simple and very, very complex at the same time.

Basically, you have the choice of trying to replicate the KTM on older operating systems or you can choose to live with the differences in behaviour between the two areas. If you want the systems to behave exactly the same, then you are going to have to add a lot of code yourself to monitor what’s going on inside the transaction and handle them as appropriate. If you can live with the discrepancy in behaviour, then you can do one of the following two things.

  1. You can rely on an exception to tell you that the API method isn’t available in that particular form and fall back to a simpler method in the catch block.
  2. You can explicitly test the operating system version to see if it is Vista or later. This is the method that I’m going to take here.

Taking yesterdays example of removing a directory, we can create a method that looks like this:

public static void DeleteDirectory(string path)

{

  if (Environment.OSVersion.Version.Major > 5 && Current.Transaction != null)

  {

    IntPtr txh = null;

    IKernelTx tx = (IKernelTx)TransactionInterop.GetDtcTransaction(Transaction.Current);

    tx.GetHandle(out txh);

    RemoveDirectoryTransacted(path, txh);

  }

  else

  {

    Directory.Delete(path);

  }

}

Note that we don’t bother trying to call the transacted version if the version is less than or equal to 5 and there is no current transaction. There, you’ve now made it so that your code will run on XP. Again, a word of caution. If your logic relies on ACID being enforced in the file system and the KTM isn’t present, you could end up in big trouble indeed, i.e. only rely on ACID if you know that the minimum version that your software runs on will always be Vista.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s