📄 installer.cs
字号:
using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration.Install;
using System.IO;
using System.Xml;
using System.Security.Permissions;
namespace myInstall
{
/// <summary>
/// Installer 的摘要说明。
/// </summary>
[RunInstaller(true)]
public class Installer : System.Configuration.Install.Installer
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;
private string ScriptPath=@"c:\oi\database\";//数据库脚本的路径
//private string TARGETDIR;//虚拟目录名称
private bool IsInstallDB;
private string DBName;//数据库名称
private string Machine;//数据库服务器实例名称
private string UserID;//登录ID
private string Password;//密码
public Installer()
{
// 该调用是设计器所必需的。
InitializeComponent();
// TODO: 在 InitializeComponent 调用后添加任何初始化
}
private void GetParameters()
{
//this.TARGETDIR=this.Context.Parameters["TARGETDIR"];//目标安装地址,比如c:\inetpub\wwwroot\OI
this.DBName=this.Context.Parameters["DBName"];//目标数据库名称
this.Machine=this.Context.Parameters["Machine"];//目标服务器
this.UserID=this.Context.Parameters["UserID"];//数据库用户名
this.Password=this.Context.Parameters["Password"];//数据库密码
this.IsInstallDB=this.Context.IsParameterTrue("IsInstallDB");//
}
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
/// <summary>
/// 安装
/// </summary>
/// <param name="stateSaver"></param>
public override void Install(IDictionary stateSaver)
{
base.Install (stateSaver);
GetParameters();
//开始安装数据库
if(IsInstallDB)
{
this.IntallDatabase();
}
else
{
System.Windows.Forms.MessageBox.Show("如果没有安装数据库可能无法运行本系统");
}
WriteWebConfig();//配置web.config文件
ConfigFileAccessPower();
}
/// <summary>
/// 设置安装目录下的upfile目录为
/// </summary>
private void ConfigFileAccessPower() {
string ds=@"C:\Inetpub\wwwroot\OI\UpFile";
FileIOPermission file=new FileIOPermission(FileIOPermissionAccess.Write,ds);
file.AllFiles=FileIOPermissionAccess.AllAccess;
file.AllLocalFiles=FileIOPermissionAccess.AllAccess;
}
/// <summary>
/// 配置web.config文件,只能识别装在C:\Inetpub\wwwroot\OI\目录的情况。
/// </summary>
private void WriteWebConfig()
{
string WebConfigPath=@"C:\Inetpub\wwwroot\OI\Web.Config";
if(!System.IO.File.Exists(WebConfigPath)){
throw new Exception("系统找不到Web.Config文件");
}
else{
XmlDocument doc=new XmlDocument();
doc.Load(WebConfigPath);
XmlNode Nodeed;
Nodeed=doc.SelectSingleNode ("//add[@key='conn']");
Nodeed.Attributes ["value"].Value="server="+Machine+";uid="+UserID+";pwd="+Password+";database="+DBName;
doc.Save(WebConfigPath);
}
}
/// <summary>
/// 回滚
/// </summary>
/// <param name="savedState"></param>
public override void Rollback(IDictionary savedState)
{
base.Rollback (savedState);
}
/// <summary>
/// 提交
/// </summary>
/// <param name="savedState"></param>
public override void Commit(IDictionary savedState)
{
base.Commit (savedState);
}
/// <summary>
/// 卸载
/// </summary>
/// <param name="savedState"></param>
public override void Uninstall(IDictionary savedState)
{
base.Uninstall (savedState);
}
/// <summary>
/// 安装数据库
/// </summary>
private void IntallDatabase()
{
//终止数据库进程
string sql="declare @spid int ,@c varchar(100) \r\n"+
"declare getspid cursor for \r\n"+
"select spid from sysprocesses where dbid=db_id('{0}') \r\n"+
"open getspid \r\n"+
"fetch next from getspid into @spid \r\n"+
"while @@fetch_status=0 \r\n"+
"begin \r\n"+
" select @c='kill '+ convert(varchar(50),@spid) \r\n "+
" exec(@c) \r\n"+
" fetch next from getspid into @spid \r\n"+
"end \r\n"+
"close getspid \r\n"+
"deallocate getspid ";
sql=string.Format(sql,this.DBName);
this.RunCommand(sql);
//删除数据库
sql="IF EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = N'{0}')\r\n"+
"DROP DATABASE [{0}]";
sql=string.Format(sql,this.DBName);
this.RunCommand(sql);
//建立数据库
sql="CREATE DATABASE [{0}] COLLATE Chinese_PRC_CI_AS\r\n";
sql=string.Format(sql,this.DBName);
this.RunCommand(sql);
//添加登录帐号
sql="if not exists (select * from master.dbo.syslogins where loginname = N'{0}')\r\n"+
"BEGIN\r\n"+
"declare @logindb nvarchar(132), @loginlang nvarchar(132) select @logindb = N'{0}', @loginlang = N'简体中文'\r\n"+
"if @logindb is null or not exists (select * from master.dbo.sysdatabases where name = @logindb)\r\n"+
" select @logindb = N'master'\r\n"+
"if @loginlang is null or (not exists (select * from master.dbo.syslanguages where name = @loginlang) and @loginlang <> N'us_english')\r\n"+
" select @loginlang = @@language\r\n"+
"exec sp_addlogin N'{0}', null, @logindb, @loginlang\r\n"+
"END";
sql=string.Format(sql,this.DBName);
this.RunCommand(sql);
//为数据库添加安全帐户
sql="if not exists (select * from dbo.sysusers where name = N'{0}' and uid < 16382)\r\n"+
"EXEC sp_grantdbaccess N'{0}', N'{0}'";
sql=string.Format(sql,this.DBName);
this.RunCommand(sql);
//为安全帐户添加角色
sql="exec sp_addrolemember N'db_owner', N'{0}'";
sql=string.Format(sql,this.DBName);
this.RunCommand(sql);
//运行批处理命令以建立数据库对象和复制数据
// System.IO.DirectoryInfo oDirectoryInfo=new System.IO.DirectoryInfo(this.GetType().Assembly.Location);
//string ProgramFilesPath=System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFiles);
//if(ProgramFilesPath.Substring(ProgramFilesPath.Length-1,1)!="\\")
// ProgramFilesPath+="\\";
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo();
string fullname=this.ScriptPath+"setup.bat";//将安装包全部拷贝到c:\目录下再执行
if(!System.IO.File.Exists(fullname))
throw new System.Exception("安装时需要的文件"+fullname+"不存在");
psi.WorkingDirectory=this.ScriptPath;
psi.FileName = fullname;
psi.Arguments=" \""+this.DBName+"\" \""+this.Machine+"\" \""+this.UserID+"\" \""+this.Password+"\"";
psi.CreateNoWindow=false;
psi.UseShellExecute=true; //msi文件,如是exe不用设
System.Diagnostics.Process.Start(psi);//开始安装
}
/// <summary>
/// 获取数据库连接
/// </summary>
/// <returns></returns>
private System.Data.SqlClient.SqlConnection GetConn()
{
string connString="Server={0};uid={1};pwd={2};Database={3};";
connString=string.Format(connString,this.Machine,this.UserID,this.Password,"master");
System.Data.SqlClient.SqlConnection conn;
conn=new System.Data.SqlClient.SqlConnection(connString);
return conn;
}
/// <summary>
/// 运行sql数组脚本
/// </summary>
/// <param name="sql"></param>
private void RunCommand(string[] sql)
{
System.Data.SqlClient.SqlCommand oSqlCommand;
System.Data.SqlClient.SqlConnection conn=this.GetConn();
oSqlCommand=new System.Data.SqlClient.SqlCommand();
oSqlCommand.Connection=conn;
if(conn.State!=System.Data.ConnectionState.Open)
conn.Open();
System.Data.SqlClient.SqlTransaction trans=conn.BeginTransaction();
oSqlCommand.Transaction=trans;
try
{
foreach(string c in sql)
{
oSqlCommand.CommandText=c;
oSqlCommand.ExecuteNonQuery();
}
trans.Commit();
}
catch(System.Data.SqlClient.SqlException e)
{
trans.Rollback();
this.Context.LogMessage("执行数据库脚本出错:\r\n"+sql+"\r\n"+e.Message);
throw new SystemException( e+"\r\n"+sql.ToString());
}
finally
{
if(conn.State==System.Data.ConnectionState.Open)
conn.Close();
}
}
/// <summary>
/// 运行sql脚本
/// </summary>
/// <param name="sql"></param>
private void RunCommand(string sql)
{
System.Data.SqlClient.SqlCommand oSqlCommand;
System.Data.SqlClient.SqlConnection conn=this.GetConn();
oSqlCommand=new System.Data.SqlClient.SqlCommand(sql,conn);
if(conn.State!=System.Data.ConnectionState.Open)
conn.Open();
try
{
oSqlCommand.ExecuteNonQuery();
}
catch(System.Data.SqlClient.SqlException e)
{
this.Context.LogMessage("执行数据库脚本出错:\r\n"+sql+"\r\n"+e.Message);
throw new SystemException(e+"\r\n"+sql.ToString());
}
finally
{
if(conn.State==System.Data.ConnectionState.Open)
conn.Close();
}
}
#region 组件设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
this.BeforeInstall+=new InstallEventHandler(Installer_BeforeInstall);
}
#endregion
private void Installer_BeforeInstall(object sender, InstallEventArgs e)
{
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -