Related Service

.Net Development

Know more about our .Net Development Services

Learn More

TransactionScope in C#

Published: Oct 9, 2020

Table of Content

  1. Introduction
  2. System.Transactions Namespace
  3. TransactionScope
  4. Create TransactionScope
  5. Complete and end a TransactionScope in C# development
  6. TransactionScope Default Properties in C# Development
  7. Use of TransactionScope
  8. Conclusion

Introduction

Transaction management is extremely significant for any business to seamlessly operate their business application. It changes from version to version like in version 2 of .NET framework it provides management of its own transaction components using TransactionScope class. TransactionScope is a class of systems. It can also be termed as Transactions Namespace. The TransactionScope class supports transactions from code blocks and that is why it plays a key role in the .NET development framework. TransactionScope is very simple, robust and easy to implement and that is why it is very popular among .NET developers. In this blog, we will cover all the aspects of encircling the Transactionscope for .net developers.

System.Transactions Namespace

System.Transactions allow you to create, enlist, and control your own Transactional applications using classes that are provided in this namespace class.system. The transaction was introduced in .Net version 2.0 and it is one of the vital design goals used to create and allow users to participate in transactions whether local or distributed within one or multiple participants.

TransactionScope

You might be wondering what is TransactionScope, so goes exactly like the name- Scope of the transaction. TransactionScope is a class that makes code block transactions after a certain time. One cannot inherit the transactions in this class, System and Transaction. TransactionScope provides an absolute programming model in which the infrastructure itself manages the transactions automatically. TransactionScope reduces the complexity of code and thus it is widely accepted and used in custom software development. The TransactionScope makes the block of code as a part of a transaction without requesting c# developers to connect within the transaction itself. A TransactionScope is allowed to select and manage transaction environments automatically. Due to its ease of access and efficiency, TransactionScope class is highly recommended in transactional applications.

Create TransactionScope

The TransactionScope is created by an object of the TransactionScope class. To create an object of the TransactionScope class, ‘using’ statement is used. We can check that scope is disposed properly or not by checking the ‘using’ statement which is available in both C# and visual basic and it works like a “try…finally” block.

Complete and end a TransactionScope in C# development

To complete the TransactionScope, Complete method is used. In a transaction when all the tasks are completed by the application, users can Commit the transaction using a special command. This command can be called only once during the entire session by implementing the “Complete method ” to keep the transaction manager informed about the successful transaction.

If this method is not called in the entire application, the transaction manager interprets it as an exception thrown or system failure within the TransactionScope and it aborts the transaction. Whether the Dispose method of TransactionScope is called or not it is ensured by “using” statement even if the exception occurs. After the Dispose method is called off, if an exception occurs, that may not affect the transaction. The dispose method also tries to restore the environmental changes by transaction and transforms it into its previous state.

namespace TestTransactionApp
{
     Public partial class TestWebForm1 : System.Web.UI.Page
         {
    public void TransactionMethod(object sender, system.EventArgs e)
      {
            using (TransationScope transScope = new TransactionScope())
                  {
              Syste.IO.StringWriter writer = new System.IO.StringWriter();
              try
              {
                  using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings[“Dbconnection”].ToString()))
            con.Open();
 
            using (SqlConnection cmd = con.CreateCommand())
            {
 
                  //Inserting Record
                 cmd.commandText = string.Format(
                   “INSERT INTO Employee VALUE (004, ‘Harshad Patel” , ‘Software Engineer’));
                cmd.ExecuteNonQuery();
 
                //Updating Record
                cmd.CommandText = string.Format(
                      “UPDATE dbo.Employee SET EmpID-003 WHERE Name= ‘Nikita Bagadiya’”);
                cmd.ExecuteNonQuery();
 
               //Deleting Record
               cms.CommandText = string.Format(
                “DELETE FROM dbo.Employee WHERE Name= ‘Sagar Rawal’”);
               cmd.ExecuteNonQuery();
            }
        }
 
        // The Complete method commits the transaction.
//  If an exception has been thrown, Complete is not called and the transaction is rolled back.
transScope.Complete();
}
 
//If any sqlexception occurs it will throw into this catch block
catch (SqlException ex)
 
{
Writer.WriteLine(“Eeception Occured in transaction”, ex.message);
transScope.Dispose();
}
      }
}
        }
}

TransactionScope Default Properties in C# Development

TransactionScope has three very important default Properties, let’s discuss each one in brief.

  • Isolation Level
  • Timeout
  • TransactionScope Option

Isolation Level

The Isolation Level of a transaction that specifies the level of access other transactions have to volatile data before the transaction is completed. You can indicate the isolation level that applies to the transaction while creating the transaction. Normally, when you execute a transaction, its isolation level is set to a flexible level to serialize. Other isolation levels are commonly utilized for read-intensive systems. The way of using read and write locks is different at different isolation levels.

Default Value: Serializable

Available options: Serializable, Read Committed, Read Uncommitted, Repeatable Read

Timeout

Timeout property used to control the timeout of the transaction. C# developers can set infinite timeout by setting timeout zero. In case when you are debugging, the infinite timeout is extremely useful.

Default Value: 1 minute

Available options: Maximum 10 Minutes

TransactionScope Option

TransactionScopeOption is an enumeration which provides additional options for creating a TransactionScope. TransactionScope has three TransactionScopeOption.

Required: If scope is instantiated with the ‘Required’ option and if an ambient transaction is present then the scope joins the transaction and if there is no ambient transaction present then the new transaction will be created by scope and become the root scope.

RequiresNew: The scope will always become a root scope if it is instantiated with ‘RequiresNew‘. The transaction will act differently and turn to become a new ambient transaction when it is in a new environment.

Suppress: The scope never takes part in a transaction, if it is instantiated with ‘Suppress’. Ambient transactions for TransactionScope with this value always have null.

Default Value: Required

Available options: Required, RequiresNew, Suppress

Use of TransactionScope

Now when you create or use transactions using ADO.NET, you just have to commit or rollback on the transaction object. In case you have forgotten to commit or rollback the transaction, it may cause problems and there can be a loss of data or inconsistent data problems. Such problems can be solved by using TransactionScope.

While using the TransactionScope in the transaction, there are no manual options for commit and rollback the transaction for c# developers. If an exception occurs, operations will be rolled back automatically and it will catch the exception in the catch block.

The transaction will commit after once you call the Complete method of the TransactionScope object. So in case of power failure, system crash or hardware failure TransactionScope considers an exception occurs in the transaction and all the transactions within the TransactionScope block will be automatically rolled back.

TransactionScope can be used to maintain multiple databases as well as a single database with multiple connection strings.

There is no need to close any database connection in the middle when working with TransactionScope.

Due to these all advantages and ease of access, the TransactionScope is popular while creating transactional applications.

Conclusion

Our intent to create this blog was to shed light on the creation and use of Transaction and  TransactionScope. It provides the best way to handle transactions from the code side. It is easy to use and simpler than other transaction handling methods. Using TransactionScope, you can handle the transaction with less code as you don’t need to write multiple statements which lead to increased code readability and efficiency.

Comments

  • Leave a message...

Related Articles

Getting Started with Firebase – Cloud Firestore

Oct 23, 2020

An Introduction to key aspects of Internet of Things (IoT)

Oct 21, 2020

Financial Information Exchange Protocol

Oct 6, 2020