Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine whether SqlConnection is enlisted into a System.Transactions' tx or not?

When we using a transation from System.Transactions (creating TransationScope for an instance) by default all Sql-connections (System.Data.SqlClient.SqlConnection) (but is't also the true for Oracle.DataAccess.OracleConnection) are enlisted on opening. That's called auto-enlistment. Nice feature. But it can be turned off throught a connection string's parameter (enlist=false). In that case connection being opened wouldn't be enlisted. But it can be enlisted manually later. So my question is: for some given SqlConnection's instance how can I determine whether that connection is enlisted or not (into an System.Transaction). I can look at connection string for the parameter. But this won't do because as I said connection could be enlisted manually.

like image 737
Shrike Avatar asked Oct 14 '08 03:10

Shrike


1 Answers

The framework doesn't appear to allow that.

Perhaps we could discuss why you need to know this information? The TransactionScopeOptions give you some flexibility about when to create transactions.

However, refusing "no" for an answer, a little source browsing later and I've created this code, which DOES work. Note, that this code could cease to function at anytime with patches to the framework!!!!

    static bool IsEnlisted(SqlConnection sqlConnection)
    {
        object innerConnection = typeof(SqlConnection).GetField("_innerConnection", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy).GetValue(sqlConnection);
        var enlistedTransactionField =
            EnumerateInheritanceChain(innerConnection.GetType())
            .Select(t => t.GetField("_enlistedTransaction", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy))
            .Where(fi => fi != null)
            .First();
        object enlistedTransaction = enlistedTransactionField.GetValue(innerConnection);
        return enlistedTransaction != null;
    }

    static IEnumerable<Type> EnumerateInheritanceChain(Type root)
    {
        for (Type current = root; current != null; current = current.BaseType)
            yield return current;
    }

Again, this is making use of private variables and internal classes within the .NET framework. While it works today, it may not tomorrow.

like image 171
TheSoftwareJedi Avatar answered Sep 28 '22 10:09

TheSoftwareJedi