Wcf Transaction

A transaction is a collection of operations with the following properties:

  • Atomicity. This ensures that either all of the updates completed under a specific transaction are committed and made durable or they are all aborted and rolled back to their previous state.
  • Consistency. This guarantees that the changes made under a transaction represent a transformation from one consistent state to another. For example, a transaction that transfers money from a checking account to a savings account does not change the amount of money in the overall bank account.
  • Isolation. This prevents a transaction from observing uncommitted changes belonging to other concurrent transactions. Isolation provides an abstraction of concurrency while ensuring one transaction cannot have an unexpected impact on the execution of another transaction.
  • Durability. This means that once committed, updates to managed resources (such as a database record) will be persistent in the face of failures.

For Example :

In IService :

[ServiceContract]
public interface IService1
{
[OperationContract]
        [TransactionFlow((TransactionFlowOption.Allowed))]
void Insert();
}

In Service Class :

public class Service1 : IService1
{
   [OperationBehavior(TransactionScopeRequired=true)]
public void Insert()
{
SqlConnection con = new SqlConnection(@”Data Source=MyServer;Initial Catalog=mydata;Integrated Security=true;”);
con.Open();
SqlCommand cmd = new SqlCommand(“insert into EmpData values(1,’pune’)”,con);
cmd.ExecuteNonQuery();
con.Close();

}
}

In Config file :

<bindings>
<wsHttpBinding>
<binding name=”TransactionalBind” transactionFlow=”true”/>
</wsHttpBinding>
</bindings>

<endpoint address =”” binding=”wsHttpBinding” contract=”WcfServiceTransaction.IService1″ bindingConfiguration=”TransactionalBind”>

In Client Program :

static void Main(string[] args)
{
using (TransactionScope ts = new TransactionScope(TransactionScopeOption.RequiresNew) )
{
try
{
ServiceReference1.Service1Client clientobj = new Service1Client();
clientobj.Insert();
//code for exception
   throw new Exception(“ERROR !! ROLLBACK…..”);
//If exception occurs the first insertion is rolled back .

ServiceReference1.Service1Client clientobj2 = new Service1Client();
clientobj2.Insert();

                    ts.Complete();
Console.ReadLine();
}
catch (Exception)
{
                        ts.Dispose();
throw;
}

}
}

refer link: http://www.codeproject.com/KB/WCF/WCFTransactions.aspx

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s