Use COM to implement transaction control in C #
.NET technology is the next-generation platform technology that Microsoft vigorously promotes, since the official release of the .NET technology architecture beta2 version, this technology is gradually maturing and stabilizing. According to Microsoft's platform system, we are not difficult to imagine, in the next two years. NET technology must be trending the mainstream technical platform, and a new technical platform is the most important premise of rapid development is : He will not completely abandon the previous technology, this point is COM / COM technology for .NET technology.
In general, in the IT technology circle and hardware industry, the upgrade speed of technology is very amazing, and the practice is all new technologies to follow the principle of downward compatibility, but .NET technology not only did this, .NET or even Implementation of each call between each other, this is very difficult to be valuable. That is, not only we can call COM components in the .NET component, but also call the .NET component in the COM component. The benefits of this point are obvious, on the one hand, we can maintain existing technical resources, on the other hand, in the existing resources, can take advantage of the various new technologies brought by .NET.
The average database transaction control requires the operations in the transaction must be in the same database so that it can roll back (rllback) to the initial state when an error occurs. There is a problem. In distributed applications, we often need to operate multiple databases simultaneously, using the transaction processing of the database itself, is difficult to meet the requirements of transaction control. In COM , a complete service service is provided, we can use it to complete transaction control in distributed applications.
The specific process is as follows
One: Generate a class library with vs.net.
2: Add a reference to System.EnterPristServices, specific steps
Menu: (Project - Add Reference - Select System.EnterpristServices - OK) at the .NET tab.
Three: Build a class
1: Source program
Using system;
Using system.enterprises;
Using system.data.sqlclient;
Using system.reflection;
Namespace Complusamples
{
// Indicates that it is necessary to support
[Transaction (TransactionOption.Required)]
// Declare a server application, you can also choose Library, indicating that the library application
[assmbly: ApplicationActivation (ActivationOption.server)]
//Description
[Assembly: Description ("Sample")]]]
Public class txcfgclass: servicedcomponent
{
Private static string init1 = "User ID = sa; password =; initial catalog = pubs; data source = (local)"; "DATA SOURCE = (local)
Private static string init2 = "User ID = sa; password =; initial catalog = northwind; data source = (local)";
Private static string add1 = "INSERT INTO AUTHORS ('au_lname') VALUES ('Test1', 'Test2')"; Private Static String Add2 = "INSERT INTO SAMPLE VALUES ('TEST1', 22)"
// the error SQL Statement
// there is not table "sample"
Public txcfgclass () {}
Private void Execsql (String Init, String SQL)
{
SqlConnection Conn = New SqlConnection (Init);
Sqlcommand cmd = conn.createCommand ();
cmd.comMandText = SQL;
Cn.open ();
cmd.executenonquery ();
CONN.CLOSE ();
}
// Add a record to the database
Public void add ()
{
Try
{
// Insert a record in a database
Execsql (init1, add1);
Console.writeline ("The Operation In The Same Database Completely);
// Insert two records in another database
// This time it is an error SQL statement
Execsql (init2, add2);
Console.writeline ("The Operation in The Other Database
");
Console.writeline ("Record (s) added, press ...");
Console.read ();
}
Catch (Exception E)
{
// Transaction rollback
Contextutil.Setabort ();
Console.Writeline ("Because There Some Errors in The Operation, SO Transcation Abort);
Console.writeLine ("The Error IS" E.MESSAGE);
Console.writeline ("Abort successful");
Console.read ();
}
}
}
}
2: Program Description:
Add namespaces for system.EnterpriseServices; because this program uses the ContextUtil class
[Transaction (TransactionOption.Required)] Description DLL requires transaction support
The TXCFGClass class of this program is inherited from the ServicesDComponent class, which does not affect the class, but only two additional methods have been added in this class, these two methods can make code sharing easier
The SQL Server database used by the program is running, init1, and init2 are two connection strings for two connection databases, init connection PUBS database, ININ2 Connect the Northwind database, which is the sample database in SQL2000. Add1 and add2 are two SQL statements that add a record to a table of two databases, respectively. Note: Add2 is a wrong statement because there is no SAMPLE table at all, so that it will cause an exception when executed. (This is what we expect)
When executing to the add2 statement, since it is wrong, it will trigger an exception, and go to the error handling statement. ContextUtil.setabort (); This statement allows all databases to roll back so that the records inserted by the add1 statement will not exist. (To achieve the expected goal)
Four: Adding strong names to the program (strong name)
1: Create a pair of keys
Tools used to create a key are called Sn.exe sharing tools. It is usually run by command prompt, which can perform various tasks to generate and extract the key. We need to run sn.exe in the following ways.
Sn -k key.snk
The key.snk represents the name of the file that will save the key. Its name can be arbitrary, but it is accustomed to with a. SNK suffix name.
2: Signature
The signature is usually done at compile. When signing, the user can use the C # Properties to notify the compiler to sign the DLL using the correct key file. To do this user needs to open the AssemblyInfo.cs file in the project and modify it.
[assembly: assemblykeyKeyfile ("..//../ key.snk")]
Note: Key.snk files and project files in the same folder
5: Compile into DLL (specific steps)
Menu: (Generate - Generation)
If everything is normal, you will generate a DLL file.
Six: Register DLL to COM Services using regsvcs.exe
We need to run regsvcs.exe in the following ways
Regsvcs DLL file name
If everything is normal, Regsvcs.exe will enter the DLL into COM Services.
At this point, we have generated and registered this class that can be used by other programs. Now, let's write a console program to verify that this class is running normally.
7: Building a client
1: New console application project
Menu (file - new - project)
Select the console application and choose to add the solution, determine
2: Add the reference to System.EnterpriseServices as the above.
3: Add a reference to the class you just do just now.
Menu (Project - Add Reference - Browse), select the DLL you just generated, determine
4: Enter the following procedure
Using system;
USING COMPLUSSAMPLES;
Using system.enterprises;
Public Class Client
{
Public static void main ()
{
TXCFGCLASS CFG = New TxcfgClass ();
Cfg.Add ();
}
}
5: Set the console program to the startup item, then compile operation, you will see the result.
As we hope, the first record does not insert the database.