SQL Server Developer Center > SQL Server Forums > SQL Server SMO/DMO > Backup and recovery of SQL Server using VB.net
Ask a questionAsk a question
 

AnswerBackup and recovery of SQL Server using VB.net

  • Tuesday, December 05, 2006 4:55 AMGRK Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    Hi,

       I have  a small application in which i'm using Sql Server as Database. my requirement is how to take the backup of the entire database or some tables from the database when there is any delete from the database. My requirement is to do from the VB.net application.Hope i delivered my question correctly. Any little help is beneficial to me.

    -regards

    GRK

Answers

  • Tuesday, December 05, 2006 5:10 AMShEi Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer

    Try this one out...

    Dim oDevice As New SQLDMO.BackupDevice
    Dim BACKUP As New SQLDMO.BACKUP
    Dim SERVER As New SQLServer

    Private Sub Form_Load()
    On Error Resume Next 'If the device already exists an error will result if you try to add it again so just resume next cos its already there

    With oDevice
      .Type = SQLDMODevice_DiskDump
      .Name = "NorthwindBakUp"
      .PhysicalLocation = "C:\Documents and Settings\Administrator\Desktop\BACKUP.bak"
    End With

    SERVER.Connect "Sanjib", "sa"
    SERVER.BackupDevices.Add oDevice
    BACKUP.Action = SQLDMOBackup_Database
    BACKUP.Database = "Northwind"
    BACKUP.Devices ="NorthwindBakUp"
    BACKUP.BackupSetDescription = "Full BackUp"
    BACKUP.BackupSetName = "By Sanjib"

    BACKUP.SQLBackup SERVER

    End Sub

  • Tuesday, December 05, 2006 5:28 AMcverdon Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer

    Hi,

    Here's my backup class of one of my project that uses Microsoft.SqlServer.Management:

    public class BackupManager

    {

        Server srvSql;

     

        SaveFileDialog saveBackupDialog = new SaveFileDialog();

        OpenFileDialog openBackupDialog = new OpenFileDialog();

        DatabaseCache dbCache = DatabaseCache.Instance;

     

        private string GetAppPath()

        {

            return System.IO.Path.GetDirectoryName

                (System.Windows.Forms.Application.ExecutablePath);

        }

     

        private void Connect()

        {

            ServerConnection srvConn = new

                  ServerConnection(dbCache.SqlConnection);

            srvSql = new Server(srvConn);

        }

     

        private string GetDatabase(SqlConnection conn)

        {

            string[] connArray = conn.ConnectionString.Split(';');

            string toMatch = "AttachDbFilename=";

            string match = null;

            foreach (string item in connArray) {

                if (item.StartsWith(toMatch))

                {

                    match = item.Substring(toMatch.Length);

                    break;

                }

            }

            if (!String.IsNullOrEmpty(match) ) {

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

            } else {

                throw new Exception(

                  "Could not extract database path from connection string");

            }

            return match;

        }

     

        public bool MakeBackup()

        {

            // If there was a SQL connection created

            if (srvSql == null) {

                Connect();

            }

     

            if (srvSql != null)

            {

                string path = GetAppPath();

                path = path += @"\Backup";

                if (!Directory.Exists(path))

                {

                    Directory.CreateDirectory(path);

                }

                saveBackupDialog.InitialDirectory = path;

                saveBackupDialog.DefaultExt = "bak";

     

                // If the user has chosen a path

                // where to save the backup file

                if (saveBackupDialog.ShowDialog() == DialogResult.OK)

                {

                    // Create a new backup operation

                    Backup bkpDatabase = 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

                    BackupDeviceItem bkpDevice = 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;

                }

            } else {

                throw new Exception("Could not connect to database.");

            }

            return true;

        }

     

        public void RestoreBackup()

        {

            //database must first be unloaded before calling this.

     

            // If there was a SQL connection created

            if (srvSql == null)

            {

                Connect();

            }

     

            if (srvSql != null)

            {

                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)

                {

                    // Create a new database restore operation

                    Restore rstDatabase = 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

                    BackupDeviceItem bkpDevice = 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 (FailedOperationException ex)

                    {

                        Log.WriteLine( "" );

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

                        Log.Write( ex );

                        throw new Exception("Error while restoring backup.", ex);

                    }

                }

               

            }

            else

            {

                throw new Exception("Could not connect to database.");

            }

     

        }

    }

    It's not generic so you'll have to change some of the code (and translate to vb...) You can see the basic idee from the code above.

    Good luck,
    Charles

All Replies

  • Tuesday, December 05, 2006 5:10 AMShEi Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer

    Try this one out...

    Dim oDevice As New SQLDMO.BackupDevice
    Dim BACKUP As New SQLDMO.BACKUP
    Dim SERVER As New SQLServer

    Private Sub Form_Load()
    On Error Resume Next 'If the device already exists an error will result if you try to add it again so just resume next cos its already there

    With oDevice
      .Type = SQLDMODevice_DiskDump
      .Name = "NorthwindBakUp"
      .PhysicalLocation = "C:\Documents and Settings\Administrator\Desktop\BACKUP.bak"
    End With

    SERVER.Connect "Sanjib", "sa"
    SERVER.BackupDevices.Add oDevice
    BACKUP.Action = SQLDMOBackup_Database
    BACKUP.Database = "Northwind"
    BACKUP.Devices ="NorthwindBakUp"
    BACKUP.BackupSetDescription = "Full BackUp"
    BACKUP.BackupSetName = "By Sanjib"

    BACKUP.SQLBackup SERVER

    End Sub

  • Tuesday, December 05, 2006 5:28 AMcverdon Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer

    Hi,

    Here's my backup class of one of my project that uses Microsoft.SqlServer.Management:

    public class BackupManager

    {

        Server srvSql;

     

        SaveFileDialog saveBackupDialog = new SaveFileDialog();

        OpenFileDialog openBackupDialog = new OpenFileDialog();

        DatabaseCache dbCache = DatabaseCache.Instance;

     

        private string GetAppPath()

        {

            return System.IO.Path.GetDirectoryName

                (System.Windows.Forms.Application.ExecutablePath);

        }

     

        private void Connect()

        {

            ServerConnection srvConn = new

                  ServerConnection(dbCache.SqlConnection);

            srvSql = new Server(srvConn);

        }

     

        private string GetDatabase(SqlConnection conn)

        {

            string[] connArray = conn.ConnectionString.Split(';');

            string toMatch = "AttachDbFilename=";

            string match = null;

            foreach (string item in connArray) {

                if (item.StartsWith(toMatch))

                {

                    match = item.Substring(toMatch.Length);

                    break;

                }

            }

            if (!String.IsNullOrEmpty(match) ) {

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

            } else {

                throw new Exception(

                  "Could not extract database path from connection string");

            }

            return match;

        }

     

        public bool MakeBackup()

        {

            // If there was a SQL connection created

            if (srvSql == null) {

                Connect();

            }

     

            if (srvSql != null)

            {

                string path = GetAppPath();

                path = path += @"\Backup";

                if (!Directory.Exists(path))

                {

                    Directory.CreateDirectory(path);

                }

                saveBackupDialog.InitialDirectory = path;

                saveBackupDialog.DefaultExt = "bak";

     

                // If the user has chosen a path

                // where to save the backup file

                if (saveBackupDialog.ShowDialog() == DialogResult.OK)

                {

                    // Create a new backup operation

                    Backup bkpDatabase = 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

                    BackupDeviceItem bkpDevice = 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;

                }

            } else {

                throw new Exception("Could not connect to database.");

            }

            return true;

        }

     

        public void RestoreBackup()

        {

            //database must first be unloaded before calling this.

     

            // If there was a SQL connection created

            if (srvSql == null)

            {

                Connect();

            }

     

            if (srvSql != null)

            {

                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)

                {

                    // Create a new database restore operation

                    Restore rstDatabase = 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

                    BackupDeviceItem bkpDevice = 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 (FailedOperationException ex)

                    {

                        Log.WriteLine( "" );

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

                        Log.Write( ex );

                        throw new Exception("Error while restoring backup.", ex);

                    }

                }

               

            }

            else

            {

                throw new Exception("Could not connect to database.");

            }

     

        }

    }

    It's not generic so you'll have to change some of the code (and translate to vb...) You can see the basic idee from the code above.

    Good luck,
    Charles

  • Thursday, December 07, 2006 3:40 AMGRK Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    Hi ,

       forgive me for the late reply.I tried the above code it is running after small changes to the code.thanks a lot

    -regards

    GRK

  • Thursday, December 14, 2006 7:49 AMsivanekar Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
     

    Hi,

    i hav the same problem...

    " I have a small application in which i'm using Sql Server as Database. my requirement is how to take the backup of the entire database or some tables from the database when there is any delete from the database. My requirement is to do from the VB.net application"

    i used tht abov code.. bt it dnt wok.. 

    so.. plz snd me the code... plz its urgent.....                       

    thnks in advance

    siva

     

  • Wednesday, December 20, 2006 5:11 PMMr.Jehan Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    brallient
  • Wednesday, December 20, 2006 6:22 PMMr.Jehan Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    where i can find DatabaseCache  class i downloaded and install SQLServer2005_XMO.msi

    but still i cant see that class, other code works fine.

    Thanks

  • Wednesday, December 20, 2006 9:21 PMcverdon Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    Hi,

    It's normal, DatabaseCache is my own class that contains all the data of my application :)

    Basically you need to remove that and replace dbCache.SqlConnection in the Connect function with the connection you use for your database.

    Charles

  • Thursday, December 21, 2006 9:12 AMMr.Jehan Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    my connectionString is 

       connectionString = "Data Source=localhost,1433;Network Library=DBMSSOCN;Initial Catalog=myDb; User ID=sa;Password=saabc;";            

    when i replaced dbCache.SqlConnection  with my own opened connection as "openedConnection", it compiled and executed, but when i click on backup button, i caught by following exception 

     "Could not extract database path from connection string"

    Could you please change the code according to my connection.

    Thanks

  • Thursday, December 21, 2006 5:16 PMcverdon Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    Ok,

    My code assumes that a database file is used. So in your case the GetDatabase method fails to find the db file from the connection string.

    Try replacing bkpDatabase.Database = GetDatabase(dbCache.SqlConnection); by

    bkpDatabase.Database = "myDb";

    or better yet to modify the GetDatabase method to take into account the Initial Catalog key.

    Charles

  • Thursday, December 21, 2006 5:25 PMMr.Jehan Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Thanks, let me check it
  • Saturday, November 07, 2009 10:26 AMMitesh Khatri Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Hello,
    I am also facing problem in the backup and restore.
    actually i have two server. i create backup from  first server to my pc, and when i try to restore this backup on the second server. the restore process is not completed and error is occurred. can any one suggest wht will i do for restore at second pc.
    Thanks

    ~Khatri Mitesh
    khatrimitesh@hotmail.com
    Software Developer
    Rajasthan-India
    http://www.youtube.com/watch?v=-oJaaPCrk3Q