.NET技術(shù)登上主流技術(shù)平臺
.NET有很多值得學(xué)習(xí)的地方,這里我們主要介紹.NET技術(shù),包括介紹COM/COM+技術(shù)等方面。
.NET技術(shù)是微軟大力推廣的下一代平臺技術(shù),自從.NET技術(shù)架構(gòu)Beta2版本的正式發(fā)布,此項技術(shù)也逐漸走向成熟和穩(wěn)定。按照微軟的平臺系統(tǒng)占有率,我們不難想象得到,在未來的一兩年內(nèi).NET技術(shù)必定會勢如破竹一般的登上主流的技術(shù)平臺,而一個新的技術(shù)平臺得以快速發(fā)展的最重要的前提是:他不會徹底的摒棄以前的技術(shù),這一點對于.NET技術(shù)來說指的就是COM/COM+技術(shù)了。
一般來說,在IT技術(shù)界以及硬件產(chǎn)業(yè),技術(shù)的更新?lián)Q代速度非常得驚人,而慣例是所有的新技術(shù)都會遵循向下兼容的原則,但是.NET技術(shù)不僅僅做到了這一點,.NET甚至實現(xiàn)了相互之間的各自調(diào)用,這一點是非常難能可貴的。也就是說,不但我們可以在.NET組件中調(diào)用COM組件,同時也可以在COM組件中正常的調(diào)用.NET組件。這點帶來的好處是顯而易見的,一方面我們可以保持現(xiàn)有的技術(shù)資源,另一方面,在現(xiàn)有資源中可以利用.NET所帶來的各種新技術(shù)。
一般的數(shù)據(jù)庫事務(wù)控制要求事務(wù)里所做的操作必須在同一個數(shù)據(jù)庫內(nèi),這樣在出現(xiàn)錯誤的時候才能回滾(RllBack)到初始狀態(tài)。這就存在一個問題,在分布式應(yīng)用程序中,我們往往需要同時操作多個數(shù)據(jù)庫,使用數(shù)據(jù)庫本身的事務(wù)處理,很難滿足程序?qū)κ聞?wù)控制的要求。在COM+中,提供了完整的事務(wù)服務(wù),我們可以利用它來完成在分布式應(yīng)用程序中的事務(wù)控制。
具體過程如下
一:用VS.NET生成一個類庫
二:添加對System.EnterpristServices的引用,具體步驟
菜單:(項目-添加引用-在.NET選項卡選擇System.EnterpristServices-確定)
三:構(gòu)建類
- using System;
- using System.EnterpriseServices;
- using System.Data.SqlClient;
- using System.Reflection;
- namespace COMPlusSamples
- {
- //表明需要事務(wù)支持[ Transaction(TransactionOption.Required) ]
- //聲明為服務(wù)器應(yīng)用程序,還可以選擇Library,表示為庫應(yīng)用程序
- [assembly: ApplicationActivation(ActivationOption.Server)]
- //描述信息
- [assembly: Description("sample")]
- public class TxCfgClass : ServicedComponent
- {
- private static string init1 = "user id=sa;password=;
initial catalog=pubs;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','au_fname') 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;
- conn.Open();
- cmd.ExecuteNonQuery();
- conn.Close();
- }
- //添加一條記錄到數(shù)據(jù)庫
- public void Add()
- {
- try
- {
- //在一數(shù)據(jù)庫中插入一條記錄
- ExecSQL(init1, add1);
- Console.WriteLine("the operation in the same database completely");
- //在另外一個數(shù)據(jù)庫中插入兩條記錄
- //這次執(zhí)行的是一個錯誤的SQL語句
- ExecSQL(init2, add2);
- Console.WriteLine("the operation in the other database
- completely");
- Console.WriteLine("Record(s) added, press enter...");
- Console.Read();
- }
- catch(Exception e)
- {
- //事務(wù)回滾
- ContextUtil.SetAbort();
- Console.WriteLine("Because there are some errors
in the operation ,so transcation abort");- Console.WriteLine("The error is " + e.Message);
- Console.WriteLine("abort successfully");
- Console.Read();
- }
- }
- }
- }
【編輯推薦】