Sunday, 1 April 2012

Get All databases to connect to specified Server....

 Private Sub btnRefreshConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRefreshConnect.Click
        Dim dbList As New Collection
        Me.ddlDatabaseNames.Items.Clear()
        Dim databaseName As String
        Try
            Me.Cursor = Cursors.WaitCursor 'Changing the Cursor to Waititng State
            If Not DBUtil.ServerName = "" Then
                dbList = DBUtil.GetDatabases()
                If Not dbList Is Nothing Then
                    For Each databaseName In dbList  'For Addig the Database Names To DropdownList
                        Me.ddlDatabaseNames.Items.Add(databaseName)
                    Next
                End If
                Dim strLastUsedDatabase As String = DBUtil.ReadValuesFromRegistry(Microsoft.Win32.Registry.CurrentUser, "SOFTWARE\FocalTechnology\DBVersionUpgrade", "LastUsedDatabase")
                If (Not strLastUsedDatabase = "") Then
                    Me.ddlDatabaseNames.SelectedIndex = Me.ddlDatabaseNames.FindString(strLastUsedDatabase)
                End If
            End If
            DBUtil.WriteValuesToRegistry(Microsoft.Win32.RegistryHive.CurrentUser, "SOFTWARE\FocalTechnology\DBVersionUpgrade", "Server", Me.txtServer.Text)
            DBUtil.WriteValuesToRegistry(Microsoft.Win32.RegistryHive.CurrentUser, "SOFTWARE\FocalTechnology\DBVersionUpgrade", "LastUsedDatabase", Me.ddlDatabaseNames.Text)
            If (chkTrustConnection.Checked = True) Then
                DBUtil.WriteValuesToRegistry(Microsoft.Win32.RegistryHive.CurrentUser, "SOFTWARE\FocalTechnology\DBVersionUpgrade", "ServerUserName", "")
                DBUtil.WriteValuesToRegistry(Microsoft.Win32.RegistryHive.CurrentUser, "SOFTWARE\FocalTechnology\DBVersionUpgrade", "ServerPassword", "")
                DBUtil.WriteValuesToRegistry(Microsoft.Win32.RegistryHive.CurrentUser, "SOFTWARE\FocalTechnology\DBVersionUpgrade", "TrustedConnection", "true")
            Else
                DBUtil.WriteValuesToRegistry(Microsoft.Win32.RegistryHive.CurrentUser, "SOFTWARE\FocalTechnology\DBVersionUpgrade", "ServerUserName", Me.txtServerUsername.Text)
                DBUtil.WriteValuesToRegistry(Microsoft.Win32.RegistryHive.CurrentUser, "SOFTWARE\FocalTechnology\DBVersionUpgrade", "ServerPassword", Me.txtServerPassword.Text)
                DBUtil.WriteValuesToRegistry(Microsoft.Win32.RegistryHive.CurrentUser, "SOFTWARE\FocalTechnology\DBVersionUpgrade", "TrustedConnection", "false")
            End If

        Catch ex As Exception
            If (ex.Message = "Invalid Login or Password") Then
                MessageBox.Show("Invalid Login or Password")
                Return
            End If
            ' ErrorLog.LogError(ex)
        Finally
            Me.Cursor = Cursors.Default
        End Try
    End Sub
----------------------------








 Public Shared Function GetDatabases() As Collection  'ByVal strSQLServerName As String, ByVal blnTrustedConnection As Boolean, Optional ByVal strSQLUsername As String = "", Optional ByVal strSQLPassword As String = "") As Collection
        'Dim dbServer As New SQLDMO.SQLServer

        Dim dbServer As Server
        Dim objSvrConn As ServerConnection

        DBUtil.DefaultTableName = System.Configuration.ConfigurationManager.AppSettings.Item("VersionTableName") 'commented by Sandeep on 15sept here connection.xml file is used instead of app.config
        'DBUtil.DefaultTableName = Helper.GetConnectionDetails.Rows(0)("VersionTableName")
        Dim db As Microsoft.SqlServer.Management.Smo.Database
        Try
            objSvrConn = New ServerConnection()

            'dbServer.LoginSecure = UseTrustedConnection

            objSvrConn.LoginSecure = False
            objSvrConn.ServerInstance = ServerName
            objSvrConn.Login = ServerUserName
            objSvrConn.Password = ServerPassword

            Try
                dbServer = New Server(objSvrConn)
                'dbServer.Connect(ServerName, ServerUserName, ServerPassword)
            Catch dbEx As Exception
                Throw New Exception("Invalid Login or Password " & dbEx.Message)
            End Try

            Dim dbTable As Microsoft.SqlServer.Management.Smo.Table
            Dim dbList As New Collection
            'retrieving all the Databases from the Database Server which have our defaultTableName
            For Each db In dbServer.Databases
                'If Not db.SystemObject And db.Status = SQLDMO_DBSTATUS_TYPE.SQLDMODBStat_Normal Then
                Try
                    For Each dbTable In db.Tables
                        ' If dbTable.Name = DBUtil.DefaultTableName Then
                        dbList.Add(db.Name)
                        Exit For
                        ' End If
                    Next dbTable
                Catch ex As System.Runtime.InteropServices.COMException

                End Try
                'End If
            Next db
            Return dbList
        Catch sqlEx As System.Runtime.InteropServices.COMException

        Catch ex As System.Exception

            Throw ex
        Finally
            'dbServer.DisConnect()
        End Try
    End Function
==================

Copy Files & Folders from source to destination (windows Application)........

 Private Sub btnUpdateSiteFiles_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdateSiteFiles.Click

        Dim Err As Integer = 0
        Dim Err2 As Integer = 0
        Try
            txtStatus.Text = ""
            lblUpdateSiteFiles.Text = ""
            lblProgress.Text = ""
            lblUpdateSiteFiles.Visible = True
            lblProgress.Visible = True
            'lblMsg.Visible = False
            Me.Cursor = Cursors.WaitCursor 'Changing the Cursor to Waititng State
            Dim selectedCount As Integer = SelectedDataBaseCount()
            If selectedCount = 0 Then
                ErrorLog.XmlError("btnUpdateSiteFiles", New ApplicationException("Please choose atleast one database to update site files."))
                txtStatus.Text &= "Please choose atleast one database to update site files. " & Environment.NewLine
                txtStatus.Refresh()
                MsgBox("Please choose atleast one database to update site files.")
                Err = 1
                Return
            End If

            Try
                'Dim SourcePath As String = ConfigurationManager.AppSettings("FilesSourcepath")
                'Dim DestinationPath As String = DBUtil.GetSettings("EasyShopFolder")
                'Dim FilePath As String = SourcePath & "\app_offline.htm"
                'NewDestinationPath = DestinationPath & "\app_offline.htm"
                'File.Copy(FilePath, NewDestinationPath, True)

                'Copy Easyshop Files
                CopySiteFiles(Err)

                'File.Delete(NewDestinationPath)

            Catch ex As Exception
                'If File.Exists(NewDestinationPath) Then
                '    File.Delete(NewDestinationPath)
                'End If
                ErrorLog.XmlError("btnUpdateSiteFiles", ex)

                txtStatus.Text &= ex.Message & vbCrLf
                txtStatus.Refresh()

                MessageBox.Show(ex.Message.ToString(), "Errors")
                Err = Err + 1
            End Try
            Try
                'Copy AimsShopLinkFiles
                CopyAimsShopLinkFiles(Err2)
            Catch ex As Exception
                ErrorLog.XmlError("btnUpdateSiteFiles", ex)

                txtStatus.Text &= ex.Message & vbCrLf
                txtStatus.Refresh()

                MessageBox.Show(ex.Message.ToString(), "Errors")
                Err2 = Err2 + 1
            End Try


        Catch ex As Exception
            ErrorLog.XmlError("btnUpdateSiteFiles", ex)
            txtStatus.Text &= ex.Message & vbCrLf
            txtStatus.Refresh()
            MessageBox.Show(ex.Message.ToString(), "Errors")
        Finally
            lblUpdateSiteFiles.Text = ""
            lblProgress.Text = ""
            lblUpdateSiteFiles.Visible = False
            lblProgress.Visible = True
            lblProgress.Text = "Completed successfully"
            ' lblMsg.Visible = True
            Me.Cursor = Cursors.Default 'Changing the Cursor to Waititng State
            If Err = 0 AndAlso Err2 = 0 Then
                MessageBox.Show("Update Site Files Process Completed successfully.", "Update SiteFiles")
            ElseIf Err = 1 Or Err2 = 1 Then
                ErrorLog.XmlError("btnUpdateSiteFiles", New ApplicationException("There is Problem in Updating Files."))
                txtStatus.Text &= "There is Problem in Updating Files." & Environment.NewLine
                txtStatus.Refresh()
                MessageBox.Show("There is Problem in Updating Files.", "Update SiteFiles")
            End If
        End Try
    End Sub
--------------
Private Function SelectedDataBaseCount() As Integer
        Dim count As Integer = 0
        For Each dr As Infragistics.Win.UltraWinGrid.UltraGridRow In dgvDatabases.Rows
            If dr.Cells("select").Value = True Then
                count = count + 1

            End If
        Next
        gCount = count
        Return count
    End Function
---------

  Public Sub CopySiteFiles(ByRef Err As Integer)
        Try
            For Each dr As Infragistics.Win.UltraWinGrid.UltraGridRow In dgvDatabases.Rows
                If dr.Cells("select").Value = True Then
                    DBUtil.DatabaseName = dr.Cells("DataBaseName_Text").Value.ToString()
                    DatabaseName = dr.Cells("DataBaseName_Text").Value.ToString()


                    Dim SourcePath As String = ConfigurationManager.AppSettings("FilesSourcepath")
                    Dim DestinationPath As String = DBUtil.GetSettings("EasyShopFolder")
                    If DestinationPath = "" Then

                        ErrorLog.XmlError("CopySiteFiles Function", New ApplicationException("Please provide Easy Shop Folder for" & DBUtil.DatabaseName))
                        txtStatus.Text &= "Please provide Easy Shop Folder for " & DBUtil.DatabaseName & Environment.NewLine
                        txtStatus.Refresh()
                        MessageBox.Show("Please provide Easy Shop Folder for " & DBUtil.DatabaseName, "Errors")
                        GoTo nextrecord
                    End If
                    ThemeName = DBUtil.GetSettings("ThemeName")
                    Dim dSourceInfo As New DirectoryInfo(SourcePath)
                    Dim dTargetInfo As New DirectoryInfo(DestinationPath)


                    Dim FilePath As String = SourcePath & "\app_offline.htm"
                    NewDestinationPath = DestinationPath & "\app_offline.htm"
                    File.Copy(FilePath, NewDestinationPath, True)

                    CopyFilesAndDirectories(dSourceInfo, dTargetInfo, ThemeName, "")

                    txtStatus.Text &= "Updated EasyShop files for " & DatabaseName & Environment.NewLine
                    txtStatus.Refresh()

                    'Aded by Team7e for Issue#1426.
                    Dim TZone As String = TimeZoneName(DateTime.Now)

                    Dim ObjSettings As New SystemSettings()
                    ObjSettings.LastMaintenanceDate = System.DateTime.Now.ToString() & "@" & TZone & "."

                    DBUtil.UpdateLastMaintenanceDate(ObjSettings, DBUtil.DatabaseName)

                    File.Delete(NewDestinationPath)

                End If
nextrecord:
            Next
        Catch ex As Exception
            If File.Exists(NewDestinationPath) Then
                File.Delete(NewDestinationPath)
            End If

            txtStatus.Text &= ex.Message & vbCrLf
            txtStatus.Refresh()

            txtStatus.Text &= "Updated EasyShop files for " & DatabaseName & " with errors." & Environment.NewLine
            txtStatus.Refresh()

            lblProgress.Text = "Updated EasyShop files for " & DatabaseName & " with errors."
            lblProgress.Refresh()

            ErrorLog.XmlError("btnUpdateSiteFiles", ex)
            MessageBox.Show(ex.Message.ToString(), "Errors")
            Err = Err + 1
        End Try

    End Sub

-------------------------
Public Shared Function TimeZoneName(ByVal dt As DateTime) As [String]
        Dim sName As [String] = If(TimeZone.CurrentTimeZone.IsDaylightSavingTime(dt), TimeZone.CurrentTimeZone.DaylightName, TimeZone.CurrentTimeZone.StandardName)

        Dim sNewName As [String] = ""
        Dim sSplit As [String]() = sName.Split(New Char() {" "c})
        For Each s As [String] In sSplit
            If s.Length >= 1 Then
                sNewName += s.Substring(0, 1)
            End If
        Next

        Return sNewName
    End Function
---------------------------------
Public Shared Sub UpdateLastMaintenanceDate(ByVal objSettings As SystemSettings, ByVal DatabaseName As String)
        Dim conn As String
        If (UseTrustedConnection) Then
            conn = "server=" & ServerName & ";Integrated Security=SSPI;Database=" & DatabaseName & ";pooling='true'; Max Pool Size=800"
        Else
            conn = "server=" & ServerName & ";user id=" & ServerUserName & ";password=" & ServerPassword & ";Database=" & DatabaseName & ";pooling='true'; Max Pool Size=800"
        End If
        Dim connection As New SqlConnection(conn)
        Try
            If connection.State <> ConnectionState.Open Then
                connection.Open()
            End If
            Dim sqlCmd As New SqlCommand()
            sqlCmd.CommandText = "SP_UpdateLastMaintenanceDate"
            sqlCmd.CommandType = CommandType.StoredProcedure
            sqlCmd.Connection = connection
            sqlCmd.Parameters.AddWithValue("@LastMaintenanceDate", objSettings.LastMaintenanceDate)
            sqlCmd.ExecuteNonQuery()

        Catch ex As Exception
            ErrorLog.XmlError("btnUpdateSettings_Click", ex)
            MessageBox.Show(ex.Message.ToString())
        Finally
            If connection.State <> ConnectionState.Closed Then
                connection.Close()
            End If
        End Try
    End Sub
---------------------------
  Public Sub CopyFilesAndDirectories(ByVal source As DirectoryInfo, ByVal target As DirectoryInfo, ByVal Theme As String, ByVal CurrentDir As String)
        Try
            ' Check if the target directory exists, if not, create it.
            If Directory.Exists(target.FullName) = False Then
                Directory.CreateDirectory(target.FullName)
            End If
            ' Copy each file into it’s new directory.
            For Each fi As FileInfo In source.GetFiles()
                If CurrentDir <> "ErrorLogs" Then
                    fi.Attributes = FileAttributes.Archive
                    fi.CopyTo(Path.Combine(target.ToString(), fi.Name), True)
                    lblUpdateSiteFiles.Text = "Copying files: " & fi.Name

                    lblProgress.Text = "Copying files: " & target.ToString() & "\" & fi.Name
                    lblProgress.Refresh()

                    lblUpdateSiteFiles.Refresh()
                End If
            Next
            'Copy each subdirectory using recursion.

            For Each diSourceSubDir As DirectoryInfo In source.GetDirectories()
                If CurrentDir = "App_Themes" Then
                    If diSourceSubDir.Name = Theme OrElse diSourceSubDir.Name.ToLower() = "notheme" OrElse diSourceSubDir.Name = "StoreLocator" OrElse diSourceSubDir.Name = "Admin" OrElse diSourceSubDir.Name = "Preview" Then 'exclude other theme files
                        GoTo Cnt
                    Else
                        GoTo Nextdir
                    End If
                End If
                If CurrentDir = "CustomPages" Then 'Added by Team7e for Issue#1446.
                    If diSourceSubDir.Name.ToLower() = Theme.ToLower() OrElse diSourceSubDir.Name.ToLower() = "images" Then
                        GoTo Cnt
                    Else
                        GoTo Nextdir
                    End If
                End If

Cnt:
                Dim nextTargetSubDir As DirectoryInfo = Nothing

                If diSourceSubDir.Name.ToLower() <> "productimages" Then
                    nextTargetSubDir = target.CreateSubdirectory(diSourceSubDir.Name)
                End If

                If diSourceSubDir.Name.ToLower() <> "productimages" Then
                    Dim strParentDirectory As String = diSourceSubDir.Name
                    CopyFilesAndDirectories(diSourceSubDir, nextTargetSubDir, Theme, strParentDirectory)
                End If
Nextdir:
            Next
        Catch ex As Exception
            ErrorLog.XmlError("CopyFilesAndDirectories Function", ex)
            txtStatus.Text &= ex.Message & vbCrLf
            txtStatus.Refresh()
            MessageBox.Show(ex.Message.ToString(), "Errors")
        End Try
    End Sub
--------------------------
 Public Sub CopyAimsShopLinkFiles(ByRef Err As Integer)
        Try
            For Each dr As Infragistics.Win.UltraWinGrid.UltraGridRow In dgvDatabases.Rows
                If dr.Cells("select").Value = True Then
                    DBUtil.DatabaseName = dr.Cells("DataBaseName_Text").Value.ToString()
                    DatabaseName = dr.Cells("DataBaseName_Text").Value.ToString()
                    Dim SourcePath As String = ConfigurationManager.AppSettings("AimsShopLinkSource")
                    Dim DestinationPath As String = DBUtil.GetSettings("AimsShopLinkFolder")
                    If DestinationPath = "" Then

                        ErrorLog.XmlError("CopyAimsShopLinkFiles Function", New ApplicationException("Please provide AimsShopLink Folder for" & DBUtil.DatabaseName))
                        txtStatus.Text &= "Please provide AimsShopLink Folder for " & DBUtil.DatabaseName & Environment.NewLine
                        txtStatus.Refresh()

                        MessageBox.Show("Please provide AimsShopLink Folder for " & DBUtil.DatabaseName, "Errors")
                        GoTo nextrecord
                    End If

                    ThemeName = DBUtil.GetSettings("ThemeName")

                    Dim dSourceInfo As New DirectoryInfo(SourcePath)
                    Dim dTargetInfo As New DirectoryInfo(DestinationPath)

                    CopyFilesAndDirectories(dSourceInfo, dTargetInfo, "")
                    txtStatus.Text &= "Updated AIMSShopLink files for " & DatabaseName & Environment.NewLine
                    txtStatus.Refresh()
                End If
nextrecord:
            Next
        Catch ex As Exception
            txtStatus.Text &= ex.Message & vbCrLf
            txtStatus.Refresh()

            txtStatus.Text &= "Updated AIMSShopLink files for " & DatabaseName & " with errors." & Environment.NewLine
            txtStatus.Refresh()

            lblProgress.Text = "Updated AIMSShopLink files for " & DatabaseName & " with errors."
            lblProgress.Refresh()

            ErrorLog.XmlError("CopyAimsShopLinkFiles", ex)
            MessageBox.Show(ex.Message.ToString(), "CopyAimsShopLinkFiles")
            Err = Err + 1
        End Try

    End Sub
------------------------------------
    'Copy Aims Shoplink Source files
    Public Sub CopyFilesAndDirectories(ByVal source As DirectoryInfo, ByVal target As DirectoryInfo, ByVal CurrentDir As String)
        Try
            ' Check if the target directory exists, if not, create it.
            If Directory.Exists(target.FullName) = False Then
                Directory.CreateDirectory(target.FullName)
            End If
            ' Copy each file into it’s new directory.
            For Each fi As FileInfo In source.GetFiles()

                If CurrentDir <> "ErrorLogs" Then
                    If fi.Extension <> ".vspscc" Then
                        fi.Attributes = FileAttributes.Archive
                        fi.CopyTo(Path.Combine(target.ToString(), fi.Name), True)
                        lblUpdateSiteFiles.Text = "Copying files: " & fi.Name

                        lblProgress.Text = "Copying files: " & target.ToString() & "\" & fi.Name
                        lblProgress.Refresh()

                        lblUpdateSiteFiles.Refresh()
                    End If
                End If
            Next
            'Copy each subdirectory using recursion.
            For Each diSourceSubDir As DirectoryInfo In source.GetDirectories()
                Dim nextTargetSubDir As DirectoryInfo = Nothing
                nextTargetSubDir = target.CreateSubdirectory(diSourceSubDir.Name)
                Dim strParentDirectory As String = diSourceSubDir.Name
                CopyFilesAndDirectories(diSourceSubDir, nextTargetSubDir, strParentDirectory)
            Next
        Catch ex As Exception
            ErrorLog.XmlError("CopyFilesAndDirectories Function", ex)

            txtStatus.Text &= ex.Message & vbCrLf
            txtStatus.Refresh()

            MessageBox.Show(ex.Message.ToString(), "CopyFilesAndDirectories")
        End Try
    End Sub

Execute Scripts in Specific Database (windows Application)....


Form1.vb
=======
 Function RunScriptsFiles(ByVal n As Integer, ByVal worker As BackgroundWorker, ByVal e As DoWorkEventArgs) As Long
        Try

            btnOK.Enabled = False
            btnCancel.Enabled = True

            Dim filecount As Integer = IO.Directory.GetFiles(Helper.GetSqlPath & "SqlScripts").Length
            pb.Minimum = 0
            pb.Value = 0

            pb.Maximum = filecount * gCount

            Dim intversion As Integer
            Dim databasename As String = ""
            Dim bool As Boolean = True
            Dim islatestversion As Boolean = True
            'below for loop will loop throught all the checked database names

            For i As Integer = 0 To dgvDatabases.Rows.Count - 1
                If dgvDatabases.Rows(i).Cells("select").Value = True Then
                    bool = True
                    databasename = dgvDatabases.Rows(i).Cells("DataBaseName_Text").Value.ToString()

                    txtStatus.Text &= "Status Log for " & databasename & " database." & vbCrLf

                    DBUtil.DatabaseName = databasename
                    'below line to make a back up of the current database on to which the scripts are running.
                    Try
                        intversion = DBUtil.GetDatabaseVersion
                    Catch sqlex As SqlException
                        txtStatus.Text &= "Sql Exception " & sqlex.Message & vbCrLf
                        bool = False
                        If sqlex.Message.Contains("Could not open a connection to SQL Server") Then
                            txtStatus.Text &= vbCrLf & "Errors occured while running scripts for the database " & databasename & ". please verify them in the above logs." & vbCrLf & vbCrLf
                            'increment the progress bar value with one percent every time.
                            pb.Value += 1
                            lblProgress.Text = "Please wait... Verifying scripts for " & databasename & " database " & Math.Round(pb.Value / (filecount * gCount) * 100) & " % completed."
                            Continue For
                        End If
                    Catch ex As Exception
                        txtStatus.Text &= ex.Message & vbCrLf
                        bool = False
                    End Try
                    'if file exist then load XML file and Append Child
                    If txtBrowsePath.Text <> "" Then
                        If File.Exists(txtBrowsePath.Text & "\" & databasename & "-" & intversion & ".bak") Then
                            File.Delete(txtBrowsePath.Text & "\" & databasename & "-" & intversion & ".bak")
                        End If
                        Try
                            BackUpDatabase(databasename, txtBrowsePath.Text & "\" & databasename & "-" & intversion & ".bak", ConfigurationManager.AppSettings.Item("SqlServer"), False, ConfigurationManager.AppSettings.Item("SqlUsername"), ConfigurationManager.AppSettings.Item("SqlPassword"))
                            txtStatus.Text &= "The database for " & databasename & " has been backed up successfully at " & txtBrowsePath.Text & vbCrLf
                        Catch ex As Exception
                            bool = False
                            txtStatus.Text &= "Error at Database backup " & ex.Message & vbCrLf
                        End Try
                    End If
                    Dim strPathToFile As String
                    'below for loop will loop through the files specified in the SqlScripts folder fo this application
                    For k As Integer = 1 To filecount
                        If worker.CancellationPending Then
                            e.Cancel = True
                            Exit Function
                        End If
                        'increment the progress bar value with one percent every time.
                        pb.Value += 1
                        lblProgress.Text = "Please wait... Verifying scripts for " & databasename & " database " & Math.Round(pb.Value / (filecount * gCount) * 100) & " % completed."
                        strPathToFile = Helper.GetSqlPath & "SqlScripts\Version" & (intversion + k) & ".sql"
                        'to check fi the script file version number is greater than the current version fo the database
                        'If (intversion + k) = intversion Then
                        'txtStatus.Text &= "Database " & databasename & " is already on the latest version." & vbCrLf & vbCrLf
                        'Else
                        If (intversion + k) > intversion Then
                            If IO.File.Exists(strPathToFile) Then
                                islatestversion = False
                                lblProgress.Text = "Please wait... Running script for " & databasename & " database " & Math.Round(pb.Value / (filecount * gCount) * 100) & " % completed."
                                txtStatus.Text &= "Started Running Script No." & (intversion + k) & "." & vbCrLf
                                'calling the DBUtil class for executing the script statements.
                                Try
                                    DBUtil.Upgrade(strPathToFile)
                                    txtStatus.Text &= "Script No." & (intversion + k) & " has been ran successfully." & vbCrLf
                                Catch ex As Exception
                                    bool = False
                                    txtStatus.Text &= "Error at executing script " & (intversion + k) & ex.Message & vbCrLf
                                End Try
                            Else
                                'in case if any script file misses in the Sqlscript folder, then try to get the next file
                                ' try this until four time. else skip the database from executing the scripts.
                                intversion += k
                                For j As Integer = 1 To 4
                                    strPathToFile = Helper.GetSqlPath & "SqlScripts\Version" & (intversion + j) & ".sql"
                                    If IO.File.Exists(strPathToFile) Then
                                        islatestversion = False
                                        lblProgress.Text = "Please wait... Running script for " & databasename & " database " & Math.Round(pb.Value / (filecount * gCount) * 100) & " % completed."
                                        'calling the DBUtil class for executing the script statements
                                        Try
                                            DBUtil.Upgrade(strPathToFile)
                                            txtStatus.Text &= "Script No." & (intversion + k) & " has been ran successfully." & vbCrLf
                                        Catch ex As Exception
                                            bool = False
                                            txtStatus.Text &= "Error at executing script " & (intversion + k) & ex.Message & vbCrLf
                                        End Try
                                    End If
                                Next
                            End If
                        Else
                            lblProgress.Text = "Please wait... Verifying scripts for " & databasename & " database " & Math.Round(pb.Value / (filecount * gCount) * 100) & " % completed."
                            txtStatus.Text &= "Script No." & (intversion + k) & " has been skipped from from execution." & vbCrLf
                        End If
                    Next
                    If bool Then
                        If islatestversion Then
                            txtStatus.Text &= "It seems like " & databasename & " is already in latest version." & vbCrLf & vbCrLf
                        Else
                            txtStatus.Text &= "Scripts ran successfully for the database " & databasename & vbCrLf & vbCrLf
                        End If
                    Else
                        txtStatus.Text &= "Errors occured while running scripts for the database " & databasename & " please verify them in the above logs." & vbCrLf & vbCrLf
                    End If
                End If
            Next
            lblProgress.Text = "Script process 100% completed."
            pb.Value = pb.Maximum
        Catch ex As Exception

            MsgBox(ex.Message)
            btnOK.Enabled = True
            errorbool = False
            Throw ex
        End Try
    End Function
 ------------------------------

  Public Shared Sub BackUpDatabase(ByVal DataBase As String, ByVal FilePath As String, ByVal strSQLServerName As String, ByVal blnTrustedConnection As Boolean, Optional ByVal strSQLUsername As String = "", Optional ByVal strSQLPassword As String = "")
        Dim sql As String = "BACKUP DATABASE [" & DataBase & "] TO DISK = '" & FilePath & "'"
        'To Generate A Backup Of The Specifed database and save it in a specifeid file
        'Dim dmoServer As New SQLDMO.SQLServer
        Dim dmoServer As Server
        Dim objSvrConn As ServerConnection

        Try
            'dmoServer.LoginSecure = blnTrustedConnection
            'dmoServer.Connect(strSQLServerName, strSQLUsername, strSQLPassword)

            objSvrConn = New ServerConnection()
            objSvrConn.LoginSecure = False
            objSvrConn.ServerInstance = strSQLServerName
            objSvrConn.Login = strSQLUsername
            objSvrConn.Password = strSQLPassword

            dmoServer = New Server(objSvrConn)

            dmoServer.ConnectionContext.ExecuteNonQuery(sql)
        Catch ex As System.Runtime.InteropServices.COMException     'ErrorCode  -2147218303    Integer
            If ex.ErrorCode = -2147218303 Then                      'When The Server And The File System Are In Different Systems
                ' Throw New Exception("Please make sure the Database and the file selected reside in same Terminal")
                Throw New Exception(ex.Message)
            End If
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

=====================================================================
Helper.vb
=========
 Public Shared Function GetSqlPath() As String
    Return Application.StartupPath & "\"     'This is like server.mappath
  End Function
======================================================================
DBUtil.vb
========
  Public Shared Sub Upgrade(Optional ByVal strPathToFile As String = "")
        Dim dr As IO.StreamReader 'which reads the script
        Dim dbServer As New SQLServer
        Try
            Dim strSQL As String = ""
            dbServer.LoginSecure = UseTrustedConnection
            dbServer.Connect(ServerName, ServerUserName, ServerPassword)
            If IO.File.Exists(strPathToFile) Then
                dr = IO.File.OpenText(strPathToFile)  'opening the file to read the SQL script
                strSQL &= "USE [" & DatabaseName & "]" & vbCrLf
                strSQL &= " GO " & vbCrLf
                strSQL &= dr.ReadToEnd
                dbServer.ExecuteImmediate(strSQL) 'executes the script
                dr.Close()
            End If
        Catch ex As System.Exception
            Throw New Exception(ex.Message)
        Finally
            dbServer.DisConnect()
        End Try
    End Sub