Click here to Skip to main content
15,891,136 members
Articles / Web Development / ASP.NET

A Beginner's Tutorial for Understanding Transactions and TransactionScope in ADO.NET

Rate me:
Please Sign up or sign in to vote.
4.80/5 (34 votes)
4 Jan 2013CPOL8 min read 154.8K   2.3K   61  
This article is a beginner's tutorial for understanding what are transactions and how can transactions be implemented using .Net framework and ADO.NET for any ASP.NET web application or any other database driven application.
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Transactions;
using System.IO;

public partial class _DefaultEx : System.Web.UI.Page 
{
    readonly string CONNECTION_STRING = ConfigurationManager.ConnectionStrings["SampleDbConnectionString1"].ConnectionString;
    
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack == false)
        {
            UpdateAmount();
        }        
    }

    protected void btnAccount1_Click(object sender, EventArgs e)
    {
        // Lets just hard code some values for demo purpose
        double amount = 0.0;
        double.TryParse(txtAmount.Text, out amount);

        PerformTransaction("2", "1", amount);
    }

    protected void btnAccount2_Click(object sender, EventArgs e)
    {   
        // Lets just hard code some values for demo purpose
        double amount = 0.0;
        double.TryParse(txtAmount.Text, out amount);

        PerformTransaction("1", "2", amount);
    }

    private void PerformTransaction(string creditAccountID, string debitAccountID, double amount)
    {
        // they will be used to decide whether to commit or rollback the transaction
        bool debitResult = false;
        bool creditResult = false;

        try
        {
            using (TransactionScope ts = new TransactionScope())
            {
                using (SqlConnection con = new SqlConnection(CONNECTION_STRING))
                {
                    con.Open();

                    // Let us do a debit first
                    using (SqlCommand cmd = con.CreateCommand())
                    {
                        cmd.CommandType = CommandType.Text;
                        cmd.CommandText = string.Format(
                            "update Account set Amount = Amount - {0} where ID = {1}",
                            amount, debitAccountID);

                        debitResult = cmd.ExecuteNonQuery() == 1;
                    }

                    // A dummy throw just to check whether the transaction are working or not
                    throw new Exception("Let see..."); // uncomment this line to see the transaction in action

                    // And now do a credit
                    using (SqlCommand cmd = con.CreateCommand())
                    {
                        cmd.CommandType = CommandType.Text;
                        cmd.CommandText = string.Format(
                            "update Account set Amount = Amount + {0} where ID = {1}",
                            amount, creditAccountID);

                        creditResult = cmd.ExecuteNonQuery() == 1;
                    }                                       

                    if (debitResult && creditResult)
                    {
                        // To commit the transaction 
                        ts.Complete();
                    }
                }
            }
        }
        catch
        {
            // the transaction scope will take care of rolling back
        }       

        UpdateAmount();
    }

    private void UpdateAmount()
    {
        // Lets show the updated balance to the user
        DataTable table = null;

        using (SqlConnection con = new SqlConnection(CONNECTION_STRING))
        {
            using (SqlCommand cmd = con.CreateCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "select * from Account";

                try
                {
                    con.Open();
                    using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                    {
                        table = new DataTable();
                        da.Fill(table);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }

        if (table != null)
        {
            GridView1.DataSource = table;
            GridView1.DataBind();
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
India India

I Started my Programming career with C++. Later got a chance to develop Windows Form applications using C#. Currently using C#, ASP.NET & ASP.NET MVC to create Information Systems, e-commerce/e-governance Portals and Data driven websites.

My interests involves Programming, Website development and Learning/Teaching subjects related to Computer Science/Information Systems. IMO, C# is the best programming language and I love working with C# and other Microsoft Technologies.

  • Microsoft Certified Technology Specialist (MCTS): Web Applications Development with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Accessing Data with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Windows Communication Foundation Development with Microsoft .NET Framework 4

If you like my articles, please visit my website for more: www.rahulrajatsingh.com[^]

  • Microsoft MVP 2015

Comments and Discussions