C#打包SQL数据库部署安装

Posted on 2007-08-12 19:40  Semmy  阅读(1991)  评论(2编辑  收藏  举报
借鉴MSDN webcasts的Asp.net程序部署李洪根的一篇文章,然后加上自己的亲身体会,把整个SQL和Asp.net(vb.net)一起打包的全过程写一下。

一.准备必要的文件

1. SQL脚本文件,生成以后安装过程中需要的表和存储过程等等;

生成之后,就暂时把它命名为db.sql(注意大小写)

2.LisenceFile.rtf的安装文件,因为我的系统是个人的,而且free的,所以就没有做。这个以后也是要用到的。

二.在自己现有的项目里面创建部署项目:

1. 在“文件”菜单上指向“添加项目”,然后选择“新建项目”。(图1-2)

2. 在“添加新项目”对话框中,选择“项目类型”窗格中的“安装和部署项目”,然后选择“模板”窗格中的“Web 安装项目”。在“名称”框中键入 Test Installer。(图1-3)

3. 单击“确定”关闭对话框。

4. 项目被添加到解决方案资源管理器中,并且文件系统编辑器打开。

5. 在“属性”窗口中,选择 ProductName 属性,并键入 GCRM。

(1-2)

(图1-3)其他项目的作用可以参考Webcast

三。将 VbNetTest项目的输出添加到部署项目中(假如你的虚拟目录是SQLANDASPNet)

1. 在“文件系统编辑器”中,选择“Web 应用程序文件夹"。在“操作”菜单上,指向“添加”,然后选择“项目输出”。(图1-4)

2. 在“添加项目输出组”对话框中,选择“项目”下拉列表中的“SQLANDASPNet”。

3. 单击“确定”关闭对话框。

4. 从列表中选择“主输出”和“内容文件”组,然后单击“确定”。(图1-5)

 

(图1-4)

(图1-5)其他的作用可以参考webcast,源文件就是所有项目的的文件

四.

创建自定义安装对话框

1. 在解决方案资源管理器中选择“Test Installer”项目。在“视图”菜单上指向“编辑器”,然后选择“用户界面”。 (图1-6)

2. 在用户界面编辑器中,选择“安装”下的“启动”节点。在“操作”菜单上,选择“添加对话框”。

3. 在“添加对话框”对话框中,选择“许可协议”对话框,然后单击“确定”关闭对话框。 (注:我没有添加,因为暂时我还是不需要,需要的要添加一下哦)

4. 在“添加对话框”对话框中,选择“文本框 (A)”对话框,然后单击“确定”关闭对话框。 (图1-7)

5. 在“操作”菜单上,选择“上移”。重复此步骤,直到“文本框 (A)”对话框位于“安装文件夹”节点之上。

6. 在“属性”窗口中,选择 BannerText 属性并键入:安装数据库.。

7. 选择 BodyText 属性并键入:安装程序将在目标机器上安装数据库。

8. 选择 Edit1Label 属性并键入:数据库名称:。

9. 选择 Edit1Property 属性并键入 CUSTOMTEXTA1。

10. 选择 Edit1Value 属性并键入:GsCrm。

11. 选择 Edit2Label 属性并键入:服务器名:。

12. 选择 Edit2Property 属性并键入 CUSTOMTEXTA2。

13. 选择 Edit2Value 属性并键入:(local)。

14. 选择 Edit3Label 属性并键入:用户名:。

15. 选择 Edit3Value 属性并键入:sa。

16. 选择 Edit3Property 属性并键入 CUSTOMTEXTA3。

17. 选择 Edit4Label 属性并键入:密码:。

18. 选择 Edit4Property 属性并键入 CUSTOMTEXTA4。

19. 选择 Edit2Visible、Edit3Visible ,并将它们设置为 False。(图1-8)

(图1-7)

(图1-8)

(五).创建自定义操作

1. 在解决方案资源管理器中选择“Test Installer”项目。在“视图”菜单上指向“编辑器”,然后选择“自定义操作”。(图1-9)

2. 在自定义操作编辑器中选择“安装”节点。在“操作”菜单上,选择“添加自定义操作”。

3. 在“选择项目中的项”对话框中,双击“应用程序文件夹”。

4. 选择“主输出来自 DBCustomAction(活动)”项,然后单击“确定”关闭对话框。

5. 在“属性”窗口中,选择 CustomActionData 属性并键入 /dbname=[CUSTOMTEXTA1] /server=[CUSTOMTEXTA2] /user=[CUSTOMTEXTA3] /pwd=[CUSTOMTEXTA4] /targetdir="[TARGETDIR]\"。 (图1-10)

附/targetdir="[targetdir]\"是安装后的目标路径,为了在dbcustomaction类中获得安装后的路径,我们设置此参数。

另外,安装后的路径也可以通过Reflection得到:

Dim Asm As System.Reflection.Assembly = _

System.Reflection.Assembly.GetExecutingAssembly

MsgBox("Asm.Location")

(图1-9)

(图1-10)

呵呵,已经好多了,剩下来的是关键性步骤,我花了好多时间研究。

(六)创建安装程序类

1. 在“文件”菜单上指向“新建”,然后选择“项目”。

2. 在“新建项目”对话框中,选择“项目类型”窗格中的“Visual Basic 项目”,然后选择“模板”窗格中的“类库”。在“名称”框中键入 DBCustomAction。

3. 单击“打开”关闭对话框。

4. 从“项目”菜单中选择“添加新项”。

5. 在“添加新项”对话框中选择“安装程序类”。在“名称”框中键入 DBCustomAction。

6. 单击“确定”关闭对话框。(图1-11,1-12)

注:这里是在原来的项目上建立一个简单的安装文件就可以了。

(图1-11)

 添加后的效果图:

(图1-12)这里的sql文件是要等一下添加的

(七)

添加文件

1. 将SQL Server生成的脚本文件db.sql添加到“Test Installer”项目(图1-12)

2. 将安装文件LisenceFile.rtf添加到“Test Installer”项目

3. 在用户界面编辑器中,选择许可协议,设置LisenceFile属性为LisenceFile.rtf文件

(八)

一下的代码是整个部署的最重要的一部分了

将代码添加到安装程序类中,dbcustomaction.vb类

  1Imports System.ComponentModel

  2

  3imports System.Configuration.Install

  4

  5imports System.IO

  6

  7imports System.Reflection

  8

  9 

 10

 11<runinstaller(true)> Public Class DBCustomActionClass DBCustomAction

 12

 13inherits System.Configuration.Install.Installer

 14

 15 

 16

 17组件设计器生成的代码#region "组件设计器生成的代码 "

 18

 19public Sub New()Sub New()

 20

 21mybase.new()

 22

 23'该调用是组件设计器所必需的

 24

 25initializecomponent()

 26

 27'在 InitializeComponent() 调用之后添加任何初始化

 28

 29end Sub

 30

 31' Installer 重写 dispose 以清理组件列表。

 32

 33protected Overloads Overrides Sub Dispose()Sub Dispose(ByVal disposing As Boolean)

 34

 35if disposing Then

 36

 37if Not (components Is Nothing) Then

 38

 39components.dispose()

 40

 41end If

 42

 43end If

 44

 45mybase.dispose(disposing)

 46

 47end Sub

 48

 49private components As System.ComponentModel.IContainer

 50

 51<system.diagnostics.debuggerstepthrough()> Private Sub InitializeComponent()Sub InitializeComponent()

 52

 53end Sub

 54

 55#end Region

 56

 57'执行sql 语句

 58

 59private Sub ExecuteSql()Sub ExecuteSql(ByVal conn As String, ByVal DatabaseName As String, ByVal Sql As String)

 60

 61dim mySqlConnection As New SqlClient.SqlConnection(conn)

 62

 63dim Command As New SqlClient.SqlCommand(Sql, mySqlConnection)

 64

 65command.connection.open()

 66

 67command.connection.changedatabase(databasename)

 68

 69try

 70

 71command.executenonquery()

 72

 73finally

 74

 75'close Connection

 76

 77command.connection.close()

 78

 79end Try

 80

 81end Sub

 82

 83public Overrides Sub Install()Sub Install(ByVal stateSaver As System.Collections.IDictionary)

 84MyBase.Install(stateSaver)

 85

 86' ------------------------建立数据库-------------------------------------------------

 87

 88try

 89

 90dim connStr As String = String.Format("data source={0};user id={1};password={2};persist security info=false;packet size=4096", Me.Context.Parameters.Item("server"), Me.Context.Parameters.Item("user"), Me.Context.Parameters.Item("pwd"))

 91

 92'根据输入的数据库名称建立数据库

 93

 94executesql(connstr, "master", "CREATE DATABASE " + Me.Context.Parameters.Item("dbname"))

 95

 96'调用osql执行脚本

 97

 98dim sqlProcess As New System.Diagnostics.Process

 99

100sqlprocess.startinfo.filename = "osql.exe "

101

102sqlprocess.startinfo.arguments = String.Format(" -U {0} -P {1} -d {2} -i {3}db.sql", Me.Context.Parameters.Item("user"), Me.Context.Parameters.Item("pwd"), Me.Context.Parameters.Item("dbname"), Me.Context.Parameters.Item("targetdir"))

103

104sqlprocess.startinfo.windowstyle = ProcessWindowStyle.Hidden

105

106sqlprocess.start()

107

108sqlprocess.waitforexit() '等待执行

109

110sqlprocess.close()

111

112'删除脚本文件

113

114dim sqlFileInfo As New System.IO.FileInfo(String.Format("{0}db.sql", Me.Context.Parameters.Item("targetdir")))

115

116if sqlFileInfo.Exists Then

117

118sqlfileinfo.delete()

119

120end If

121

122catch ex As Exception

123

124throw ex

125

126end Try

127

128 

129

130' ---------------------将连接字符串写入Web.config-----------------------------------

131

132try

133

134dim FileInfo As System.IO.FileInfo = New System.IO.FileInfo(Me.Context.Parameters.Item("targetdir") & "\web.config")

135

136if Not FileInfo.Exists Then

137

138throw New InstallException("没有找到配置文件")

139

140end If

141

142'实例化xml文档

143

144dim XmlDocument As New System.Xml.XmlDocument

145

146xmldocument.load(fileinfo.fullname)

147

148 

149

150'查找到appsettings中的节点

151

152dim Node As System.Xml.XmlNode

153

154dim FoundIt As Boolean = False

155

156for Each Node In XmlDocument.Item("configuration").Item("appSettings")

157

158if Node.Name = "add" Then

159

160if Node.Attributes.GetNamedItem("key").Value = "connString" Then

161

162'写入连接字符串

163

164node.attributes.getnameditem("value").value = String.Format("Persist Security Info=False;Data Source={0};Initial Catalog={1};User ID={2};Password={3};Packet Size=4096;Pooling=true;Max Pool Size=100;Min Pool Size=1", _

165

166me.context.parameters.item("server"), Me.Context.Parameters.Item("dbname"), Me.Context.Parameters.Item("user"), Me.Context.Parameters.Item("pwd"))

167

168foundit = True

169

170end If

171

172end If

173

174next Node

175

176if Not FoundIt Then

177

178throw New InstallException("web.Config 文件没有包含connString连接字符串设置")

179

180end If

181

182xmldocument.save(fileinfo.fullname)

183

184catch ex As Exception

185

186throw ex

187

188end Try

189

190end Sub

191

192end Class

193

194

有点难度的就是那个Process类,它调用了osql.exe程序,来执行sql语句osql -U,-P,,-d,-i。

web.config的修改代码是利用xml的语法实现。不是很难理解。

最后编译生成!如图:

安装界面:如图

哈哈,总算写完了,也不知道有没有写好

最后还是感谢李洪根老师和微软的讲师。结合他们的共同的经验,部署起来真的很简单。

参考《ASP.NET与SQL一起打包部署安装》,这篇文章是针对VB.NET与SQL 一起打包的,但是我使用的是C#,当然只要修改一下主要安装类库就行了!C#的类库代码如下:DBCustomAction.cs

using System;
using System.Collections;
using System.Data.SqlClient;
using System.ComponentModel;
using System.Configuration.Install;
using System.Diagnostics;
using System.IO;
using System.Xml;
using System.Reflection;


namespace PMS
{
 /// <summary>
 /// DBCustomAction 的摘要说明。
 /// </summary>
 [RunInstaller(true)]
 public class DBCustomAction : System.Configuration.Install.Installer
 {
  /// <summary>
  /// 必需的设计器变量。
  /// </summary>
  private System.ComponentModel.Container components = null;

  public DBCustomAction()
  {
   // 该调用是设计器所必需的。
   InitializeComponent();

   // TODO: 在 InitializeComponent 调用后添加任何初始化
  }

  private void ExecuteSql(string conn,string DatabaseName,string Sql)
  {
   SqlConnection mySqlConnection=new SqlConnection(conn); 
   SqlCommand Command=new SqlCommand(Sql, mySqlConnection); 
   mySqlConnection.Open(); 
   mySqlConnection.ChangeDatabase(DatabaseName); 
   try
   {
    Command.ExecuteNonQuery();
   } 
   finally
   {
    //close Connection 
    mySqlConnection.Close();
   }
  }

  /// <summary>
  /// 清理所有正在使用的资源。
  /// </summary>
  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
    if(components != null)
    {
     components.Dispose();
    }
   }
   base.Dispose( disposing );
  }

  //

  public override void Install(System.Collections.IDictionary stateSaver)
  {
   base.Install(stateSaver);
 
   // ------------------------建立数据库-------------------------------------------------
 
   try
   {
    string connstr = String.Format("data source={0};user security info=false;packet size=4096", Context.Parameters["server"],Context.Parameters["user"], Context.Parameters["pwd"]);
    //'根据输入的数据库名称建立数据库 
    ExecuteSql(connstr, "master", "CREATE DATABASE " +Context.Parameters["dbname"]); 
    //'调用osql执行脚本 
    Process sqlprocess=new System.Diagnostics.Process();
    sqlprocess.StartInfo.FileName = "osql.exe "; 
    sqlprocess.StartInfo.Arguments = String.Format(" -U {0} -P {1} -d {2} -i {3}db.sql", Context.Parameters["user"], Context.Parameters["pwd"],Context.Parameters["dbname"],Context.Parameters["targetdir"]);
    sqlprocess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    sqlprocess.Start(); 
    sqlprocess.WaitForExit(); // '等待执行
    sqlprocess.Close();
 
    //'删除脚本文件
    FileInfo sqlfileinfo =new FileInfo(String.Format("{0}db.sql",Context.Parameters["targetdir"]));
 
    if (sqlfileinfo.Exists)
    {
     sqlfileinfo.Delete();
    }
   }
   catch(Exception ex)
   {
    throw ex; 
   }
 
   //' ---------------------将连接字符串写入Web.config-----------------------------------
  /*
   try
   {
    FileInfo fileinfo = new FileInfo(Context.Parameters["targetdir"] + "\\web.config");
    if (!fileinfo.Exists)
    {
     throw new InstallException("没有找到配置文件");
 
    }
 
    //'实例化xml文档
 
    XmlDocument xmldocument=new XmlDocument();
 
    xmldocument.Load(fileinfo.FullName);
 
  
 
    //'查找到appsettings中的节点
 
    //XmlNode node=new XmlNode();
 
    Boolean FoundIt  = false;
 
    foreach(XmlNode node in xmldocument.SelectSingleNode("appSettings").ChildNodes)
    { 
     if (node.Name == "add")
     { 
      if (node.Attributes.GetNamedItem("key").Value == "connString")
      {
       //'写入连接字符串
       node.Attributes.GetNamedItem("value").Value= String.Format("Persist Security Info=False;Data Source={0};Initial Catalog={1};User Size=4096;Pooling=true;Max Pool Size=100;Min Pool Size=1",Context.Parameters["server"],Context.Parameters["dbname"], Context.Parameters["user"], Context.Parameters["pwd"]);
       FoundIt= true; 
      } 
     } 
    }
 
    if (!FoundIt)
    { 
     throw new InstallException("web.Config 文件没有包含connString连接字符串设置");
    }  
    xmldocument.Save(fileinfo.FullName);
   }
   catch(Exception ex)
   {
    throw ex;
   }
   */        
  }

  #region 组件设计器生成的代码
                 /// <summary>
                 /// 设计器支持所需的方法 - 不要使用代码编辑器修改
                 /// 此方法的内容。
                 /// </summary>
                 private void InitializeComponent()
                 {
                  components = new System.ComponentModel.Container();
                 }
  #endregion
 }
}

我不需要修改Web.config的部分.
注意.如果不用SA用户登录数据库的,请先在服务器上建立特定的SQL用户

Copyright © 2024 Semmy
Powered by .NET 8.0 on Kubernetes