Click here to Skip to main content
Click here to Skip to main content
Articles » Database » Database » ADO.NET » Downloads
 
Add your own
alternative version

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

, 4 Jan 2013 CPOL
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.
TransactionScopeDemo.zip
TransactionScopeDemo
App_Code
App_Data
SampleDb.mdf
SampleDb_log.LDF
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;

public partial class _DefaultSql : 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)
    {        
        SqlConnection con = null;

        // they will be used to decide whether to commit or rollback the transaction
        bool result = false;
       
        string updateCommand = @"BEGIN TRY
                                    BEGIN TRANSACTION
                                        update Account set Amount = Amount - {0} where ID = {1}
                                        update Account set Amount = Amount + {2} where ID = {3}
                                    COMMIT TRANSACTION
                                END TRY
                                BEGIN CATCH
                                    ROLLBACK TRANSACTION
                                END CATCH";

        try
        {
            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(updateCommand,                    
                    amount, debitAccountID,
                    amount, creditAccountID);

                // check if 2 records are effected or not
                result = cmd.ExecuteNonQuery() == 2;
            }
        }
        catch
        {
            
        }
        finally
        {
            con.Close();
        }

        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)

Share

About the Author

Rahul Rajat Singh
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[^]
Follow on   Twitter   Google+   LinkedIn

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141223.1 | Last Updated 5 Jan 2013
Article Copyright 2013 by Rahul Rajat Singh
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid