Saturday, 22 March 2014

Atomic Transactions in .NET

Transactions are the base part of ACID theory. When you are including transaction be sure that it won't create any problem when multiple process call that code. Description  : It is based on ACID theory, Atomicity, Consistency, Isolation and Durability. What is an Atomic transaction?  The best way to understand is a bank accounting system. Consider that two  bank X and bank Y want to Withdrew amount with someone's account at the same time.  Suppose the account has $100.00 in it.  If bank X withdrow $70.00 and at the same time bank B tries to get $50.00, Than what happen?  When they start the transaction each bank believes there is $100.00 available in the account.  When one of them finishes other one finds there isn't enough money to finish the transaction. Code for Transaction : defining a class where ServiceComponent are inheriting.



using System;
using System.Text;
using System.EnterpriseServices;
using System.Data;
using System.Data.SqlClient; 
 
namespace AtomicTransactions
{
    public class MyTransaction  : ServicedComponent
   {


Main Logic to handle transaction, After adding the value in to database, It checks a constraint which cause and threw the exception,  if value was not between 10 and 100. Please see below for code; 

public void Transfer(int accountID, int intValues,
    string connectionString)
{
    try
    {
        AddValue(accountID, intValues, connectionString);
        if ((intValues< 10) || (intValues> 100))
            throw new 
                ArgumentException("Value is not valid!");
 
        
        ContextUtil.SetComplete();// Atomic transaction ends here

    }
    catch (Exception ex)
    {
        throw new Exception
            ("An error occurred in transaction");
    }
}

Calling add Logic value to save data into database;

private void AddValue(int id, int value, 
    string connectionString)
{
    try
    {
        using (SqlConnection connection =
            new SqlConnection(connectionString))
        {
            SqlCommand command = 
                new SqlCommand("AddToAccount", connection);
            command.CommandType = CommandType.StoredProcedure;
 
 
            command.Parameters.AddWithValue("id", id);
            command.Parameters.AddWithValue("value", value);
 
 
            connection.Open();
            command.ExecuteNonQuery();
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

No comments:

Post a Comment

Others

You will like to read it