Transaction in WCF

WCF Transactions

 
I am sure that transactions are not a new thing for you. For WCF Transactions specifically, let's think of a scenario of two tables in a database, Login and LoginTrans.
 
And in our service there are two functions, INSERT that takes one string parameter and inserts it into the LOGIN table and the UPDATE function that updates the LoginTrans table. The client will send his / her user id to the insert method and it will insert the user id into the login table and update the LoginTrans table. The problem however is the update code is written in a different function so the client will first call the insert method then the update method so the question becomes, how to maintain the atomicity, in other words either both function should execute and make changes to the database or neither. Let's see now how to use a WCF Transaction to deal with this. In the Service Contract use a TransactionFlow attribute on the functions that you want to run under the transaction, like this:
  1. [ServiceContract]  
  2. public interface IAhmarService  
  3. {  
  4.     [FaultContract(typeof(string))]  
  5.     [OperationContract]  
  6.     [TransactionFlow(TransactionFlowOption.Allowed)]  
  7.     void Insert(string UserId);  
  8.     [FaultContract(typeof(string))]  
  9.     [OperationContract]  
  10.     [TransactionFlow(TransactionFlowOption.Allowed)]  
  11.     string Update();  
  12. }  
The Transaction flow attribute has a parameter, TransactionFlowOption that has the following three values:
  1. Allowed: Implies if client has transaction, it will be accepted otherwise not a problem.
  2. NotAllowed: Client cannot send transaction to server while calling a method.
  3. Mandatory: Client has to create a transaction otherwise the method cannot be called.
In the service class decorate the functions with[OperationBehavior(TransactionScopeRequired = true)]
 
It will look like:
  1. public class AhmarService : IAhmarService  
  2. {  
  3.     [OperationBehavior(TransactionScopeRequired = true)]  
  4.     public void Insert(string uid)  
  5.     {  
  6.         try  
  7.         {  
  8.             string constring = @"Data Source=AHMAR-PC\SQLEXPRESS;Initial Catalog=DEVDB;Integrated Security=True;User ID=Ahmar-PC\Ahmar";  
  9.             SqlConnection con = new SqlConnection(constring);  
  10.             con.Open();  
  11.             SqlCommand cmd = new SqlCommand("insert into Login values(@uid)", con);  
  12.             cmd.Parameters.AddWithValue("@uid", uid);  
  13.             cmd.ExecuteNonQuery();  
  14.         }  
  15.         catch (Exception ex)  
  16.         {  
  17.             throw new FaultException("error");  
  18.         }  
  19.     }  
  20.     [OperationBehavior(TransactionScopeRequired = true)]  
  21.     public string Update()  
  22.     {  
  23.         try  
  24.         {  
  25.             string constring = @"Data Source=AHMAR-PC\SQLEXPRESS;Initial Catalog=DEVDB;Integrated Security=True;User ID=Ahmar-PC\Ahmar";  
  26.             SqlConnection con = new SqlConnection(constring);  
  27.             //throw new Exception("asa");  
  28.             con.Open();  
  29.             SqlCommand cmd = new SqlCommand("Update  LoginTrans set Islogin='1'", con);  
  30.             cmd.ExecuteNonQuery();  
  31.             return "1";  
  32.         }  
  33.         catch (Exception ex)  
  34.         {  
  35.             throw new FaultException("error");  
  36.         }  
  37.     }  
  38. }  
The code is as simple as I described earlier. The Insert method will insert a userid into the login table and the update method will update the logintrans table. Now the most important thing is to allow the transaction flow in the web config of the service. 
  1. <bindings>  
  2.     <wsHttpBinding>  
  3.        <binding name="httpBin" ="" transactionFlow="true"/>           
  4.   </wsHttpBinding>  
  5. </bindings>  
The entire web config will look like this:
  1. <?xml version="1.0"?>  
  2. <configuration>   
  3.     <system.web>  
  4.         <compilation debug="true" targetFramework="4.0" />    
  5.   </system.web>  
  6.     <system.serviceModel>  
  7.         <bindings>  
  8.             <wsHttpBinding>  
  9.             <binding name="httpBin" ="" transactionFlow="true"/>               
  10.       </wsHttpBinding >  
  11.     </bindings>  
  12.         <services>  
  13.             <service name="WcfService2.AhmarService">  
  14.             <endpoint address="" behaviorConfiguration="webby" binding="wsHttpBinding" bindingConfiguration="httpBin"  
  15.             contract="WcfService2.IAhmarService" />  
  16.             <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />               
  17.       </service>  
  18.     </services>   
  19.         <behaviors>  
  20.             <endpointBehaviors>  
  21.             <behavior name="webby" >  
  22.             <!--<webHttp helpEnabled="true"/>-->  
  23.         </behavior>  
  24.       </endpointBehaviors>  
  25.             <serviceBehaviors>  
  26.                 <behavior>  
  27.                     <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->  
  28.                     <serviceMetadata httpGetEnabled="true"/>  
  29.                     <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->  
  30.                     <serviceDebug includeExceptionDetailInFaults="false"/>  
  31.         </behavior>  
  32.       </serviceBehaviors>  
  33.     </behaviors>  
  34.         <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />  
  35.   </system.serviceModel>  
  36.     <system.webServer>  
  37.         <modules runAllManagedModulesForAllRequests="true"/>  
  38.   </system.webServer>   
  39. </configuration>  
Our service is ready; let's move to the client application. Open a console application; the target framework should be .NET Framework 4.0 and add a Service Reference to it.
 
That will generate an app.config and Proxy class. If you want to generate it using SVCUTIL.EXE then you can do that.
 
Add a namespace as "using System.Transactions",the code will look like this:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Transactions;  
  6. using System.ServiceModel;  
  7. namespace ConsoleApplication1  
  8. {  
  9.     class Program  
  10.     {  
  11.         static void Main(string[] args)  
  12.         {  
  13.             using (TransactionScope ts = new TransactionScope())  
  14.             {  
  15.                 try  
  16.                 {  
  17.                     ServiceReference1.AhmarServiceClient sc = new ServiceReference1.AhmarServiceClient();  
  18.                     sc.Insert("ahmar");  
  19.                     sc.Update();  
  20.                     ts.Complete();  
  21.                 }  
  22.                 catch (FaultException ex)  
  23.                 {  
  24.                     ts.Dispose();  
  25.                     Console.WriteLine("Data RollBacked error in service");  
  26.                 }  
  27.                 catch (Exception ex)  
  28.                 {  
  29.                 }  
  30.             }  
  31.         }  
  32.     }  
  33. }  
It is important to call the methods in the Transaction Scope because if any error occurs from the service then control will execute the catch block of the fault exception where ts.dispose will roll back the data.


Similar Articles