65.9K
CodeProject 正在变化。 阅读更多。
Home

.NET COM+ 事务

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.67/5 (8投票s)

2005 年 8 月 13 日

8分钟阅读

viewsIcon

37302

实现 .NET COM+ 事务

引言

      

                        .NET COM+ 事务

 

引言

 

大多数组件用于访问或检索数据库中的数据。这些组件最好通过事务来完成,以便利用 .Net 中内置的事务的优势。正如我们从 DBMS 概念中学到的那样,事务的优势总结为 ACID。A-原子性 (Atomicity)。C-一致性 (Consistency)。I-隔离性 (Isolation)。D-持久性 (Durability)。现在,我们不必担心 ACID。.Net 会处理这一切。

 

让我们看看创建 .Net COM+ 事务的步骤

 

  1. 使用内置的 .Net 事务对象。

 

  1. 使用 ApplicationName 属性,它将包含程序集组件。

 

  1. 使用 ApplicationActivation.ActivationOption 属性指定程序集组件在激活时加载的位置。

 

4.   使用 AssemblyKeyFile 指定将用于签名程序集的强名称密钥的名称。      

 

  1. 使用 Transaction.TransactionOption 属性指定类是否需要事务。

 

  1. 编写类的代码。(类名必须继承自 ServicedComponent 类。

 

  1. 使用 Serializable 属性以支持异常从 COM+ 传递到客户端时的序列化。

 

  1. 构建组件。

 

9. 从接口访问组件。

 

 

 

现在,让我们进入正题

 

  1. 使用内置的 .Net 事务对象。

 

using System;

using System.Data;

using System.Data.OleDb;

using System.Reflection;

using System.EnterpriseServices;  //使用组件时必须使用此项。

using System.Runtime.InteropServices; //此项用于组件互操作性。

using System.Runtime.Serialization;//此项用于序列化。

 

  1. 使用 ApplicationName 属性,它将包含程序集组件。

 

[assembly: ApplicationName("SRS")]

 

 

 

  1. 使用 ApplicationActivation.ActivationOption 属性指定程序集组件在激活时加载的位置。

 

            [assembly: ApplicationActivation(ActivationOption.Library)]

 

 

使用 AssemblyKeyFile 指定将用于签名程序集的强名称密钥的名称。

 

(sn.exe 已生成 .snk 文件)

注意:在 .net 命令提示符中使用,例如在同一个 Com+ 项目文件夹中

C:\SRS>sn –k SRS.snk

 

#if BuildBat  // 从命令行构建时使用

                        [assembly: AssemblyKeyFile("SRS.snk")]

#else        // 在 Visual Studio .NET 中构建时使用

[assembly: AssemblyKeyFile("SRS.snk")]

#endif

 

           

            在这里,您实际上拥有命名空间。创建项目时,.Net 会为您创建一个与项目同名的命名空间。例如,我们创建一个 SRS (学生注册系统),我们将拥有如下命名空间。

 

namespace SRS

{

 

}

 

 

注意:在命名空间内,我们编写所有代码,这些代码在步骤 5 和 6 中。

 

5.   使用 Transaction.TransactionOption 属性指定类是否需要事务。

 

[Transaction(TransactionOption.Required)]

 

 

6.   编写类的代码。(类名必须继承自 ServicedComponent 类。

 

 

public class Term : ServicedComponent

            {

// 此方法以 Dataset 的形式返回咨询学期列表

                        protected string ConnString;

                        protected OleDbConnection connection;

                        // 首先需要设置 SQLConnection。

                        public string ConnectionString                

                        {

                                    get

                                    {

                                                return ConnString;

                                    }

                                    set

                                    {

                                                ConnString = value;

                                    }

                        }

                        public OleDbConnection Connection                   

                        {

                                    get

                                    {

                                                if(ConnString==null)

                                                {

                                                            throw new ConnectionStringException();

                                                }

                                                if (connection== null)

                                                {

                                                            connection = new OleDbConnection(ConnString);

                                                }

                                                return connection;

                                    }

                        }

                        public void CloseDatabaseOnError()

                        {

                                    try

                                    {

                                                Connection.Close();

                                    }

                                    catch

                                    {

                                    }

                        }

public DataSet GetAdvisingTerms()

                        {

                                    DataSet termDS = new DataSet();

                                    try

                                    {                                  

                                                Connection.Open();

                                                OleDbCommand oledbCommand = new OleDbCommand();

                                                oledbCommand.Connection = Connection;

                                                oledbCommand.CommandType = CommandType.StoredProcedure;

                                                oledbCommand.CommandText = "Ssp_SRS_GetAdvisingTerms";

                                                OleDbDataAdapter termDA = new OleDbDataAdapter();

                                                termDA.SelectCommand = oledbCommand;

           

                                                termDA.Fill(termDS, "Ssp_SRS_GetAdvisingTerms");

                                                Connection.Close();

                                               

                                    }

                                    catch(Exception e)

                                    {

                                                CloseDatabaseOnError();

                                                throw new AdvisingTermNotReadException(e);

                                    }

                                    return termDS ;

                        }

 

 

}

 

注意:类必须声明为 public,以便您可以在任何需要使用它的地方调用它。

 

7. 使用 Serializable 属性以支持异常从 COM+ 传递到客户端时的序列化。

 

// AdvisingTermNotReadException 在读取数据库中的

            // 咨询学期时发生错误时出现。

            [Serializable]

            public class AdvisingTermNotReadException : Exception

            {

                        public AdvisingTermNotReadException(Exception ex)

                                    base("无法从数据库获取咨询学期。 "+ex.Message , ex)

                        {

                        }

 

                        public AdvisingTermNotReadException(SerializationInfo info,

                                    StreamingContext context) : base(info, context)

                        {

                        }

            }

 

  1. 构建组件。

创建一个 build.bat 文件并将其放在项目文件夹中。

build.bat 将包含以下内容

 

csc /target:library %DEBUGSAMPLE% /d:BuildBat /out:SRS.dll /r:System.EnterpriseServices.dll  /r:System.dll /r:System.Data.dll *.cs

 

regsvcs SRS.dll

gacutil -i SRS.dll

 

@echo.

@echo 要卸载 Transactions Sample,请运行 "build -u"

@echo.

 

@goto exit

 

:clean

gacutil /u SRS,PublicKeyToken=b7073b6138b34cac

regsvcs /u SRS.dll

 

:exit

 

转到“开始”菜单 > Microsoft Visual Studio .Net > Microsoft Studio .Net Tools > Visual Studio .NET Command Prompt。

 

                  转到项目所在的位置,然后,

使用 Build 命令构建组件。例如

c:\SRS>build

 

 现在您可以开始使用该组件了。

 

  1. 从接口访问组件。例如,从按钮或 Page_Load() 函数等。这通常是另一个项目在访问该组件。

 

      注意:不要忘记引用 dll 组件。

      执行此操作:右键单击“引用”>“浏览”> c:\SRS\SRS.dll

      SRS.dll 将加载到您的项目中。

      您也可以对 System.EnterpriseServices 做同样的操作。

 

            Using(SRS.Term _Term = new SIS.Term())

{

            DataSet DSTerm = new DataSet();

            DSTerm = _Term.GetAdvisingTerms()

 

                        //检索数据

                        int i;

                        i = DSTerm.Tables.Rows.Count;

                        while(i > 0)

                        {

Response.Write(DSTerm.Tables.Rows[i-1][“Term_Desc”].ToString());

                        }

}

 

 

本文使用的代码包含 3 个文件

 

   

1.   Term.cs

 

using System;

using System.Data;

using System.Data.OleDb;

using System.Reflection;

using System.EnterpriseServices;  //使用组件时必须使用此项。

using System.Runtime.InteropServices; //此项用于组件互操作性。

using System.Runtime.Serialization;//此项用于序列化。

 

[assembly: ApplicationName("SRS")]

[assembly: ApplicationActivation(ActivationOption.Library)]

 

#if BuildBat  // 从命令行构建时使用

[assembly: AssemblyKeyFile("SRS.snk")]

#else        // 在 Visual Studio .NET 中构建时使用

[assembly: AssemblyKeyFile("SRS.snk")]

#endif

 

namespace SRS

{

 

[Transaction(TransactionOption.Required)]

 

public class Term : ServicedComponent

     {

// 此方法以 Dataset 的形式返回咨询学期列表

           protected string ConnString;

           protected OleDbConnection connection;

           // 首先需要设置 SQLConnection。

           public string ConnectionString      

           {

                get

                {

                     return ConnString;

                }

                set

                {

                     ConnString = value;

                }

           }

           public OleDbConnection Connection         

           {

                get

                {

                     if(ConnString==null)

                     {

                           throw new ConnectionStringException();

                     }

                     if (connection== null)

                     {

                           connection = new OleDbConnection(ConnString);

                     }

                     return connection;

                }

           }

           public void CloseDatabaseOnError()

           {

                try

                {

                     Connection.Close();

                }

                catch

                {

                }

           }

public DataSet GetAdvisingTerms()

           {

                DataSet termDS = new DataSet();

                try

                {              

                     Connection.Open();

                     OleDbCommand oledbCommand = new OleDbCommand();

                     oledbCommand.Connection = Connection;

                     oledbCommand.CommandType = CommandType.StoredProcedure;

                     oledbCommand.CommandText = "Ssp_SRS_GetAdvisingTerms";

                     OleDbDataAdapter termDA = new OleDbDataAdapter();

                     termDA.SelectCommand = oledbCommand;

    

                     termDA.Fill(termDS, "Ssp_SRS_GetAdvisingTerms");

                     Connection.Close();

                    

                }

                catch(Exception e)

                {

                     CloseDatabaseOnError();

                     throw new AdvisingTermNotReadException(e);

                }

                return termDS ;

           }

 

 

}

 

 

// AdvisingTermNotReadException 在读取数据库中的

     // 从数据库读取咨询学期时发生错误。

     [Serializable]

     public class AdvisingTermNotReadException : Exception

     {

           public AdvisingTermNotReadException(Exception ex)

           base("无法从数据库获取咨询学期。 "+ex.Message , ex)

           {

           }

 

           public AdvisingTermNotReadException(SerializationInfo info,

                StreamingContext context) : base(info, context)

           {

           }

     }

}

 

 

 

2.               buid.bat

 

csc /target:library %DEBUGSAMPLE% /d:BuildBat /out:SRS.dll /r:System.EnterpriseServices.dll  /r:System.dll /r:System.Data.dll *.cs

 

regsvcs SRS.dll

gacutil -i SRS.dll

 

@echo.

@echo 要卸载 Transactions Sample,请运行 "build -u"

@echo.

 

@goto exit

 

:clean

gacutil /u SRS,PublicKeyToken=b7073b6138b34cac

regsvcs /u SRS.dll

 

:exit

 

 

3. frmTerm.cs 使用组件

 

 

private void Button_Click(

objectsender, System.EventArgs e

)

{

     Using(SRS.Term _Term = new SIS.Term())

{

     DataSet DSTerm = new DataSet();

     DSTerm = _Term.GetAdvisingTerms()

 

           //检索数据

           int i;

           i = DSTerm.Tables.Rows.Count;

           while(i > 0)

           {

Response.Write(DSTerm.Tables.Rows[i-1][“Term_Desc”].ToString());

           }

}

  }

 

参考:Microsoft .Net Help

© . All rights reserved.