using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Web.Configuration;
using System.Xml;
using System.Data;
using System.Data.SqlClient;
using SysDoor;

public partial class Root_DB_SetDB : System.Web.UI.Page
{

    string path = HttpContext.Current.Server.MapPath("~/App_Data/site.xml");
    protected void Page_Load(object sender, EventArgs e)
    {
        new RootControl().CheckRootLogin();
        if (!Page.IsPostBack)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(path);
            string db_ip = doc.GetElementsByTagName("db_ip")[0].InnerText;
            string db_user = doc.GetElementsByTagName("db_user")[0].InnerText;
            string db_pwd = doc.GetElementsByTagName("db_pwd")[0].InnerText;
            txt_db_ip.Text = db_ip;
            txt_db_user.Text = db_user;
            txt_db_pwd.Text = db_pwd;
            
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        XmlDocument doc = new XmlDocument();
        doc.Load(path);
        doc.GetElementsByTagName("db_ip").Item(0).InnerText = txt_db_ip.Text;
        doc.GetElementsByTagName("db_user").Item(0).InnerText = txt_db_user.Text;
        doc.GetElementsByTagName("db_pwd").Item(0).InnerText = txt_db_pwd.Text;
        doc.Save(path);
        lbl_msg.Text = "保存成功！";
    }
    protected void btnTest_Click(object sender, EventArgs e)
    {
        XmlDocument doc = new XmlDocument();
        doc.Load(path);
        string db_ip = doc.GetElementsByTagName("db_ip")[0].InnerText;
        string db_user = doc.GetElementsByTagName("db_user")[0].InnerText;
        string db_pwd = doc.GetElementsByTagName("db_pwd")[0].InnerText;
        string conn_string = "Data Source=[db_ip];Initial Catalog=master;User ID=[db_user];Password=[db_pwd]";
        conn_string = conn_string.Replace("[db_ip]", db_ip)
           .Replace("[db_user]", db_user)
           .Replace("[db_pwd]", db_pwd);
        SqlConnection conn = new SqlConnection(conn_string);
        string msg = "";
        try
        {
            conn.Open();
            conn.Close();
            msg = "数据库连接成功！";
        }
        catch (Exception err)
        {
            msg = "数据库连接失败！<br/><br/>具体原因:" + err.Message;
        }
        lbl_msg.Text = "";
        
        //string js = "<script type='text/javascript'>alert(\"" + msg + "\");</script>";
        lbl_msg.Text = msg;
    }
}