using System;
using System.IO;
using System.Web.UI;

namespace FineUIPro.Web.common.SysManage
{
    public partial class DataBackup : PageBase
    {
        /// <summary>
        /// 数据库名称
        /// </summary>
        public string DataName
        {
            get
            {
                return (string)ViewState["DataName"];
            }
            set
            {
                ViewState["DataName"] = value;
            }
        }

        public string FilePath
        {
            get
            {
                return (string)ViewState["FilePath"];
            }
            set
            {
                ViewState["FilePath"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                this.LbtnDownLoad.Hidden = true;
                string str = BLL.Funs.ConnString;
                string[] group = str.Split(';');

                foreach (string s in group)
                {
                    if (s.Contains("Database"))
                    {
                        string[] bak = s.Split('=');
                        DataName = bak[1];
                    }
                }
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (BLL.CommonService.GetAllButtonPowerList(this.CurrUser.UserId, BLL.Const.DataBakMenuId, BLL.Const.BtnDataBak))
            {
                string newname = DataName + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + ".bak";
                
                string nepath = Server.MapPath("../App_Data/") + newname;
                FilePath = "App_Data\\" + newname;
                string sql = "BACKUP DATABASE " + DataName + " to DISK ='" + nepath + "'";
                try
                {
                    //if (!File.Exists(nepath))
                    //{
                        BLL.SQLHelper.ExecutSql(sql);
                    //}
                }
                catch (Exception ex)
                {
                    ScriptManager.RegisterStartupScript(this, typeof(string), "_alert", "alert('Database Backup Fail. Possible Reason:" + ex.Message.ToString() + "')", true);
                }

                string path = "../App_Data/" + newname;
                this.LbtnDownLoad.Text = "File " + newname + " backuped to server successfully, Please Click and Download to local computer!";
                LbtnDownLoad.Hidden = false;
            }
            else
            {
                ShowNotify("You are not Authorized. Please Contact the Administrator!");
            }
        }

        protected void LbtnDownLoad_Click(object sender, EventArgs e)
        {
            ShowFile(FilePath);
        }
    }
}