' MSDE Manager - Phase I
' Developed by George Nava - DotNetGeek

Imports System.Windows.Forms
Imports System.Text
Imports System.IO
Imports System.Xml
Imports System.Xml.Serialization
Imports System.Data.SqlClient
Imports System.Data.OleDb


Public Class MainForm : Inherits System.Windows.Forms.Form

#Region " Some variables                         "
    Public oldSettings As New Settings()
    Public newSettings As New Settings()

    Dim activeServerName As String
    Dim activeDatabaseName As String
    Dim activeDataset As DataSet
    Dim activeObject As TreeNode
    Dim activeConnection As SqlClient.SqlConnection
    Dim connectionString As String
#End Region

#Region " CONST Icons defined here               "
    Const ICON_DatabaseDiagrams = 0
    Const ICON_DataFunctions = 1
    Const ICON_DataViews = 2
    Const ICON_DataTables = 3
    Const ICON_DiagramObject = 4
    Const ICON_FieldObject = 5
    Const ICON_ProcedureObject = 6
    Const ICON_Server = 7
    Const ICON_ServerConnected = 8
    Const ICON_ServerDisconnected = 9
    Const ICON_StoredProcedures = 10
    Const ICON_TableObject = 11
    Const ICON_ViewObject = 12
#End Region

#Region " Windows Form Designer generated code   "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents treeServers As System.Windows.Forms.TreeView
    Friend WithEvents dataImages As System.Windows.Forms.ImageList
    Friend WithEvents StatusBar As System.Windows.Forms.StatusBar
    Friend WithEvents BarPanel1 As System.Windows.Forms.StatusBarPanel
    Friend WithEvents BarPanel2 As System.Windows.Forms.StatusBarPanel
    Friend WithEvents BarPanel3 As System.Windows.Forms.StatusBarPanel
    Friend WithEvents DataPanel As System.Windows.Forms.Panel
    Friend WithEvents MainMenu1 As System.Windows.Forms.MainMenu
    Friend WithEvents MenuItem1 As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem2 As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem3 As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem4 As System.Windows.Forms.MenuItem
    Friend WithEvents Splitter1 As System.Windows.Forms.Splitter
    Friend WithEvents CommandPanel As System.Windows.Forms.Panel
    Friend WithEvents Splitter2 As System.Windows.Forms.Splitter
    Friend WithEvents Panel1 As System.Windows.Forms.Panel
    Friend WithEvents Panel2 As System.Windows.Forms.Panel
    Friend WithEvents richCommand As System.Windows.Forms.RichTextBox
    Friend WithEvents Panel3 As System.Windows.Forms.Panel
    Friend WithEvents sqlImages As System.Windows.Forms.ImageList
    Friend WithEvents btnNew As System.Windows.Forms.Button
    Friend WithEvents btnOpen As System.Windows.Forms.Button
    Friend WithEvents btnSave As System.Windows.Forms.Button
    Friend WithEvents btnExecute As System.Windows.Forms.Button
    Friend WithEvents btnDataProperties As System.Windows.Forms.Button
    Friend WithEvents btnDataEdit As System.Windows.Forms.Button
    Friend WithEvents btnDataNew As System.Windows.Forms.Button
    Friend WithEvents btnDataBrowse As System.Windows.Forms.Button
    Friend WithEvents Button1 As System.Windows.Forms.Button
    Friend WithEvents Button2 As System.Windows.Forms.Button
    Friend WithEvents ToolTips As System.Windows.Forms.ToolTip


    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.components = New System.ComponentModel.Container()
        Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(MainForm))
        Me.treeServers = New System.Windows.Forms.TreeView()
        Me.dataImages = New System.Windows.Forms.ImageList(Me.components)
        Me.StatusBar = New System.Windows.Forms.StatusBar()
        Me.BarPanel1 = New System.Windows.Forms.StatusBarPanel()
        Me.BarPanel2 = New System.Windows.Forms.StatusBarPanel()
        Me.BarPanel3 = New System.Windows.Forms.StatusBarPanel()
        Me.DataPanel = New System.Windows.Forms.Panel()
        Me.Panel3 = New System.Windows.Forms.Panel()
        Me.Panel1 = New System.Windows.Forms.Panel()
        Me.Button2 = New System.Windows.Forms.Button()
        Me.btnDataBrowse = New System.Windows.Forms.Button()
        Me.sqlImages = New System.Windows.Forms.ImageList(Me.components)
        Me.btnDataProperties = New System.Windows.Forms.Button()
        Me.btnDataEdit = New System.Windows.Forms.Button()
        Me.btnDataNew = New System.Windows.Forms.Button()
        Me.MainMenu1 = New System.Windows.Forms.MainMenu()
        Me.MenuItem1 = New System.Windows.Forms.MenuItem()
        Me.MenuItem2 = New System.Windows.Forms.MenuItem()
        Me.MenuItem3 = New System.Windows.Forms.MenuItem()
        Me.MenuItem4 = New System.Windows.Forms.MenuItem()
        Me.Splitter1 = New System.Windows.Forms.Splitter()
        Me.CommandPanel = New System.Windows.Forms.Panel()
        Me.richCommand = New System.Windows.Forms.RichTextBox()
        Me.Panel2 = New System.Windows.Forms.Panel()
        Me.Button1 = New System.Windows.Forms.Button()
        Me.btnExecute = New System.Windows.Forms.Button()
        Me.btnSave = New System.Windows.Forms.Button()
        Me.btnOpen = New System.Windows.Forms.Button()
        Me.btnNew = New System.Windows.Forms.Button()
        Me.Splitter2 = New System.Windows.Forms.Splitter()
        Me.ToolTips = New System.Windows.Forms.ToolTip(Me.components)
        CType(Me.BarPanel1, System.ComponentModel.ISupportInitialize).BeginInit()
        CType(Me.BarPanel2, System.ComponentModel.ISupportInitialize).BeginInit()
        CType(Me.BarPanel3, System.ComponentModel.ISupportInitialize).BeginInit()
        Me.DataPanel.SuspendLayout()
        Me.Panel3.SuspendLayout()
        Me.Panel1.SuspendLayout()
        Me.CommandPanel.SuspendLayout()
        Me.Panel2.SuspendLayout()
        Me.SuspendLayout()
        '
        'treeServers
        '
        Me.treeServers.Dock = System.Windows.Forms.DockStyle.Fill
        Me.treeServers.ImageList = Me.dataImages
        Me.treeServers.Name = "treeServers"
        Me.treeServers.Nodes.AddRange(New System.Windows.Forms.TreeNode() {New System.Windows.Forms.TreeNode("SQL Servers", 7, 7)})
        Me.treeServers.Size = New System.Drawing.Size(248, 437)
        Me.treeServers.TabIndex = 4
        '
        'dataImages
        '
        Me.dataImages.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit
        Me.dataImages.ImageSize = New System.Drawing.Size(16, 16)
        Me.dataImages.ImageStream = CType(resources.GetObject("dataImages.ImageStream"), System.Windows.Forms.ImageListStreamer)
        Me.dataImages.TransparentColor = System.Drawing.Color.Transparent
        '
        'StatusBar
        '
        Me.StatusBar.Location = New System.Drawing.Point(0, 467)
        Me.StatusBar.Name = "StatusBar"
        Me.StatusBar.Panels.AddRange(New System.Windows.Forms.StatusBarPanel() {Me.BarPanel1, Me.BarPanel2, Me.BarPanel3})
        Me.StatusBar.ShowPanels = True
        Me.StatusBar.Size = New System.Drawing.Size(704, 22)
        Me.StatusBar.TabIndex = 5
        Me.StatusBar.Text = "StatusBar"
        '
        'BarPanel1
        '
        Me.BarPanel1.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Spring
        Me.BarPanel1.Text = "Something here"
        Me.BarPanel1.Width = 488
        '
        'BarPanel2
        '
        Me.BarPanel2.Text = "Ok"
        '
        'BarPanel3
        '
        Me.BarPanel3.Text = "Ready"
        '
        'DataPanel
        '
        Me.DataPanel.Controls.AddRange(New System.Windows.Forms.Control() {Me.Panel3, Me.Panel1})
        Me.DataPanel.Dock = System.Windows.Forms.DockStyle.Left
        Me.DataPanel.Name = "DataPanel"
        Me.DataPanel.Size = New System.Drawing.Size(248, 467)
        Me.DataPanel.TabIndex = 6
        '
        'Panel3
        '
        Me.Panel3.Controls.AddRange(New System.Windows.Forms.Control() {Me.treeServers})
        Me.Panel3.Dock = System.Windows.Forms.DockStyle.Fill
        Me.Panel3.Location = New System.Drawing.Point(0, 30)
        Me.Panel3.Name = "Panel3"
        Me.Panel3.Size = New System.Drawing.Size(248, 437)
        Me.Panel3.TabIndex = 6
        '
        'Panel1
        '
        Me.Panel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
        Me.Panel1.Controls.AddRange(New System.Windows.Forms.Control() {Me.Button2, Me.btnDataBrowse, Me.btnDataProperties, Me.btnDataEdit, Me.btnDataNew})
        Me.Panel1.Dock = System.Windows.Forms.DockStyle.Top
        Me.Panel1.Name = "Panel1"
        Me.Panel1.Size = New System.Drawing.Size(248, 30)
        Me.Panel1.TabIndex = 5
        '
        'Button2
        '
        Me.Button2.Anchor = ((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
                    Or System.Windows.Forms.AnchorStyles.Right)
        Me.Button2.Enabled = False
        Me.Button2.Location = New System.Drawing.Point(104, 0)
        Me.Button2.Name = "Button2"
        Me.Button2.Size = New System.Drawing.Size(140, 26)
        Me.Button2.TabIndex = 13
        Me.Button2.TabStop = False
        '
        'btnDataBrowse
        '
        Me.btnDataBrowse.Image = CType(resources.GetObject("btnDataBrowse.Image"), System.Drawing.Bitmap)
        Me.btnDataBrowse.ImageIndex = 6
        Me.btnDataBrowse.ImageList = Me.sqlImages
        Me.btnDataBrowse.Location = New System.Drawing.Point(78, 0)
        Me.btnDataBrowse.Name = "btnDataBrowse"
        Me.btnDataBrowse.Size = New System.Drawing.Size(26, 26)
        Me.btnDataBrowse.TabIndex = 12
        Me.btnDataBrowse.TabStop = False
        Me.ToolTips.SetToolTip(Me.btnDataBrowse, "Browse")
        '
        'sqlImages
        '
        Me.sqlImages.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit
        Me.sqlImages.ImageSize = New System.Drawing.Size(16, 16)
        Me.sqlImages.ImageStream = CType(resources.GetObject("sqlImages.ImageStream"), System.Windows.Forms.ImageListStreamer)
        Me.sqlImages.TransparentColor = System.Drawing.Color.Transparent
        '
        'btnDataProperties
        '
        Me.btnDataProperties.Image = CType(resources.GetObject("btnDataProperties.Image"), System.Drawing.Bitmap)
        Me.btnDataProperties.ImageIndex = 5
        Me.btnDataProperties.ImageList = Me.sqlImages
        Me.btnDataProperties.Location = New System.Drawing.Point(52, 0)
        Me.btnDataProperties.Name = "btnDataProperties"
        Me.btnDataProperties.Size = New System.Drawing.Size(26, 26)
        Me.btnDataProperties.TabIndex = 11
        Me.btnDataProperties.TabStop = False
        Me.ToolTips.SetToolTip(Me.btnDataProperties, "Properties")
        '
        'btnDataEdit
        '
        Me.btnDataEdit.Image = CType(resources.GetObject("btnDataEdit.Image"), System.Drawing.Bitmap)
        Me.btnDataEdit.ImageIndex = 4
        Me.btnDataEdit.ImageList = Me.sqlImages
        Me.btnDataEdit.Location = New System.Drawing.Point(26, 0)
        Me.btnDataEdit.Name = "btnDataEdit"
        Me.btnDataEdit.Size = New System.Drawing.Size(26, 26)
        Me.btnDataEdit.TabIndex = 10
        Me.btnDataEdit.TabStop = False
        Me.ToolTips.SetToolTip(Me.btnDataEdit, "Design")
        '
        'btnDataNew
        '
        Me.btnDataNew.Image = CType(resources.GetObject("btnDataNew.Image"), System.Drawing.Bitmap)
        Me.btnDataNew.ImageIndex = 7
        Me.btnDataNew.ImageList = Me.sqlImages
        Me.btnDataNew.Name = "btnDataNew"
        Me.btnDataNew.Size = New System.Drawing.Size(26, 26)
        Me.btnDataNew.TabIndex = 9
        Me.btnDataNew.TabStop = False
        Me.ToolTips.SetToolTip(Me.btnDataNew, "New")
        '
        'MainMenu1
        '
        Me.MainMenu1.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.MenuItem1, Me.MenuItem3})
        '
        'MenuItem1
        '
        Me.MenuItem1.Index = 0
        Me.MenuItem1.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.MenuItem2})
        Me.MenuItem1.Text = "File"
        '
        'MenuItem2
        '
        Me.MenuItem2.Index = 0
        Me.MenuItem2.Text = "Exit"
        '
        'MenuItem3
        '
        Me.MenuItem3.Index = 1
        Me.MenuItem3.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.MenuItem4})
        Me.MenuItem3.Text = "Help"
        '
        'MenuItem4
        '
        Me.MenuItem4.Index = 0
        Me.MenuItem4.Text = "About"
        '
        'Splitter1
        '
        Me.Splitter1.Location = New System.Drawing.Point(248, 0)
        Me.Splitter1.Name = "Splitter1"
        Me.Splitter1.Size = New System.Drawing.Size(3, 467)
        Me.Splitter1.TabIndex = 7
        Me.Splitter1.TabStop = False
        '
        'CommandPanel
        '
        Me.CommandPanel.Controls.AddRange(New System.Windows.Forms.Control() {Me.richCommand, Me.Panel2})
        Me.CommandPanel.Dock = System.Windows.Forms.DockStyle.Bottom
        Me.CommandPanel.Location = New System.Drawing.Point(251, 347)
        Me.CommandPanel.Name = "CommandPanel"
        Me.CommandPanel.Size = New System.Drawing.Size(453, 120)
        Me.CommandPanel.TabIndex = 9
        '
        'richCommand
        '
        Me.richCommand.Dock = System.Windows.Forms.DockStyle.Fill
        Me.richCommand.Font = New System.Drawing.Font("Courier New", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.richCommand.Location = New System.Drawing.Point(0, 30)
        Me.richCommand.Name = "richCommand"
        Me.richCommand.Size = New System.Drawing.Size(453, 90)
        Me.richCommand.TabIndex = 1
        Me.richCommand.Text = "Select * From anyTable"
        '
        'Panel2
        '
        Me.Panel2.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
        Me.Panel2.Controls.AddRange(New System.Windows.Forms.Control() {Me.Button1, Me.btnExecute, Me.btnSave, Me.btnOpen, Me.btnNew})
        Me.Panel2.Dock = System.Windows.Forms.DockStyle.Top
        Me.Panel2.Name = "Panel2"
        Me.Panel2.Size = New System.Drawing.Size(453, 30)
        Me.Panel2.TabIndex = 0
        '
        'Button1
        '
        Me.Button1.Anchor = ((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
                    Or System.Windows.Forms.AnchorStyles.Right)
        Me.Button1.Enabled = False
        Me.Button1.Location = New System.Drawing.Point(130, 0)
        Me.Button1.Name = "Button1"
        Me.Button1.Size = New System.Drawing.Size(319, 26)
        Me.Button1.TabIndex = 12
        Me.Button1.TabStop = False
        '
        'btnExecute
        '
        Me.btnExecute.Image = CType(resources.GetObject("btnExecute.Image"), System.Drawing.Bitmap)
        Me.btnExecute.ImageIndex = 3
        Me.btnExecute.ImageList = Me.sqlImages
        Me.btnExecute.Location = New System.Drawing.Point(78, 0)
        Me.btnExecute.Name = "btnExecute"
        Me.btnExecute.Size = New System.Drawing.Size(52, 26)
        Me.btnExecute.TabIndex = 11
        Me.btnExecute.TabStop = False
        Me.ToolTips.SetToolTip(Me.btnExecute, "Execute")
        '
        'btnSave
        '
        Me.btnSave.Image = CType(resources.GetObject("btnSave.Image"), System.Drawing.Bitmap)
        Me.btnSave.ImageIndex = 2
        Me.btnSave.ImageList = Me.sqlImages
        Me.btnSave.Location = New System.Drawing.Point(52, 0)
        Me.btnSave.Name = "btnSave"
        Me.btnSave.Size = New System.Drawing.Size(26, 26)
        Me.btnSave.TabIndex = 8
        Me.btnSave.TabStop = False
        Me.ToolTips.SetToolTip(Me.btnSave, "Save")
        '
        'btnOpen
        '
        Me.btnOpen.Image = CType(resources.GetObject("btnOpen.Image"), System.Drawing.Bitmap)
        Me.btnOpen.ImageIndex = 1
        Me.btnOpen.ImageList = Me.sqlImages
        Me.btnOpen.Location = New System.Drawing.Point(26, 0)
        Me.btnOpen.Name = "btnOpen"
        Me.btnOpen.Size = New System.Drawing.Size(26, 26)
        Me.btnOpen.TabIndex = 7
        Me.btnOpen.TabStop = False
        Me.ToolTips.SetToolTip(Me.btnOpen, "Open")
        '
        'btnNew
        '
        Me.btnNew.Image = CType(resources.GetObject("btnNew.Image"), System.Drawing.Bitmap)
        Me.btnNew.ImageIndex = 0
        Me.btnNew.ImageList = Me.sqlImages
        Me.btnNew.Name = "btnNew"
        Me.btnNew.Size = New System.Drawing.Size(26, 26)
        Me.btnNew.TabIndex = 6
        Me.btnNew.TabStop = False
        Me.ToolTips.SetToolTip(Me.btnNew, "New")
        '
        'Splitter2
        '
        Me.Splitter2.Dock = System.Windows.Forms.DockStyle.Bottom
        Me.Splitter2.Location = New System.Drawing.Point(251, 345)
        Me.Splitter2.Name = "Splitter2"
        Me.Splitter2.Size = New System.Drawing.Size(453, 2)
        Me.Splitter2.TabIndex = 10
        Me.Splitter2.TabStop = False
        '
        'MainForm
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(704, 489)
        Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.Splitter2, Me.CommandPanel, Me.Splitter1, Me.DataPanel, Me.StatusBar})
        Me.IsMdiContainer = True
        Me.Menu = Me.MainMenu1
        Me.Name = "MainForm"
        Me.Text = "MSDE Manager"
        CType(Me.BarPanel1, System.ComponentModel.ISupportInitialize).EndInit()
        CType(Me.BarPanel2, System.ComponentModel.ISupportInitialize).EndInit()
        CType(Me.BarPanel3, System.ComponentModel.ISupportInitialize).EndInit()
        Me.DataPanel.ResumeLayout(False)
        Me.Panel3.ResumeLayout(False)
        Me.Panel1.ResumeLayout(False)
        Me.CommandPanel.ResumeLayout(False)
        Me.Panel2.ResumeLayout(False)
        Me.ResumeLayout(False)

    End Sub

#End Region

#Region " Form open/close                        "
    '覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
    Private Sub MainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        LoadSettings()
        Me.richCommand.Select(0, 0) ' SelectOnEntry = false
        GetSqlServers() 'This could be in a thread after form is loaded ;-)
    End Sub
    '覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
    Protected Overrides Sub OnClosing(ByVal e As System.ComponentModel.CancelEventArgs)
        SaveSettings()
    End Sub
#End Region

#Region " Form methods                           "
    Private Sub GetSqlServers()
        Dim sqlApp As SQLDMO.Application = New SQLDMO.ApplicationClass()
        Dim listServers As SQLDMO.NameList = sqlApp.ListAvailableSQLServers()
        Dim server As Object

        Dim root, node As TreeNode

        root = Me.treeServers.Nodes(0)
        For Each server In listServers
            node = New TreeNode(server.ToString(), ICON_ServerDisconnected, ICON_ServerDisconnected)
            node.Tag = "Server"
            root.Nodes.Add(node)
        Next server

        If root.GetNodeCount(False) = 0 Then
            node = New TreeNode("<No available SQL Servers>", ICON_ServerDisconnected, ICON_ServerDisconnected)
            node.Tag = "Nothing"
            root.Nodes.Add(node)
        End If

        root.Expand()
        SetStatus("Connected", "Ok", "Ready")
    End Sub
    '覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
    Private Sub GetDatabases(ByVal node As TreeNode)
        Cursor = Cursors.WaitCursor
        SetStatus("Connecting to server...", "Wait", "Not Ready")

        ' get all available databases from selected SQL Server
        Dim server As SQLDMO.SQLServer2 = New SQLDMO.SQLServer2Class()
        Dim serverName As String = node.Text
        Dim connected As Boolean

        server.LoginSecure = True
        server.LoginTimeout = 10

        Try
            server.Connect(serverName)
            connected = True
        Catch e As Exception
            MessageBox.Show(e.Message, "Sql Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            server.DisConnect()
            connected = False
        End Try

        If Not connected Then
            SetStatus("Could not connect to server", "Error", "Ready")
            Cursor = Cursors.Default
            Return
        End If

        activeServerName = serverName
        Dim database As SQLDMO.Database
        Dim newNode As TreeNode

        For Each database In server.Databases
            If Not database.Name Is Nothing Then
                newNode = New TreeNode(database.Name, ICON_ServerDisconnected, ICON_ServerDisconnected)
                newNode.Tag = "Database"
                node.Nodes.Add(newNode)
            End If
        Next database

        If node.GetNodeCount(False) > 0 Then
            node.ImageIndex = ICON_ServerConnected
            node.SelectedImageIndex = ICON_ServerConnected
            node.Expand()
        End If
        server.DisConnect()

        SetStatus("Connected", "Ok", "Ready")
        Cursor = Cursors.Default
    End Sub
    '覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
    Private Sub GetDatabaseComponents(ByVal node As TreeNode)
        Cursor = Cursors.WaitCursor
        SetStatus("Loading database objects...", "Wait", "Not Ready")

        ' Get all Stored procedures - tables are in the Tables collection, views are in the Views collection 
        Dim server As SQLDMO.SQLServer = New SQLDMO.SQLServerClass()
        Dim serverName As String = node.Parent.Text ' NodeClicked.Parent
        Dim database As SQLDMO.Database2
        Dim databaseName As String = node.Text
        Dim connected As Boolean

        server.LoginSecure = True
        server.LoginTimeout = 10
        Try
            server.Connect(serverName)
            connected = True
        Catch e As Exception
            MessageBox.Show(e.Message, "Sql Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            server.DisConnect()
            connected = False
        End Try

        If Not connected Then
            SetStatus("Could not connect to server", "Error", "Ready")
            Cursor = Cursors.Default
            Return
        End If

        activeServerName = serverName

        Dim newGroup, newObject, newField As TreeNode
        Dim field As SQLDMO.Column
        Dim I, J, K As Integer

        database = server.Databases.Item(databaseName)
        Console.WriteLine(database.Name)

        node.Nodes.Clear()

        ' Database Diagrams
        newGroup = New TreeNode("Database Diagrams", ICON_DatabaseDiagrams, ICON_DatabaseDiagrams)
        newGroup.Tag = "Database Diagrams"
        'TODO: Dunno how to get the diagrams ;-)
        'Dim diagram AS something ???
        'For Each diagram In database.Diagrams ???
        '   newObject = New TreeNode(diagram.Name,ICON_DiagramObject,ICON_DiagramObject)
        '   newObject.Tag = "Diagram"
        '   newGroup.Nodes.Add(newObject)
        'Next
        node.Nodes.Add(newGroup)

        'Tables and Fields
        newGroup = New TreeNode("Tables", ICON_DataTables, ICON_DataTables)
        newGroup.Tag = "Tables"
        Dim table As SQLDMO.Table
        For Each table In database.Tables
            If Not table.SystemObject Then
                newObject = New TreeNode(table.Name, ICON_TableObject, ICON_TableObject)
                newObject.Tag = "Table"
                For Each field In table.Columns
                    newField = New TreeNode(field.Name, ICON_FieldObject, ICON_FieldObject)
                    newField.Tag = "Field"
                    newObject.Nodes.Add(newField)
                Next
                newGroup.Nodes.Add(newObject)
            End If
        Next
        node.Nodes.Add(newGroup)

        'Views
        newGroup = New TreeNode("Views", ICON_DataViews, ICON_DataViews)
        newGroup.Tag = "Views"
        Dim view As SQLDMO.View
        For Each view In database.Views
            If Not view.SystemObject Then
                newObject = New TreeNode(view.Name, ICON_ViewObject, ICON_ViewObject)
                newObject.Tag = "View"
                For Each field In view.ListColumns
                    newField = New TreeNode(field.Name, ICON_FieldObject, ICON_FieldObject)
                    newField.Tag = "Field"
                    newObject.Nodes.Add(newField)
                Next
                newGroup.Nodes.Add(newObject)
            End If
        Next
        node.Nodes.Add(newGroup)

        'Stored Procedures
        newGroup = New TreeNode("Stored Procedures", ICON_StoredProcedures, ICON_StoredProcedures)
        newGroup.Tag = "Stored Procedures"
        Dim procedure As SQLDMO.StoredProcedure
        For Each procedure In database.StoredProcedures
            If Not procedure.SystemObject Then
                newObject = New TreeNode(procedure.Name, ICON_ProcedureObject, ICON_ProcedureObject)
                newObject.Tag = "StoredProcedure"
                newGroup.Nodes.Add(newObject)
            End If
        Next
        node.Nodes.Add(newGroup)

        'Functions
        newGroup = New TreeNode("Functions", ICON_DataFunctions, ICON_DataFunctions)
        newGroup.Tag = "Functions"
        Dim userFunction As SQLDMO.UserDefinedFunction
        For Each userFunction In database.UserDefinedFunctions
            newObject = New TreeNode(userFunction.Name, ICON_DataFunctions, ICON_DataFunctions)
            newObject.Tag = "Function"
            newGroup.Nodes.Add(newObject)
        Next
        node.Nodes.Add(newGroup)

        node.ImageIndex = ICON_ServerConnected
        node.SelectedImageIndex = ICON_ServerConnected
        node.Expand()

        server.DisConnect()

        SetStatus("Database opened", "Ok", "Ready")
        Cursor = Cursors.Default
    End Sub
    '覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
    Private Sub SetActiveServer(ByVal serverName As String)
        activeServerName = serverName
    End Sub
    '覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
    Private Sub SetActiveDatabase(ByVal databaseName As String)
        If activeServerName Is Nothing Then
            activeDatabaseName = Nothing
            activeConnection = Nothing
            Me.Text = "MSDE Manager  -  Database: <Not Selected>"
            Return
        End If

        activeDatabaseName = databaseName
        Me.Text = "MSDE Manager  -  Database: " & activeDatabaseName

        SetActiveConnection()
    End Sub
    '覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
    Private Sub SetActiveConnection()
        If activeServerName Is Nothing Or activeDatabaseName Is Nothing Then
            Return
        End If
        connectionString = String.Format("Data Source={0};Initial Catalog={1};Integrated Security=SSPI", activeServerName, activeDatabaseName)
        activeConnection = New SqlConnection(connectionString)
    End Sub
    '覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
    Private Sub RefreshDataToolbar(ByVal nodeType As String)
        Select Case nodeType
            Case "Servers", "Server"
                Me.ToolTips.SetToolTip(btnDataNew, "New Database")
            Case "Database"
                Me.ToolTips.SetToolTip(btnDataNew, "New Database")
            Case "Database Diagrams", "Diagram"
                Me.ToolTips.SetToolTip(btnDataNew, "New Diagram")
            Case "Tables", "Table"
                Me.ToolTips.SetToolTip(btnDataNew, "New Table")
            Case "Views", "View"
                Me.ToolTips.SetToolTip(btnDataNew, "New View")
            Case "Stored Procedures", "StoredProcedure"
                Me.ToolTips.SetToolTip(btnDataNew, "New Procedure")
            Case "Functions", "Function"
                Me.ToolTips.SetToolTip(btnDataNew, "New Function")
            Case Else ' Nothing
        End Select

        Select Case nodeType
            Case "Servers", "Server"
                btnDataNew.Enabled = True
                btnDataEdit.Enabled = False
                btnDataProperties.Enabled = True
                btnDataBrowse.Enabled = False
            Case "Database"
                btnDataNew.Enabled = True
                btnDataEdit.Enabled = False
                btnDataProperties.Enabled = True
                btnDataBrowse.Enabled = False
            Case "Database Diagrams", "Diagram"
                btnDataNew.Enabled = False
                btnDataEdit.Enabled = False
                btnDataProperties.Enabled = False
                btnDataBrowse.Enabled = False
            Case "Tables"
                btnDataNew.Enabled = True
                btnDataEdit.Enabled = False
                btnDataProperties.Enabled = False
                btnDataBrowse.Enabled = False
            Case "Table"
                btnDataNew.Enabled = True
                btnDataEdit.Enabled = False
                btnDataProperties.Enabled = True
                btnDataBrowse.Enabled = True
            Case "Views"
                btnDataNew.Enabled = True
                btnDataEdit.Enabled = False
                btnDataProperties.Enabled = False
                btnDataBrowse.Enabled = False
            Case "View"
                btnDataNew.Enabled = True
                btnDataEdit.Enabled = False
                btnDataProperties.Enabled = True
                btnDataBrowse.Enabled = True
            Case "Stored Procedures"
                btnDataNew.Enabled = True
                btnDataEdit.Enabled = False
                btnDataProperties.Enabled = False
                btnDataBrowse.Enabled = False
            Case "StoredProcedure"
                btnDataNew.Enabled = False
                btnDataEdit.Enabled = True
                btnDataProperties.Enabled = False
                btnDataBrowse.Enabled = False
            Case "Functions"
                btnDataNew.Enabled = False
                btnDataEdit.Enabled = False
                btnDataProperties.Enabled = False
                btnDataBrowse.Enabled = False
            Case "Function"
                btnDataNew.Enabled = False
                btnDataEdit.Enabled = False
                btnDataProperties.Enabled = False
                btnDataBrowse.Enabled = False
            Case Else ' Nothing
                btnDataNew.Enabled = False
                btnDataEdit.Enabled = False
                btnDataProperties.Enabled = False
                btnDataBrowse.Enabled = False
        End Select

    End Sub
    '覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
    Private Sub treeServers_AfterSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles treeServers.AfterSelect
        RefreshDataToolbar(e.Node.Tag)

        Dim node As TreeNode = e.Node
        Dim nodeName As String = e.Node.Text
        Dim nodeType As String = e.Node.Tag

        Select Case nodeType
            Case "Server"
                SetActiveServer(nodeName)
            Case "Database"
                SetActiveDatabase(nodeName)
            Case "Diagram"
            Case "Table"
            Case "View"
            Case "StoredProcedure"
            Case "Function"
            Case Else
                ' Nothing
        End Select

        ' Has Children ? Do nothing...
        If e.Node.GetNodeCount(False) > 0 Then
            Return
        End If

        Select Case nodeType
            Case "Server"
                GetDatabases(node)
            Case "Database"
                GetDatabaseComponents(node)
            Case "Diagram"
            Case "Table"
            Case "View"
            Case "StoredProcedure"
            Case "Function"
            Case Else
                ' Nothing
        End Select
    End Sub
    '覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
    Private Sub SetStatus(ByVal message1 As String, ByVal message2 As String, ByVal message3 As String)
        StatusBar.Panels(0).Text = message1
        StatusBar.Panels(1).Text = message2
        StatusBar.Panels(2).Text = message3
    End Sub
    '覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
    Private Sub ShowProperties(ByVal anyObject As Object, ByVal caption As String)
        Dim formProperties As New ShowProperties()
        formProperties.Text = caption
        formProperties.MdiParent = Me
        formProperties.PropertyGrid1.SelectedObject = anyObject
        formProperties.Show()
    End Sub
    '覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
    Private Sub ShowProcedure(ByVal procedureName As String, ByVal caption As String)
        Dim procedureText As String = GetProcedureText(procedureName)
        If procedureText Is Nothing Then
            Return
        End If
        Dim formProcedure As New ViewProcedure()
        formProcedure.Text = caption
        formProcedure.MdiParent = Me
        formProcedure.richProcedure.Text = procedureText
        formProcedure.Show()
    End Sub
    '覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
    Private Sub ShowFunction(ByVal functionName As String, ByVal caption As String)
        Dim userFunction As String = GetFunctionText(functionName)
        If userFunction Is Nothing Then
            Return
        End If
        Dim formProcedure As New ViewProcedure()
        formProcedure.Text = caption
        formProcedure.MdiParent = Me
        formProcedure.richProcedure.Text = userFunction
        formProcedure.Show()
    End Sub
    '覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
    Private Function ExecuteSql(ByVal command As String)
        If command Is Nothing Then
            Return Nothing
        End If

        If activeConnection Is Nothing Or connectionString Is Nothing Then
            MessageBox.Show("Please select Server and Database before executing SQL command", "SQL Error", MessageBoxButtons.OK, MessageBoxIcon.Hand)
            Return Nothing
        End If

        Cursor = Cursors.WaitCursor
        SetStatus("Executing SQL command...", "Wait", "Not Ready")

        Dim sqlCommand As SqlClient.SqlCommand
        Dim dataSet As DataSet
        Dim dataAdapter As SqlDataAdapter

        Try
            sqlCommand = New SqlClient.SqlCommand(command, activeConnection)
            sqlCommand.Connection.Open()
            dataAdapter = New SqlDataAdapter(command, activeConnection)
            dataSet = New DataSet()
            dataAdapter.Fill(dataSet, "Query")
            sqlCommand.Connection.Close()
        Catch ex As Exception
            Cursor = Cursors.Default
            SetStatus("SQL command not successful...", "Ok", "Ready")
            sqlCommand.Connection.Close()
            ShowException(ex)
            Return Nothing
        End Try

        Cursor = Cursors.Default
        SetStatus("SQL command executed...", "Ok", "Ready")
        Return dataSet
    End Function
    '覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
    Private Sub ShowData(ByVal dataSet As DataSet, ByVal tableName As String)
        Dim formBrowse As Form = New BrowseData(dataSet, tableName)
        formBrowse.MdiParent = Me
        formBrowse.Show()
    End Sub
    '覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
    Private Sub ShowException(ByVal e As Exception)
        MessageBox.Show(e.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Hand)
    End Sub
    '覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
    Private Sub CreateDatabase()
        Dim request As New IFormData()
        Dim response As New IFormData()
        Dim result As DialogResult

        request.serverName = activeServerName
        Dim formNewDatabase As New NewDatabase(request)

        result = formNewDatabase.ShowDialog(Me)
        response = formNewDatabase.response

        If result = DialogResult.Cancel Then
            Return
        End If
        If response.databaseName = Nothing Then
            Return
        End If

        ' Now we have a database name, let's roll !
        Cursor = Cursors.WaitCursor

        Dim server As SQLDMO.SQLServer2 = New SQLDMO.SQLServer2Class()
        Dim serverName As String = activeServerName
        Dim connected As Boolean

        server.LoginSecure = True
        server.LoginTimeout = 10

        Try
            server.Connect(serverName)
            connected = True
        Catch e As Exception
            MessageBox.Show(e.Message, "Sql Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            server.DisConnect()
            connected = False
        End Try

        If Not connected Then
            SetStatus("Could not connect to server", "Error", "Ready")
            Cursor = Cursors.Default
            Return
        End If

        Dim database As New SQLDMO.Database()
        database.Name = response.databaseName

        Try
            server.Databases.Add(database)
        Catch e As Exception
            MessageBox.Show(e.Message, "Sql Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            server.DisConnect()
            Cursor = Cursors.Default
            Return
        End Try

        Dim node, child, newNode As TreeNode

        ' new database node
        newNode = New TreeNode()
        With newNode
            .Text = response.databaseName
            .ImageIndex = ICON_ServerDisconnected
            .SelectedImageIndex = ICON_ServerDisconnected
            .Tag = "Database"
        End With

        ' hmm, try to locate server and add database node in the right place
        For Each node In treeServers.Nodes(0).Nodes
            If node.Text.ToUpper() = activeServerName.ToUpper() Then  ' This is the server
                If node.GetNodeCount(False) < 1 Then
                    node.Nodes.Add(newNode)
                    Exit For
                End If

                Dim index As Integer = 0
                For Each child In node.Nodes
                    If child.Text.ToUpper() > CType(response.databaseName, String).ToUpper Then ' Add it here 
                        Exit For
                    End If
                    index += 1
                Next
                node.Nodes.Insert(index, newNode)
                Exit For
            End If
        Next

        Cursor = Cursors.Default

    End Sub
    '覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
    Private Sub CreateTable()
        Dim request As New IFormTable()
        Dim response As New IFormTable()
        Dim result As DialogResult

        request.databaseName = activeDatabaseName
        Dim formNewDataTable As New NewDataTable(request)

        result = formNewDataTable.ShowDialog(Me)
        response = formNewDataTable.response

        If result = DialogResult.Cancel Then
            Return
        End If
        If response.tableName = Nothing Then
            Return
        End If

        ' TODO: Phase II
    End Sub
    '覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
    Private Function GetServerObject(ByVal serverName As String)
        Dim sqlApp As SQLDMO.Application = New SQLDMO.ApplicationClass()
        Dim server As SQLDMO.SQLServer = sqlApp.SQLServers.Item(serverName)
        ShowProperties(server, serverName)
    End Function
    '覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
    Private Function GetDatabaseObject(ByVal databaseName As String)
        Dim sqlApp As SQLDMO.Application = New SQLDMO.ApplicationClass()
        Dim server As SQLDMO.SQLServer = sqlApp.SQLServers.Item(activeServerName)
        Dim database As SQLDMO.Database2 = server.Databases.Item(databaseName)
        ShowProperties(database, databaseName)
    End Function
    '覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
    Private Function GetProcedureText(ByVal procedureName As String)
        Dim sqlApp As SQLDMO.Application = New SQLDMO.ApplicationClass()
        Dim server As SQLDMO.SQLServer = sqlApp.SQLServers.Item(activeServerName)
        server.Connect()
        Dim database As SQLDMO.Database2 = server.Databases.Item(activeDatabaseName)
        Dim procedure As SQLDMO.StoredProcedure2 = database.StoredProcedures.Item(procedureName)
        Dim content As String = procedure.Text
        server.DisConnect()
        Return content
    End Function
    '覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
    Private Function GetFunctionText(ByVal functionName As String)
        Dim sqlApp As SQLDMO.Application = New SQLDMO.ApplicationClass()
        Dim server As SQLDMO.SQLServer = sqlApp.SQLServers.Item(activeServerName)
        server.Connect()
        Dim database As SQLDMO.Database2 = server.Databases.Item(activeDatabaseName)
        Dim userFunction As SQLDMO.UserDefinedFunction = database.UserDefinedFunctions.Item(functionName)
        Dim content As String = userFunction.Text
        server.DisConnect()
        Return content
    End Function
#End Region

#Region " User Interaction - SQL                 "
    Private Sub btnNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNew.Click
        NewFile()
    End Sub
    '覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
    Private Sub btnOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpen.Click
        OpenFile()
    End Sub
    '覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
        SaveFile()
    End Sub
    '覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
    Private Sub btnExecute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExecute.Click
        activeDataset = ExecuteSql(Me.richCommand.Text)
        If Not activeDataset Is Nothing Then
            ShowData(activeDataset, "Query results")
        End If
    End Sub
    '覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
    Private Sub NewFile()
        If newSettings.LastCommand <> Me.richCommand.Text Then
            Dim response As DialogResult = AskForSaving()
            Select Case response
                Case DialogResult.Cancel
                    Me.richCommand.Focus()
                    Return
                Case DialogResult.No
                    ' Overwrite
                Case DialogResult.Yes
                    If Not SaveFile() Then
                        Me.richCommand.Focus()
                        Return
                    End If
            End Select
        End If
        newSettings.LastCommand = ""
        Me.richCommand.Text = ""
        Me.richCommand.Focus()
    End Sub
    '覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
    Private Sub OpenFile()
        If newSettings.LastCommand <> Me.richCommand.Text Then
            Dim response As DialogResult = AskForSaving()
            Select Case response
                Case DialogResult.Cancel
                    Me.richCommand.Focus()
                    Return
                Case DialogResult.No
                    ' Overwrite
                Case DialogResult.Yes
                    If Not SaveFile() Then
                        Me.richCommand.Focus()
                        Return
                    End If
            End Select
        End If

        Dim openDialog As New OpenFileDialog()
        openDialog.DefaultExt = "sql"
        openDialog.Filter = "SQL Commands (*.sql)|*.sql|All files (*.*)|*.*"
        openDialog.ShowDialog()
        If openDialog.FileName Is Nothing Then
            Return
        End If
        Dim command As String = FileToString(openDialog.FileName)
        newSettings.LastCommand = command
        Me.richCommand.Text = command
        Me.richCommand.Focus()
    End Sub
    '覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
    Private Function SaveFile() As Boolean
        If newSettings.LastCommand = Me.richCommand.Text Then
            Return True
        End If
        Dim fileName As String
        Dim response As DialogResult
        Dim saveDialog As New SaveFileDialog()
        saveDialog.DefaultExt = "sql"
        saveDialog.FileName = "myCommand1.sql"
        saveDialog.Filter = "SQL Commands (*.sql)|*.sql|All files (*.*)|*.*"
        response = saveDialog.ShowDialog()
        If response = DialogResult.Cancel OrElse saveDialog.FileName Is Nothing Then
            Return False
        End If
        Dim command As String = Me.richCommand.Text
        StringToFile(command, saveDialog.FileName)
        newSettings.LastCommand = command
        Me.richCommand.Focus()
        Return True
    End Function
    '覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
    Private Function AskForSaving() As DialogResult
        Dim result As DialogResult = MessageBox.Show("Do you want to save your command?", "Save", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)
        Return result
    End Function
#End Region

#Region " User Interaction - Data                "
    '覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
    Private Sub btnDataNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDataNew.Click
        Dim nodeType As String = treeServers.SelectedNode.Tag
        Select Case nodeType
            Case "Server"
                CreateDatabase()
            Case "Database"
                CreateDatabase()
            Case "Tables", "Table"
                CreateTable()
            Case "Views", "View"
                'CreateView()
            Case Else
                ' Nothing...
        End Select
    End Sub
    '覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
    Private Sub btnDataEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDataEdit.Click
        Dim nodeType As String = treeServers.SelectedNode.Tag
        Dim nodeName As String = treeServers.SelectedNode.Text
        Select Case nodeType
            Case "Server"
                '
            Case "Database"
                '
            Case "Table"
                '
            Case "View"
                '
            Case "StoredProcedure"
                ShowProcedure(nodeName, "Stored Procedure: " & nodeName)
            Case "Function"
                'ShowFunction(nodeName, "Function: " & nodeName)
            Case Else
                ' Nothing...
        End Select

    End Sub
    '覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
    Private Sub btnDataProperties_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDataProperties.Click
        Dim nodeType As String = treeServers.SelectedNode.Tag
        Dim nodeName As String = treeServers.SelectedNode.Text
        Dim selectedObject As New Object()
        Select Case nodeType
            Case "Server"
                selectedObject = GetServerObject(activeServerName)
            Case "Database"
                selectedObject = GetDatabaseObject(activeDatabaseName)
            Case "Table"
                'selectedObject = GetTableObject()
            Case "View"
                'selectedObject = GetViewObject()
            Case Else
                ' Nothing...
        End Select

        ShowProperties(selectedObject, nodeName)

    End Sub
    '覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
    Private Sub btnDataBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDataBrowse.Click
        Dim nodeName As String = treeServers.SelectedNode.Text
        Dim command As String
        command = String.Format("Select TOP 100 * From {0} ", nodeName)
        activeDataset = ExecuteSql(command)
        If Not activeDataset Is Nothing Then
            ShowData(activeDataset, nodeName)
        End If
    End Sub
#End Region

#Region " Load/Save Settings                     "
    Private Sub LoadSettings()
        DeserializeObject() ' get oldSettings
        If oldSettings Is Nothing Then
            Return
        End If
        Me.richCommand.Text = oldSettings.LastCommand

        If oldSettings.WindowState = 0 Then     'WindowState.Normal
            Dim i() As String = oldSettings.Location.Split(",")
            Me.Top = CType(i(0), Int16)
            Me.Left = CType(i(1), Int16)
            Me.Width = CType(i(2), Int16)
            Me.Height = CType(i(3), Int16)
        Else
            Me.WindowState = FormWindowState.Maximized
        End If
    End Sub
    '覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
    Private Sub SaveSettings()
        If Me.WindowState = FormWindowState.Normal Then
            newSettings.Location = String.Format("{0},{1},{2},{3}", Me.Top, Me.Left, Me.Width, Me.Height)
        End If
        newSettings.LastCommand = Me.richCommand.Text
        newSettings.WindowState = CType(Me.WindowState, Integer)

        If Not newSettings.Equals(oldSettings) Then
            SerializeObject()
        End If
    End Sub
    '覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
    Private Sub SerializeObject()
        Dim fileName As String = System.Windows.Forms.Application.StartupPath.ToString() & "\application.config"
        ' Create an XmlTextWriter using a FileStream.
        Dim serializer As New XmlSerializer(GetType(Settings))
        Dim fileStream As New FileStream(fileName, FileMode.Create)
        Dim xmlWriter As New XmlTextWriter(fileStream, New UTF8Encoding())

        ' Serialize using the XmlTextWriter.
        serializer.Serialize(xmlWriter, newSettings)
        xmlWriter.Flush()
        xmlWriter.Close()
    End Sub
    '覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
    Private Sub DeserializeObject()
        Dim fileName As String = System.Windows.Forms.Application.StartupPath.ToString() & "\application.config"
        If Not System.IO.File.Exists(fileName) Then
            oldSettings = Nothing
            Return
        End If

        ' Create an instance of the XmlSerializer specifying type and namespace.
        Dim serializer As New XmlSerializer(GetType(Settings))

        ' A FileStream is needed to read the XML document.
        Dim fileStream As New FileStream(fileName, FileMode.Open)
        Dim xmlReader As New XmlTextReader(fileStream)

        ' Use the Deserialize method to restore the object's state.
        oldSettings = CType(serializer.Deserialize(xmlReader), Settings)
        fileStream.Flush()
        fileStream.Close()
        xmlReader.Close()
    End Sub
#End Region

#Region " Utilities                              "
    Public Shared Sub StringToFile(ByVal content As String, ByVal fileName As String)
        'Check if the specified file exists
        If System.IO.File.Exists(fileName) = True Then
            'If so then Erase the file first as in this case we are overwriting
            System.IO.File.Delete(fileName)
        End If

        'Create the file if it does not exist and open it
        Dim stream As FileStream = New FileStream(fileName, FileMode.CreateNew, FileAccess.ReadWrite)

        'Create a writer for the file
        Dim writer As StreamWriter = New StreamWriter(stream)

        'Write the contents
        writer.Write(content)
        writer.Flush()
        writer.Close()

        stream.Close()
    End Sub
    '覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
    Public Shared Function FileToString(ByVal fileName As String) As String
        'Create a StreamReader and open the file
        Dim reader As StreamReader = System.IO.File.OpenText(fileName)

        'Read all the contents of the file in a string
        Dim content As String = reader.ReadToEnd()

        'Close the StreamReader and return the string
        reader.Close()
        Return content
    End Function

#End Region

End Class

#Region " Settings Class                         "

' This is the class that will be serialized.
Public Class Settings
    <XmlElement()> Public WindowState As Integer
    <XmlElement()> Public Location As String
    <XmlElement()> Public LastCommand As String
End Class

#End Region