Prizes & Awards
My Profile
Active Members
TodayLast 7 Days
more...
|
Resources » Articles » .NET Framework »
.NET and COM+ (Part 2) - Creating Transactional Component
|
Introduction The first part of this article dealt with the basics of COM+ interoperability in .NET applications. In the next two parts of this article, you will learn how to create and use transactions controlled by COM+ in .NET windows application. Here, I am updating the “qtyonhand” column in the product table. After validating the quantity entered (it should be between 0 and 100) transaction is committed. If the user enters an invalid quantity, transaction is aborted. User can always retrieve the quantity on hand values at any time.
Transaction
A transaction is a set of operations that works as a single unit so that they should either be performed or not be performed. Whenever one of the operations in the transaction fails, all prior operations should rollback to ensure consistency
ContextUtil Class
The ContextUtil class is used to tell the system either to abort or complete the transaction. SetAbort() method in this class can be called anytime when you want to abort the transaction. Similary, SetComplete() method can be called to manually commit the transaction.
There are quite a few attributes that you need to accomplish this transactional process.
AutoCompleteAttribute - Enables automatic transactions applicable for a method. TransactionAttribute - Enables transactions applicable for a class.
COM+ is the underlying system that automates the transactions in .NET. A ServicedComponent is required to implement the above features for a .NET class to enroll in COM+ system.
The following sample application written in C# has two parts: client application and the COM+ component.
Testing the sample
The quantity on hand for a given product is read from the database and displayed. Now you enter a new quantity >0 and <100 in the 'New Quantity' box. Click on the button named “Update”. On clicking 'OK' the updated value for 'Current Quantity’ is displayed.
Now, you enter a number >100 in the 'New Quantity’ box. Click on the button named “Update”. On clicking 'OK' the original value for 'Current Quantity’ is displayed.
With the above values, click on the “Auto Update” button. It throws a COMException to notify the AutoComplete to do an abort.
Creating a Transactional component in COM+
using System; using System.Data; using System.Data.SqlClient; using System.Reflection; using System.Windows.Forms; using System.EnterpriseServices; using System.Runtime.InteropServices; using System.Runtime.Serialization;
// The following attribute specifies the name of the assembly that holds the component [assembly: ApplicationName("TransServer")]
// The following attribute specifies where assembly components are loaded on activation // Library: components run in the creator's process // Server: components run in a system process, dllhost.exe
[assembly: ApplicationActivation(ActivationOption.Library)]
// AssemblyKeyFile specifies the name of the strong key that isused to sign the assembly. // The .snk file is generated with sn.exe and is used when building from within VS. .NET
[assembly: AssemblyKeyFile("..\\..\\TransServer.snk")]
namespace TransServer {
// To host a class in COM+, include the following attributes // The transaction attribute enables us to do transactions within this class. // Requires creates a new transaction if there isn't one present already, The other option is // to take part in the existing transaction.
[Transaction(TransactionOption.Required)] public class TransServer : ServicedComponent { private SqlConnection Conn = new SqlConnection ("server=myserver;Trusted_Connection=yes;database=Purchase");
// Retrieve the current quantity on hand public int GetQtyOnHand(int prodid) { int qty = 0; try { Conn.Open(); SqlCommand Comm = new SqlCommand("select qtyonhand from product where productid = " + prodid.ToString(), Conn); SqlDataReader Drdr = Comm.ExecuteReader(); Drdr.Read(); qty = (int)Drdr["qtyonhand"]; Conn.Close(); } catch(Exception e) { CloseConnOnError(); MessageBox.Show(e.Message); } return qty ; } public void CloseConnOnError() { try { Conn.Close(); } catch { } }
If the invalid value is used, it throws an COMException so the [AutoComplete()] Attribute automatically does a rollback of the transaction. Note that this sample doesn’t include user defined exceptions which handle COMException. COM Exceptions can also be handled by providing SerializationInfo with the StreamingContext.
[AutoComplete] public void AutoUpdateQty(int newQty) { try { Conn.Open(); SqlCommand Comm = new SqlCommand(@" UPDATE product SET qtyonhand=@currentValue", Conn); Comm.Parameters.Add("@currentValue",SqlDbType.Int,4); Comm.Parameters["@currentValue"].Value = newQty; Comm.ExecuteNonQuery(); } catch(Exception e) { CloseConnOnError(); MessageBox.Show(e.Message ); } if (newQty<0 || newQty>100) { MessageBox.Show("Aborting the transaction because the new qty (" + newQty + ") is either <0 or >100"); } else { MessageBox.Show("Committing the transaction"); } try { Conn.Close(); } catch(Exception e) { MessageBox.Show(e.Message); } }
This method is similar to the above method except that it tries to update the qty in the database first, then it does validation, if it fails then calls ContextUtil.SetAbort to rollback the transaction.
public void UpdateQty(int newQty) { try { Conn.Open(); SqlCommand Comm = new SqlCommand(@" UPDATE product SET qtyonhand=@currentValue", Conn); Comm.Parameters.Add("@currentValue",SqlDbType.Int,4); Comm.Parameters["@currentValue"].Value = newQty; Comm.ExecuteNonQuery(); } catch(Exception e) { CloseConnOnError(); MessageBox.Show(e.Message ); } if (newQty<0 || newQty>100) { MessageBox.Show("Aborting the transaction because the new qty (" + newQty + ") is either <0 or >100"); } else { MessageBox.Show("Committing the transaction"); } try { Conn.Close(); } catch(Exception e) { MessageBox.Show(e.Message); } }
} }
Summary
The next part of the article would deal with developing a User Interface, which uses the above transactional component.
|
Responses
|
No responses found. Be the first to respond and make money from revenue sharing program.
|
|