Home > Articles > Programming > Windows Programming

This chapter is from the book

Automatic Transactions

With automatic transactions, you do not have to pass a transaction as an argument of a method; instead, a transaction flows automatically with the context. Using transaction attributes, you can specify whether a transaction is needed.

Using the class attribute [Transaction], you can specify whether objects of the class are aware of transactions, and whether transactions should be created automatically by the Enterprise Services runtime.

The class attribute is applied to the class of the serviced component, as shown in this code segment:

[Transaction(TransactionOption.Required)]
   public class CustomerDataComponent : ServicedComponent
   {

Transaction Attributes

The [Transaction] attribute that can be applied to classes that implement serviced components has five different values that you can set with the enumeration TransactionOption. The values of the enumeration TransactionOption are Required, RequiresNew, Supported, NotSupported, and Disabled. Table 7-1 describes what these values mean.

Table 7-1 TransactionOption Enumeration

TransactionOption Value

Description

Required

The value Required marks that the component needs a context with a transaction. If the context of the calling object does not have a transaction, a new transaction is started inside a new context. If the calling object does have a transaction, the same transaction from the calling object is used.

RequiresNew

Similar to the value Required, with RequiresNew the component always gets a context with a transaction; but contrary to Required, a new transaction is always created. The transaction is always independent of a possible transaction of the calling object.

Supported

The value Supported means that the component is happy with or without a transaction. This value is useful if the component does not need a transaction itself, but it may invoke components that do need transactions, and it may be called by components that have already created transactions. Supported makes it possible for a transaction to cross the component, and the calling and called components can participate in the same transaction.

NotSupported

If the component is marked with NotSupported, the component never participates in a transaction. If the calling object does not have a context with a transaction, it can run inside the same context. If the calling object does have a context with a transaction, a new context is created.

Disabled

The option Disabled differs from NotSupported insofar as the transaction in the context of the calling component is ignored.


The meaning of the transaction values you can set with the attribute [Trans-action] is greatly influenced by the context of the calling component. Table 7-2 helps make this behavior more clear. In this table, all five transaction values are listed with both variants, whether the calling component is running inside a transaction or not. Column 3 shows whether the component is running in a transaction, and column 4 shows whether the component is running in a new transaction.

Table 7-2 TransactionOption Behaviors

Attribute

Calling Component Running in a Transaction

Running in a Transaction

Running in a New Transaction

Required

Yes No

Always

No Yes

Requires New

Yes No

Always

Always

Supported

Yes No

Yes

Never

Not Supported

Yes No

Never

Never

Disabled

Yes No

Yes, if calling context is shared No

Never


Supported or NotSupported?

I’m often asked, "Why should a component be marked with Supported to support transactions, although the component does not need transactions itself?"

Figures 7-4 and 7-5 describe why the transactional value Supported is a useful option. In both figures, three objects that call each other are shown. In Figure 7-4, object A has the transactional option Required, and because the client does not have a transaction, a new transaction is created. Object B is marked with the transactional value NotSupported, and object C again has the value Required. Because object B does not support transactions, the context of object B does not have a transaction associated. When object C is called by object B, a new transaction is created. Here the transactions of object A and object C are completely independent. The transaction of object C may commit, whereas the transaction of object A may be aborted.

Figure 7.4

Figure 7-4 Transactional behavior with an interim object transaction NotSupported.

Figure 7-5 shows a similar scenario but with object B marked with the transactional attribute Supported. Here the transaction from object A is propagated to B and C. If the database access fails with object C, a rollback with object A occurs, because both objects are running inside the same transaction.

Figure 7.5

Figure 7-5 Transactional behavior with an interim object transaction Supported.

Required or Requires New?

With the transactional value Required, a new transaction is created if a transaction does not already exist in the calling object. If the calling object has a context with a transaction, the same transaction is used. Under some scenarios, a different behavior is required. For example, if object A in Figure 7-6 changes a course map, but object B writes the information to a log database, writing the information to the log should happen independently if the transaction with object A succeeds. To make this possible, object B is marked with the transactional configuration RequiresNew (a new transaction is required).

Figure 7.6

Figure 7-6 Transactional behavior with RequiresNew.

Transaction Streams

A single transaction cannot only be spread across multiple objects; it can also be spread across multiple applications that can run on multiple systems. Inside a transaction stream, all database connections are automatically enlisted in the distributed transaction coordinator (DTC).

A transaction stream (Figure 7-7) is started with a root object. A root object is the first object in the transaction stream; it starts the transaction. Depending on the configuration of the objects that are called, they will either be part of the same transaction stream, or a new transaction stream will be created.

Figure 7.7

Figure 7-7 Transaction stream.

Transaction Outcomes

Every object, every resource dispenser, and every resource manager participating in a transaction can influence the outcome of a transaction. A transaction is completed as soon as the root object of the transaction deactivates. Whether the transaction should be committed or aborted depends on the done, consistent, and abort bits. The done and consistent bits are part of every context of every object that participates in the transaction. The done bit is also known as the happy bit. The abort bit (also known as the doomed bit) is part of the complete transaction stream. Figure 7-8 shows the done, consistent, and abort bits in conjunction with the serviced components and their contexts.

Figure 7.8

Figure 7-8 Done, consistent, and abort bits.

At object creation time, the done and consistent bits are set to false. With the help of the class ContextUtil, the values of these bits can be changed. Setting the done bit to true means that the work of the object is complete and the object can be deactivated. The consistent bit is responsible for the outcome of the transaction. If the consistent bit is true, the object is happy with the transactional part of its work—the transactional part succeeded.

The abort bit is set to false when the transaction is created. When an object is deactivated, the context of the object is lost, and so are the done and consistent bits. Here the result of the consistent bit is propagated to the abort bit. The object context is deactivated as soon as the done bit is set to true. Now, if the consistent bit is set to false, the abort bit of the transaction stream is set to true, so that the transaction will be aborted. If the consistent bit is set to true, it does not influence the value of the abort bit.

ContextUtil Methods

The ContextUtil class has four methods to influence the values of the done and consistent bits. The methods and their influence of the done and consistent bits are shown in Table 7-3. One thing to keep in mind is that calling these methods only influences the outcome of the method of the serviced component but does not have an immediate result.

Table 7-3 ContextUtil Methods

ContextUtil Method

Done Bit

Consistent Bit

Description

SetComplete

true

true

The method SetComplete marks the object as done and consistent. The work of the object is completed, and the transaction can be committed. When the method returns, the object is deactivated, and the vote of the object regarding the transaction is to commit the transaction.

SetAbort

true

false

The work of the object is completed, but it did not succeed; the transaction must be aborted. When the method returns, the object is deactivated, but the transaction vote is to abort the transaction.

EnableCommit

false

true

The work of the object is not completed; it should not be deactivated. However, the first phase of the transactional work was successfully completed. When the method returns, the object will not be deactivated, but the vote for the transaction is to commit the transaction. If the root object of the transaction completes the transaction before the object is called for a second time, the object is deactivated.

DisableCommit

false

false

Similar to EnableCommit, with DisableCommit the work of the object is not completed. State of the object will be kept, so that it can be invoked another time. However, contrary to the EnableCommit method, if the transaction is completed before the object is invoked a second time, the transaction vote is to abort the transaction.


Automatic Transaction Example

Figure 7-9 shows the assemblies for the sample application. With the sample application, the assembly Samples.Courses.Data includes the class CourseData that is doing the database access code with the methods AddCourse, UpdateCourse, and DeleteCourse. The assembly Samples.Courses.Components includes the serviced component CourseDataComponent that uses the class CourseData. The assembly Samples.Courses.Entities includes business classes such as Course, CourseData, and CourseDataCollection. These classes are used all over within the application.

Figure 7.9

Figure 7-9 Assemblies with the transaction sample.

Listing 7-5 shows the AddCourse method from the CourseData class. This method is very similar to the AddCourse method that was shown in Listing 7-2. But, contrary to the first implementation of AddCourse, here the transactional code has been removed because the transactional support will be added within the serviced component class.

Listing 7-5 AddCourse Method Without Programmatic Transactions

public void AddCourse(Course course)
      {
         SqlConnection connection = 
               new SqlConnection(connectionString);
         insertCourseCommand.Connection = connection;
         insertCourseCommand.Parameters["@CourseId"].Value = 
               course.CourseId;
         insertCourseCommand.Parameters["@Number"].Value = 
               course.Number;
         insertCourseCommand.Parameters["@Title"].Value = 
               course.Title;
         insertCourseCommand.Parameters["@Active"].Value = 
               course.Active;
         connection.Open();
         try
         {
            insertCourseCommand.ExecuteNonQuery();
         }
         finally
         {
            connection.Close();
         }
      }

The implementation of the serviced component class is shown in Listing 7-6. The class CourseUpdateComponent derives from the base class ServicedComponent and is marked with the attribute [Transaction(TransactionOption.Required)], so that a transaction stream will be created automatically when a new instance is created. The construction string2 is passed with the method Construct that is overridden from the base class. Serviced component construction is enabled with the attribute [ConstructionEnabled]. This way the construction string can be changed later by the system administrator.

In the method AddCourse, the transaction outcome is influenced with the methods of the class ContextUtil: SetComplete and SetAbort. If the method db.AddCourse completes successfully, ContextUtil.SetComplete sets the done and consistent bits to mark a successful outcome. If an exception occurs, the exception is caught in the catch block. Here, the consistent bit is set to false by calling the method ContextUtil.SetAbort. The exception is rethrown, so that the calling method can get some information about the reason why the method failed. Of course, you can also create a custom exception that is thrown in case of an error.

Listing 7-6 Serviced Component Class CourseUpdateComponent

using System;
using System.EnterpriseServices;
using Samples.Courses.Data;
using Samples.Courses.Entities;
namespace Samples.Courses.Components
{
   public interface ICourseUpdate
   {
      void AddCourse(Course c);
      void UpdateCourse(Course c);
      void DeleteCourse(Course c);
   }
   [Transaction(TransactionOption.Required)]
   [ConstructionEnabled(true, 
         Default="server=localhost;database=courses;"            
         "trusted_connection=true")]
   [EventTrackingEnabled(true)]
   public class CourseUpdateComponent: ServicedComponent, 
         ICourseUpdate
   {
      public CourseComponent()
      {
      }
      private string connectionString;
      protected override void Construct(string s)
      {
         connectionString = s;
      }
      public void AddCourse(Course c)
      {
         CourseData db = new CourseData(connectionString);
         try
         {
            db.AddCourse(c);
            ContextUtil.SetComplete();
         }
         catch
         {
            ContextUtil.SetAbort();
            throw;
         }
      }
      public void UpdateCourse(Course c)
      {
         //...
      }
      public void DeleteCourse(Course c)
      {
         //...
      }
   }
}

After you have registered the serviced component assembly, you can see the transactional options with the Component Services Explorer. You just have to select the properties of the component and open the Transaction tab (see Figure 7-10). In this dialog box, you can see the transactional option that was defined with the attribute [Transaction].

Figure 7.10

Figure 7-10 Component Services Explorer—transactional options.

If you change the option from Required to Not Supported with the Component Services Explorer, a runtime exception will occur with Windows Server 2003. During runtime, it is checked whether the programmatic configuration corresponds to the manual configuration regarding the transactional behavior.

Setting the Transactional Vote

Instead of setting the transactional vote with the ContextUtil class and the methods SetComplete, SetAbort, EnableCommit, and DisableCommit indirectly, you can set them directly. The class ContextUtil offers the property MyTransactionVote for this purpose, which you can set to one value of the enumeration TransactionVote: Commit or Abort. Setting MyTransactionVote to Commit sets the consistent bit to true, whereas setting MyTransactionVote to Abort sets the consistent bit to false.

The done bit is directly influenced when you set the property DeactivateOn-Return of the ContextUtil class. ContextUtil.DeactivateOnReturn = true sets the done bit to true.

The AddCourse method does not change a lot, as you can see in Listing 7-7.

Listing 7-7 AddCourse Using the Property MyTransactionVote

public void AddCourse(Course c)
      {
         ContextUtil.DeactivateOnReturn = true;
         CourseData db = new CourseData(connectionString);
         try
         {
            db.AddCourse(c);
            ContextUtil.MyTransactionVote = 
                  TransactionVote.Commit;         
         }
         catch
         {
            ContextUtil.MyTransactionVote = 
                  TransactionVote.Abort;
            throw;
         }
      }

AutoComplete Attribute

Instead of calling SetComplete and SetAbort, all transaction handling can be done if you apply the attribute [AutoComplete] to a method. In this way, the implementation of the method AddCourse gets easier, because it is not necessary to catch and to rethrow exceptions. Instead, if the method completes successfully, by applying the attribute [AutoComplete], the done and consistent bits are set to true. On the other hand, if an exception is generated, the consistent bit is set to false at the end of the method. You can see the implementation of AddCourse using the [AutoComplete] attribute in Listing 7-8.

Listing 7-8 AddCourse Using the [AutoComplete] Attribute

[AutoComplete]
      public void AddCourse(Course c)
      {
         CourseData db = new CourseData(connectionString);
         db.AddCourse(c);
      }

Using the [AutoComplete] attribute, you have to throw exceptions to the caller. The [AutoComplete] attribute sets the consistent bit to false only if an exception is thrown. If you want to handle exceptions in the AddCourse method, you can add a try/catch block where the exception is rethrown (see Figure 7-9). Instead of rethrowing the same exception, you can throw an exception of a custom exception type—it is just important to throw an exception in case of an error.

Listing 7-9 [AutoComplete] Attribute with Exception Handling

[AutoComplete]
      public void AddCourse(Course c)
      {
         try
         {
            CourseData db = new CourseData(connectionString);
            db.AddCourse(c);
         }
         catch (Exception ex)
         {
            // do some event logging
            // re-throw exception
            throw;
         }
      }

Distributed Transactions

Enterprise Services transactions are enlisted in the DTC, so these transactions can run across multiple systems and across multiple databases. Figure 7-11 demonstrates such a distributed scenario. A single transaction can consist of an update to a SQL Server database, an update to an Oracle database, and writing some messages to a message queue server,4 all on different systems.

Figure 7.11

Figure 7-11 Distributed transactions.

Figure 7.12

Figure 7-12 Enable DTC with Windows Server 2003.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020