部署web项目

来源:互联网 发布:小蜜蜂网络兼职 编辑:程序博客网 时间:2024/05/16 00:32

using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration.Install;
using System.Reflection;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Text;
namespace install
{
    /// <summary>
    /// Installer1 的摘要说明。
    /// </summary>
    [RunInstaller(true)]
    public partial class Installer1 : System.Configuration.Install.Installer
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        //private System.ComponentModel.Container components = null;
        public Installer1()
        {
            // 该调用是设计器所必需的。
            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
        private string GetSql(string Name)
        {
            //   //调用osql执行脚本
            //
            //   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}db.sql", this.Context.Parameters["user"], this.Context.Parameters["pwd"],"master", this.Context.Parameters["targetdir"]);
            //
            //   sqlProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            //
            //   sqlProcess.Start();
            //
            //   sqlProcess.WaitForExit() ;//等待执行
            //
            //   sqlProcess.Close();
            try
            {
                //    Assembly Asm = Assembly.GetExecutingAssembly();
                //    System.IO.FileInfo FileInfo = new System.IO.FileInfo(Asm.Location);
                //    string path=FileInfo.DirectoryName+@"/"+Name;
                string path = this.Context.Parameters["targetdir"] + Name;
                FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
                StreamReader reader = new StreamReader(fs, System.Text.Encoding.Default);
                //System.Text.Encoding.ASCII;
                return reader.ReadToEnd();
            }
            catch (Exception ex)
            {
                Console.Write("In GetSql:" + ex.Message);
                throw ex;
            }
        }


            public static void ExecuteSqlInFile(string connectionString, string pathToScriptFile)
            {

                try
                {
                    StreamReader _reader = null;

                    string sql = "";

                    if (false == System.IO.File.Exists(pathToScriptFile))
                    {
                        throw new Exception("文件   " + pathToScriptFile + "   未找到");
                    }
                    Stream stream = System.IO.File.OpenRead(pathToScriptFile);
                    _reader = new StreamReader(stream);

                    SqlConnection connection = new SqlConnection(connectionString);
                    SqlCommand command = new SqlCommand();

                    connection.Open();
                    command.Connection = connection;
                    command.CommandType = System.Data.CommandType.Text;

                    while (null != (sql = ReadNextStatementFromStream(_reader)))
                    {
                        command.CommandText = sql;

                        command.ExecuteNonQuery();
                    }

                    _reader.Close();
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Trace.WriteLine("在文件:   " + pathToScriptFile + "   中产生异常。");
                    System.Diagnostics.Trace.WriteLine(ex.Message);
                    //MessageBox.Show("处理文件错误", "Error");
                }
            }

            private static string ReadNextStatementFromStream(StreamReader _reader)
            {

                StringBuilder sb = new StringBuilder();

                string lineOfText;

                while (true)
                {
                    lineOfText = _reader.ReadLine();

                    if (lineOfText == null)
                    {
                        if (sb.Length > 0)
                        {
                            return sb.ToString();
                        }
                        else
                        {
                            return null;
                        }
                    }

                    if (lineOfText.TrimEnd().ToUpper() == "GO")
                    {
                        break;
                    }

                    sb.AppendFormat("{0}/r/n", lineOfText);
                }

                return sb.ToString();
            }  

 

        private void ExecuteSql(string DataBaseName, string Sql)
        {
            SqlConnection sqlConnection1 = new SqlConnection();
            //sqlConnection1.ConnectionString = string.Format("server=cq; user id=aspuser; password=000000; Database=master", "cq", "aspuser", "000000");
            sqlConnection1.ConnectionString = string.Format("server={0}; user id={1}; password={2}; Database=master", this.Context.Parameters["server"], this.Context.Parameters["user"], this.Context.Parameters["pwd"]);
            System.Data.SqlClient.SqlCommand Command = new System.Data.SqlClient.SqlCommand(Sql, sqlConnection1);

            try
            {
                Command.Connection.Open();
                Command.Connection.ChangeDatabase(DataBaseName);

                Command.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                Console.Write("In exception handler :" + ex.Message);
            }
            finally
            {
                Command.Connection.Close();
            }
        }

        protected void AddDBTable(string strDBName)
        {
            string path = this.Context.Parameters["targetdir"] + "sql.txt";
            //string path = "E://cltest//ClassLibrar//sql.txt";
            try
            {
                ExecuteSql("master", "USE MASTER IF EXISTS (SELECT NAME FROM SYSDATABASES WHERE NAME='" + strDBName + "') DROP DATABASE " + strDBName);
                ExecuteSql("master", "CREATE DATABASE " + strDBName);
                ExecuteSqlInFile("server=" + this.Context.Parameters["server"] + "; user id=" + this.Context.Parameters["user"] + "; password=" + this.Context.Parameters["pwd"] + "; Database=" + strDBName + "", path);
              
                //ExecuteSql(strDBName, GetSql("sql.txt"));
                ExecuteSql("master", "exec sp_addlogin 'myoamaster','myoamaster','" + strDBName + "',Null,Null");
                ExecuteSql(strDBName, "EXEC sp_grantdbaccess 'myoamaster', 'myoamaster'");
                ExecuteSql(strDBName, "exec sp_addrolemember 'db_owner','myoamaster'");
            }
            catch (Exception ex)
            {
                Console.Write("In exception handler :" + ex.Message);
            }
        }
       // public override void Install(System.Collections.IDictionary stateSaver)
        public override void Install(System.Collections.IDictionary stateSaver)
        {
            base.Install(stateSaver);
            AddDBTable(this.Context.Parameters["dbname"]);
        } 

    }
}

 

 

 

 

 

 

 

 

 

//using System;
//using System.Collections.Generic;
//using System.ComponentModel;
//using System.Configuration.Install;
//using System.Data.SqlClient;
//using System.Diagnostics;
//using System.IO;
//using System.Xml;

//namespace ClassLibrary1
//{
//    [RunInstaller(true)]
//    public partial class Installer1 : Installer
//    {
//        public Installer1()
//        {
//            InitializeComponent();
//        }


//        public void ExecuteSql(string connectionString, string databaseName, string sql)
//        {
//            SqlConnection sqlConnection = new SqlConnection(connectionString);
//            SqlCommand sqlCommand = new SqlCommand(sql, sqlConnection);
//            try
//            {
//                sqlCommand.Connection.Open();
//                sqlCommand.Connection.ChangeDatabase(databaseName);
//                sqlCommand.ExecuteNonQuery();
//            }
//            catch (Exception exception)
//            {
//                throw exception;
//            }
//            finally
//            {
//                sqlCommand.Connection.Close();
//            }
//        }

//        public  void Install()
//        //public override void Install(System.Collections.IDictionary stateSaver)
//        {
//            string server = "cq";
//            string database = "dbname";
//            string user = "aspuser";
//            string password = "000000";
//            string targetDir = "C://Program Files//Microsoft SQL Server//80//Tools//Binn//";
//            //string server = this.Context.Parameters["server"];
//            //string database = this.Context.Parameters["dbname"];
//            //string user = this.Context.Parameters["user"];
//            //string password = this.Context.Parameters["pwd"];
//            //string targetDir = this.Context.Parameters["targetdir"];
//            try
//            {
//                string connectionString = String.Format("data source={0};user id={1};password={2};persist security info=false;packet size=4096",
//                server, user, password);

//                //create db
//                ExecuteSql(connectionString, "master", "CREATE DATABASE " + database);

//                //set user
//                string setUserString = "sp_addlogin 'PrinteryERP', 'PrinteryERP', 'PrinteryERP'";
//                string setAccessString = "sp_grantdbaccess 'PrinteryERP'";
//                string setRole = "sp_addrolemember 'db_owner', 'PrinteryERP'";
//                setRole = "sp_addrolemember 'db_datawrite', 'PrinteryERP'";
//                setRole = "sp_addrolemember 'db_datareader', 'PrinteryERP'";

//                //create new user login
//                //try
//                //{
//                //    ExecuteSql(connectionString, "master", setUserString);
//                //}
//                //catch { }

//                ////set default database
//                //try
//                //{
//                //    ExecuteSql(connectionString, "PrinteryERP", setAccessString);
//                //}
//                //catch { }

//                ////set read role
//                //try
//                //{
//                //    ExecuteSql(connectionString, "PrinteryERP", setRole);
//                //}
//                //catch { }

//                //create table,store produce......
//                Process osqlProcess = new Process();
//                osqlProcess.StartInfo.FileName = targetDir + "osql.exe";
//                osqlProcess.StartInfo.Arguments = String.Format(" -U {0} -P {1} -S {2} -d {3} -i {4}createdb.sql",
//                user, password, server, database, targetDir);
//                osqlProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
//                osqlProcess.Start();
//                osqlProcess.WaitForExit();
//                osqlProcess.Close();

//                //add data
//                osqlProcess.StartInfo.Arguments = String.Format(" -U {0} -P {1} -S {2} -d {3} -i {4}insertdata.sql",
//                user, password, server, database, targetDir);
//                osqlProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
//                osqlProcess.Start();
//                osqlProcess.WaitForExit();
//                osqlProcess.Close();
//            }
//            catch (Exception exception)
//            {
//                throw exception;
//            }

//            try
//            {
//                string configFile = targetDir + "Web.config";
//                if (!File.Exists(configFile))
//                {
//                    throw new InstallException("没有找到配置文件。");
//                }

//                XmlDocument xmlDoc = new XmlDocument();
//                xmlDoc.Load(configFile);

//                GC.Collect();
//                File.Delete(configFile);
//                GC.Collect();

//                foreach (XmlNode xmlNode in xmlDoc["configuration"]["connectionStrings"].ChildNodes)
//                {
//                    if (xmlNode.Name == "add")
//                    {
//                        if (xmlNode.Attributes["name"].Value == "DBConnection")
//                        {
//                            xmlNode.Attributes["connectionString"].Value = String.Format("Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID=PrinteryERP;Password=PrinteryERP",
//                            server, database);
//                        }
//                        if (xmlNode.Attributes["name"].Value == "UserManageServicesConnection")
//                        {
//                            xmlNode.Attributes["connectionString"].Value = String.Format("Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID=PrinteryERP;Password=PrinteryERP",
//                            server, database);
//                        }
//                    }
//                }
//                xmlDoc.Save(configFile);
//            }
//            catch (Exception exception)
//            {
//                throw exception;
//            }
//        }


//    }
//}