Data Access and Transactions

Previous Topic Next Topic

Transactional ASP

IIS 5.0 makes it possible to easily write scalable, reliable, and transactional Web applications. The features of Component Services are available to all ASP and ISAPI applications. IIS frees developers to focus on what is really important in an application
—the business logic.

For all ASP transactions, the “unit of work” is the ASP page. Transactions are limited to a single page; they cannot span multiple pages.

To perform a transaction, the ASP file containing the application script simply needs to include a command at the beginning of the script to declare that a transaction is needed: <%@ transaction=required %>. For these pages, a new ASP built-in object, ObjectContext, is defined that is used to commit or abort the transaction.

You indicate when the transaction is over by using the ObjectContext object, and then, if all is well, you commit the transaction using the SetComplete method. If the operation has failed, use SetAbort. Unless one of these methods is called explicitly, the transaction will commit automatically when the page has completed processing. Two event handlers are available on transactional pages, OnTransactionCommit and OnTransactionAbort.

The following example demonstrates each of these transaction elements by randomly aborting a transaction. Although it doesn’t do any real database processing, it illustrates how easy it is to add the power of transactions to Web-based applications. Click the browser’s Refresh button repeatedly to see the event handlers at work.

<%@ LANGUAGE=VBScript Transaction=Required EnableSessionState=False %>
<HTML>
  <HEAD>
    <TITLE>Transactional ASP</TITLE>

  <SCRIPT Language=VBScript Runat=Server>
    Sub OnTransactionCommit()
    'Code used when transaction succeeds.
    Response.Write "<FONT color=green>committed</FONT>"
    End Sub
    Sub OnTransactionAbort()
    'Code used when transaction fails.
    Response.Write "<FONT color=red>aborted</FONT>"
    End Sub
  </SCRIPT>
  </HEAD>

  <BODY BGCOLOR=#FFFFFF>
    The transaction was:
    <% 'Randomly abort the transaction.
    Randomize
    If Rnd > 0.5 Then
    ObjectContext.SetAbort
    End If
    %>
  </BODY>
</HTML>

Because the transactional event handlers aren’t called until the page has completely finished processing, the final messages in the example appear after the closing HTML tag. A better implementation would consist of pure script in ASP pages, whose event handlers redirect to a separate page containing the appropriate HTML response. For a discussion of redirection, see Developing Web Applications in this book.

Any components used on the transactional ASP page indirectly affect the outcome of the transaction, even if the components themselves are not transactional.


© 1997-1999 Microsoft Corporation. All rights reserved.