using System;
using System.Collections;
using System.Configuration;
using System.IO;
using System.Web;
using System.Web.UI.WebControls;
using TopWinCMS.BLL;
using TopWinCMS.Common;
namespace TopWinCMS.WebUI
{
    /// <summary>
    /// DataBase 的摘要说明。
    /// </summary>
    public partial class Access : System.Web.UI.Page
    {
        //SQLModel s_model = new SQLModel();
        string DbPath;

        protected void Page_Load(object sender, System.EventArgs e)
        {
            if (Config.DAL.ToLower().Contains("sqlserver"))
            {
                Response.Redirect("SqlServer.aspx?" + Request.QueryString);
            }

            if (File.Exists(ConfigurationManager.AppSettings["ConnectionAccess"]))
            {
                DbPath = ConfigurationManager.AppSettings["ConnectionAccess"];
            }
            else
            {
                DbPath = HttpRuntime.AppDomainAppPath + ConfigurationManager.AppSettings["ConnectionAccess"];
            }

            if (!IsPostBack)
            {
                string strAction = Request["Action"];
                if (strAction == "Backup")
                {
                    RightsCheck.CheckWorkPower("D_1");

                    Panel1.Visible = true;
                    Panel2.Visible = false;
                    Panel3.Visible = false;
                    LB_Path.Text = "数据库管理 → Access → 备份数据库";
                    path.Text = System.IO.Path.GetDirectoryName(DbPath) + @"\";
                    DBname.Text = DateTime.Now.ToString("yyyyMMddHHmmss") + ".cs";

                    this.Title = "备份数据库";
                }
                else if (strAction == "Restore")
                {
                    RightsCheck.CheckWorkPower("D_2");
                    Panel1.Visible = false;
                    Panel2.Visible = true;
                    Panel3.Visible = false;
                    LB_Path.Text = "数据库管理 → Access → 还原数据库";
                    path1.Text = System.IO.Path.GetDirectoryName(DbPath) + @"\";
                    System.IO.DirectoryInfo di = new DirectoryInfo(System.IO.Path.GetDirectoryName(DbPath));
                    //CBB_BackUpDB.Items.Clear();
                    //foreach (FileInfo fi in di.GetFiles())
                    //{
                    //    if (fi.FullName != DbPath)
                    //    {
                    //        ListItem li = new ListItem();
                    //        li.Text = fi.Name;
                    //        CBB_BackUpDB.Items.Add(li);
                    //    }
                    //}
                  
                
                    CBB_BackUpDB.DataSource = di.GetFiles();
                    CBB_BackUpDB.DataTextField = "Name";
                    CBB_BackUpDB.DataValueField = "Name";
                    CBB_BackUpDB.DataBind();

                    this.Title = "还原数据库";
                }
                else if (strAction == "Compact")
                {
                    RightsCheck.CheckWorkPower("D_3");
                    LB_Path.Text = "数据库管理 → Access → 压缩数据库";
                    Panel1.Visible = false;
                    Panel2.Visible = false;
                    Panel3.Visible = true;

                    this.Title = "压缩数据库";
                }
            }
        }



        protected void BT_Backup_Click(object sender, System.EventArgs e)
        {
            string strDataBase = DbPath;
            //strTemp目标数据库绝对路径 
            string strTemp = this.path.Text + DBname.Text.Trim();
            if (!File.Exists(strDataBase)) //检查数据库是否已存在
            {
                MsgBox.Alert("源数据库不存在", UpdatePanel1);
                return;
            }
            try
            {
                File.Copy(strDataBase, strTemp, true);
                MsgBox.Alert("数据库备份成功！", UpdatePanel1);
            }
            catch (IOException ixp)
            {
                MsgBox.Alert(ixp.ToString(), UpdatePanel1);
            }

        }

        protected void BT_Restore_Click(object sender, System.EventArgs e)
        {
            string strDataBase = DbPath;
            //strTemp为当前数据库绝对路径
            string strTemp = this.path1.Text + CBB_BackUpDB.Text.Trim();
            if (File.Exists(strTemp) == false) //检查备份是否已存在
            {
                MsgBox.Alert("备份数据库不存在", UpdatePanel1);
                return;
            }
            else
            {
                try
                {
                    File.Copy(strTemp, strDataBase, true);
                    MsgBox.Alert("数据库还原成功！", UpdatePanel1);
                }
                catch (IOException ixp)
                {
                    MsgBox.Alert(ixp.ToString(), UpdatePanel1);
                }
            }
        }

        protected void BT_Compact_Click(object sender, System.EventArgs e)
        {
            string strDataBase = DbPath;
            if (!File.Exists(strDataBase)) //检查数据库是否已存在
            {
                MsgBox.Alert("目标数据库不存在,无法压缩", UpdatePanel1);
                return;
            }
            try
            {
                string tempFileName = Path.Combine(Path.GetDirectoryName(strDataBase), Guid.NewGuid().ToString("N") + ".mdb");
                object[] oParams;
                string connectionString = AccBase.ConnectionString;
                object objJRO =
                  Activator.CreateInstance(Type.GetTypeFromProgID("JRO.JetEngine"));
                oParams = new object[] { connectionString, "Provider=Microsoft.Jet.OLEDB.4.0;Data" + " Source=" + tempFileName + ";Jet OLEDB:Engine Type=5" };
              
                objJRO.GetType().InvokeMember("CompactDatabase",
                    System.Reflection.BindingFlags.InvokeMethod,
                    null,
                    objJRO,
                    oParams);

                System.IO.File.Delete(strDataBase);
                System.IO.File.Move(tempFileName, strDataBase);
                //clean up (just in case)
                System.Runtime.InteropServices.Marshal.ReleaseComObject(objJRO);
                objJRO = null;
            }
            catch (Exception ex)
            {
                MsgBox.Alert(ex.ToString(), UpdatePanel1);
            }


            //try
            //{
            //    string oldFileName = strDataBase;
            //    //声明临时数据库的名称
            //    string newFileName = Path.Combine(Path.GetDirectoryName(oldFileName), Guid.NewGuid().ToString("N") + ".mdb");

            //    JRO.JetEngine engine = (JRO.JetEngine)HttpContext.Current.Server.CreateObject("JRO.JetEngine");

            //    const string AccessOleDbConnectionStringFormat = "Data Source={0};Provider=Microsoft.Jet.OLEDB.4.0;";

            //    engine.CompactDatabase(
            //     String.Format(AccessOleDbConnectionStringFormat, oldFileName),
            //     String.Format(AccessOleDbConnectionStringFormat, newFileName));

            //    File.Delete(oldFileName);

            //    File.Move(newFileName, oldFileName);

            //    MsgBox.Alert("压缩成功！", UpdatePanel1);
            //}
            //catch (IOException ixp)
            //{
            //    MsgBox.Alert(ixp.ToString(), UpdatePanel1);
            //}
            //catch (Exception ex)
            //{
            //    MsgBox.Alert(ex.ToString(), UpdatePanel1);
            //}


            System.IO.FileInfo fi = new FileInfo(strDataBase);

            LB_DataSize.Text = LB_DataSize.Text.Replace("$$", FileIO.FileSize(fi.Length));
        }

    }
}