Creating Transactional Services


Imagine that you are creating a web service for a bank and you have several methods on that web service: transfer, Inquiry, and Deposit. In order to produce the most reliable web service possible, you need to make it so that if an error occurs during a transfer or a Deposit method call, the changes will be rolled back in order to avoid placing a customer's bank account in an inconsistent state. The Inquiry method doesn't need to have any transactional support because it is a read-only method, and an exception within that method call won't create inconsistent data.

The way transactional support is added to a web service method is through the transactionOption parameter to the WebMethod attribute. Listing 32.5 shows the three sample web methods discussed in the preceding paragraph, two of which have been set to use transactions.

Listing 32.5. transactional Web Services

[WebMethod(Description="Transfers money between accounts.",     TransactionOption=System.EnterpriseServices.TransactionOption.Required)] public void Transfer(string sourceAccount, string destAccount,     decimal amount) {     // transfer 'amount' from 'sourceAccount' to 'destAccount' } [WebMethod(Description="Inquires about a specific bank account's balance.")] public decimal Inquiry(string account) {     return 0.0m; } [WebMethod(Description="Deposits money into an account.",     TransactionOption=System.EnterpriseServices.TransactionOption.Required)] public void Deposit(string destAccount, decimal amount) {     // deposit 'amount' into 'destAccount' } 

The transactionOption enumeration tells the underlying transaction system how to handle transactions. In the preceding code, Required indicates that if a transaction already exists, it will be reused; otherwise, a new transaction will be created. The transaction system used to support transactional web services is found in the System.EnterpriseServices namespace, which is part of the COM+ system. COM+ and Enterprise Services are discussed in Chapter 40, "Using Enterprise Services."

If any of the transactional methods throw an exception, the current transaction will be rolled back and any changes will be lost. Keep in mind that only transaction-aware resources will roll back. This means that if your code makes changes to a disk file during the transactional method and an exception occurs and the transaction is rolled back, the disk file will still contain any changes made during the method call. Resources like SQL Server connections, Oracle connections, Microsoft Message Queues, and others are all aware of transactions and capable of rolling back changes.



Microsoft Visual C# 2005 Unleashed
Microsoft Visual C# 2005 Unleashed
ISBN: 0672327767
EAN: 2147483647
Year: 2004
Pages: 298

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net