Transcations in Web Services - Part 1

Introduction

I believe most of the database developers are familiar with transactions. Transactions are one of the common activities a database developer has to deal with. Transactions are also used in Web Services. Transactions are used to maintain data integrity and avoid redundency of data.

This article discusses what transactions are and how trasactions can be used in Web services by Web developers. First, we'll see some basic definitions of transactions and then we'll see how .Net Framework utilizes transactions.

What is a Transaction?

Before we start using transactions in our application, we should have a clear idea what a transaction is? There are a lot of definitions about transaction, which are very easy to understand.

"A transaction is a series of operation performed as a single unit of work".
A transaction is a single operation. If any error occurs during this operation, every thing rolls back means back to the previous state.

Ok, now we are going to take a look at an example. It's a very classical example, which I have found in many books. Suppose I have a bank account and I want to transfer money from my account to my friend's account. Suppose I have deducted some money from my account (before adding it to my friends account) and an error occurred during transaction, what will happen? Neither money will come back to my account nor gets to my friend's account. By using transactions, if any errors occur, transaction rolls back means the operation will be in previous state and money will still be in my account. If operation (transaction) is sccuessful and there is no error occurs during the operation, transaction will commit means every thing went fine and changes were made to boty my friend's and my account.

A transaction has ACID properties. These properties are defined as following:

ATOMICITY: Guarantees that a transaction is never incomplete.
CONSISTENSY: Data used in a transaction is never inconsistent.
ISOLATION: Guarantees that concurrent transactions are independent.
DURABILITY: The effects of a transaction are persistent.

Transaction always maintains these properties.

Transaction Types

What types of transactions we can have in Web services? We have four types of transactions.

Local And Distributed Transaction
These transactions are used in SQL SERVER and **MSMQ message queue. In case of MSMQ, we have two types of transactions - innternal transactions and external transactions.

Database Transactions
Invoking a stored procedure that wraps required operations within the BEGIN TRANSACTION and COMMIT/ROLLBACK TRANSACTION statements yields the best performance by allowing you to run the transaction in a single round-trip to the database server. Database transactions also support nested transactions, which means you can start a new transaction from within an active transaction.

Manual Transactions
A manual transaction allows you to explicitly control the transaction boundary with explicit instructions to begin and end the transaction. This model also supports nested transactions that allow you to start a new transaction from within an active transaction.

Automatic Transactions
The .NET Framework relies on ***MTS/COM+ services to support automatic transactions.

***MTS - MicroSoft Transaction Server, which are integrated with operating system Windows XP Professional, Windows 2000 professional, Windows 2000 Server (family /advanced) also with Windows NT4.

** MSMQ - Microsoft Message Queuing, which you have to install. Just open AD/Remove, select Add remove Component for windows and then select Message queuing (here I have to say in Windows 2000 professional you can only use private Message queue if you are working under a workgroup. have to use private and public Message Queue you must use Windows 2000 Active directory. also if you are a Windows 2000 professional user then when you are going to install MSMQ please go to details and deselect "Active Directory Integration ").

A Web service uses all kinds of transactions, which we just saw in the previous paragraph. Generally transactions occur when a Web service (webmethod /any method) deals with databases. But in Web services, when a Web method invoke another or when one Web service connected (means invoke another Web method from another Web service) to another Web service. If you don't know how how you can invoke Web method from one Web service to another Web service please read my previous article "invoking Web methods from another Web service" found in the Web Services section of www.c-sharpcorner.com.

Step by step we will write programs for every kind of transactions. First of all, we will take a look at mutual transactions.

MANUAL TRANSACTIONS

Requirement: Microsoft Visual Studio 7,Sql Server.

ADO.NET data provider enables manual transactions by providing a set of object that creates a connection to the data source. To try this, let's make a new project with template as "ASP.NET Web Service". After creating the project, build and run the project for confirmation that Web service is working. Now we are ready to write some code for manual transactions.

In this code, we will use SQL server for connecting with the data source. If you have installed SQL server, make sure that it's running (you can see a small icon in system try). For your information SQL server is integrated with VISUAL STUDIO 7.0 (final release). Just open catalog " program files\ Microsft.net\frameworkSDK\samples\setup " and click instMSDE (install Microsft Data base Engine). After installation is done, reboot your computer you can see a new icon on your system tray. Click it and run the Service. We are now ready to use SQL server.

Now create a database and test it with NT authentication. Create one table named "useraccount".
The commands are as follows:

Sql>create database shamim
Sql>create table useraccount (char username, char password)

This table has two fields - username and password.

Now let's move to the Web service. In my service, I'll use Sql data provider to access SQL Server. Before I use any Sql data provider classes, I must add reference to the System.SqlClient namespace and import the namepace by adding a using directive:

using System.SqlClient;

Now add a Web method. The Web method "adduser" looks like the following code:

[Web Method]
public string adduser( string UserName, string UserPassword)
{
string uname,upassword;
uname=UserNmae;
upassword=userPassword;
string mycon="Intial Catalog=test;Data Source= yourcomputername\SDK; Integrated security =SSPI";
//declare a sql connection by building a object named myconnection
SqlConnection mysqlConnection =new SqlConnection(mycon);
// declare sql command by using a object named mycommand
SqlCommand mysqlCommand = new SqlCommand();
// using sql transaction class
SqlTransaction myTrans;
// Open the connection.
mysqlConnection.Open();
// Assign the connection property.
mysqlCommand.Connection = mysqlConnection;
// Begin the transaction.
myTrans = myConnection.BeginTransaction();
// Assign transaction object for a pending local transation
mysqlCommand.Transaction = myTrans;
try
{
// Insert the user record.
mysqlCommand.CommandText = "Insert into useraccount VALUES ('"+uname+"','"+ufamily+"')";
mysqlCommand.ExecuteNonQuery();
// pass the data .transaction complete
myTrans.Commit();
return "transaction completed";
}
catch(Exception e)
{
// transaction cancel
myTrans.Rollback();
return e.ToString()+"********** transaction abort*******";
}
}

Now debug the program and provide a username and a password. If this program can write down the new data to the database, it will say transaction completed. If any error occurs, transaction will be rolled back.

It's just a very simple example by using SqlTransaction class and the class members Commit and Rollback.

Commit -Commits the database transaction.
Rollback- Rolls back the transaction from pending state.

For more information see .net Framework SDK. It was the first part. Oh I am getting tired. I'll be coming soon with the second part.


Similar Articles