Wednesday 8 February 2012

database cleaner, taken backup, check all table info, clear table data

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
namespace Master_Clear_Database
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        DataTable databaseTable = new DataTable();
        public static string tableId;
        public static string allconn;
        private void button1_Click(object sender, EventArgs e)
        {//---connect check
            try
            {
                if (txtserver.Text != "" && txtDatabase.Text != "")
                {
                    databaseTable.Rows.Clear();
                    string _constr = ConnStr();
                    SqlConnection con = new SqlConnection(_constr);
                    string _allTable = "SELECT * FROM sys.tables order by name asc";
                    SqlDataAdapter da = new SqlDataAdapter(_allTable, con);
                    da.Fill(databaseTable);
                    dataGridView1.DataSource = databaseTable;
                    label6.Text = "Connection Succeed";
                    label7.Text = "Total Tables - " + databaseTable.Rows.Count;
                }
                else
                {
                    label6.Text = "Not Connected, Please Fill Currect Information";
                }
              
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.ToString(),"error in connection",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }


     
        }
        private void FillGrid()
        {
            try
            {
                if (txtserver.Text != "" && txtDatabase.Text != "")
                {
                    databaseTable.Rows.Clear();
                    string _constr = ConnStr();
                    SqlConnection con = new SqlConnection(_constr);
                    string _allTable = "SELECT * FROM sys.tables order by name asc";
                    SqlDataAdapter da = new SqlDataAdapter(_allTable, con);
                    da.Fill(databaseTable);
                    dataGridView1.DataSource = databaseTable;
                    label6.Text = "Connection Succeed";
                    label7.Text = "Total Tables - " + databaseTable.Rows.Count;
                }
                else
                {
                    label6.Text = "Not Connected, Please Fill Currect Information";
                }

            }
            catch (Exception)
            {

                throw;
            }

        }
        private string ConnStr()
        {
           
             string _connectBase = "Data Source=" + txtserver.Text + ";Initial Catalog=" + txtDatabase.Text + ";";
            if (radioButton1.Checked)
                {//--windo
                _connectBase=_connectBase+"Integrated Security=True";
                }
            else if (radioButton2.Checked)
                {//---server

                    _connectBase = _connectBase + "User ID=" + txtUid.Text.Trim() + ";Password=" + txtpwd.Text.Trim() + "";
                }
            allconn = _connectBase;
            return _connectBase;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
       
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton1.Checked)
            {
                txtUid.Enabled = false;
                txtpwd.Enabled = false;

                txtUid.Text = "";
                txtpwd.Text = "";
            }
            else
            {
                txtUid.Enabled = true;
                txtpwd.Enabled = true;

            }
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {//--truncate table coding
            switch (e.ColumnIndex)
            {
                case 0:
                    string Task = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
                    if (Task == "clear")
                    {
                        if (MessageBox.Show("Are you sure to clear data?", "Clening...", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                      
                            string DelId = dataGridView1.Rows[e.RowIndex].Cells["name"].Value.ToString();


                            string delQuery = "TRUNCATE TABLE  " + DelId + "";
                            string _constr = ConnStr();

                            SqlConnection con = new SqlConnection(_constr); con.Open();
                            SqlCommand cmd = new SqlCommand(delQuery,con);
                            cmd.ExecuteNonQuery(); con.Close();
                            MessageBox.Show("" + DelId + "  table data clear");

                        }
                    }
                    break;

                case 1:
                string Task1 = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
                if (Task1 == "showdata")
                {
                    if (MessageBox.Show("Are you sure to show data?", "showing...", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {

                        string showid = dataGridView1.Rows[e.RowIndex].Cells["name"].Value.ToString();
                        showdata _sh = new showdata();
                        tableId = showid;
                        _sh.ShowDialog();
                    }
                }
                break;
              
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {//---back up

            SecondBackUp();
        }
          private void SecondBackUp()
        {//Second backUp userDefine Location
            try
            {
                string Location;

                SaveFileDialog ofd = new SaveFileDialog();
                ofd.FileName = txtDatabase.Text;
                ofd.Filter = "Backup files (*.bak)|*.BAK|All files (*.*)|*.*";
                ofd.RestoreDirectory = true;
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    Location = ofd.FileName;
                    Location = Path.GetDirectoryName(Location);
                  
                    //----------backup coding
                   // Backup bkp = new Backup();

                    ////DateTime dt = DateTime.Now;

                    ////string mydt = string.Format("{0:yyyy/MM/dd}", dt);

                    bool bBackUpStatus = true;

                    Cursor.Current = Cursors.WaitCursor;

                    if (Directory.Exists(@"" + ofd.FileName + ""))
                    {
                        if (File.Exists(@"" + Location + "\\"+txtDatabase.Text+".bak"))
                        {
                            File.Delete(@"" + Location + "\\"+txtDatabase.Text+".bak");
                        }
                        else
                        {
                            bBackUpStatus = false;
                        }
                    }
                    else
                        Directory.CreateDirectory(@"" + Location + "");
               
                    if (bBackUpStatus)
                    {
                        //----------------------------------------------------------------------------------------------------

                        SqlCommand command;
                        string query;
                       // query = "BACKUP DATABASE [Billing] TO  DISK = N'" + Location + "'\\Billing.bak' WITH NOFORMAT, NOINIT,  NAME = N'Billing-Full Database Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10";
                     query = "BACKUP DATABASE ["+txtDatabase.Text+"] TO DISK = N'" + Location + "\\"+txtDatabase.Text+".bak' WITH NOFORMAT, NOINIT,  NAME = N'"+txtDatabase.Text+"-Full Database Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10";
                     string _constr = ConnStr();

                            SqlConnection con = new SqlConnection(_constr); con.Open();
                            SqlCommand cmd = new SqlCommand(query,con);
                            cmd.ExecuteNonQuery(); con.Close();
                         
                        //-------------------------------------------------------------------------------------------------------------------------------
                      //  bkp.Action = BackupActionType.Database;

                        this.Cursor = Cursors.Default;

                        //dut.cnn.Close();
                        MessageBox.Show("Backup SuccessFully Save In " + Location + " Drive", "* Backup *", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        //Application.Exit();

                        //this.progressBar1.Value = 100;
                    }
                }
            }
            catch (Exception)
            {

               // throw;
            }

        }

    }
}
//-----add new window form for show data


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


namespace Master_Clear_Database
{
    public partial class showdata : Form
    {
        public showdata()
        {
            InitializeComponent();
        }

        private void showdata_Load(object sender, EventArgs e)
        {
            string _mytable = Form1.tableId;
            string _allCon = Form1.allconn;
            SqlConnection con = new SqlConnection(_allCon);
            string query = "Select * from " + _mytable + "";
            SqlDataAdapter da = new SqlDataAdapter(query, con);
            DataTable dt = new DataTable();
            da.Fill(dt);
            dataGridView1.DataSource = dt;
        }
    }
}

//---happy programing

No comments:

Post a Comment