<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Xml" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Text.RegularExpressions" %>

<script type="text/C#" runat="Server">
    public SqlConnection Conn;

    public void OpenConn()
    {
        if (this.Conn == null)
        {
            this.Conn = new SqlConnection(ConfigurationManager.AppSettings["Custmerconn"].ToString());
        }
        if (this.Conn.State == ConnectionState.Closed)
        {
            this.Conn.Open();
        }
    }

    public void CloseConn()
    {
        if (this.Conn != null)
        {
            this.Conn.Close();
        }
    }

    public bool ExecSql(string strSql)
    {
        this.OpenConn();
        SqlCommand Cmd = new SqlCommand(strSql, Conn);
        try
        {
            Cmd.ExecuteNonQuery();
            return true;
        }
        catch
        {
            return false;
        }
        finally
        {
            Cmd.Dispose();
            this.CloseConn();
        }
    }
    
    protected override void OnInit(EventArgs e)
    {
        Response.Buffer = false;
        Response.ContentType = "text/html";
        Response.Charset = "gb2312";
        if (Request["step"] == "1")
        {
            SetWebConfig();
        }
        else if (Request["step"] == "2")
        {
            CreateSqlServerDataBase();
        }
        else if (Request["step"] == "3")
        {
            SetDefaultUser();
        }
        else if (Request["step"] == "4")
        {
            RenameAppCodeFiles();
        }
        else if (Request["step"] == "5")
        {
            RemoveUnusefulFiles();
        }
        Response.Write("{'result' : 1, 'url' : '" + Request.QueryString.ToString() + "'}");
    }

    private bool SetWebConfig()
    {
        string connstring = "server=" + Request.Form["server"] + ";database=" + Request.Form["dbname"] + ";user id=" + Request.Form["uid"] + ";pwd=" + Request.Form["pwd"] + ";";
        string file = Server.MapPath("~/Web.config");
        XmlDocument xml = new XmlDocument();
        xml.Load(file);
        XmlNodeList xnodes = xml.DocumentElement.ChildNodes;
        foreach (XmlElement xelement in xnodes)
        {
            if (xelement.Name.ToLower() == "appsettings")
            {
                XmlNodeList nodes = xelement.ChildNodes;
                foreach (XmlNode node in nodes)
                {
                    if (node.GetType() == typeof(XmlElement))
                    {
                        XmlElement element = (XmlElement)node;
                        if (element.Attributes["key"].InnerXml == "Custmerconn")
                        {
                            element.Attributes["value"].Value = connstring;
                        }
                    }
                }
            }
        }
        xml.Save(file);
        return true;
    }
    
    private bool CreateSqlServerDataBase()
    {
        string sqlfile = Server.MapPath("~/install/mssql.sql");
        using (StreamReader reader = new StreamReader(sqlfile, System.Text.Encoding.GetEncoding("GB2312")))
        {
            string[] arr = reader.ReadToEnd().Split((char)10);
            foreach (string sql in arr)
            {
                this.ExecSql(sql);
            }
            return true;
        }
        return true;
    }
    
    private void SetDefaultUser()
    {
        string name = Request.Form["adminname"].Trim();
        string pass = Request.Form["adminpass"].Trim();
        this.ExecSql("Update UserAdmin Set UserName='" + name + "',UserPwd='" + pass + "',EndTime='" + DateTime.Now.ToString() + "' Where Id = 1000001");
    }

    private void RenameAppCodeFiles()
    {
        //Directory.Move(Server.MapPath("~/install/App_Code"), Server.MapPath("~/App_Code"));
        //File.Move(Server.MapPath("~/install/Global.asax"), Server.MapPath("~/Global.asax"));
        //File.Move(Server.MapPath("~/install/licence.html"), Server.MapPath("~/licence.html"));
        //File.Move(Server.MapPath("~/install/mssql.sql"), Server.MapPath("~/App_Data/mssql.sql"));
    }
    
    private void RemoveUnusefulFiles()
    {
        //Directory.Delete(Server.MapPath("~/install"), true);
    }
</script>

