Getting Started with WCF (10)---WCF Transactions

Source: Internet
Author: User

Transaction processing in WCF (Windows communication Foundation) is a set of operations that follow some nature, collectively known as acid. Here, if one operation fails, the entire system will fail automatically. If an online order is generated, a transaction may be used. The following example can help to understand simpler terminology in the process of transactions.

Example

Suppose an LCD TV is the amount you order from the online store and you will pay by credit card. When you enter the necessary information to place an order, there are two actions. A specific amount is deducted from your bank account and the second is the same as the vendor credit. Two operations must be executed successfully with a successful transaction.

WCF Transaction Properties

WCF transactions have the following four properties.

    • Atomicity – All operations must act as an indivisible operation in the completion of a transaction.

    • Consistency – Regardless of the operation settings, the system is always in the same state as expected, that is, the result of the transaction is consistent.

    • Isolation – the middle state of the system is not visible to any entity of the outside world until the transaction is complete.

    • Persistence – The commit status is maintained regardless of any form of failure (hardware, power outage, etc.).

There are a number of factors to consider when configuring a WCF transaction. These binding and operational behaviors.

    • Binding – There are only a few WCF bindings that support transactions, which is critical, from only those bindings, which are disabled by default, and should be able to obtain the office support to make a choice. These bindings are described below.

      • NetTcpBinding
      • NetNamedPipeBinding
      • Wshttpbinding
      • Wsdualhttpbinding
      • WSFederationHttpBinding
    • Operational behavior – While combining the path of facilitating transactional propagation, operational responsibility and operational configuration are critical. The main purpose of the two attributes is the same. They are transactionflow and transactionscoperequired. It should be noted here that the TransactionFlow property mainly has three values, which are allowed, Mandatory, and notallowed.

The following code shows the binding of the change and whether the transaction contract configuration facilitates the customer's propagation specification.

<bindings><wsHttpBinding><binding name ="Mandatorytransbinding"  transactionflow ="true"> <reliablesession enabled  ="true"/> </binding> </wsHttpBinding> </bindings >                           
Transaction protocol

WCF uses three protocol transactions, all of which are lightweight, old transactions, and ws-Atomic transactions (Ws-at). Ws-at is an interoperable protocol that can distribute traffic across firewalls in a distributed transaction. However, the agreement should not be strictly based on Microsoft technical use of the transaction.

WCF Transaction phase

There are two phases of a WCF transaction, as described below.

    • Preparation phase-At this stage, the transaction manager checks whether all entities are ready to commit the transaction.

    • Submission phase-At this stage, the submission of the entity gets started in reality.

To understand the two-phase functionality of a WCF transaction, let's look at the following figure.

Enable WCF transaction processing

To succeed in making a WCF transaction successful, you need to follow a series of six steps. The necessary steps are shown below.

Step 1: Create two WCF services

In this regard, the most important step is to build two service projects in WCF and participate in a transaction. Database transactions will be executed in both of these services, and it should be understood how they are unified by a WCF transaction. Wcftransactions Web applications are also created in a single transactional scope that occupies two created services.

2nd Step: Create a method and its properties have the TransactionFlow property

Here, the UpdateData method is created to insert the WCF service into the database with the OperationContract attribute. In order to accomplish this task, the interface class ServiceContract is created first. Used to implement the transaction in the newly created method, which has the TransactionFlow property and the transaction uses the same value.

[ServiceContract] public  interfaceIService1{[operationcontract] [transactionflow(transactionflowoption.  Allowed)]voidupdatedata();}           

3rd Step: WCF Service implementation with TransactionScopeRequired property

This is done by the encoding shown below.

[OperationBehavior(TransactionScopeRequired = True)]Public void UpdateData(){ Try { SqlConnectionObjconnection= New SqlConnection(Strconnection);Objconnection.Open(); Using(SqlTransactionTransaction= Program.DbConnection.BeginTransaction()) { BooleanDorollback= False; Using(SqlCommandCmd= New SqlCommand("INSERT into Customer (customer name, customer code) VALUES (' SSS ', ' SSS ')"Objconnection)) Try {Cmd.ExecuteNonQuery(); } Catch(SqlException) {Dorollback= True; break; } } ifdorollback)  Transaction. Rollbackelse Transaction. Commit} finally {. Close}}          /span>                

Step 4: Enable transaction flow by WCF service configuration file

The same code is given below:

<bindings>  <wsHttpBinding>     <bindingname="Transactionalbind "transactionflow=" true "/></wsHttpBinding></bindings>  

It is important to value the transaction to allow the endpoint binding to expose the WCF service.

<endpointAddress= ""binding="Wshttpbinding"bindingconfiguration=" Transactionalbind "Contract=" Wcfservice1.iservice1 ">      

5th step: Invoke two services in one transaction

Here, the above two services are called in a transaction, for this purpose, the TransactionScope object is used for both services. The complete method of the above object is called to commit the WCF transaction. If it is rolled back, then the Dispose method is called.

Using (TransactionScopeTs= New TransactionScope(TransactionScopeOptionrequiresnew)) { try  { //Call your WebService transactions Here ts complete (); } catch  ( Exception Ex)  { Tsdispose (); }}          /span>                

The complete code for the following small slices, where WCF commit data has been grouped in a range.

Using (TransactionScopeTs= New TransactionScope(TransactionScopeOption.RequiresNew)){ Try { ServiceReference1.Service1clientObj= New ServiceReference1.Service1client();Obj.UpdateData(); ServiceReference2.Service1clientObj1= new  Servicereference2. Service1client  Obj1. Updatedata  Ts. Complete} catch  ( Exception Ex)  { Tsdispose (); }}          /span>                

6th step: Testing WCF Transactions

The test is an exception (forced) after the 6th and final step and the 1th WCF service is called.

Original address: http://www.yiibai.com/wcf/wcf_transactions.html

Getting Started with WCF (10)---WCF Transactions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.