A quick TransactionScope Example

Published Thu, Jul 8 2004 0:57 | William

Ok, I promised I'd have some examples by Monday and I'm late.  Anyway, I'm working on a full fledged article where I really test this thing including MessageQueue as well but this gives you the gist of it.  Basically it's just a fleshed out example of what Angel posted but it should give you a feel for how easy this guy is to use.  That's not to say this is a simplistic class - as Angel pointed out there are 15 overloads for the constructor alone.  But it is easy as hell to use in its simplest form.  I'm having some trouble getting another chunk of it to work (non-db related) but that's due to me being dumb in all likelihood.  Anyway, here it is:

const string ConnectString = @"Data Source=.\SQLExpress;Integrated Security=True;AttachDBFilename=C:\Visual EmptyDatabase1.mdf";

private void btnTryTransaction_Click(object sender, EventArgs e)

{

TimeSpan ts = new TimeSpan(0, 0, 5);//Didin't do this yet - should have taken it out.

TransactionScope scopeObject = new TransactionScope();

string sql = "INSERT INTO tb_Customers(Customer_ID, Customer_FirstName, Customer_LastName) VALUES (@CustID, @FirstName , @LastName)";

using (scopeObject)

{

using (SqlConnection cn = new SqlConnection(ConnectString))

{

     SqlCommand cmd = new SqlCommand(sql, cn);

     cmd.Parameters.Add("@CustID", SqlDbType.Int, 4).Value = 8;

     cmd.Parameters.Add("@FirstName", SqlDbType.VarChar, 50).Value = "William";

     cmd.Parameters.Add("@LastName", SqlDbType.VarChar, 50).Value = "Gates";

     cn.Open();

     cmd.ExecuteNonQuery();

     cmd.Parameters.Clear();

     cmd.CommandText = "SELECT COUNT(*) FROM tb_Customers";

     int i = (int)cmd.ExecuteScalar();//7 Records after Successful Insert

     cn.Close();

    }

  scopeObject.Consistent = false;

   }

   scopeObject.Dispose();

   MessageBox.Show(GetTotalCount().ToString());

   //Now this will equal 6 Proving it was rolled back with

   //Absolutely NO effort on my part other than setting consistent

   //to false. Now, a better example (forgive me, I'm just trying

   //an illustration, I'll have a hardcore example very soon

   //you could have a bool Property - in the exception handler

   //set it to false, initialize it to true and set .Consistent

   //to the property you created

}

private int GetTotalCount()

{

     using (SqlConnection cn = new SqlConnection(ConnectString))

     {

         SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM tb_Customers", cn);

          cn.Open();

          int i = (int)cmd.ExecuteScalar();

         cn.Close();

       return i;

     }

}

If I don't set .Consistent to false then I keep all seven records.  As soon as I get the MessageQueue part to work, I'll have everything up - promise.

Filed under:

Comments

# TrackBack said on July 7, 2004 10:00 PM:

# William said on February 18, 2005 1:14 PM:

Are you sure this is right? I thought you had to set Consistent true explicitally to keep anything.

Also, calling scopeObject.Dispose() is a bit redundant :)

# William said on October 20, 2005 8:48 PM:


hi...

Are you test SQL2K or Oracle? (yeah.. Not SQL2005),

When I try to Enlist Transaction to Connectoin object for SQL2k,
Excepton (Does Not support Partner DTC Manager...)
was raised.

SQL2K Server is in another Wi2003 Server.





# casper said on October 24, 2006 4:06 AM:

Ehh why "scopeObject.Dispose();" when u are already "using" it?

Furthermore why declare the scopeObject outside the "using" statement.

using (TransactionScope scope = new TransactionScope())

{

[...]

}

//scope is dispose()d by the using statement at this point.

Small things I know, but they display some insecurity in the usage of c# and therefore people are less likely to take heed of the actual message in your blog.

Well just my 2 cents.

# Jportelas said on December 21, 2006 1:14 PM:

Any hints on configuring the MSDTC when the TransactionScope is implemented in a aspnet 2.0 web application with a remote database server?

Search

This Blog

Tags

Community

Archives

News

My other sites

Cool Stuff

Book Stuff

Security

ORM

Data Access

Funny Stuff

Compact Framework Stuff

Web Casts

My KnowledgeBase Articles

My MVP Profile

Design Patterns

Performance

Debugging

Remoting

My Fellow Authors

My Books

LINQ

Misc

Speech

Syndication

Email Notifications