Concept Of Transaction Scope (Local and Distributed Transaction)

  1. What is Transaction

    Transaction is nothing but a logical unit of work consisting of one or more than one activities which need to succeed or fail all activities to maintain the integrity of information of business, work consistency and separation of work from each other to avoid conflict of information and durability of work with atomicity means guaranteed success of all activities otherwise guaranteed failure of all, no partial success or partial failure (refer ACID various article available on internet).

    We are not going to learn too much theory about Transaction, Transaction Scope, Local and Distributed since there are already tones of article available on the internet.

  2. Types of Transaction

    a. Business Transaction

    Business Transaction means activities involved between Customer, Sales Person, and Stakeholder, Vendor etc. in order to carry out day to day business of Company or a set of activities involved to achieve long running business deals.

    b. Database Transaction

    Database Transaction is nothing but a set of actions involved to manipulate the database or databases. Database Transaction can be classified as Non-Distributed Transaction (Local Transaction) and Distributed Transaction.

    • Non-Distributed Transaction (Local Transaction) - Where application only deals with the single database and perform all data manipulation action on same database.

    • Distributed Transaction- Where application deals with various databases and perform all data manipulation action on multiple database. To apply Distributed Transaction we have to start DTC (Distributed Transaction Coordinator) service from Services panel.

    Note- An application can have both types of Transactions.

  3. History

    Before introduction of .Net Framework, classic Visual Basic was widely used to develop RAD and Enterprise Level Application and successfully used by small to enterprise level industry, where COM and COM+ technology was playing role to implement distributed technology, which was generally called COM era.

    Classic Visual Basic contains various Data Access Components called DAO, RDO and ADODB and each one used to provide programming interface to control Non-Distributed Transaction (Local Transaction).

    COM+ was/is one of the robust technology to implement Transaction Scope which maintain the theory of ACID which is used to control Distributed Transaction by wrapping series of action of related operations together in a COM+ transaction that either completely succeeds or completely fails.

  4. When to use

    When Application deals several DML statement under single event either on single or multiple databases.

  5. Various ways of implementing Transaction Scope

    There are various ways to implement Transaction Scope for either Non- Distributed or Distributed Transaction and they depend upon various Data Access technologies.

    In this article we will cover implementation of Transaction Scope with the help of various features and frameworks given by Microsoft as Data Access Components which comes under .Net Framework.
    However before diving into Transaction Scope, let us see what are all major components available under .Net framework to Access the Data source?

    These are main Data Access Components in .Net Framework now some of available as open source.

    1. ADO .Net
    2. Entity Framework
    3. LINQ to SQL

    Note-LINQ technology is similar to Entity Framework so we are not covering its code implementation.

  6. Transaction Implementation using ADO .Net

    ADO .Net allow us to control the Local Transaction using given Data Access methodology like SQL Client, OLEDB, ODBC and Oracle Client.

    • Local Transaction
    1. //LOCAL TRANSACTION  
    2.        //USING TRANSACTION OBJECT OF SAME DATA PROVIDER  
    3.        internal void FirstMethod()  
    4.        {  
    5.            string connectionString = ConfigurationManager.ConnectionStrings["DatabaseOne"].ToString();  
    6.            SqlTransaction transaction = null;  
    7.   
    8.            using (var conn = new SqlConnection(connectionString))  
    9.            {  
    10.                conn.Open();  
    11.   
    12.                try  
    13.                {  
    14.                    transaction = conn.BeginTransaction();  
    15.   
    16.                    var cmd = new SqlCommand("Insert Into Savings (AccountID,Amount) Values (@AccountID,@Amount)", conn, transaction);  
    17.                    cmd.Parameters.Add(new SqlParameter() { ParameterName = "@AccountID", DbType = System.Data.DbType.Int32, Value = 11100001 });  
    18.                    cmd.Parameters.Add(new SqlParameter() { ParameterName = "@Amount", DbType = System.Data.DbType.Int32, Value = 10000 });  
    19.   
    20.                    cmd.ExecuteNonQuery();  
    21.                    transaction.Commit();  
    22.                }  
    23.                catch (Exception)  
    24.                {  
    25.                    if (transaction != null) { transaction.Rollback(); }  
    26.                }  
    27.            }  
    28.        }  
    Local Transaction can also be implemented using Transaction Scope Class:
    1. //LOCAL TRANSACTION  
    2.         //USING TRANSACTION SCOPE OBJECT  
    3.         internal void SecondMethod()  
    4.         {  
    5.             string connectionString = ConfigurationManager.ConnectionStrings["DatabaseOne"].ToString();  
    6.   
    7.             using (TransactionScope scope = new TransactionScope())  
    8.             {  
    9.                 using (var conn = new SqlConnection(connectionString))  
    10.                 {  
    11.                     var cmd = new SqlCommand("Insert Into Savings (AccountID,Amount) Values (@AccountID,@Amount)", conn);  
    12.                     cmd.Parameters.Add(new SqlParameter() { ParameterName = "@AccountID", DbType = System.Data.DbType.Int32, Value = 11100001 });  
    13.                     cmd.Parameters.Add(new SqlParameter() { ParameterName = "@Amount", DbType = System.Data.DbType.Int32, Value = 10000 });  
    14.   
    15.                     cmd.ExecuteNonQuery();  
    16.                 }  
    17.                 scope.Complete();  
    18.             }  
    19.         } 
    • Distributed Transaction

    .Net framework gives Transaction Scope class to deal with the multiple Transaction applied on multiple database.
    1. //DISTRIBUTED TRANSACTION  
    2.        //USING TRANSACTION SCOPE OBJECT  
    3.        internal void FirstMethod()  
    4.        {  
    5.            string connectionString = ConfigurationManager.ConnectionStrings["DatabaseOne"].ToString();  
    6.            string connectionString1 = ConfigurationManager.ConnectionStrings["DatabaseTwo"].ToString();  
    7.   
    8.            using (TransactionScope scope = new TransactionScope())  
    9.            {  
    10.                using (var conn = new SqlConnection(connectionString))  
    11.                {  
    12.                    conn.Open();  
    13.                    var cmd = new SqlCommand("Insert Into Savings (AccountID,Amount) Values (@AccountID,@Amount)", conn);  
    14.                    cmd.Parameters.Add(new SqlParameter() { ParameterName = "@AccountID", DbType = System.Data.DbType.Int32, Value = 11100001 });  
    15.                    cmd.Parameters.Add(new SqlParameter() { ParameterName = "@Amount", DbType = System.Data.DbType.Int32, Value = -10000 });  
    16.                    cmd.ExecuteNonQuery();  
    17.                    using (var conn1 = new SqlConnection(connectionString1))  
    18.                    {  
    19.                        conn1.Open();  
    20.                        var cmd1 = new SqlCommand("Insert Into Savings (AccountID,Amount) Values (@AccountID,@Amount)", conn1);  
    21.                        cmd1.Parameters.Add(new SqlParameter() { ParameterName = "@AccountID", DbType = System.Data.DbType.Int32, Value = 44400001 });  
    22.                        cmd1.Parameters.Add(new SqlParameter() { ParameterName = "@Amount", DbType = System.Data.DbType.Int32, Value = 10000 });  
    23.                        cmd1.ExecuteNonQuery();  
    24.                    }  
    25.                }  
    26.                scope.Complete();  
    27.            }  
    28.        }  
    29.    }  
  7. Transaction Implementation using Entity Framework

    As we know Entity Framework (EF) is an object-relational mapper that enables .NET developers to work with relational data using domain-specific objects means don’t need to work on SQL queries instead developer has to focus on classes and properties which maps the physical structure of database.

    • Local Transaction
    1. //LOCAL TRANSACTION  
    2.        //USING TRANSACTION OBJECT OF SAME DATA PROVIDER  
    3.        internal void FirstMethod()  
    4.        {  
    5.            DatabaseOne db = new DatabaseOne();  
    6.            System.Data.Entity.DbContextTransaction transaction = null;  
    7.   
    8.            try  
    9.            {  
    10.                transaction = db.Database.BeginTransaction();  
    11.   
    12.                db.Savings.Add(new EntityOne.Saving() { AccountID = 11100001, Amount = 1000 });  
    13.                db.SaveChanges();  
    14.                transaction.Commit();  
    15.            }  
    16.            catch (Exception)  
    17.            {  
    18.                transaction.Rollback();  
    19.            }  
    20.        }  
    Local Transaction can also be implemented using Transaction Scope Class:
    1. //LOCAL TRANSACTION  
    2.        //USING TRANSACTION SCOPE OBJECT  
    3.        internal void SecondMethod()  
    4.        {  
    5.            using (TransactionScope scope = new TransactionScope())  
    6.            {  
    7.                DatabaseOne db = new DatabaseOne();  
    8.   
    9.                db.Savings.Add(new EntityOne.Saving() { AccountID = 11100001, Amount = 1000 });  
    10.                db.SaveChanges();  
    11.   
    12.                scope.Complete();  
    13.            }  
    14.  }  
    • Distributed Transaction
    1. //DISTRIBUTED TRANSACTION  
    2.       //USING TRANSACTION SCOPE OBJECT  
    3.       void FirstMethod()  
    4.       {  
    5.           using (TransactionScope scope = new TransactionScope())  
    6.           {  
    7.               DatabaseOne dbOne = new DatabaseOne();  
    8.   
    9.               dbOne.Savings.Add(new EntityOne.Saving() { AccountID = 11100001, Amount = -1000 });  
    10.               dbOne.SaveChanges();  
    11.   
    12.               DatabaseTwo dbTwo = new DatabaseTwo();  
    13.   
    14.               dbTwo.Savings.Add(new EntityTwo.Saving() { AccountID = 44400001, Amount = 1000 });  
    15.               dbTwo.SaveChanges();  
    16.   
    17.               scope.Complete();  
    18.           }  
    19. }  
    Hope the given explanation and code block might clear any developer doubts. Enjoy coding with C# or VB.
Read more articles on Transaction:


Similar Articles