. Net transaction control

Source: Internet
Author: User
Tags msmq
Transaction control is often used in distributed applications. A transaction has a beginning and a end, which specifies the transaction boundary. A transaction can span across processes and computers within its boundary. All resources within the transaction boundary participate in the same transaction. To maintain consistency between resources within the transaction boundary, the transaction must have the acid attribute, I .e. atomicity, consistency, isolation and continuity.

Local transactions and distributed transactions
--------------------
A local transaction is a transaction whose range is a single data resource that can identify the transaction (for example, Microsoft SQL Server database or MSMQ Message Queue ). For example, when a single database system has all the data involved in a transaction, it can follow the acid rule. In the case of SQL Server, the internal Transaction Manager is used to commit and roll back transactions.

Distributed transactions can span different types of data resources that can recognize transactions and include multiple operations (for example, retrieve data from the SQL database, read messages from the Message Queue Server, and write data to other databases ). You can simplify the programming of distributed transactions by using software that coordinates the submission, suspension, and recovery across several data resources. Microsoft Distributed Transaction Coordinator (DTC) is a technology like this. It adopts a two-phase commit protocol that ensures that the transaction results are consistent among all data resources involved in the transaction. DTC only supports applications that have implemented compatible interfaces for transaction management. These applications are called resource managers (for more information about this topic, see. net Framework developer's guide in distributed transactions
Database transactions
-------------
If you call a stored procedure that encapsulates the required operations in the begin transaction and commit/rollback transaction statements, you can run the transaction in a single round-trip to the database server, to achieve optimal performance. Database transactions also support nested transactions, which means you can start a new transaction from an active transaction.

In the following code snippet, The begin transaction statement starts a new transaction. You can use the commit transaction statement to commit the changes to the database to end the transaction, or, in the case of any errors, use the rollback transaction statement to undo all the changes to end the transaction:

Create procedure proc1
...
As
-- Begin the transaction
Begin transaction
-- Do transaction operations
...
-- Check for any error
If @ error <> 0
-- Rollback the transaction
Rollback transaction
...
-- Commit the transaction
Commit transaction

Manual transactions
-------------
With manual transactions, you can use explicit commands for starting and ending transactions to explicitly control transaction boundaries. This mode also supports nested transactions that allow you to start a new transaction from an active transaction. However, applying this control adds an extra burden to you. You need to register data resources with the transaction boundary and coordinate these resources. Because there is no built-in support for distributed transactions, if you choose to manually control distributed transactions, you will assume a lot of responsibility; you need to control each connection and resource registration, and maintain the acid attribute of the transaction by providing implementation.

Ado. Net manual transaction

These two types of Microsoft ADO.. NET data provider enables manual transactions by providing a set of objects that create a connection to the data storage area, start a transaction, commit or stop the transaction, and finally close the connection. We will take the ADO. Net SQL hosting provider as an example.

To perform operations in a single transaction, you need to create a sqltransaction object, use the sqlconnection object to start the transaction, ensure that the database interaction is performed within the transaction, and commit or stop the transaction. The sqltransaction object provides multiple methods and attributes to control transactions. If each operation in the transaction has been successfully completed, you can use the "Submit" method to submit the changes to the database. You can use the "rollback" method of the sqltransaction object to roll back the changes.

Note that the transaction attribute of the "command" object must be set to a starting transaction so that it can be executed in the transaction.

Visual C #. net

Sqlconnection conn = new sqlconnection ("connstring ");
Sqlcommand cmd = new sqlcommand;
// Open a connection
Conn. open ();
// Begin a transaction
Sqltransaction txn = conn. begintransaction ();
// Set the transaction in which the command executes
Cmd. Transaction = txn;
...

MSMQ manual transaction

. Net Framework supports MSMQ transactions in two different ways: Manual (internal) Support by allowing multiple messages to be sent or received as part of the transaction; by participating in Distributed Transaction Coordinator (DTC) automatic (external) Support for transactions.

MSMQ manual transactions are supported by the messagequeuetransaction class and are completely processed in the MSMQ engine. For more information, see the article "reliable messaging with MSMQ and. Net" in the Duncan McDonald's article.


Automatic transactions
-------------
. NET Framework relies on MTS/COM + to support Automatic transactions. COM + uses Microsoft Distributed Transaction Coordinator (DTC) as the Transaction Manager and Transaction Coordinator to run transactions in a distributed environment. In this way.. NET application programs run across multiple resources combined with different operations (for example, insert orders into the SQL Server database, write messages to Microsoft Message Queue (MSMQ) queue, send emails, and retrieve data from the Oracle database.

By providing a declarative transaction-based programming model, COM + enables applications to easily run transactions across different types of resources. The disadvantage of this approach is that, due to the existence of DTC and COM interoperability overhead, performance is reduced, and nested transactions are not supported.

ASP. NET pages, Web Service methods, and. Net classes can be marked as transactional by setting declarative transaction attributes.

ASP. NET

<@ Page transaction = "required">

ASP. NET Web Service

<% @ WebService Language = "VB" class = "class1" %>
<% @ Assembly name = "system. enterpriseservices" %>
...
Public class class1
Inherits WebService
<Webmethod (transactionoption: = transactionoption. requiresnew)> _
Public Function Method1 ()
...

To participate in Automatic transactions, the. NET class must be inherited from the system. enterpriseservices. servicedcomponent class, which enables the. NET class to run in COM +. In this process, you need to interact COM + with DTC to create a distributed transaction and register all the resource connections in the background. You also need to set declarative transaction properties for this class to determine their transaction behavior.

Visual C #. net
[Transaction (transactionoption. Required)]
Public class class1: servicedcomponent {
...
}

You can set the transaction attribute of the class to any of the following options:

"Disabled"
-Indicates that the object is never created in the COM + transaction. This object can directly use DTC for transactional support.

Notsupported
-Indicates that this object is never created in a transaction.

"Supported"
-Indicates that the object runs in the context of the transaction of its creator. If the object itself is the root object, or its creator is not running in the transaction, the object will be created without using the transaction.

"Required"
-Indicates that the object runs in the context of the transaction of its creator. If the object itself is the root object, or its creator is not running in the transaction, the object will be created using a new transaction.

Requiresnew
-Indicates that the object requires a transaction and the object is created using a new transaction.

The following code shows the. NET class configured to run in COM + and set the Assembly property to the COM + application property.

Visual C #. net
Using system;
Using system. runtime. compilerservices;
Using system. enterpriseservices;
Using system. reflection;
// Registration details.
// COM + application name as it appears in the COM + catalog
[Assembly: applicationname ("class1")]
'Strong name for assembly
[Assembly: assemblykeyfileattribute ("class1.snk")]
[Assembly: applicationactivation (activationoption. Server)]
[Transaction (transactionoption. Required)]
Public class class1: servicedcomponent {
[AutoComplete]
Public void example1 ()
{
...
}
}

Specifies the name of the COM + application of the component to install the assembly. Specifies whether the COM + application is a server application or library application. When specifying applicationactivation (activationoption. Server), you must use the gacutil command line tool (gacutil.exe) to install the assembly to the Global Assembly Cache (GAC ).

You can use the regsvcs.exe command line tool to convert an assembly to a Type Library, and register and install the Type Library in the specified COM + application. This tool can also be used to configure attributes that you have added to the Assembly programmatically. For example, if applicationactivation (activationoption. Server) is specified in a dataset, the tool creates a server application. If you call an assembly without using COM + to install the Assembly, a type library is created and registered at runtime, and the library is installed using COM +. You can view and configure the COM + application created for the assembly in the component service management unit.

By using the system. enterpriseservices. contextutil class, you can obtain information about the COM + object context. It provides the setcomplete and setabort methods to explicitly commit and roll back transactions respectively. As you expected, when all operations have been successfully executed, the contextutil. setcomplete method is called at the end of the try block to commit the transaction. Any exceptions thrown will be caught in the catch block, which uses contextutil. setabort to stop the transaction.

You can also use the system. enterpriseservices. AutoComplete attribute class to enable the Service component to automatically choose whether to commit or stop a transaction. If a successful method call is returned, the component will prefer to commit the transaction. If a method call causes an exception, the transaction is automatically aborted. You do not need to explicitly call contextutilsetabort. To use this function, you should insert the <AutoComplete> Attribute before the class method:

Visual C #. net
[Transaction (transactionoption. Required)]
Public class class1: servicedcomponent {
[AutoComplete]
Public void example1 ()
{
...
}
}

In systems that require transactions to run across MSMQ and other resources that can identify transactions (such as SQL Server databases), you can only use DTC or COM + transactions, but there is no other choice. DTC coordinates all resource managers involved in distributed transactions and manages transaction-related operations.

Summary
----------
Each transaction method compromises application performance and code maintainability. The database transactions that run in the Stored Procedure provide the best performance, because it only requires a single round trip to the database. In addition, this method provides the flexibility to explicitly control the transaction boundary. Although it provides good performance and flexibility, you need to use transact SQL to write code, which is not as simple as using. Net to write code.

Manual transactions using ADO. net transaction objects are easy to write code, and enable the flexibility of starting and ending transactions with explicit commands to control transaction boundaries. However, in order to achieve this simplicity and flexibility, it is necessary to complete some additional round-trips to the database required by the firm, which leads to performance reduction.

If a transaction spans multiple transaction managers that can be identified (including SQL Server databases and MSMQ message queues), automatic transactions are the only choice. This method greatly simplifies application design and reduces coding requirements. However, as the COM + Service performs all the coordination work, there may be some additional overhead.

More resources:
----------
Writing Serviced components
Http://msdn.microsoft.com/library/default.asp? Url =/library/en-US/cpguide/html/cpconwritingservicedcomponents. asp

Processing transactions
Http://msdn.microsoft.com/library/en-us/cpguide/html/cpconprocessingtransactions.asp

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.