Transaction Scope (C#)
C#, Programming April 3rd, 2009Hi,
Wouldn’t it be fun ot have you code covered?
To be able to clean your database transactions if something goes wrong, well you can do this with a transaction scope.
The TransactionScope class provides a simple way to mark a block of code as participating in a transaction, without requiring you to interact with the transaction itself. A transaction scope can select and manage the ambient transaction automatically. Due to its ease of use and efficiency, it is recommended that you use the TransactionScope class when developing a transaction application.
In addition, you do not need to enlist resources explicitly with the transaction. Any System.Transactions resource manager (such as SQL Server 2005) can detect the existence of an ambient transaction created by the scope and automatically enlist.
Here’s a very simple example on how to use a transactionscope.
public void RenderUsers()
{
ManagementService managementService = new ManagementService();
UserDTO user1 = new UserDTO();
UserDTO user2 = new UserDTO();
UserDTO user3 = new UserDTO();
try
{
using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.RequiresNew))
{
user1.email = "user1@edu3.be";
user1.userName = user1.email;
user1.firstName = "u1";
user1.lastName = "u1";
user1.languageId = 1;
user1.password = "pw";
user1.id = -1;
user2.email = "user2@edu3.be";
user2.userName = user2.email;
user2.firstName = "u2";
user2.lastName = "u2";
user2.languageId = 1;
user2.password = "pw";
user2.id = -1;
user3.email = "user3@edu3.be";
user3.userName = user3.email;
user3.firstName = "u3";
user3.languageId = 1;
user3.lastName = "u3";
user3.password = "pw";
user3.id = -1;
managementService.SaveUser(user1);
managementService.SaveUser(user2);
managementService.SaveUser(user3);
throw new Exception("error");
transactionScope.Complete();
}
}
catch
{ }
Console.WriteLine(user1.email);
Console.WriteLine(user2.email);
Console.WriteLine(user3.email);
Console.Read();
}
As you can see, the error is thrown before the transaction can be completed. Therefore the method “RenderUsers” failed and we would prefer to “RollBack” all of our transaction.
If the object “transactionScope” is destroyed before the function “completed” is called (like in the example) the transaction scope will rollback all the database calls.
HOWEVER!: the objects are not rolled back, so the objects still keep their new properties (if you run the example you’ll notice that).
Well this was a very easy introduction on the use of transaction scope a more detailed explanation can be found here.
Cheers,
Sem
Recent Comments