Click here to Skip to main content
6,629,885 members and growing! (21,380 online)
Email Password   helpLost your password?
Database » Database » SQL Server     Beginner License: The Code Project Open License (CPOL)

SqlServer Backup/Restore Utility

By alioglu

SqlServer Backup/Restore Utility helps to backup and restore database
C# (C# 2.0), Windows, WinForms
Version:6 (See All)
Posted:9 Jun 2009
Views:5,743
Bookmarked:36 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
7 votes for this article.
Popularity: 3.97 Rating: 4.69 out of 5

1

2

3
1 vote, 14.3%
4
6 votes, 85.7%
5
BackupRestore_Source

Introduction 

Sometimes you need to migrate the database from the server where Management Studio is not installed (for example, when you use SQL Server Express Edition). This utility helps you to instantly backup, then restore to database server. 

Using the Application

Before running an application, edit connectionStrings section in BackupRestore.exe.config file to connect your database.  

Using the Code

At first, you need to get a list of available databases using the default connection string. The list of databases is bound to two combo boxes used for selecting database to backup or restore.

sqlConn = new SqlConnection(Properties.Settings.Default.masterConnectionString);
sqlServer = new Server(new ServerConnection(sqlConn));

dbList = new List<database>();
foreach (Database db in sqlServer.Databases)
{
        dbList.Add(db);
}

cmbBackupDb.DataSource = dbList;
cmbRestoreDb.DataSource = dbList;

Database Backup

back_rest_1.png

Database backup process is performed using the Microsoft.SqlServer.Management.Smo.Backup class. When user selects database and file to save the backup to, the following method will be executed: 

private void BackupDb()
{
    dbName = ((Database)cmbBackupDb.SelectedItem).Name;
    Backup dbBackup = new Backup();

    try
    {
        dbBackup.Action = BackupActionType.Database;
        dbBackup.Database = dbName;
        dbBackup.BackupSetName = string.Format("{0} backup set.", dbName);
        dbBackup.BackupSetDescription = string.Format("Database: {0}. Date: {1}.", 
			dbName, DateTime.Now.ToString("dd.MM.yyyy hh:m"));
        dbBackup.MediaDescription = "Disk";

        BackupDeviceItem device = new BackupDeviceItem
			(saveBakFile.FileName, DeviceType.File);
        dbBackup.Devices.Add(device);

        txtBackupSql.Text = dbBackup.Script(sqlServer);

        progBar.Visible = true;
        progBar.Value = 0;

        dbBackup.Complete += new ServerMessageEventHandler(dbBackup_Complete);
        dbBackup.PercentCompleteNotification = 10;
        dbBackup.PercentComplete += 
		new PercentCompleteEventHandler(PercentComplete);

        dbBackup.SqlBackup(sqlServer);
    }
    catch (Exception exc)
    {
        dbBackup.Abort();
        MessageBox.Show(string.Format
		("Exception occurred.\nMessage: {0}", exc.Message));
    }
    finally
    {
        sqlConn.Close();
    }
}

Database Restore

back_rest_2.png

Database restore process is performed using the Microsoft.SqlServer.Management.Smo.Restore class. When user selects database and the file to restore from, the following method will be processed:

private void RestoreDb()
{
    Database restoreDb = (Database)cmbRestoreDb.SelectedItem;
    dbName = restoreDb.Name;

    Restore dbRestore = new Restore();
    dbRestore.Database = restoreDb.Name;
    dbRestore.Action = RestoreActionType.Database;
    dbRestore.ReplaceDatabase = true;
       
    string fileLocation = ConfigurationManager.AppSettings["SqlFileLocations"];

    try
    {
        BackupDeviceItem device = new BackupDeviceItem
			(openBakFile.FileName, DeviceType.File);
        dbRestore.Devices.Add(device);
        DataTable dtFiles = dbRestore.ReadFileList(sqlServer);
        string backupDbLogicalName = dtFiles.Rows[0]["LogicalName"].ToString();

        RelocateFile dbRf = new RelocateFile
	(backupDbLogicalName, string.Format("{0}\\{1}.mdf", fileLocation, dbName));
        RelocateFile logRf = new RelocateFile(string.Format("{0}_log", 
	backupDbLogicalName), string.Format("{0}\\{1}_Log.ldf", 
	fileLocation, dbName));
        dbRestore.RelocateFiles.Add(dbRf);
        dbRestore.RelocateFiles.Add(logRf);

        string sql = string.Empty;
        StringCollection scriptColl = dbRestore.Script(sqlServer);
        foreach (string str in scriptColl)
        {
            sql += str;
        }
        txtBackupSql.Text = sql;

        progBar.Visible = true;
        progBar.Value = 0;

        dbRestore.Complete += new ServerMessageEventHandler(dbRestore_Complete);
        dbRestore.PercentComplete += 
		new PercentCompleteEventHandler(PercentComplete);
        dbRestore.SqlRestore(sqlServer);
    }
    catch (Exception exc)
    {
        dbRestore.Abort();
        MessageBox.Show(string.Format
		("Exception occurred.\nMessage: {0}", exc.Message));
    }
    finally
    {
        sqlConn.Close();
    }
}

History

  • 9th June, 2009: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

alioglu


Member

Location: Azerbaijan Azerbaijan

Other popular Database articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 7 of 7 (Total in Forum: 7) (Refresh)FirstPrevNext
GeneralWhy did the progress don't working when i backup Pinmemberlxg_831122:37 17 Nov '09  
Questiondon't want to show system databases? Pinmemberwael32gh20:49 4 Oct '09  
AnswerRe: don't want to show system databases? Pinmemberalioglu1:53 5 Oct '09  
GeneralRe: don't want to show system databases? PinmemberLeleHalfon4:54 11 Nov '09  
NewsExclusive access could not be obtained because the database is in use Pinmemberwael32gh7:30 4 Oct '09  
GeneralSMO objects always bugs me PinmemberAbhishek Sur12:01 9 Jun '09  
GeneralSimple and to the point Pinmemberameetj8511:48 9 Jun '09  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 9 Jun 2009
Editor: Deeksha Shenoy
Copyright 2009 by alioglu
Everything else Copyright © CodeProject, 1999-2009
Web18 | Advertise on the Code Project