本文实现的主要功能:
1、判断安装的数据库是否存在,如果存在会报错!
2、配置数据库链接。
3、生成开始菜单中的快捷方式。【感觉我的做法有点笨,呵呵!】
4、还原数据库,并设置mdf和ldf的路径!【感觉我的做法比网上公布的sql语句生成或微软提出的方法好些!】
5、动态生成dll文件,记录硬件信息。【其它地方使用同样获取方法,比较一下,就知道安装的程序是否被移植了,反盗啊,呵呵,当然这招不是很好用!】
using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration.Install;
using System.Xml;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.CodeDom;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Reflection;
using System.Management;
namespace DBCustomAction
{
/// <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 调用后添加任何初始化
}
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region 组件设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
/// <summary>
/// 安装程序
/// </summary>
///
private void ExecuteSql(string conn,string DatabaseName ,string Sql)
{
SqlConnection myConnection = new SqlConnection(conn);
SqlCommand myCommand = new SqlCommand(Sql,myConnection);
myCommand.Connection.Open();
myCommand.Connection.ChangeDatabase(DatabaseName);
try{myCommand.ExecuteNonQuery();}
finally{ myCommand.Connection.Close();}
}
public override void Install(IDictionary stateSaver)
{
base.Install (stateSaver);
//实例化XML文档
try
{
System.IO.FileInfo FileInfo =new System.IO.FileInfo(this.Context.Parameters["targetdir"] +"\\web.config");
if(!FileInfo.Exists)
throw new InstallException("没有找到配置文件");
XmlDocument XmlDoc = new XmlDocument();
XmlDoc.Load(FileInfo.FullName);
bool FoundIt=false;
foreach(XmlNode Node in XmlDoc.SelectSingleNode("/configuration/appSettings"))
{
if(Node.Attributes["key"].Value=="connString")
{
Node.Attributes["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", this.Context.Parameters["server"], this.Context.Parameters["dbname"], this.Context.Parameters["user"], this.Context.Parameters["pwd"]);
FoundIt = true;
}
}
if(!FoundIt)
throw new InstallException("web.Config 文件没有包含connString连接字符串设置");
XmlDoc.Save(FileInfo.FullName);
}
catch(Exception e)
{
throw new Exception("写入数据库连接串失败!"+e);
}
//实例化快捷方式文档
try
{
string sdir=this.Context.Parameters["targetdir"];
string FileInfo =sdir +"\\WebERP1.0.htm";
string adir="";
adir=sdir.Substring(0,sdir.Length-1);
adir=adir.Substring(adir.LastIndexOf('\\'),adir.Length-adir.LastIndexOf('\\'));
string htmltext="<html>" ;
htmltext+="<head>";
if(Convert.ToInt32(this.Context.Parameters["targetPort"])==80)
htmltext+="<meta http-equiv='Refresh' content='0;url=http://localhost/"+adir+"'>" ;
else
htmltext+="<meta http-equiv='Refresh' content='0;url=http://localhost:"+this.Context.Parameters["targetPort"]+"/"+adir+"'>";
htmltext+="</head>";
htmltext+="</html>";
StreamWriter stw = new StreamWriter(FileInfo,true,System.Text.Encoding.GetEncoding("GB2312"));
stw.Write(htmltext);
stw.Flush();
stw.Close();
}
catch(Exception e)
{
throw new Exception("写入快捷方式文档!"+e);
}
// 还原数据库
try
{
string sqlback="USE master"+ "\r\n" +
// "go"+ "\r\n" +
" RESTORE FILELISTONLY"+ "\r\n" +
" FROM DISK = '"+this.Context.Parameters["targetdir"]+"\\db.bak' "+ "\r\n" +
" RESTORE DATABASE "+this.Context.Parameters["dbname"]+ "\r\n" +
" FROM DISK = '"+this.Context.Parameters["targetdir"]+"\\db.bak' "+ "\r\n" +
" WITH REPLACE, "+ "\r\n" +
" MOVE 'webnews_data' TO '"+this.Context.Parameters["targetdir"]+this.Context.Parameters["dbname"]+"_data.mdf', "+ "\r\n" +
" MOVE 'webnews_log' TO '"+this.Context.Parameters["targetdir"]+this.Context.Parameters["dbname"]+"_log.ldf' "+ "\r\n"
// +"go "
;
string connstr= String.Format("server={0};uid={1};pwd={2};persist security info=false;packet size=4096",this.Context.Parameters["server"], this.Context.Parameters["user"], this.Context.Parameters["pwd"]);
ExecuteSql(connstr, "master", "CREATE DATABASE " + this.Context.Parameters["dbname"]);
ExecuteSql(connstr, "master", sqlback);
}
catch(Exception e)
{
throw new Exception("安装数据库失败!"+e);
}
}
protected override void OnAfterInstall(IDictionary savedState)
{
base.OnAfterInstall (savedState);
try
{
string sdir=this.Context.Parameters["targetdir"];
// string FileInfo =sdir +"\\WebERP.txt";
// string adir="";
// adir=sdir.Substring(0,sdir.Length-1);
// adir=adir.Substring(adir.LastIndexOf('\\'),adir.Length-adir.LastIndexOf('\\'));
// string text=GetValue(sdir).ToString();
GetValue(sdir);
File.Copy("Eval.dll",sdir+"bin\\Eval.dll",true);
File.Delete("Eval.dll");
// StreamWriter stw = new StreamWriter(FileInfo,true,System.Text.Encoding.GetEncoding("GB2312"));
// stw.Write(text);
// stw.Flush();
// stw.Close();
}
catch(Exception e)
{
throw new Exception("写入序列号失败!"+e);
}
}
static object GetValue(string sdir)
{
try
{
string codeSnippet = "using System; " + "\r\n" +
"using System.Management; " + "\r\n" +
"namespace WebApplication {" + "\r\n" +
" public class Eval" + "\r\n" +
" {" + "\r\n" +
" public Eval(){} " + "\r\n" +
" public object GetValue()" + "\r\n" +
" {" + "\r\n" +
" string strsn=\""+strGetSN().ToString()+"\";" + "\r\n" +
" return strsn ;" + "\r\n" +
" }" + "\r\n" +
" } }";
CodeSnippetCompileUnit unit = new CodeSnippetCompileUnit( codeSnippet );
ICodeCompiler compiler = new CSharpCodeProvider().CreateCompiler();
CompilerParameters para = new CompilerParameters();
para.ReferencedAssemblies.Add( "System.dll" );
para.ReferencedAssemblies.Add( "System.Management.dll" );
para.GenerateInMemory = true;
para.GenerateExecutable = false;
para.OutputAssembly = "Eval.dll";
Assembly asm = compiler.CompileAssemblyFromDom( para , unit ).CompiledAssembly;
Type type = asm.GetType( "WebApplication.Eval" );
MethodInfo mi = type.GetMethod( "GetValue" , BindingFlags.Public | BindingFlags.Instance );
object obj = asm.CreateInstance( "WebApplication.Eval" );
return mi.Invoke( obj , null );
}
catch(Exception e)
{
throw new Exception("获得序列号失败!"+e);
}
}
public static object strGetSN()
{
//获得硬盘序列号" + "\r\n" +
ManagementObjectSearcher cmicWmi=new System.Management.ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
string strHDSN= "";
foreach(ManagementObject cmicWmiObj in cmicWmi.Get())
{
strHDSN += cmicWmiObj["signature"];
}
//获得CPU序列号
ManagementObjectSearcher Wmi =new System.Management.ManagementObjectSearcher("SELECT * FROM Win32_Processor");
string strCPUSN="";
foreach(ManagementObject WmiObj in Wmi.Get())
{
strCPUSN += WmiObj["ProcessorId"];
}
//获取网卡序列号
string strMacSN = string.Empty;
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach(ManagementObject mo in moc)
{
if ((bool)mo["IPEnabled"] == true)
{
strMacSN += mo["MacAddress"].ToString();
}
}
return strHDSN + strCPUSN + strMacSN ;
}
}
}