Hi guys, Today i am going to show you how to use transactions in asp.net. Transaction becomes a major part when we have to check whether all process are correctly executed.
Firstly please add following namespaces.In order to use transaction namespace , add system.transaction reference like below.
using System.Transactions;// to fetch transaction class
using System.Data.SqlClient;//for sql queries
using System.Configuration;//for sql configuration
Now you can use following code on your event. Here we have used two sql tables thats are TestEntry and TestData.
protected void btnSave_Click(object sender, EventArgs e)
{
using (TransactionScope ts = new TransactionScope())
{
//Blog where you can maintain code to be used in transaction
conAsp.Open();
SqlCommand cmdInsertTestEntry = new SqlCommand(" insert into TestEntry(FirstName,LastName) values(@fName,@lName)", conAsp);
cmdInsertTestEntry.Parameters.AddWithValue("@fName", "Sandeep");
cmdInsertTestEntry.Parameters.AddWithValue("@lName", "Pal");
int flagTestEntry = cmdInsertTestEntry.ExecuteNonQuery();//If this query produces 1 value that means query is executed correctly
SqlCommand cmdInsertTestData = new SqlCommand(" insert into TestData(City,Zip) values(@City,@Zip)", conAsp);
cmdInsertTestData.Parameters.AddWithValue("@City", "Noida");
cmdInsertTestData.Parameters.AddWithValue("@Zip", "201301");
int flagTestData = cmdInsertTestData.ExecuteNonQuery();//If this query produces 1 value that means query is executed correctly
conAsp.Close();
if (flagTestData==1 && flagTestEntry==1) // A flag that shows that both queryies will be executed correctly so now execute transaction.
{
ts.Complete();// Here transaction is complete and sql query will be excuted
//So now always both table TestEntry and TestData will be executed
}
else
{
ts.Dispose();
//Sql query will not be executed.
// No table will be executed.
}
}
}
So by this technique you can manage transactions in your code.
For furher queries feel free to ask in comments.

0 comments:
Post a Comment