Two Phase Commit Protocol In C#

Two phase commit protocol is a distributed algorithm, which works with the processes that are coordinating with regular transaction management. Transaction is a unit of work, be it a single transaction or discrete transaction.

If you have 3 records and all records must be added before saving, than we call it as a single transaction, whereas if you add 3 records and you save between each, then those are 3 discrete transactions. Mostly, we use processes in our day to day transaction in banking and financial activity.

There are two terms that are very viable in transaction as well as in two phase commit protocol - to Commit or to Rollback.

With Rollback command, you can undo any transaction, and it will rollback all the changes back to the beginning of a transaction. It can be back to the last begin transaction in some cases.

Whereas with Commit command, you are telling the database to save any changes, it can be any addition, modification or deletion on the data that you have made.

In our tutorial, we are going to learn these two important aspect of two phase commit protocol. For that, we are using SQL Transaction in our code. The logic is very simple - we will take two entities that are having account number and some balance. We are having 200 as total balance in the database. Now, if one customer wants to transfer some money from his account to another account, the immediate response in the balance will be shown in runtime.

We will also see the commit and rollback modules in the transaction. If the transaction succeeds, the commit module is called, but if somehow due to server crash or node crash or any other calamity the transaction failed, then the rollback module is called.

You need to first create database as,

Account Numbernvarchar(50)
Customer Namenvarchar(50)



In this page, you have to design your application as below figure.



  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Data;  
  8. using System.Data.SqlClient;  
  9. namespace WebApplication2 {  
  10.     public partial class WebForm1: System.Web.UI.Page {  
  11.         protected void Page_Load(object sender, EventArgs e) {  
  12.             if (!IsPostBack) {  
  13.                 refreshdata();  
  14.             }  
  15.         }  
  16.         private void refreshdata() {  
  17.             SqlConnection con = new SqlConnection(@ "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True");  
  18.             SqlCommand cmd = new SqlCommand("Select * from tbl_data", con);  
  19.             con.Open();  
  20.             SqlDataReader sdr = cmd.ExecuteReader();  
  21.             while (sdr.Read()) {  
  22.                 if (sdr["AccountNumber"].ToString() == "AccountNo1") {  
  23.                     lblac1.Text = "AccountNo1";  
  24.                     lblbal1.Text = sdr["Balance"].ToString();  
  25.                     lblcst1.Text = sdr["CustomerName"].ToString();  
  26.                 } else {  
  27.                     lblac2.Text = "AccountNo2";  
  28.                     lblbal2.Text = sdr["Balance"].ToString();  
  29.                     lblcst2.Text = sdr["CustomerName"].ToString();  
  30.                 }  
  31.             }  
  32.         }  
  33.         protected void Button1_Click(object sender, EventArgs e) {  
  34.             SqlConnection con = new SqlConnection(@ "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True");  
  35.             con.Open();  
  36.             SqlTransaction trans = con.BeginTransaction();  
  37.             try {  
  38.                 SqlCommand cmd = new SqlCommand("Update tbl_data set Balance = Balance - 10 where AccountNumber = 'AccountNo1'", con, trans);  
  39.                 cmd.ExecuteNonQuery();  
  40.                 cmd = new SqlCommand("Update tbl_data1 set Balance = Balance + 10 where AccountNumber = 'AccountNo2'", con, trans);  
  41.                 cmd.ExecuteNonQuery();  
  42.                 trans.Commit();  
  43.                 Label7.Text = "Transaction Successful";  
  44.             } catch (Exception ex) {  
  45.                 trans.Rollback();  
  46.                 Label7.Text = "Transaction Failed";  
  47.             }  
  48.             refreshdata();  
  49.         }  
  50.     }  
  51. }   


When you transfer Rs10 from Account1 to Account 2 , both Accounts get committed to the transaction and therefore the integrity maintains as 10 +190 = Rs 200, and the transaction is successful.



But as you change the parameters in the query, like - node crash, link failure, down network, the transaction fails and the transaction is rolled back. Hence if you don’t use any transaction in the system, there will be loss in the transaction and sometimes you even can’t notice these changes.


Hope you like it. Thank you for reading and have a good day.