转自:http://blog.csdn.net/xiaohutu626/archive/2010/12/28/6102200.aspx
一).创建部署项目
1. 打开VS.NET。
2.在“文件”菜单上指向“新建项目”。
3. 在“新建项目”对话框中,选择“项目类型”窗格中的”其他项目类型”中的“安装和部署”,然后选择“模板”窗格中的“安装项目”。在“名称”框中键入 Setup1。
4. 单击“确定”关闭对话框。
5. 项目被添加到解决方案资源管理器中,并且文件系统编辑器打开。如下图所示:
6. 在“属性”窗口中,选择 ProductName 属性,并键入 数据库打包安装。
二).创建安装程序类
1. 在“解决方案资源管理器”中的”解决方Setup1”上右键选择”添加”后选择“新建项目”。
2. 在“添加新项目”对话框中,选择“项目类型”窗格中的“Visual C#”下的”Windows”,然后选择“模板”窗格中的“类库”。在“名称”框中键入 InstallDB。
3. 单击“确定”关闭对话框。
4. 从“InstallDB”类库下右键选择”添加”中的”新建项”。
5. 在“添加新项”对话框中选择“安装程序类”。在“名称”框中键入 InstallDB。
6. 单击“添加”关闭对话框。
7. “InstallDB”安装程序类详细代码附后。
如下图所示:
三).创建自定义安装对话框
1. 在解决方案资源管理器中选择“setup1”项目。右键然后在“视图”菜单上选择“用户界面”。
2. 在用户界面编辑器中,选择“安装”下的“启动”节点选择“添加对话框”。
3 在“添加对话框”对话框中,选择“文本框 (A)”对话框,然后单击“确定”关闭对话框。
4. 在“文本框 (A)”右键菜单上,选择“上移”。重复此步骤,直到“文本框 (A)”对话框位于“安装文件夹”节点之上。
5 在“文本框 (A)”的“属性”窗口中,选择 BannerText 属性并键入:安装数据库。
6. 选择 BodyText 属性并键入:安装程序将在目标机器上安装数据库。
7. 选择 Edit1Label 属性并键入:数据库名称:
8 选择 Edit1Property 属性并键入 DBNAME
9. 选择 Edit1Value 属性并键入: budgetSysDB
10. 选择 Edit2Label 属性并键入:服务器名:
11. 选择 Edit2Property 属性并键入 SERVER
12. 选择 Edit2Value 属性并键入:(local)
13. 选择 Edit3Label 属性并键入:用户名:
13. 选择 Edit3Value 属性并键入:sa
15. 选择 Edit3Property 属性并键入 USER
16. 选择 Edit4Label 属性并键入:密码:
18. 选择 Edit4Property 属性并键入 PWD
19. 选择Edit2Visible 属性,设置为 false;选择Edit2Visible、Edit3Visible 和 Edit4Visible 属性,并将它们设置为 true
四).创建自定义操作
1. 在解决方案资源管理器中选择“setup1”项目,右键在“视图”菜单上选择“自定义操作”。
2. 在自定义操作编辑器中选择“安装”节点。右键选择“添加自定义操作”。
3. 在“选择项目中的项”对话框中,双击“应用程序文件夹”。
3.5 单击”添加输出”按钮选择”项目”中的”你的项目”,在下面框中选择”主输出”(此项一般为默认)+内容文件,然后单击“确定”关闭对话框。
4. 单击”添加输出”按钮选择”项目”中的” InstallDB”,在下面框中选择”主输出”(此项一般为默认),然后单击“确定”关闭对话框。
5. 在”主输出来自InstallDB(活动)的属性窗口中,选择 CustomActionData属性并键入:/dbname=[DBNAME] /server=[SERVER]/user=[USER]/pwd=[PWD]/targetdir="[TARGETDIR]/"。
附:/targetdir="[TARGETDIR]/"是安装后的目标路径,为了在installDB类中获得安装后的路径,我们设置此参数。
如下图所示:
五).添加数据库文件
1. 在解决方案资源管理器中选择“Setup1”项目,右键在“添加”选择“文件”。
2.把数据文件”sql”” 添加到” Setup1”。
六)InstallDB文件。
using System;
using System.Data.SqlClient;
using System.ComponentModel;
using System.Configuration.Install;
using System.Diagnostics;
using System.DirectoryServices;
using System.IO;
using System.Text;
using System.Xml;
namespace DBInstall
{
[RunInstaller(true)]
public partial class DBInstaller : System.Configuration.Install.Installer
{
private string strSitePort = string.Empty;
private string strDirectoryPath = string.Empty;
public DBInstaller()
{
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
{
mySqlConnection.Close();
}
}
public override void Install(System.Collections.IDictionary stateSaver)
{
base.Install(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"]);
string connsql = String.Format("Data Source={0};Initial Catalog=master;User ID={2};Password={3};Packet Size=4096;Pooling=true;Max Pool Size=100;Min Pool Size=1", Context.Parameters["server"], Context.Parameters["dbname"], Context.Parameters["user"], Context.Parameters["pwd"]);
//ExecuteSql(connsql, "COMINF", "select * from ");
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
SqlCommand mycmd = new SqlCommand("select * from sys.databases where name='" + Context.Parameters["dbname"] + "'", conn);
object n = mycmd.ExecuteScalar();
if (n != null)
{
}
else
{
//'根据输入的数据库名称建立数据库
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}BOICCDB.sql", Context.Parameters["user"], Context.Parameters["pwd"], Context.Parameters["dbname"], Context.Parameters["targetdir"]);
sqlprocess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
sqlprocess.Start();
sqlprocess.WaitForExit(); // '等待执行
sqlprocess.Close();
}
conn.Close();
//'删除脚本文件
FileInfo sqlfileinfo = new FileInfo(String.Format(Context.Parameters["targetdir"] + "BOICCDB.sql"));
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(Context.Parameters["targetdir"]);
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("configuration/connectionStrings").ChildNodes)
{
if (node.Name == "add")
{
if (node.Attributes.GetNamedItem("name").Value == "oaConn")
{
// '写入连接字符串
node.Attributes.GetNamedItem("connectionString").Value = String.Format("Data Source={0};Initial Catalog={1};User ID={2};Password={3};Packet 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;
}
//创建IIS网站
DirectoryEntry rootEntry = CreateNewSite("易成商标软件", Context.Parameters["targetdir"]);
}
/// <summary>
/// 获取新网站ID
/// </summary>
/// <returns></returns>
private string GetNewWebSiteID()
{
int iWebSiteCount = 0;
DirectoryEntry siteEntry = new DirectoryEntry("IIS://localhost/w3svc");
foreach (DirectoryEntry childEntry in siteEntry.Children)
{
if (childEntry.SchemaClassName == "IIsWebServer") iWebSiteCount++;
}
return (iWebSiteCount + 1).ToString();
}
/// <summary>
/// 获取新站点端口,默认为当前最大端口号加一
/// </summary>
/// <returns></returns>
private string GetNewSitePort()
{
int iDefault = 8000;
DirectoryEntry siteEntry = new DirectoryEntry("IIS://localhost/w3svc");
foreach (DirectoryEntry childEntry in siteEntry.Children)
{
if (childEntry.SchemaClassName == "IIsWebServer")
{
if (childEntry.Properties["ServerBindings"].Value != null)
{
string strSettings = childEntry.Properties["ServerBindings"].Value.ToString();
int iSettingPort = int.Parse(strSettings.Substring(strSettings.IndexOf(':') + 1, (strSettings.LastIndexOf(':') - strSettings.IndexOf(':') - 1)));
iDefault = iSettingPort > iDefault ? iSettingPort : iDefault;
}
}
}
return (iDefault + 1).ToString();
}
/// <summary>
/// 判断网站是否已经存在
/// </summary>
/// <param name="strSiteName"></param>
/// <returns></returns>
private bool IsExist(string strSiteName)
{
bool blExist = false;
DirectoryEntry siteEntry = new DirectoryEntry("IIS://localhost/w3svc");
foreach (DirectoryEntry childEntry in siteEntry.Children)
{
if (childEntry.SchemaClassName == "IIsWebServer")
{
if (childEntry.Properties["ServerComment"].Value != null)
{
if (childEntry.Properties["ServerComment"].Value.ToString() == strSiteName) blExist = true;
}
}
}
return blExist;
}
/// <summary>
/// 创建网站
/// </summary>
/// <param name="strPort"></param>
/// <param name="strSiteName"></param>
/// <param name="strFilePath"></param>
/// <returns></returns>
private DirectoryEntry CreateNewSite(string strSiteName, string strFilePath)
{
try
{
strSitePort = GetNewSitePort();
DirectoryEntry deyRoot = new DirectoryEntry("IIS://localhost/w3svc");
DirectoryEntry siteEntry = deyRoot.Children.Add(GetNewWebSiteID(), "IIsWebServer");
siteEntry.Properties["ServerComment"].Value = strSiteName;
siteEntry.Properties["ServerBindings"].Value = String.Format("{0}:{1}:{2}", "", strSitePort, "");
siteEntry.Properties["ServerAutoStart"].Value = true;
//添加虚拟目录,网站本身没有路径,默认的路径即名称为Root的虚拟目录
DirectoryEntry rootEntry = siteEntry.Children.Add("Root", "IIsWebVirtualDir");
rootEntry.Properties["Path"].Value = strFilePath; //文件夹路径
rootEntry.Properties["AppFriendlyName"][0] = "默认应用程序";//应用程序名称
rootEntry.Properties["AccessRead"][0] = true; //读取权限
rootEntry.Properties["AccessExecute"][0] = false; //执行(如ISAPI应用程序或CGI)
rootEntry.Properties["AccessWrite"][0] = true; //写入
rootEntry.Properties["AccessScript"][0] = true; //执行脚本(如ASP)
rootEntry.Properties["EnableDirBrowsing"][0] = true; //浏览
rootEntry.Properties["DefaultDoc"][0] = "UserLogin.aspx,Default.aspx"; //设置默认文档,多值情况下中间用逗号分割
rootEntry.CommitChanges(); siteEntry.CommitChanges(); return rootEntry;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 创建虚拟目录
/// </summary>
/// <param name="strDirName">虚拟目录名称</param>
/// <param name="strDirPath">虚拟目录路径</param>
/// <param name="siteEntry">要创建虚拟目录的原站点</param>
/// <returns></returns>
private bool CreateVirtualDirectory(string strDirName, string strDirPath, DirectoryEntry rootEntry)
{
try
{
DirectoryEntry childEntry = rootEntry.Children.Add(strDirName, "IIsWebVirtualDir");
childEntry.Invoke("AppCreate", true);
childEntry.Properties["Path"].Value = strDirPath; //文件夹路径
childEntry.Properties["AppFriendlyName"][0] = strDirName;//应用程序名称
childEntry.Properties["AccessRead"][0] = true; //读取权限
childEntry.Properties["AccessExecute"][0] = false; //执行(如ISAPI应用程序或CGI)
childEntry.Properties["AccessWrite"][0] = true; //写入
childEntry.Properties["AccessScript"][0] = true; //执行脚本(如ASP)
childEntry.Properties["EnableDirBrowsing"][0] = true; //浏览
childEntry.Properties["DefaultDoc"][0] = "login.aspx,Default.aspx"; 设置默认文档,多值情况下中间用逗号分割
childEntry.CommitChanges(); rootEntry.CommitChanges(); return true;
}
catch (Exception ex)
{
throw ex;
}
}
}
}