Transaction Processing Technology under the. NET Framework

Source: Internet
Author: User
Tags net command

Summary of several methods for implementing transactions in. Net:
1. transactions are implemented using SQL statements in the background database, and the transfer service is implemented on the Database End using statements, as shown below:

Set xact_abort on

Begin tran

Update a_user set balance = balance-10000 where uid = '000000'

Update B _user set balance = balance + 10000 where uid = '000000'

Commit tran

Set xact_abort on is very important. If no, the database will not roll back the wrong transaction automatically.

You can also manually roll back the transaction,CodeAs follows:

Declare @ a_usererror int,

Declare @ B _usererror int

Begin tran

Update a_user set balance = balance-10000 where uid = '000000'

Set @ a_usererror = @ Error

Update B _user set balance = balance + 10000 where uid = '000000'

Set @ B _usererror = @ Error

If @ a_usererror = 0 and @ B _usererror = 0 then

Begin

Commit tran

Return (1) -- return 1 meaning is trans commit successful

End

Else

Begin

Rollback tran

Return (0)-return 0 meaning is trans commit failed

End

There are more statements for manual rollback, but there are return values so thatProgramTo determine whether the execution is successful.
2. Implement transactions through the ADO. NET component:

With *** transaction, you can create a transaction processing object on the database connection and call the transaction processing object to submit or roll back the transaction. The preceding transfer example is as follows:

Sqlconnection conn = new sqlconnection ("");

Conn. open ();

Sqltransaction TRAN = conn. begintransaction ();

Sqlcommand cmd = new sqlcommand ();

Cmd. Connection = conn;

Cmd. Transaction = Tran;

Try

{

Cmd. commandtext = "Update a_user set balance = balance-10000 where uid = '000000 '";

Cmd. executenonquery ();

Cmd. commandtext = "Update B _user set balance = balance + 10000 where uid = '000000 '";

Cmd. executenonquery ();

Tran. Commit ();

}

Catch (exception ex)

{

Tran. rollback ();

}

The code structure of the transaction commit implemented in this method is clear, but in the case of hard-coded transactions, any changes to the business logic or user requirements need to be modified and compiled again.Source code.

3. Transaction processing through the transaction support provided by COM +:

In. net to access the transaction support provided by COM +, you must first set.. Net Assembly registered to the COM + component container.. Net Assembly registration to COM + must meet the following conditions:

A. The Assembly must be signed with a strong name.

B. Classes contained in the Assembly must be inherited from the servicedcomponent class.

C. The Assembly must be added to a specific COM + application.

D. The Assembly must be registered in the Windows registry.

1) Use the sn.exe tool to generate a strong name in the. NET command first, as shown in figureSn-K test. SNKCopy the generated key file to the program directory and modify the path of assemblykeyfile in assemblyinfo. CS, for example:

[Assembly: assemblykeyfile (".. \ test. SNK")]

2) inherit from the servicedcomponent class. to inherit from this class, you must first introduce the system. enterpriseservice. dll class library.

3) declare that the Assembly is added to the COM + application name, as shown in figure: [Assembly: applicationname ("testcomplus")]

This line of code must be added to the class file before the class code definition after the using command.

In this way, you can use the contextutil class in the class code to call the context environment provided by COM + for transaction processing. The following code:

Using system. enterpriseservices;

Using system. Data. sqlclient;

// Declare that the current component is added to the testcomplus application in COM +.

[Assembly: applicationname ("testcomplus")]

Namespace complusappdemo

{

// Use the transaction attribute to declare the current component. COM + is required to provide transaction support.

[Transaction (transactionoption. Required)]

Public class transactiondemo: servicedcomponent

{

Public transactiondemo (){}

Public bool transdemo ()

{

Sqlconnection conn = new sqlconnection ("");

Conn. open ();

Sqlcommand cmd = new sqlcommand ();

Cmd. Connection = conn;

Try

{

Cmd. commandtext = "Update a_user set balance = balance-10000 where uid = '000000 '";

Cmd. executenonquery ();

Cmd. commandtext = "Update B _user set balance = balance + 10000 where uid = '000000 '";

Cmd. executenonquery ();

Contextutil. setcomplete (); // call COM + context to submit data

Return true;

}

Catch (exception ex)

{

Contextutil. setabout (); // call COM + context rollback transaction

Return false;

}

}

}

}

Code and use ADO. net implements very similar transaction processing code, but they execute different principles, ADO. the sqltransaction class of net calls the transaction processing engine of the background database when implementing transactions, while the COM + transaction calling COM + supports the DTC (Distributed Transaction Coordinator distributed transaction coorator) service.

After the project is compiled into complusappdemo.dll, use the regsvcs.exe tool to compile the complusappdemo. write the type information of the DLL component to the system registry, create a COM + application based on [Assembly: applicationname ("testcomplus")], and add the component to the application. In this way, you can call the transactiondemo class transdemo () method in the application to implement transaction processing.

4. Use the. NET transaction component as the transactionscope object in the namespace system. Transactions.

Using (transactionscope Ts = new transactionscope (transactionscospontion. Required ))

{

Dal. insert (order );

// Update the inventory to reflect the current inventory after the order submission

Inventory inventory = new inventory ();

Inventory. takestock (order. lineitems );

// Calling complete commits the transaction.

// Excluding this call by the end of transactionscope's scope will rollback the transaction

TS. Complete ();

}

V. Distributed Transaction Processing

All the above are transaction processing based on a single database. However, if the two or more days of business to be processed are located in different databases, it is necessary to implement transaction processing across databases, this requires the use of Distributed Transaction processing technology. In. NET Framework programming, we can implement distributed transaction processing in two different ways: database-based linked server and COM +.

A. Distributed Transaction Processing Based on the linked server:

First, we need to build a linked server. Refer to the SQL Server online help. After the linked server is built, you can see the remote server in the SQL Server Manager. Then you can write the following SQL statement to implement distributed transactions:

Set xact_abort_on

Begin distributed tran

Update a_user set balance = balance-10000 where uid = '000000'

Update bcenter. northwind. DBO. B _user set balance = balance + 10000 where uid = '123'

Commit tran

Different from the transaction processing of a single database server, there are 2nd rows and 4th rows, of which 2nd rows declare that the current transaction is processed as a distributed transaction, row 3 declares the B _user data table operation on the northwind database on the bcenter server.

Therefore, this distributed method is relatively simple in coding, but the workload for configuration and deployment increases, because we need to create a connection server first.

B. implemented based on COM +

Both the Distributed Transaction processing through COM + and the transaction processing of a single database are implemented through DTC, but the Distributed Transaction processing is different from that of a single server in principle. To implement distributed transaction processing in COM +, the transaction processing engine of DTC needs to communicate with the transaction managers of different databases and send the transaction operations to be executed, after the Transaction Manager of the database executes this operation, it returns the result to DTC. If all the transaction managers return correct information, the DTC sends the submit command to each Database Transaction Manager, the background database submitted for data modification, and distributed transactions are completed. If any Database Transaction Manager returns an error message, DTC sends a rollback command to cancel the distributed transaction. This is the distributed transaction operation committed in two phases.

The code is similar to implementing the transaction processing of a single database. You only need to execute these two Command commands on two different database connections.

Comparing the two different distributed transaction processing methods above, we can see that it is difficult to deploy distributed transactions using the linked server, and convenient to deploy using the COM + implementation, however, the distributed transactions implemented by the linked server can be encapsulated as stored procedures, which makes it easier to modify the business logic and upgrade the application in the future, when implemented through COM +, once the business rules change, the code needs to be modified and compiled again.

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.