Transaction Scope and legacy code with SqlTransaction

已鎖定 Transaction Scope and legacy code with SqlTransaction

  • Friday, August 24, 2012 12:15 AM
     
     

    I am developing a "wrapper" (.NET 4.0) that will call several c# legacy components (.NET 2.0) developed using its own transaction controls. Internally, these components are using SqlTransactions (with BeginTran, Commit and Rollback) explicitly. We want to avoid to change these components.

    We also need to call some of those methods of those components controlling the transaction at the wrapper level (using TransactionScope).

    Do you think it is possible to do this ? Or will we need to refactor the legacy code ? Will the SqlTransaction obey the transactionScope ?

    Thanks

All Replies

  • Friday, August 24, 2012 7:45 PM
     
     

    Complementing my question:

    We are running a "Proof of concept" (POC)  and we noticed that when the "rollback" is simulated, the following exception raises:

    "The transaction under which this method call was executing was asynchronously aborted."

    Internally is generating the following error: "No Corresponding BEGIN TRANSACTION error When ROLLBACK TRANSACTION".

    The POC code is:

     static void Main(string[] args)
            {
                try
                {
                    using (TransactionScope txScope = new TransactionScope(TransactionScopeOption.Required))
                    {
                        bool ret = ExecuteQuery();

                        txScope.Complete();

                        Console.WriteLine("Transaction OK");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Transaction Failed");
                }
                
                Console.ReadKey();
            }


    public static bool ExecuteQuery()
            {
                string strSQL = string.Empty;
                string strConn = string.Empty;

                string sqlQuery = "UPDATE statement...";

                SqlTransaction tran = null;

                try
                {
                    strConn = @"xxxx; Database=XXX; Integrated Security=true";

                    SqlCommand sqlCMD = new SqlCommand();
                    SqlConnection con = new SqlConnection(strConn);

                    con.Open();

                    tran = con.BeginTransaction();

                    sqlCMD.Connection = con;
                    sqlCMD.Transaction = tran;
                    sqlCMD.CommandText = sqlQuery;
                    sqlCMD.CommandType = CommandType.Text;
                    sqlCMD.ExecuteNonQuery();

                    tran.Commit();
                    
                    con.Close();
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    throw ex;
                }

                return true;
            }