Web Service Transactions

ADO.NET fully supports transactions, but Web Services offer an easy way to roll an entire Web Service method into a single transaction. It's as simple as adding additional information to the [WebMethod] attribute. The following code shows how to specify that a Web Service method will be a part of a single transaction:

C#
 [ WebMethod(TransactionOption=TransactionOption.RequiresNew)] 
VB
 < WebMethod(TransactionOption:=TransactionOption.RequiresNew)> 

Once you have specified that a Web Service method will participate as a single transaction, you can expect that any exception that is thrown will abort the transaction and roll back all operations that preceded the exception.

I've created an example Web Service that uses the default HelloWorld() method to demonstrate using transactions. It deletes a table that exists in a database, and then it tries to delete another table that doesn't exist in the database. Because the second delete fails, the first delete is not committed, and the table is never deleted. The code for the HelloWorld() method can be seen in Listing 14.12.

Listing 14.12 This Web Service Method Is Contained in a Single Transaction.
 [ WebMethod(TransactionOption=TransactionOption.RequiresNew)] public string HelloWorld() {     SqlConnection myConnection =         new SqlConnection( "server=localhost;uid=sa;pwd=;database=pubs" );     SqlCommand myCommand = new SqlCommand( "delete Table1", myConnection );     myConnection.Open();     myCommand.ExecuteNonQuery();     myCommand = new SqlCommand( "delete Table55", myConnection );     myCommand.ExecuteNonQuery();     return "Hello World"; } 


ASP. NET Solutions - 24 Case Studies. Best Practices for Developers
ASP. NET Solutions - 24 Case Studies. Best Practices for Developers
ISBN: 321159659
EAN: N/A
Year: 2003
Pages: 175

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net