VB.NET - BackUp sql server database using vb.net to a user defined Path

Asked By waleed
18-Nov-10 01:30 PM
Dear All ,

I need to backup the sql server 2005 express database . It works fine if I make backup to specific folder"C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Backup" . But if I change the path to any other path . I got an error "Backup failed for Server 'server name'. "

my code is

Dim sqlBackup As New Backup()
sqlBackup.Action = BackupActionType.Database
sqlBackup.BackupSetDescription = "ArchiveDataBase:" + DateTime.Now.ToShortDateString()
sqlBackup.BackupSetName = "Archive"
sqlBackup.Database = "data"
Dim deviceItem As New BackupDeviceItem("C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Backup\rft.bak", DeviceType.File)
Dim connection As New ServerConnection(".\SQLEXPRESS")
Dim sqlServer As New Server(connection)
Dim db As Database = sqlServer.Databases("RegServer")
sqlBackup.Initialize = True
sqlBackup.Checksum = True
sqlBackup.ContinueAfterError = True
sqlBackup.Devices.Add(deviceItem)
sqlBackup.Incremental = False
sqlBackup.ExpirationDate = DateTime.Now.AddDays(3)
sqlBackup.LogTruncation = BackupTruncateLogType.Truncate
sqlBackup.FormatMedia = False
sqlBackup.SqlBackup(sqlServer)






please help
  Anoop S replied to waleed
18-Nov-10 01:43 PM
Backup failed for Server 'ServerName' error will come when you do not pass the server name correctly if you are using Windows authentication.

 Use the follwing code.... to resolve the issue..
ServerConnection conn = new ServerConnection("Server name"); //Windows Authentication.

ServerConnection conn = new ServerConnection("Server name", "User Name" , "Password"); //SQL Server Authentication.

Server myServer = new Server(conn);
  waleed replied to Anoop S
18-Nov-10 01:58 PM
Thanks for your fast reply .

I tried your code , it did not work . May you please send me the entire code to check it or a working application .

Moreover , the code I send in the original question works fine but only If I stated the backup location to the default backup location of the the sqlserver installation path , ie , "C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Backup" , this means that there is no problem with the code or the server connection string , I guess so . I may be wrong .

Any idea ? .
  Anoop S replied to waleed
19-Nov-10 12:43 AM
You can refer this code

Public Class BackupManager
  Private srvSql As Server
  Private saveBackupDialog As New SaveFileDialog()
  Private openBackupDialog As New OpenFileDialog()
  Private dbCache As DatabaseCache = DatabaseCache.Instance
 
  Private Function GetAppPath() As String
    Return System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath)
  End Function
  Private Sub Connect()
    Dim srvConn As New ServerConnection(dbCache.SqlConnection)
    srvSql = New Server(srvConn)
  End Sub
  Private Function GetDatabase(conn As SqlConnection) As String
    Dim connArray As String() = conn.ConnectionString.Split(";"C)
    Dim toMatch As String = "AttachDbFilename="
    Dim match As String = Nothing
    For Each item As String In connArray
      If item.StartsWith(toMatch) Then
        match = item.Substring(toMatch.Length)
        Exit For
      End If
    Next
    If Not [String].IsNullOrEmpty(match) Then
      match = match.Replace("|DataDirectory|", GetAppPath())
    Else
      Throw New Exception("Could not extract database path from connection string")
    End If
    Return match
  End Function
  Public Function MakeBackup() As Boolean
    ' If there was a SQL connection created
    If srvSql Is Nothing Then
      Connect()
    End If
    If srvSql IsNot Nothing Then
      Dim path As String = GetAppPath()
      path = path += "\Backup"
      If Not Directory.Exists(path) Then
        Directory.CreateDirectory(path)
      End If
      saveBackupDialog.InitialDirectory = path
      saveBackupDialog.DefaultExt = "bak"
      ' If the user has chosen a path
      ' where to save the backup file
      If saveBackupDialog.ShowDialog() = DialogResult.OK Then
        ' Create a new backup operation
        Dim bkpDatabase As New Backup()
        ' Set the backup type to a database backup
        bkpDatabase.Action = BackupActionType.Database
        ' Set the database that we want to perform a backup on
        bkpDatabase.Database = GetDatabase(dbCache.SqlConnection)
        ' Set the backup device to a file
        Dim bkpDevice As New BackupDeviceItem(saveBackupDialog.FileName, DeviceType.File)
        ' Add the backup device to the backup
        bkpDatabase.Devices.Add(bkpDevice)
        ' Perform the backup
        bkpDatabase.SqlBackup(srvSql)
      Else
        Return False
      End If
    Else
      Throw New Exception("Could not connect to database.")
    End If
    Return True
  End Function
  Public Sub RestoreBackup()
    'database must first be unloaded before calling this.
    ' If there was a SQL connection created
    If srvSql Is Nothing Then
      Connect()
    End If
    If srvSql IsNot Nothing Then
      openBackupDialog.InitialDirectory = "./Backup"
      openBackupDialog.DefaultExt = "bak"
      ' If the user has chosen the file from which he wants the database to be restored
      If openBackupDialog.ShowDialog() = DialogResult.OK Then
        ' Create a new database restore operation
        Dim rstDatabase As New Restore()
        ' Set the restore type to a database restore
        rstDatabase.Action = RestoreActionType.Database
        ' Set the database that we want to perform the restore on
        rstDatabase.Database = GetDatabase(dbCache.SqlConnection)
        ' Set the backup device from which we want to restore, to a file
        Dim bkpDevice As New BackupDeviceItem(openBackupDialog.FileName, DeviceType.File)
        ' Add the backup device to the restore type
        rstDatabase.Devices.Add(bkpDevice)
        ' If the database already exists, replace it
        rstDatabase.ReplaceDatabase = True
        ' Perform the restore
        Try
          rstDatabase.SqlRestore(srvSql)
        Catch ex As FailedOperationException
 
          Log.WriteLine("")
          Log.WriteLine("Error: (BackupManager.RestoreBackup)")
 
          Log.Write(ex)
          Throw New Exception("Error while restoring backup.", ex)
 
        End Try
      End If
    Else
      Throw New Exception("Could not connect to database.")
    End If
  End Sub
End Class


  waleed replied to Anoop S
19-Nov-10 08:37 AM
 

Dear Sir ,

Thanks for the code , it seems professional . Unfortunately , I can not test it because vb.net does not understand the sentence
"  Private dbCache As DatabaseCache = DatabaseCache.Instance"

Can you please advice how to add reference to support to the "DatebaseCache" class.


Thanks,


Waleed
  Anoop S replied to waleed
19-Nov-10 11:14 AM
actually its not reference,
instead of that code try with this code

Public Class BackupManager
  
  Dim srvSql As Server
  Dim saveBackupDialog As SaveFileDialog =  New SaveFileDialog()
  Dim openBackupDialog As OpenFileDialog =  New OpenFileDialog()
  Dim dbCache As DatabaseCache =  DatabaseCache.Instance
  
  
  Private Function GetAppPath() As String
    Return System.IO.Path.GetDirectoryName
      (System.Windows.Forms.Application.ExecutablePath)
  End Function
  Private  Sub Connect()
    ServerConnection srvConn = New
        ServerConnection(dbCache.SqlConnection)
    srvSql = New Server(srvConn)
  End Sub
  
  Private Function GetDatabase(ByVal conn As SqlConnection) As String
    Dim connArray() As String =  conn.ConnectionString.Split(";"c)
    Dim toMatch As String "AttachDbFilename="
    Dim match As String Nothing
    Dim item As String
    For Each item In connArray
      If item.StartsWith(toMatch) Then
        match = item.Substring(toMatch.Length)
        Exit For
      End If
    Next
    If Not String.IsNullOrEmpty(match) Then
       match = match.Replace("|DataDirectory|", GetAppPath())
    Else
       Throw New Exception(
        "Could not extract database path from connection string")
    End If
    Return match
  End Function
  
  Public Function MakeBackup() As Boolean
    ' If there was a SQL connection created
    If srvSql Is Nothing Then
      Connect()
    End If
    If Not srvSql Is Nothing Then
      Dim path As String =  GetAppPath()
      path = path += "\Backup"
      If Not Directory.Exists(path) Then
        Directory.CreateDirectory(path)
      End If
      saveBackupDialog.InitialDirectory = path
      saveBackupDialog.DefaultExt = "bak"
  
      ' If the user has chosen a path
      ' where to save the backup file
      If saveBackupDialog.ShowDialog() = DialogResult.OK Then
         ' Create a new backup operation
        Dim bkpDatabase As Backup =  New Backup()
        ' Set the backup type to a database backup
        bkpDataMyBase.Action = BackupActionType.Database
        ' Set the database that we want to perform a backup on
        bkpDataMyBase.Database = GetDatabase(dbCache.SqlConnection)
        ' Set the backup device to a file
        Dim bkpDevice As BackupDeviceItem =  New BackupDeviceItem(saveBackupDialog.FileName,DeviceType.File)
        ' Add the backup device to the backup
        bkpDataMyBase.Devices.Add(bkpDevice)
         ' Perform the backup
        bkpDataMyBase.SqlBackup(srvSql)
      Else
        Return False
      End If
    Else 
      Throw New Exception("Could not connect to dataMyBase.")
    End If
    Return True
  End Function
   
  Public  Sub RestoreBackup()
     'database must first be unloaded before calling this.
     ' If there was a SQL connection created
    If srvSql Is Nothing Then
      Connect()
    End If
    If Not srvSql Is Nothing Then
      openBackupDialog.InitialDirectory = "./Backup"
      openBackupDialog.DefaultExt = "bak"
      ' If the user has chosen the file from which he wants the database to be restored
      If openBackupDialog.ShowDialog() = DialogResult.OK Then
        ' Create a new database restore operation
        Dim rstDatabase As Restore =  New Restore() 
        ' Set the restore type to a database restore
        rstDataMyBase.Action = RestoreActionType.Database
        ' Set the database that we want to perform the restore on
        rstDataMyBase.Database = GetDatabase(dbCache.SqlConnection)
        ' Set the backup device from which we want to restore, to a file
        Dim bkpDevice As BackupDeviceItem =  New BackupDeviceItem(openBackupDialog.FileName,DeviceType.File) 
        ' Add the backup device to the restore type
        rstDataMyBase.Devices.Add(bkpDevice)
        ' If the database already exists, replace it
        rstDataMyBase.ReplaceDatabase = True
        ' Perform the restore
        Try
          rstDataMyBase.SqlRestore(srvSql)
        Catch ex As FailedOperationException
          Log.WriteLine("")
          Log.WriteLine("Error: (BackupManager.RestoreBackup)")
          Log.Write(ex)
          Throw New Exception("Error while restoring backup.", ex)
        End Try
      End If
     Else 
      Throw New Exception("Could not connect to dataMyBase.")
    End If  
  End Sub
End Class

  waleed replied to Anoop S
19-Nov-10 11:24 AM
Dear Anoop ,

Thanks for your fast response , but Unfortunately , the same error exists , I need to get the reference or type for the datatype DatabaseCache . are there a definition for it .
I do not know why the code works with you and does not work with me . are there any missing things with my PC .


Thank you in advance for your support.


Waleed
  Anoop S replied to waleed
19-Nov-10 12:41 PM
refer this
http://msdn.microsoft.com/en-us/library/bb882690.aspx
  waleed replied to Anoop S
19-Nov-10 12:52 PM
Dear Anoops ,

It seems that I am not as proffessional as you, this is article is very complicated for me to get . I appreciate if you can make a sample vb.net or c# sample application .


Thank you in advance for your support.
  Anoop S replied to waleed
19-Nov-10 02:11 PM
Hi
try with this code in c#
public void (string databaseName, string filePath)
{
try
      {
        Server localServer = new Server(); //local using windows athuentication
        Backup backupMgr = new Backup();
        backupMgr.Devices.AddDevice(filePath, DeviceType.File);
        backupMgr.Database = databaseName;
        backupMgr.Action = BackupActionType.Database;
        backupMgr.SqlBackup(localServer);
      }
      catch(Exception ex)
      {
        MessageBox.Show(ex.Message + " " + ex.InnerException);
      }
}

refer
http://www.daniweb.com/forums/thread202843.html
http://www.dotnetspider.com/forum/162986-database-backup-restore-through-C.aspx
  waleed replied to Anoop S
19-Nov-10 06:22 PM
 I tried it but i wonder where is the  connection string to the server ?

Anyway, I tried it and got the below error :


Backup failed for Server 'BOSHBOSH-E83188'. ....Microsoft.SqlServer.Management.Common.ConnectionFailureException: Failed to connect to server .. ---> System.Data.SqlClient.SqlException: An error has occurred while establishing a connection to the server.  When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
   at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, SqlConnection owningObject)
   at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject)
   at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart)
   at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance)
   at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance)
   at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)
   at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options)
   at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject)
   at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject)
   at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)
   at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
   at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
   at System.Data.SqlClient.SqlConnection.Open()
   at Microsoft.SqlServer.Management.Common.ConnectionManager.InternalConnect(WindowsIdentity impersonatedIdentity)
   at Microsoft.SqlServer.Management.Common.ConnectionManager.Connect()
   --- End of inner exception stack trace ---
   at Microsoft.SqlServer.Management.Common.ConnectionManager.Connect()
   at Microsoft.SqlServer.Management.Common.ConnectionManager.get_ServerVersion()
   at Microsoft.SqlServer.Management.Smo.ExecutionManager.GetServerVersion()
   at Microsoft.SqlServer.Management.Smo.Backup.Script(Server targetServer)
   at Microsoft.SqlServer.Management.Smo.Backup.SqlBackup(Server srv)
  Anoop S replied to waleed
19-Nov-10 09:43 PM
the error is getting because there is no connection established,You need to add connection string, the code only for backup portion, 1st add your connection string info to the code and then try
string ConnectionString = "Data Source=" + Server + ";";
ConnectionString += "User ID=" + Username + ";";
ConnectionString += "Password=" + Password + ";";
ConnectionString += "Initial Catalog=" + Database;

 SQLConnection.ConnectionString = ConnectionString;
    SQLConnection.Open();
  waleed replied to Anoop S
20-Nov-10 11:20 AM
Still not working.
I appreciate if you can write code and test it in vb.net then send the application . I am afraid that I have a problem with my SQL Server installation . Thus , we can solve this issue faster.

Thank you in advance for your support.


Waleed
  Manu replied to waleed
29-Dec-10 05:38 PM

Waleed,

Find the modified version of VB.Net coding for your understanding.

Imports System.Data

Imports System.Data.SqlClient

Imports System.IO

Imports Microsoft.SqlServer.Management.Smo

 Imports Microsoft.SqlServer.Management.Common

 

Public Class DbBackup_Class

'Class used for my application

Dim db_Cls As New DB_Class

Dim srvSql As Server

Dim saveBackupDialog As New SaveFileDialog

Dim openBackupDialog As New OpenFileDialog

'strCon As String = "Data Source=OFFICE-PC;Initial Catalog=Table_Master;User ID=admin;pwd=admin"

Dim sqlConn As New SqlConnection(db_Cls.strCon)

Private Function GetAppPath() As String

 'Return System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath)

 Return "C:\sqlBackup"

End Function

 

Private Sub Connect()

Dim srvConn As New ServerConnection(sqlConn)

srvSql = New Server(srvConn)

End Sub

 

Private Function GetDatabase(ByVal conn As SqlConnection) As String

Dim connArray() As String = conn.ConnectionString.Split(";")

Dim toMatch As String = "Initial Catalog="

Dim match As String = Nothing

 

For Each item As String In connArray

  If item.StartsWith(toMatch) Then

    match = item.Substring(toMatch.Length)

    Exit For

  End If

Next

 

If Not String.IsNullOrEmpty(match) Then

   match = match.Replace("|DataDirectory|", GetAppPath())

Else

   Throw New Exception("Could not extract database path from connection string")

End If

 

Return match

End Function

 

Public Function MakeBackup() As Boolean

 'If there was a SQL connection created

If srvSql Is Nothing Then

   Connect()

End If

 

If Not srvSql Is Nothing Then

  Dim path As String = GetAppPath()

  path += "\Backup" & Now.Date.Day & Now.Date.Month & Now.Date.Year

  If Not Directory.Exists(path) Then

    Directory.CreateDirectory(path)

  End If

  saveBackupDialog.InitialDirectory = path

  saveBackupDialog.DefaultExt = "bak"

 

  'If the user has chosen a path where to save the backup file

  If saveBackupDialog.ShowDialog() = DialogResult.OK Then

    'Create a new backup operation

    Dim bkpDatabase As New Backup

    
    'Set the backup type to a database backup

    bkpDatabase.Action = BackupActionType.Database

    'Set the database that we want to perform a backup on

    bkpDatabase.Database = GetDatabase(sqlConn)

    'Set the backup device to a file

    Dim bkpDevice As New BackupDeviceItem(saveBackupDialog.FileName, DeviceType.File)

    'Add the backup device to the backup

    bkpDatabase.Devices.Add(bkpDevice)

    'Perform the backup

    bkpDatabase.SqlBackup(srvSql)

  Else

     Return False

  End If

Else

  Throw New Exception("Could not connect to database.")

End If

 

Return True

 

End Function

 

Public Sub RestoreBackup()

'database must first be unloaded before calling this. If there was a SQL connection created

 

If srvSql Is Nothing Then

 

Connect()

End If

 

If Not srvSql Is Nothing Then

 

openBackupDialog.InitialDirectory = "C:\sqlBackup"

 

openBackupDialog.DefaultExt = "bak"

 

' If the user has chosen the file from which he wants the database to be restored

 

If openBackupDialog.ShowDialog() = DialogResult.OK Then

 

' Create a new database restore operation

 

Dim rstDatabase As New Restore()

' Set the restore type to a database restore

 

rstDatabase.Action = RestoreActionType.Database

' Set the database that we want to perform the restore on

 

rstDatabase.Database = GetDatabase(sqlConn)

' Set the backup device from which we want to restore, to a file

 

Dim bkpDevice As BackupDeviceItem = New BackupDeviceItem(openBackupDialog.FileName, DeviceType.File)

' Add the backup device to the restore type

 

rstDatabase.Devices.Add(bkpDevice)

' If the database already exists, replace it

 

rstDatabase.ReplaceDatabase = True

 

' Perform the restore

 

Try

 

rstDatabase.SqlRestore(srvSql)

Catch ex As FailedOperationException

Dim LogFile As File

Dim Log As StreamWriter

Log = LogFile.CreateText("C:\sqlRestoreError.txt")

Log.WriteLine("")

Log.WriteLine("Error: (BackupManager.RestoreBackup)")

Log.Write(ex)

Log.Close()

Throw New Exception("Error while restoring backup.", ex)

End Try

 

End If

 

Else

 

Throw New Exception("Could not connect to dataMyBase.")

End If

 

End Sub

End Class

For your doubt about DatabaseCache in your previous communication you can refer below link:

http://social.msdn.microsoft.com/Forums/en/sqlsmoanddmo/thread/1bef2612-6820-4ddd-bb64-087d0bc9d93d

Regards

Manu Gaffur

  Ram Singh replied to Anoop S
23-Dec-11 12:21 PM
You can try this vb.net code and for further help you may visit http://ram-a-singh.blogspot.com/2011/12/how-to-take-backup-from-database-vbnet.html 


Dim s As StreamWriter
Dim portfolioPath As String = My.Application.Info.DirectoryPath
If Not Directory.Exists("C:\Backup") Then
Directory.CreateDirectory("C:\Backup")
File.Create("C:\ Backup\PIS.Mdb").Close()
File.Create("C: \Backup\Backup log.rtf").Close()
s = New StreamWriter("C:\Backup\Backup log.rtf", True)
s.WriteLine("This backup was initially taken on - " & Date.Now)
        s.Flush()
        s.Close()
FileCopy(portfolioPath & "\PIS.mdb", "C:\Backup\PIS.Mdb")
s = New StreamWriter("C:\Backup\Backup log.rtf", True)
 MsgBox("New directory and backup file created")
Create New Account
help
SQL Vb.Net 2005 .NET Framework Is there a way to backup and restore an SQL database with Vb.Net 2005 VB.NET Discussions SQL Server (1) ADO.NET (1) Database (1) Show (1) You can issue
backup and retore of sql-server database in vb.net. How to take backup of sql-server database in vb.net. And how to retore it using vb.net. Hi, here is the nice article for
Backup of Remote SQL Server using VB Net Code .NET Framework Jan 26, 2010 Hi all I am using VB Net 2008 and SQL 2008. I am taking a backup of a local SQL Server Database using the following code: Dim backup As SQLDMO.Backup
backup and restore of mysql database in vb.net hello to all i m making a project in vb.net using mysql database i want to give an utility to take backup and restore database in vb.net (window application) how can i do this? Try this: For Backup: Process.Start("C: \ MySQL