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 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 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 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 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 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 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 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 typeit 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 Distributed transactions.
Figure 7-12 Enable DTC with Windows Server 2003.