using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;

namespace Attach_Database
{
    public partial class Form1 : Form
    {
        # region Variables
        public static string ConnectionString = "";
        SqlConnection cnn = new SqlConnection(ConnectionString);
        SqlCommand cmd;
        SqlDataAdapter da;
        DataTable dt;
        //
        string fName = "";
        string cmdString = "";
        #endregion

        public Form1()
        {
            InitializeComponent();
            //
            lblLdf.Text = "";
            lblMdf.Text = "";
            //
            txtFileName.Enabled = false;
            btnFileNameChange.Enabled = false;
            //
            OFD.Title = "Open";
            OFD.Filter = "All MDF SQL Server 2000 file (*.mdf)|*.mdf";
            //
        }
        #region Properties
        /// <summary>
        /// چك كردن وجود ديتابيس با نام داده شده
        /// </summary>
        /// <param name="dbName">نام داده شده</param>
        /// <returns>درصورت وجود نام مشابه مقدار 1 و در غير اينصورت صفر </returns>
        private int CheckDatabases(string dbName)
        {
            int var = -1;
            try
            {
                if (cnn.State == ConnectionState.Closed)
                    cnn.Open();
                cmd = new SqlCommand("sp_helpDb", cnn);
                cmd.CommandType = CommandType.StoredProcedure;
                //
                SqlDataReader dr = cmd.ExecuteReader();
                if(dr.Read())
                {
                    while(dr.Read())
                    {
                        if (dr[0].ToString() == dbName)
                        {
                            var = 1;
                            break;
                        }
                        else
                        {
                            var = 0;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            if (cnn.State == ConnectionState.Open)
                cnn.Close();
            return var;
        }
        /// <summary>
        /// پر كردن كمبو با نام ديتابيس ها
        /// </summary>
        private void FillCombo()
        {
            cbDbs.Items.Clear();
            try
            {
                if (cnn.State == ConnectionState.Closed)
                    cnn.Open();
                cmd = new SqlCommand("select [name] from master.dbo.sysdatabases", cnn);
                cmd.CommandType = CommandType.Text;
                //
                SqlDataReader dr = cmd.ExecuteReader();
                if (dr.Read())
                {
                    while (dr.Read())
                    {
                        cbDbs.Items.Add(dr[0].ToString());
                    }
                }
                if (dr.IsClosed == false)
                    dr.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            if (cnn.State == ConnectionState.Open)
                cnn.Close();
        }
        /// <summary>
        /// چسباندن ديتابيس
        /// </summary>
        private void AttachDb()
        {
            if (txtBrowse.Text != "")
            {
                if (File.Exists(lblMdf.Text) && File.Exists(lblLdf.Text))
                {
                    if (CheckDatabases(txtFileName.Text) == 0)
                    {
                        try
                        {
                            cmdString = "EXEC sp_attach_db @dbname = N'" + txtFileName.Text + "' ,@filename1 = N'" + lblLdf.Text + "',@filename2 = N'" + lblMdf.Text + "'";
                            cmd = new SqlCommand(cmdString);
                            cmd.Connection = cnn;
                            cmd.Connection.Open();
                            SqlDataReader dr = cmd.ExecuteReader();
                            dr.Read();
                            if (dr.IsClosed == false)
                                dr.Close();
                            MessageBox.Show("اتصال بانك اطلاعاتي با موفقيت انجام شد", "توجه");
                            lblLdf.Text = "";
                            lblMdf.Text = "";
                            txtFileName.Text = "";
                            txtBrowse.Text = "";
                            btnFileNameChange.Enabled = false;
                            txtFileName.Enabled = false;
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                        }
                        if (cnn.State == ConnectionState.Open)
                            cnn.Close();
                    }
                    else
                    {
                        MessageBox.Show("بانك مورد نظر موجود ميباشد", "توجه");
                    }
                }
                else
                {
                    MessageBox.Show("فايل ldf مربوطه وجود ندارد", "اخطار");
                }
            }
            else
            {
                MessageBox.Show("ابتدا فايل مورد نظر را انتخاب نمائيد", "توجه");
            }
        }
        /// <summary>
        /// جدا سازي ديتابيس
        /// </summary>
        private void DetachDb()
        {
            if (cbDbs.Items.Count != 0 && cbDbs.Text!="")
            {
                string dbName;
                if (cbDbs.SelectedItem == null)
                    dbName = cbDbs.Text.Trim();
                else
                    dbName = cbDbs.SelectedItem.ToString();
                try
                {
                    cmdString = "EXEC sp_detach_db @dbname = N'" + dbName + "'";
                    cmd = new SqlCommand(cmdString);
                    cmd.Connection = cnn;
                    cmd.Connection.Open();
                    SqlDataReader dr = cmd.ExecuteReader();
                    dr.Read();
                    MessageBox.Show("جداسازي بانك اطلاعاتي با موفقيت انجام شد", "توجه");
                    if (dr.IsClosed == false)
                        dr.Close();
                    FillCombo();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                if (cnn.State == ConnectionState.Open)
                    cnn.Close();
            }
            else
            {
                MessageBox.Show("آيتم مورد نظر را انتخاب نماييد", "توجه");
            }

        }
        #endregion
        #region Events
        
        private void Form1_Load(object sender, EventArgs e)
        {
            FillCombo();
        }
        private void btnBrowse_Click(object sender, EventArgs e)
        {
            if (OFD.ShowDialog() == DialogResult.OK)
            {
                if (OFD.CheckFileExists)
                {
                    txtBrowse.Text = OFD.FileName;
                    lblMdf.Text = OFD.FileName;
                    lblLdf.Text = OFD.FileName.Substring(0, OFD.FileName.Length - 4) + ".ldf";
                    //
                    FileInfo fi = new FileInfo(OFD.FileName);
                    fName = fi.Name.Substring(0, fi.Name.Length - 4);
                    //
                    txtFileName.Text = fName;
                    btnFileNameChange.Enabled = true;
                }
            }
        }
        private void btnFileNameChange_Click(object sender, EventArgs e)
        {
            txtFileName.Enabled = true;
            txtFileName.Focus();
            txtFileName.SelectAll();
        }   
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            FillCombo();
        }
        private void btnAttach_Click(object sender, EventArgs e)
        {
            AttachDb();
            FillCombo();

        }
        private void btnDetach_Click(object sender, EventArgs e)
        {
            DetachDb();
            cbDbs.Text = "";
        }
        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        
        #endregion

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }
    }
}
