The .NET Transaction Support


.NET transaction support is based on the original Microsoft Transaction Server (MTS) introduced in Windows NT 4.0. Later, MTS became part of the Microsoft Windows 2000 COM+ Services and is now incorporated into Windows Server 2003. The .NET Common Language Runtime (CLR) leverages an automatic distributed transaction model introduced in MTS. At the core of the MTS architecture lays the MTS Executive that hosts individual components such as C# objects or ASP.NET pages. MTS relies on the Distributed Transaction Coordinator (DTC) component to perform the role of transaction manager to coordinate the correct execution of a transaction across multiple resource managers. Interaction between DTC and resource managers is achieved using OLE Transaction interfaces. DTC also supports X/Open Distributed Transaction Processing (DTP) XA standard, see [XASPEC]. You may recall that Java Transaction Service also supports the XA standard. Transactional applications can be built with any of the .NET languages including VB.NET, J++, C#, and ASP.NET. Transactional support can be achieved by one of two mechanismsimplicit via programmatic transaction support or declarative. Starting with .NET Framework 2.0, there is a new transactional API available with System.Transactions namespace. Please refer to [SYSTXN] for more details.

Programmatic Transaction Support

Manual transaction management can be achieved by explicitly calling the SetComplete and SetAbort methods of the System.EnterpriseServices.ContextUtil class. If the MTS receives SetAbort from any of the objects involved in the transaction, the runtime instructs the transaction coordinator to abort the transaction. Otherwise, MTS waits to receive a SetComplete call from all of the components and then instructs the transaction coordinator to commit the transaction. When managing transactions manually, the transaction attribute has to be set to Disabled. An object then can make direct calls to the Distributed Transaction Coordinator using OLE Transaction interfaces. The manual mechanism of handling transactions is analogous to the Java EE BMT demarcation. The .NET transaction Isolation Levels are very similar to the ones discussed in the Java EE overview.

There are six Isolation Levels to support transactions: Chaos, ReadCommited, ReadUncommited, RepeatableRead, Serializable, and Unspecified. The Chaos isolation level prevents pending changes from more highly isolated transactions from being overwritten. Manual transactions, unlike automatic, can be used to implement pseudo-nested transactions (they are not truly nested as they don't support nested scopes of Moss' locking rules). However, manually managing distributed transaction management, recovery, concurrency, and data integrity in an effective manner is fairly complicated. Microsoft ActiveX Data Objects (ADO), OLE DB, Open Database Connectivity (ODBC), and Message Queuing resource APIs all enable manual transaction processing.

Listing 12-5 demonstrates how to implement a local database transaction using C#. Database access is achieved using ADO.NET API.

Listing 12-5. UpdateProductCount Class

private void updateProductCount (int prodId, int newProdCount,    String connectionInfo ) { // Create and open database connection SqlConnection connection = new SqlConnection(connectionInfo); connection.Open(); // Begin a local database transaction SqlTransaction txn = connection.BeginTransaction(IsolationLevel.Serializable); // Enlist the command in the current transaction SqlCommand command = connection.CreateCommand(); command.Transaction = txn; try {    // Update product inventory    command.CommandText = "UPDATE inventory                         SET product_quantity='                         & newProdCount & '                         WHERE product_id=' & prodId '";    command.ExecuteNonQuery();    // Commit the transaction    txn.Commit(); } catch(Exception e) {    try {     txn.Rollback();   } catch (SqlException ex) { // Process error   }   } finally {     // Release resources and delist connection from the transaction     connection.Close();   } } 

In this example when creating SqlCommand, the Connection object automatically enlists resources in an active transaction. This is the default platform setting. By enlisting in a distributed transaction, the transaction commit or abort will be propagated to the resource manager, and changes to the data will be committed or rolled back in the database. The Connection.EnlistDistributeTransaction() method can be used to enlist in an existing distributed transaction if automatic settings are disabled. If an application design requires disabling auto-enlist, SqlConnection should be created with Enlist=false:

SqlConnection connection =  new SqlConnection("Data Source=localhost;  Initial Catalog=Northwind;Integrated Security=SSPI;Enlist=false"); 


Automatic Transaction Support

.NET CLR automatic transaction support is similar to the CMT demarcation of the Java EE architecture. The .NET Framework relies on MTS/COM+ services to support automatic transactions, which is enabled through the System.EnterpriseServices namespace. This namespace provides .NET objects with access to the COM+ services. Any .NET class that derives from System.EnterpriseServices.ServiceComponent, [SVCCMP], can be exposed as a COM+ configured component. To participate in automatic transactions, a .NET class must be inherited from the System.EnterpriseServices.ServicedComponent class, which enables it to run inside COM+ service.

Declarative Transaction Support

How objects participate in transactions can be controlled declaratively using predefined transaction attributes. Based on the application business logic, a C# class, an ASP.NET page, or an XML Web service method, a value for transaction attribute can be declared accordingly. For example, a method can automatically participate in an already existing transaction or never participate in a transaction. Attributes are similar to the EJB transaction attributes that can be used to demarcate transaction boundaries.

  • NotSupported An object does not run within the scope of a transaction.

  • Supported If a component is invoked within the scope of a transaction, that context will be used. Otherwise, no transactional context is created.

  • Required A new transaction will be started unless a caller is associated with a transaction context, in which case a method will be executed within the existing transaction. This is the default attribute value for C#.

  • RequiresNew A new transaction will be started regardless of the caller's transaction.

  • Disabled Automatic transaction settings are removed. To manage transactions, an object should explicitly call the Distributed Transaction Coordinator. Disabled is the default setting for ASP.NET.

Implementing the declarative model to manage a transaction, a C# class that requires a new transaction can be declared in the following way (Listing 12-6):

Listing 12-6. InventoryHandler class in C#

 [Transaction(TransactionOption.RequiresNew)] public class InventoryHandler {   public void checkInventory(PORequest Request) {       // check inventory and update product count   } } 

.NET distributed transactions allow individual participants to vote for committing or aborting a transaction. This feature is available when using automatic transaction settings with System.EnterpriseServices.AutoCompleteAttribute. In the absence of an explicit vote within a method, a vote is automatically set to Commit.

There are some limitations to both programmatic and declarative transaction models. All transactions are based on the System.EnterpriseServices namespace and automatically rely on distributed transaction coordinator (DTC). This imposes a performance overhead for applications utilizing a single resource, for example a single database. Additionally, there is no way for multiple transactions to participate in the same transaction, as the Enterprise Services are thread-safe. This may be a potential limitation for certain types of applications. Thus, the .NET Framework 2.0 introduces a new transaction manager model.

Managing Transactions with System.Transactions

The .NET Framework 2.0 introduces two types of transaction managers, the Lightweight Transaction Manager (LTM) and the OleTx Transaction Manager. The latter one is similar to the DTC, while the Lightweight Transaction Manager, as its name implies, is used for managing transactions across a single application domain and a single resource. The new transaction model is available via the System.Transactions namespace. The new transaction model automatically selects a transaction manager for your application. If a single application interacts with a single database, the LTM will be selected. If application changes and a new durable resource is added, the transaction manager is switched to OleTx automatically, see [TXME]. This transaction management escalation model decouples an application from the underlying transaction manager. In addition to the dynamic transaction manager escalation, there is a feature of promotable enlistment of durable resources. This means that if there is only one resource such as a database participating in a transaction, it can take the ownership of the transaction. Additionally, the System.Transactions infrastructure supports a number of useful featuresfor instance, subscribing to a TRansactionCompleted event to notify an application upon transaction completion. Similarly, you can subscribe to DistributedTransactionStarted event. A WorkerThread class can be used to execute the transaction in a separate thread from the client application, thus contributing to application performance.

If an application relies on declarative model, there are no changes needed to take advantage of the System.Transactions. The application will have to be modified if there needs to be manual programming support for the transaction. The System.Transactions libraries are included in the Systems.Transactions.dll. You can refer to [SYSTSAMP] for additional resources.

.NET transaction support is consistent across different .NET languages, which provides transactional interoperability across .NET objects, ASP.NET pages, and Web methods.




Java EE and. Net Interoperability(c) Integration Strategies, Patterns, and Best Practices
Java EE and .NET Interoperability: Integration Strategies, Patterns, and Best Practices
ISBN: 0131472232
EAN: 2147483647
Year: N/A
Pages: 170

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net