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
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.