在.NET平台下,部署 Web 解决方案是比较方便的。我们可以利用Visual Studio.NET 2003添加一个WEB安装项目,在部署的“文件系统编辑器”中添加项目的主输出和内容文件,非常简易地完成安装程序的制作。
但是,这样制作的安装程序,只是将Web页和ASP.NET程序编译的DLL文件安装到目标机器的IIS目录,对于一般的应用程序是可以的(比如用Access数据库,可以一起打包到安装程序中);如果数据库是SQL SERVER,需要在部署的时候一并安装数据库,安装程序的制作就会复杂一些,需要我们自定义安装程序类。在安装程序类中执行SQL脚本并将连接字符串写入Web.config。
l 安装数据库
微软MSDN上介绍过在部署应用程序的时候建立数据库。如:
这种方法是创建一个安装程序类,在安装程序类中调用ADO.NET执行SQL 语句(SQL语句放在一个文本文件中)来创建数据库。
但是,这种方法有一个问题,如果用SQL Server2000生成了所有建表、视图、存储过程的一个脚本文件,用ADO.NET来执行这个脚本文件,就会因为脚本中有许多“GO”语句而出现错误。当然,我们可以把“GO”替换成换行符,利用ADO.NET一条条执行SQL 语句。很显然,这样的效率比较低。
最好的办法是调用osql执行脚本。(或者创建一个数据库项目的cmd文件,而cmd文件建立数据库的时候也是调用的osql)。
首先,我们新建一个ASP.NET Web应用程序,http://localhost/VbNetTest,并打开VbNetTest 项目
创建部署项目![](http://dev.csdn.net/Develop/ArticleImages/27/27814/CSDN_Dev_Image_2004-5-141330200.jpg)
![](http://dev.csdn.net/Develop/ArticleImages/27/27814/CSDN_Dev_Image_2004-5-141330202.jpg)
Imports System.ComponentModel
Imports System.Configuration.Install
Imports System.IO
Imports System.Reflection
<RunInstaller(True)> Public Class DBCustomAction
Inherits System.Configuration.Install.Installer
#Region "组件设计器生成的代码 "
Public Sub New()
MyBase.New()
'该调用是组件设计器所必需的
InitializeComponent()
'在 InitializeComponent() 调用之后添加任何初始化
End Sub
' Installer 重写 dispose 以清理组件列表。
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub
Private components As System.ComponentModel.IContainer
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
End Sub
#End Region
'执行SQL 语句
Private Sub ExecuteSql(ByVal conn As String, ByVal DatabaseName As String, ByVal Sql As String)
Dim mySqlConnection As New SqlClient.SqlConnection(conn)
Dim Command As New SqlClient.SqlCommand(Sql, mySqlConnection)
Command.Connection.Open()
Command.Connection.ChangeDatabase(DatabaseName)
Try
Command.ExecuteNonQuery()
Finally
'Close Connection
Command.Connection.Close()
End Try
End Sub
Public Overrides Sub Install(ByVal stateSaver As System.Collections.IDictionary)MyBase.Install(stateSaver)
' ------------------------建立数据库-------------------------------------------------
Try
Dim 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"))
'根据输入的数据库名称建立数据库
ExecuteSql(connStr, "master", "CREATE DATABASE " + Me.Context.Parameters.Item("dbname"))
'调用osql执行脚本
Dim sqlProcess As New System.Diagnostics.Process
sqlProcess.StartInfo.FileName = "osql.exe "
sqlProcess.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"))
sqlProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
sqlProcess.Start()
sqlProcess.WaitForExit() '等待执行
sqlProcess.Close()
'删除脚本文件
Dim sqlFileInfo As New System.IO.FileInfo(String.Format("{0}db.sql", Me.Context.Parameters.Item("targetdir")))
If sqlFileInfo.Exists Then
sqlFileInfo.Delete()
End If
Catch ex As Exception
Throw ex
End Try
' ---------------------将连接字符串写入Web.config-----------------------------------
Try
Dim FileInfo As System.IO.FileInfo = New System.IO.FileInfo(Me.Context.Parameters.Item("targetdir") & "/web.config")
If Not FileInfo.Exists Then
Throw New InstallException("没有找到配置文件")
End If
'实例化XML文档
Dim XmlDocument As New System.Xml.XmlDocument
XmlDocument.Load(FileInfo.FullName)
'查找到appSettings中的节点
Dim Node As System.Xml.XmlNode
Dim FoundIt As Boolean = False
For Each Node In XmlDocument.Item("configuration").Item("appSettings")
If Node.Name = "add" Then
If Node.Attributes.GetNamedItem("key").Value = "connString" Then
'写入连接字符串
Node.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", _
Me.Context.Parameters.Item("server"), Me.Context.Parameters.Item("dbname"), Me.Context.Parameters.Item("user"), Me.Context.Parameters.Item("pwd"))
FoundIt = True
End If
End If
Next Node
If Not FoundIt Then
Throw New InstallException("web.Config 文件没有包含connString连接字符串设置")
End If
XmlDocument.Save(FileInfo.FullName)
Catch ex As Exception
Throw ex
End Try
End Sub
End Class
最后编译生成!![](http://dev.csdn.net/Develop/ArticleImages/27/27814/CSDN_Dev_Image_2004-5-141330204.jpg)
![](http://dev.csdn.net/Develop/ArticleImages/27/27814/CSDN_Dev_Image_2004-5-141330206.jpg)
![](http://dev.csdn.net/Develop/ArticleImages/27/27814/CSDN_Dev_Image_2004-5-141330208.jpg)
![](http://dev.csdn.net/Develop/ArticleImages/27/27814/CSDN_Dev_Image_2004-5-1413302010.jpg)
![](http://dev.csdn.net/Develop/ArticleImages/27/27814/CSDN_Dev_Image_2004-5-1413302012.jpg)
我已经能成功地安装了。c#代码:
我把"主输出来自DBCustomAction(活动)项"的CustomActionData属性中的targetdir="[TARGETDIR]/"改为了targetdir=[TARGETDIR]
using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration.Install;
using System.IO;
using System.Reflection;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Xml;
namespace DBCustomAction
{
[RunInstaller(true)]
public class DBCustomAction : System.Configuration.Install.Installer
{
private System.ComponentModel.Container components = null;
//execute sql
private void ExecuteSql(string conn,string DatabaseName,string Sql)
{
SqlConnection myConnection=new SqlConnection(conn);
SqlCommand myCommand=new SqlCommand(Sql,myConnection);
myConnection.Open();
try
{
myCommand.ExecuteNonQuery();
}
finally
{
myConnection.Close();
}
}
//create database
public override void Install(System.Collections.IDictionary stateSaver)
{
try
{
string connStr=String.Format("data source={0};user id={1};password={2};persist security info=false;packet size=4096",Context.Parameters["server"],Context.Parameters["user"],Context.Parameters["pwd"]);
//create database following the db name
ExecuteSql(connStr,Context.Parameters["dbname"],"CREATE DATABASE "+Context.Parameters["dbname"]);
System.Diagnostics.Process sqlProcess=new System.Diagnostics.Process();
sqlProcess.StartInfo.FileName="osql.exe";
sqlProcess.StartInfo.Arguments=String.Format("-U {0} -P {1} -d {2} -i {3}ecomm.sql",Context.Parameters["user"],Context.Parameters["pwd"],Context.Parameters["dbname"],Context.Parameters["targetdir"]);
sqlProcess.StartInfo.WindowStyle=ProcessWindowStyle.Hidden;
sqlProcess.Start();
sqlProcess.WaitForExit();
sqlProcess.Close();
}
catch (Exception ex)
{
throw ex;
}
//write the connstring into the Web.Config
try
{
FileInfo myFileInfo=new FileInfo(Context.Parameters["targetdir"]+"/"+"Web.config");
if (!myFileInfo.Exists)
{
throw new InstallException("No find the web.config");
}
XmlDocument myXmlDocument=new XmlDocument();
myXmlDocument.Load(myFileInfo.FullName);
//search the appSetting Node
bool FoundIt;
FoundIt=false;
foreach (XmlNode myNode in myXmlDocument["configuration"]["appSettings"])
{
if (myNode.Name=="add")
{
if (myNode.Attributes.GetNamedItem("key").Value=="ConnectionString")
{
myNode.Attributes.GetNamedItem("value").Value=String.Format("server={0};database={1};uid={2};pwd={3}",Context.Parameters["server"],Context.Parameters["dbname"],Context.Parameters["user"],Context.Parameters["pwd"]);
FoundIt=true;
}
}
}
if(FoundIt==false)
{
throw new InstallException("web.Config not inculding connString");
}
myXmlDocument.Save(myFileInfo.FullName);
}
catch(Exception ex)
{
throw ex;
}
}
}
}