VB.NET•Auto Enlist—Or Not

Listing 2. In the automatic model, enlistment in the transaction occurs if the SQLConnection object is opened or retrieved from the connection pool. You can disable auto-enlistment by setting the SQLConnection's Enlist property to False. Also note the use of the ContextUtil class to control transaction outcome with a Try/Catch block.

' Supply the COM+ application name. 
<Assembly: ApplicationName("SalesComponent")> 
' Supply a strong-named assembly.
<Assembly: AssemblyKeyFileAttribute

Namespace BusinessLogic

' Add transactional support to this class.
<Transaction(TransactionOption.Required)> _
	Public Class SalesComponentCOM
	Inherits ServicedComponent
	Implements ISalesComponent

	Public Function MakeSale(ByVal _
		connectionString As String, _
		ByVal customerID As String, _
		ByVal productID As Integer, _
		ByVal requestedQty As Integer, _
		ByVal unitPrice As Double, _
		ByVal discount As Double) _
		As Boolean Implements _

		Dim conn As New SqlClient.SqlConnection
		Dim successfulSale As Boolean = True
		Dim dataAccess As New DataAccess


			' The SQLConnection object used here
			' is automatically enlisted in the 
			' transaction. A separate 
			' SQLTransaction object isn't needed.
			conn.ConnectionString = _

			' Attempt to add a new order 
			successfulSale = _
				dataAccess.newOrder(conn, _
				customerID, productID, _
				requestedQty, unitPrice, discount)

			If successfulSale Then

				' Attempt to adjust inventory
				successfulSale = _
					dataAccess.adjustInventory(conn, _
					requestedQty, productID)

				If successfulSale Then

					successfulSale = _

				End If

			End If

			If successfulSale Then

				' If the sale is successful, 
				' commit the transaction


				' If some part of sale was 
				' unsuccessful, rollback transaction
				successfulSale = False

			End If

		Catch ex As Exception

			' If error occurs, rollback transaction
			Throw ex


			MakeSale = successfulSale

		End Try

	End Function

End Class