Click here to Skip to main content
15,896,730 members
Articles / Database Development / SQL Server

A SQL Management Console for MSSQL 2000 & 2005, MySQL 5.0,...

Rate me:
Please Sign up or sign in to vote.
4.86/5 (14 votes)
20 Apr 2008Ms-PL4 min read 68.6K   2.5K   68  
An article on a SQL IDE for different type of RDBMS databases
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections.ObjectModel;
using System.Reflection;
using System.IO;

namespace SQLMgtConsole
{
    public partial class SQLMgtConsole : System.Windows.Forms.Form
    {
        #region Private variables
        Collection<IToolWindow> _toolWindows;
        #endregion

        public SQLMgtConsole()
        {
            InitializeComponent();

            this.WindowState = FormWindowState.Maximized;
            this.tscbDBList.DropDownStyle = ComboBoxStyle.DropDownList;
            this.txtQueryMsg.ReadOnly = false;
            // allow user use accelerator
            this.tsmiExecute.ShortcutKeys = Keys.F5;
            // ms-help://MS.MSDNQTR.v80.en/MS.MSDN.v80/MS.VisualStudio.v80.en/dv_fxmclictl/html/699ef759-458c-426d-ac87-7c7e71b018ae.htm
            this.dgvQueryResult.RowsDefaultCellStyle.BackColor = Color.Bisque;
            this.dgvQueryResult.AlternatingRowsDefaultCellStyle.BackColor = Color.Beige;
            // these property and events could not be found in RichTextBox property grid
            this.rtbQueryConsole.AllowDrop = true;
            this.rtbQueryConsole.DragEnter += new System.Windows.Forms.DragEventHandler(this.rtbQueryConsole_DragEnter);
            this.rtbQueryConsole.DragDrop += new System.Windows.Forms.DragEventHandler(this.rtbQueryConsole_DragDrop);
            _toolWindows = new Collection<IToolWindow>();
        }

        #region Control Events
        private void SQLMgtConsole_Load(object sender, EventArgs e)
        {
            fnLoginToDB();
        }

        private void fnLoginToDB()
        {
            frmLogin frmLogin = new frmLogin();
            if (frmLogin.ShowDialog() == DialogResult.OK)
            {
                string strConnString = "server = " + frmLogin.getServerName + ";" +
                                        "user id = " + frmLogin.getLoginID + ";" +
                                        "password = " + frmLogin.getPassword;
                string strDataProvider = "";
                switch (frmLogin.getDBType)
                {
                    case "MSSQL":
                        strDataProvider = "System.Data.SqlClient";
                        break;
                    case "MySQL":
                        strDataProvider = "MySql.Data.MySqlClient";
                        break;
                    default:
                        break;
                }

                fnFindWindows(frmLogin.getDBType, strConnString, strDataProvider);
            }
            // ms-help://MS.MSDNQTR.v80.en/MS.MSDN.v80/MS.VisualStudio.v80.en/dv_mancli/html/63ad8645-6842-45e8-b215-73f778e29a55.htm
            /* When a form is displayed as a modal dialog box, 
             * clicking the Close button (the button with an X in the top-right corner of the form) 
             * causes the form to be hidden and the DialogResult property to be set to DialogResult.Cancel. 
             * The Close method is not automatically called when the user clicks the Close button of a dialog box 
             * or sets the value of the DialogResult property. 
             * Instead, the form is hidden and can be shown again without creating a new instance of the dialog box. 
             * Because of this behavior, 
             * you must call the Dispose method of the form when the form is no longer needed by your application.
             */
            frmLogin.Dispose();
        }

        private void fnFindWindows(string strDBType, string strConnString, string strDataProvider)
        {
            // Clear out the collection
            _toolWindows.Clear();

            // Use reflection to look for types
            foreach (Type t in Assembly.GetExecutingAssembly().GetTypes())
            {
                if (t.GetInterface("IToolWindow") != null)
                {
                    // load one database type per each session
                    if(t.Name.ToUpper().Equals(strDBType.ToUpper()))
                    {
                        // Try the empty constructor
                        if (t.GetConstructor(new Type[0]) != null)
                        {
                            _toolWindows.Add((IToolWindow)Activator.CreateInstance(t));
                        }
                        else
                        {
                            _toolWindows.Add((IToolWindow)Activator.CreateInstance(t, new object[] { this.rtbQueryConsole, this.tscbDBList, 
                                                                                                        strConnString, strDataProvider }));
                        }
                    }
                }
            }

            // Add toolwindows to each ToolWindowHost
            foreach (Control c in this.Controls)
            {
                ToolWindowHost host = c as ToolWindowHost;
                if (host != null)
                {
                    foreach (IToolWindow tw in _toolWindows)
                    {
                        host.AddToolWindow(tw);
                        host.ShowToolWindow(tw);
                        host.Dock = DockStyle.Left;
                    }
                }
            }
        }

        // ms-help://MS.MSDNQTR.v80.en/MS.MSDN.v80/MS.VisualStudio.v80.en/dv_fxmclictl/html/ca167d1c-2014-4cf0-96a0-20598470be3b.htm
        private void rtbQueryConsole_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.Copy;
            else
                e.Effect = DragDropEffects.None;
        }
         
        private void rtbQueryConsole_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] arrstrFileContent = (string[])e.Data.GetData(DataFormats.FileDrop);
                String strFileContent = "";
                if (arrstrFileContent != null && arrstrFileContent.Length > 0)
                {
                    //TODO : Take the first one; will be added later if tabbed page is supported
                    strFileContent = File.ReadAllText(arrstrFileContent[0]);
                }
                rtbQueryConsole.Text = strFileContent;
            }
        }
        #endregion

        #region Menu & Context-Menu
        private void tsmiLogin_Click(object sender, EventArgs e)
        {
            //TODO : Remove at fnFindWindows()
            //fnLoginToDB();
        }

        private void tsmiOpen_Click(object sender, EventArgs e)
        {
            // ms-help://MS.MSDNQTR.v80.en/MS.MSDN.v80/MS.NETDEVFX.v20.en/CPref17/html/T_System_Windows_Forms_OpenFileDialog.htm
            OpenFileDialog ofdLoadFile = new OpenFileDialog();

            ofdLoadFile.InitialDirectory = "c:\\";
            ofdLoadFile.Filter = "SQL Server files (*.sql)|*.sql|txt files (*.txt)|*.txt|All files (*.*)|*.*";
            // Use the FilterIndex property to set which filtering option is shown first to the user.
            // The index value of the first filter entry is 1.
            ofdLoadFile.FilterIndex = 1;

            if (ofdLoadFile.ShowDialog() == DialogResult.OK)
            {
                // ms-help://MS.MSDNQTR.v80.en/MS.MSDN.v80/MS.VisualStudio.v80.en/dv_fxmclictl/html/c03451be-f285-4428-a71a-c41e002cc919.htm
                // ms-help://MS.MSDNQTR.v80.en/MS.MSDN.v80/MS.NETDEVFX.v20.en/CPref17/html/T_System_Windows_Forms_RichTextBoxStreamType.htm
                // PlainText :  A plain text stream that includes spaces 
                //              in places of Object Linking and Embedding (OLE) objects.
                rtbQueryConsole.LoadFile(ofdLoadFile.FileName, RichTextBoxStreamType.PlainText);
            }
        }

        private void tsmiSaveAs_Click(object sender, EventArgs e)
        {
            // ms-help://MS.MSDNQTR.v80.en/MS.MSDN.v80/MS.NETDEVFX.v20.en/CPref17/html/M_System_Windows_Forms_RichTextBox_SaveFile_1_16219e3a.htm
            // Create a SaveFileDialog to request a path and file name to save to.
            SaveFileDialog sfdSaveQuery = new SaveFileDialog();

            // Initialize the SaveFileDialog to specify the SQL extention for the file.
            sfdSaveQuery.DefaultExt = "*.sql";
            sfdSaveQuery.Filter = "SQL Server files (*.sql)|*.sql|txt files (*.txt)|*.txt";

            // Determine whether the user selected a file name from the saveFileDialog.
            if (sfdSaveQuery.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
                sfdSaveQuery.FileName.Length > 0)
            {
                // Save the contents of the RichTextBox into the file.
                rtbQueryConsole.SaveFile(sfdSaveQuery.FileName, RichTextBoxStreamType.PlainText);
            }
        }

        private void tsmiExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void tsmiAbout_Click(object sender, EventArgs e)
        {
            frmAboutBox frmAbout = new frmAboutBox();
            frmAbout.ShowDialog();
            frmAbout.Dispose();
        }

        private void tsmiExecute_Click(object sender, EventArgs e)
        {
            string strQuery = "";
            if (!rtbQueryConsole.SelectedText.Trim().Equals(""))
            {
                // find the highlighted text
                strQuery = rtbQueryConsole.SelectedText.Trim();
            } 
            else
            {
                strQuery = rtbQueryConsole.Text.Trim();
            }

            if (!strQuery.Trim().Equals(""))
            {
                // further split
                if (strQuery.Contains(";"))
                {
                    //TODO : use the first semi-colon separated text
                    strQuery = strQuery.Substring(0, rtbQueryConsole.Text.IndexOf(";"));
                }
                if (tscbDBList.Items.Count > 0 && tscbDBList.SelectedItem != null
                    && _toolWindows != null && _toolWindows.Count > 0)
                {
                    Exception exDisplay = new Exception();
                    //TODO : Use the first one first
                    DataTable dtResult = _toolWindows[0].GetData((string)tscbDBList.SelectedItem, strQuery, ref exDisplay);
                    if (dtResult != null)
                    {
                        // show selected tab
                        if (tcResultPane.TabCount > 0 && tcResultPane.TabPages.IndexOfKey("tpResults") >= 0)
                        {
                            tcResultPane.SelectedTab = tcResultPane.TabPages["tpResults"];
                        }
                        dgvQueryResult.DataSource = dtResult;
                        // read-only for all bands
                        foreach (DataGridViewBand dgvBand in dgvQueryResult.Columns)
                        {
                            dgvBand.ReadOnly = true;
                        }
                        txtQueryMsg.ForeColor = Color.Black;
                        txtQueryMsg.Text = "( " + dtResult.Rows.Count + " row(s) affected )";
                    }
                    else
                    {
                        if (exDisplay != null)
                        {
                            // show selected tab
                            if (tcResultPane.TabCount > 0 && tcResultPane.TabPages.IndexOfKey("tpMessages") >= 0)
                            {
                                tcResultPane.SelectedTab = tcResultPane.TabPages["tpMessages"];
                            }
                            // display error msg with red color, then restore
                            txtQueryMsg.ForeColor = Color.Red;
                            txtQueryMsg.Text = exDisplay.Message;
                        }
                    }
                }
                else
                {
                    MessageBox.Show("No Database/Please select a database");
                }
            }
        }
        #endregion
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)


Written By
Software Developer
Malaysia Malaysia
My blog: http://start-coding.blogspot.com/

Comments and Discussions