怎样在打包程序中自动安装SQL Server数据库?[转贴,加注]

1、创建安装项目“Setup1”安装项目

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

在“添加新项目”对话框中,选择“项目类型”窗格中的“安装和部署项目”,然后选择“模板”窗格中的“安装项目”。在“名称”框中键入 “setup1”。

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

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

在“属性”窗口中,选择 ProductName 属性,并键入”亿万电器成套报价系统”。

 

2、在安装项目中创建安装程序类(install.cs)。[注解:这个类不能在安装项目下创建,应该在解决方案里添加新建类库项目,以下几个脚本文件也放在此项目中]

添加创建数据库(InstallDatabase.txt)、删除数据库(DropDatabase.txt)、初始化数据基本数据(InitializeData.txt)脚本文件,将属性“生成操作”设为“嵌入的资源”。代码如下:[需要添加引用System.Windows,另外代码中用到的加密类,在文后提供,放在这个类库项目中]

using System;

using System.Collections;

using System.ComponentModel;

using System.Configuration.Install;

using System.Data;

using System.Data.SqlClient;

using System.IO;

using System.Reflection;

using System.Text.RegularExpressions;

using System.Windows.Forms;

using System.Text;

using Microsoft.Win32;

 

namespace install

{

     /// <summary>

     /// Installer 的摘要说明。

     /// </summary>

     [RunInstaller(true)]

     public class Installer : System.Configuration.Install.Installer

     {

         /// <summary>

         /// 必需的设计器变量。

         /// </summary>

         string conStr="packet size=4096;integrated security=SSPI;"+

              "data source=""(local)"";persist security info=False;"+

              "initial catalog=master;connect timeout=300";

         RijndaelCryptography rijndael = new RijndaelCryptography();

         private System.ComponentModel.Container components = null;

 

         public Installer()

         {

              // 该调用是设计器所必需的。

              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

 

         #region 重载自定义安装方法

         protected override void OnBeforeInstall(IDictionary savedState)

         {

              base.OnBeforeInstall (savedState);

         }

         public override void Install(IDictionary stateSaver)

         {

              base.Install (stateSaver);

              string databaseServer = Context.Parameters["server"].ToString();

              string userName = Context.Parameters["user"].ToString();

              string userPass = Context.Parameters["pwd"].ToString();

              string targetdir = this.Context.Parameters["targetdir"].ToString();

        

              conStr = GetLogin(databaseServer,userName,userPass,"master");

              SqlConnection sqlCon = new SqlConnection();

 

              try

              {

                  

                   sqlCon.ConnectionString = conStr;

                   sqlCon.Open();

 

                   rijndael.GenKey();

                   rijndael.Encrypt(conStr);

 

                   stateSaver.Add("key",rijndael.Key);

                   stateSaver.Add("IV",rijndael.IV);

                   stateSaver.Add("conStr",rijndael.Encrypted);

             

                   ExecuteSql(sqlCon,"InstallDatabase.txt");

                   ExecuteSql(sqlCon,"InitializeData.txt");

    

                   if(sqlCon.State!=ConnectionState.Closed)sqlCon.Close();

              }

              catch(SqlException)

              {

                   MessageBox.Show("安装失败!"n数据库配置有误,请正确配置信息!","错误",MessageBoxButtons.OK,MessageBoxIcon.Error);

                   if(sqlCon.State!=ConnectionState.Closed) sqlCon.Close();

                   this.Rollback(stateSaver);

              }

 

         }

         protected override void OnAfterInstall(IDictionary savedState)

         {

              base.OnAfterInstall(savedState);

         }

 

         public override void Rollback(IDictionary savedState)

         {

              base.Rollback (savedState);

         }

         public override void Uninstall(IDictionary savedState)

         {

              base.Uninstall (savedState);

              if(savedState.Contains("conStr"))

              {

                   string targetdir = this.Context.Parameters["targetdir"].ToString();

                   RijndaelCryptography rijndael = new RijndaelCryptography();

                   rijndael.Key = (byte[])savedState["key"];

                   rijndael.IV = (byte[])savedState["IV"];

                   conStr = rijndael.Decrypt((byte[])savedState["conStr"]);    

                   SqlConnection sqlCon = new SqlConnection(conStr);

                   ExecuteDrop(sqlCon);

              }

         }

         #endregion

 

         #region 数据操作方法

         //从资源文件获取中数据执行脚本

private static string GetScript(string name)

         {

              Assembly asm = Assembly.GetExecutingAssembly();

              Stream str = asm.GetManifestResourceStream(asm.GetName().Name+ "." + name);

              StreamReader reader = new StreamReader(str,System.Text.Encoding.Default);

              System.Text.StringBuilder output = new System.Text.StringBuilder();

              string line = "";

              while((line = reader.ReadLine())!=null)

              {

                   output.Append(line + ""n");

              }

              return output.ToString();

 

         }

         //获取数据库登录连接字符串

         private static string GetLogin(string databaseServer,string userName,string userPass,string database)

         {

              return "server=" + databaseServer + ";database="+database+";User ID=" + userName + ";Password=" + userPass +";connect timeout=300;";

         }

         //执行数据库脚本方法

         private static void ExecuteSql(SqlConnection sqlCon,string sqlfile)

         {

              string[] SqlLine;

              Regex regex = new Regex("^GO",RegexOptions.IgnoreCase | RegexOptions.Multiline);

             

              string txtSQL = GetScript(sqlfile);

              SqlLine = regex.Split(txtSQL);

 

              if(sqlCon.State!=ConnectionState.Closed)sqlCon.Close();

              sqlCon.Open();

 

              SqlCommand cmd = sqlCon.CreateCommand();

              cmd.Connection = sqlCon;

 

              foreach(string line in SqlLine)

              {

                   if(line.Length>0)

                   {

                       cmd.CommandText = line;

                       cmd.CommandType = CommandType.Text;

                       try

                       {

                            cmd.ExecuteNonQuery();

                       }

                       catch(SqlException ex)

                       {

                            //rollback

                            string ss = ex.Message;

                            ExecuteDrop(sqlCon);

                            break;

                       }

                   }

              }

         }

         //删除数据库

         private static void ExecuteDrop(SqlConnection sqlCon)

         {   

              if(sqlCon.State!=ConnectionState.Closed)sqlCon.Close();

              sqlCon.Open();

              SqlCommand cmd = sqlCon.CreateCommand();

              cmd.Connection = sqlCon;

              cmd.CommandText = GetScript("DropDatabase.txt");

              cmd.CommandType = CommandType.Text;

              cmd.ExecuteNonQuery();

              sqlCon.Close();

         }

         #endregion

}

     单击“生成”菜单下“生成解决方案”,生成install.dll安装类文件。

3、将“主程序”项目的输出添加到部署项目中

     在“文件系统编辑器”中,选择“应用程序文件夹”,单击右键指向“添加”,添加“项目输出”。

     在“添加项目输出组”对话框中,选择“项目”下拉表框中选择你的主安装程序类,如上面的“install”。

     从列表框中选择“主输出”组,然后单击“确定”关闭。

4、创建自定义安装对话框

在解决方案资源管理器中选择安装项目“Setup1”项目,在“视图”菜单上指向“编辑器”,然后选择“用户界面”。

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

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

在“操作”菜单上,选择“上移”,重复此步骤,移到“安装文件夹”上。

     在“文本框(A)”上单击“属性窗口”,设置如下图所示:

    

5、建自定义操作

在解决方案资源管理器中选择安装项目“Setup1”项目,在“视图”菜单上指向“编辑器”,然后选择“自定义操作”。

在“自定义操作编辑器”中选择“安装”节点。单击右键“添加自定义操作”,在选择项目中的项中选择“应用程序文件夹”,选择“主输出来自install(活动)”。

在“属性窗口”中选择“CustomActionData”属性并键入“/server=[EDITA1] /user=[EDITA2] /pwd=[EDITA3] /targetdir="[TARGETDIR]""”。

 

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

单击“生成”菜单下的“生成解决方案”,编译安装项目。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace install
{
    /// <summary>
    /// Simple Rijndael implementation
    /// </summary>
    internal class RijndaelCryptography
    {
        RijndaelManaged myRijndael;
        ASCIIEncoding textConverter;
        byte[] fromEncrypt;
        byte[] encrypted;
        byte[] toEncrypt;
        byte[] _key;
        byte[] _IV;

        internal byte[] Key
        {
            get { return _key; }
            set { _key = value; }
        }
        internal byte[] IV
        {
            get { return _IV; }
            set { _IV = value; }
        }
        internal byte[] Encrypted
        {
            get { return encrypted; }
        }

        internal RijndaelCryptography()
        {
            myRijndael = new RijndaelManaged();
            myRijndael.Mode = CipherMode.CBC;
            textConverter = new ASCIIEncoding();
        }

        internal virtual void GenKey()
        {
            //Create a new key and initialization vector.
            myRijndael.GenerateKey();
            myRijndael.GenerateIV();

            //Get the key and IV.
            _key = myRijndael.Key;
            _IV = myRijndael.IV;
        }

        internal void Encrypt(string TxtToEncrypt)
        {
            //Get an encryptor.
            ICryptoTransform encryptor = myRijndael.CreateEncryptor(_key, _IV);

            //Encrypt the data.
            MemoryStream msEncrypt = new MemoryStream();
            CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor,
                                                      CryptoStreamMode.Write);

            //Convert the data to a byte array.
            toEncrypt = textConverter.GetBytes(TxtToEncrypt);

            //Write all data to the crypto stream and flush it.
            csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
            csEncrypt.FlushFinalBlock();

            //Get encrypted array of bytes.
            encrypted = msEncrypt.ToArray();
        }

        internal string Decrypt(byte[] crypted)
        {
            //Get a decryptor.
            ICryptoTransform decryptor = myRijndael.CreateDecryptor(_key, _IV);

            //Decrypting the encrypted byte array.
            MemoryStream msDecrypt = new MemoryStream(crypted);
            CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor,
                                                      CryptoStreamMode.Read);

            fromEncrypt = new byte[crypted.Length];

            //Read the data out of the crypto stream.
            csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);

            //Convert the byte array into a string.
            return textConverter.GetString(fromEncrypt);


        }
    }

}

转载于:https://www.cnblogs.com/strun/archive/2009/09/19/1570168.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值