日期:2011-03-13  浏览次数:20420 次

以下演练演示在安装期间如何使用自定义操作和 CustomActionData 属性创建数据库和数据库表。
创建安装程序类
  1. 在“文件”菜单上指向“新建”,然后选择“项目”。
  2. 在“新建项目”对话框中,选择“项目类型”窗格中的“Visual Basic 项目”,然后选择“模板”窗格中的“类库”。在“名称”框中键入 DBCustomAction
  3. 从“项目”菜单中选择“添加新项”。
  4. 在“添加新项”对话框中选择“安装程序类”。在“名称”框中键入 DBCustomAction

创建数据连接对象
  1. 在“服务器资源管理器”中,选择“数据连接”。右击并选择“添加连接”。
  2. 在“数据链接属性”对话框中,输入对您的 SQL Server 配置有效的服务器名称、用户名和密码值。在“数据库”框中,键入 master。选中“允许保存密码”复选框。
  3. 将新连接拖到“DBCustomAction.vb”设计器中以创建“sqlConnection1 对象”。

创建包含 SQL 语句的文本文件以创建数据库
  1. 在“解决方案资源管理器”中,选择“DBCustomAction”项目。从“项目”菜单中选择“添加新项”。
  2. 在“添加新项”对话框中,选择“文本文件”。在“名称”框中,键入 sql.txt(必须是小写)。
  3. 将以下内容添加到 sql.txt 文件中:
    CREATE TABLE [dbo].[Employees] ([Name] [char] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,[Rsvp] [int] NULL ,[Requests] [nvarchar] (4000) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ) ON [PRIMARY];ALTER TABLE [dbo].[Employees] WITH NOCHECK ADD CONSTRAINT [PK_Employees] PRIMARY KEY CLUSTERED ([Name]) ON [PRIMARY];
  4. 在“解决方案资源管理器”中,选择“sql.txt”。在“属性”窗口中,将“生成操作”属性设置为“嵌入的资源”。

将代码添加到安装程序类中以阅读文本文件
  1. 在“解决方案资源管理器”中,选择“DBCustomAction.vb”。在“视图”菜单上,选择“代码”。
  2. 在模块的顶部添加以下 Imports 语句:
    Imports System.IOImports System.Reflection
  3. 将以下代码添加到类中:
    Private Function GetSql(ByVal Name As String) As String   Try      ' Get the current assembly.      Dim Asm As [Assembly] = [Assembly].GetExecutingAssembly()      ' Resources are named using a fully qualified name.      Dim strm As Stream = Asm.GetManifestResourceStream(Asm.GetName().Name + "." + Name)      ' Read the contents of the embedded file.      Dim reader As StreamReader = New StreamReader(strm)      Return reader.ReadToEnd()   Catch ex As Exception      MsgBox("In GetSQL: " & ex.Message)      Throw ex   End TryEnd FunctionPrivate Sub ExecuteSql(ByVal DatabaseName As String, ByVal Sql As String)   Dim Command As New SqlClient.SqlCommand(Sql, sqlConnection1)   Command.Connection.Open()   Command.Connection.ChangeDatabase(DatabaseName)   Try      Command.ExecuteNonQuery()   Finally      ' Finally, blocks are a great way to ensure that the connection       ' is always closed.      Command.Connection.Close()   End TryEnd SubProtected Sub AddDBTable(ByVal strDBName As String)   Try      ' Create the database.      ExecuteSql("master", "CREATE DATABASE " + strDBName)      ' Create the tables.      ExecuteSql(strDBName, GetSql("sql.txt"))   Catch ex As Exception       ' Report any errors and abort.       MsgBox("In exception handler: " & ex.Message)       Throw ex   End TryEnd SubPublic Overrides Sub Install(ByVal stateSaver As System.Collections.IDictionary)   MyBase.Install(stateSaver)   AddDBTable(Me.Context.Parameters.Item("dbname"))End Sub
  4. 在“生成”菜单上,选择“生成 DBCustomAction”。

创建部署项目
  1. 在“文件”菜单上,选择“添加项目”->“新建项目”。
  2. 在“添加项目”对话框中,选择“项目类型”窗格中的“安装和部署项目”,然后选择“模板”窗格中的“安装项目”。在“名称”框中,键入 DBCustomAction Installer
  3. 在“属性”窗口中,选择 ProductName 属性并键入 DB Installer
  4. 在文件系统编辑器中,选择“应用程序文件夹”。在“操作”菜单上,选择“添加”->“项目输出”。
  5. 在“添加项目输出组”对话框中,为“DBCustomAction”项目选择主输出。
  6. <