ASP数据库事务处理
by Chris Payne Introduction
Transactions are important to maintain data integrity, among other things, and have been used with
databases for some time now. Luckily, transactions aren't restricted to databases - you can use them in
Active Server Pages as well, and without having to create custom components using Microsoft Transaction
Server (MTS). This article will take a look at what transactions are, how they will help ASP developers,
and how to implement them.
What are Transactions?
Before we dive into the meat, we have to understand the terminology (believe me, I was lost for a long
time because no one explained these terms to me).
Basically, using a transaction means it's an all-or-none deal. No halfways, no maybes. Let's suppose
you're modifying a database, and you have to add 100 new items, one at a time. Before adding each item,
however, you have to check to make sure it fits certain criteria - if it doesn't, then your database
cries, you receive an error, and the process quits. It may not be desirable to quit halfway - for whatever
reason, you either want all the new rows or none of them.
Enter transactions. If you put the process in a transaction, and if an error occurs, the transaction
will "roll back" to a state just before you started your process. Thus, if any of the new items doesn't
meet the criteria, none of items gets added, instead of only the first few.
The classic example is a banking application. Suppose someone wants to transfer funds from one account to
another. You would deduct x amount from account A, and then add it to account B. Suppose after you have
deducted the money from account A (and before you add it to account B), you notice a problem (perhaps
account B has restrictions, or is not available for some reason). If the application just quits here with
some error message, then account A will be in an incorrect state, meaning it has funds missing. These
funds are not in account B yet, so they are just floating off in cyberspace, and you have one very unhappy
customer. With transactions, should you encounter this error, the process will roll back to a previous
state, and the money will automatically go back to where it started. If there are no problems, however,
the transaction will commit, and everything will go through.
Another example more apropos to web development is user registration. Suppose a user comes to your
community building web site and decides to register. Once they submit their information, you have to enter
it into a database, and also set up their personal web page. Thus, every user in the database must have a
personal web page as well, or no one will ever know that they are there. Your ASP script adds the user
into the database perfectly, but a server error causes your web page building routine to fail
unexpectedly. You now have a floating user - a user in the database, but without a web page. If this
process were transactional, you could roll back to just before you inserted the user into the database
(thereby eliminating the floating user problem), and gracefully display a nice error message to the user.
Pretty slick, huh?
So How Does it Help Me?
It's always got to be about "me," doesn't it? Well, if you didn't gather it from above, transactions are
mainly used for error handling. They stop you from getting in weird positions that you can't get out of by
easily allowing you to 'undo' the changes you've made. As you develop more and more complex web
applications, the need for strong state protection will become increasingly necessary.
What is MTS?
MTS is Microsoft's answer to transactions. We won't go into too much detail here, but MTS is the engine
that keeps track of object states, and rolls them back or commits them when necessary. Even though it
won't be apparent in your ASPs, MTS is working busily behind the scenes to keep track of what you're
doing.
MTS requires all objects that use transactions to be registered in MTS. IIS itself has many different
components that process web applications that are all registered with MTS, which is why ASPs can run
transactionally through MTS, invisible to the user (and sometimes to the developer). So just trust us when
we say you need MTS.
NOTE: Though MTS is installed with Windows NT, it usually is not set up to run automatically. Therefore,
before running any of the examples below, make sure the MTS service (MSDTC) is running (in the services
control panel).
The Basics
So what does transaction ASP code look like? The answer is, exactly like regular ASP code. We must simply
add a one line directive to the beginning code to get it to behave properly:
<%@ TRANSACTION = value %>
Where value can be any one of the following:
Requires_New
The script will always start a new transaction.
Required
The script will use a transaction, and will participate in any open transaction, or create a new one if
none are open.
Supported
The script will use any open transaction but will not start a new one if none are currently open.
Not_Supported
The script will neither initiate nor participate in a transaction.
Typically, each ASP page will be its own transaction, however, it is possible to continue transactions
across more than one page by using the Server.Transfer and Server.Execute methods (new to IIS 5). If the
calling page is transacted, and the current page uses "Transaction = Required" or "Transaction =
Supported" then the current page will continue the existing transaction, which makes some very complex
applications possible.
Now you simply write ASP code as you would normally, and things will work transactionally.
Committing and Rolling Back
There are two ways to commit a transaction (meaning that everything is okee-dokee and there are no errors
in the process). The first (and more simple) method is to do this inline with your code. Let's take a
look:
<%@ TRANSACTION = Required %>
<%
If Request.Form("submit") = "Accept" then
ObjectContext.SetComplete
Response.write("Operation completed successfully")
End if
%>
Use the ObjectContext.SetComplete method to tell MTS that this process is ready to be committed, and no
roll backs are required. You can then do whatever you want after you know the transaction is committed
(for instance, transfer funds in the bank scenario, or simply alert the user). This method is easy to use
since you can do this anywhere in the code you wish - you can use it as a simple error checking procedure.
To roll back the transaction, you use the ObjectContext.SetAbort method:
<%
If Request.Form("submit") = "Decline" then
ObjectContext.SetAbort
Response.write("Operation was unsuccessful")
End if
%>
This tells MTS that there were errors, and we need to roll back to the previous state. Calling
ObjectContext.SetAbort rolls back any data that has changed, and then you can perform any tasks necessary
(such as displaying an error message to the user).
The second method to commit changes is a bit more complex, but offers you much more functionality. Here we
use transaction events to perform the functions.
<%@ TRANSACTION = Required %>
<%
strText = Request.form("Textbox")
if strText = "" then
ObjectContext.SetAbort
Response.write("You did not enter the text<p>")
else
Response.write("Processing transaction...<p>")
end if
%>
<%
'commit and rollback code
sub OnTransactionCommit()
Response.write("Operation was successful")
End Sub
sub OnTransactionAbort()
Response.write("Operation was unsuccessful")
End Sub
%>
In this scenario, we've moved the commit and abort functions out of the inline code to separate
procedures. Our script runs normally in the first script block. In the second script block, we create the
sub procedures OnTransactionCommit and OnTransactionAbort. These two procedures tell the application what
to do if the transaction is successful or unsuccessful.
Note that the only way to let the application know the transaction is unsuccessful is by calling the
ObjectContext.SetAbort method as outlined above. Unless you explicitly call this method somewhere in the
code, MTS will always think the transaction is successful, and therefore execute the code in
OnTransactionCommit. For example, if your code completes its execution, and no SetAbort method has been
called, OnTransactionCommit will run. On the other hand, as soon as you call SetAbort, the code execution
stops, the process rolls back, and then OnTransactionAbort runs.
In the following code, even though the application should err out when the variable strText is empty, MTS
thinks this is successful, and will always execute OnTransactionCommit. This can have dire consequences in
a real world situation, so don't forget to tell the application where to stop in case of an error!
<%@ TRANSACTION = value %>
<%
strText = Request.form("Textbox")
if strText = "" then
Response.write("You did not enter the text.<p>")
else
Response.write("Processing transaction...<p>")
end if
%>
<%
'commit and rollback code
sub OnTransactionCommit()
Response.write("Operation was successful")
End Sub
sub OnTransactionAbort()
Response.write("Operation was unsuccessful")
End Sub
%>
NOTE: It is not necessary to separate code blocks as I've shown above. The examples are done in this way
simply for clarity's sake. You can combine the @Transaction directive and all other code in one <%...%>
script block.
We have done very simple examples here, but these can easily be expanded to very complex code. It is
simple even to modify existing code to take part in transactions simply by adding the @Transactions
directive and making sure to properly use SetAbort and build the transaction events OnTransactionCommit
and OnTransactionAbort.
COM Objects and MTS
Many times you will want to use transactions with custom built components, or COM objects, in your ASPs.
In the bank scenario, for example, it would probably be a good idea to encapsulate the business logic of
transferring the funds in a separate COM object for security, flexibility, and architecture reasons.
When using COM objects with transactions, you can either build the transaction logic into the component,
or keep it in the ASP. For example, if your COM object has a method called TransferFunds, then you can
either build in error checking and call SetAbort in the TransferFunds method itself, or keep that code in
the ASP script as we've done above (just remember to put it somewhere). This decision is not crucial,
though it is necessary (and will depend on the overall architecture of your web application).
In order for a COM object to work transactionally, you must register it with MTS. The Microsoft
Transaction Server keeps track of all components on your system that can participate in transactions, and
tells each component how to do so (i.e. required, requires_new, support, or not_supported). If you do not
register your component, it may function normally, but will not be able to work transactionally, and may
also produce errors when asked to do so.
Conclusion
By using transactions in ASP, you are opening up a whole new world of professional functionality.
Transactions make your applications stronger, and can ease development pains. The best part is that they
are simple to use once you've learned the basics.
Happy scripting!