Performing Database Restore by SMO
By : Kasim Wirama, MCITP, MCDBA
This series of SMO posting, I would like to show how to do database restore with SMO. Backup operation is represented by Microsoft.SqlServer.Management.Smo.Restore class. The example I show here is how to use the SMO Restore class by doing full AdventureWorks2008 database restore on my local SQL Server Machine, so let’s get started by creating windows form application in Visual Studio 2008.
Add 4 references : Microsoft.SqlServer.ConnectionInfo, Microsoft.SqlServer.Management.Sdk.Sfc, Microsoft.SqlServer.Smo, Microsoft.SqlServer.SmoExtended. Double click on Form1 to switch into code behind page and put 2 namespace declaration here : using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;create 1 button, 1 label, and 1 progress bar control on the form, and create click event handler of the button and put code here :progressBar1.value = 0;
progressBar1.Maximum = 100;
Restore rst = new Restore();rst.Action = RestoreActionType.Database;
rst.Database = “AdventureWorks2008”;
rst.Devices.AddDevice (@”C:\AdventureWorks2008.bak”, DeviceType.File);
rst.ReplaceDatabase = true;
rst.PercentCompleteNotification = 10;
rst.PercentComplete += new PercentCompleteEventHandler(restore_PercentComplete);Server srv = new Server(“(local)”);
rst.SqlRestore (srv); Let’s go through code steps above. Create instance of SMO Restore class. Define restore type and specify database you would like to restore (for example AdventureWorks2008). Specify restore filename by adding filename into restore device with FILE device type enumeration value.If you would like to replace existing database, put value true into ReplaceDatabase property of the restore instance. If you would like to specify restore progress you could set PercentCompleteNotification property to 10 or any number you prefer; in this sample the 10 means that you instruct the restore object to let you know restore progress for each 10% increment. And specify eventhandler for each completion 10% incremental steps.2 remaining last steps is define SQL Server and run restore by issuing method : SqlRestore on the SQL Server.You could set restore progress value into label and progress bar control so that user could see backup progress inside the event handler (restore_PercentComplete). In the event handler put the code below :
progressBar1.value = e.Percent;
label1.Text = e.Percent.ToString() + “ % complete”;