/// <summary> /// Runs a VERIFYONLY on the provided SQL database backup file. /// </summary> /// <param name="srv"><code>Server</code> connection isntance used to connect to SQL Server</param> /// <param name="filePath">string containing the file path of the database backup file (.bak)</param> /// <returns></returns> public bool VerifyBackupFile(Server srv, string filePath) { Restore res = new Restore(); res.Devices.AddDevice(filePath, DeviceType.File); return(res.SqlVerify(srv)); }
private void VerifyBackup() { if (this.DataFilePath == null) { this.Log.LogError("DataFilePath is required"); return; } if (!File.Exists(this.DataFilePath.GetMetadata("FullPath"))) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "DataFilePath not found: {0}", this.DataFilePath.GetMetadata("FullPath"))); return; } this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Verifying Backup: {0}", this.DataFilePath.GetMetadata("FullPath"))); Restore sqlRestore = new Restore(); sqlRestore.Devices.AddDevice(this.DataFilePath.GetMetadata("FullPath"), DeviceType.File); string error; bool verified = sqlRestore.SqlVerify(this.sqlServer, out error); if (!verified) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Verification failed for: {0}. Error: {1}", this.DataFilePath.GetMetadata("FullPath"), error)); return; } this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Backup successfully verified: {0}", this.DataFilePath.GetMetadata("FullPath"))); }
public static bool VerifyDatabaseBackup(string BackupPath, SqlConnection aSqlConnection) { Restore rest = new Restore(); string fileName = BackupPath; ServerConnection __ServerConnection = new ServerConnection(aSqlConnection); Server __Server = new Server(__ServerConnection); try { rest.Devices.AddDevice(fileName, DeviceType.File); bool verifySuccessful = rest.SqlVerify(__Server); if (verifySuccessful) { return(true); } else { return(false); } } catch (SmoException exSMO) { throw new Exception(exSMO.Message); } catch (Exception ex) { throw new Exception(ex.Message); } finally { aSqlConnection.Close(); } }
/// <summary> /// Metodo responsavel pelo processo de validação do backup. /// </summary> /// <param name="srvServidor"> Nome do servidor </param> /// <param name="strDiretorioDestino"> Diretorio do arquivo de backup </param> /// <returns> </returns> public bool Validacao(Server srvServidor, String strDiretorioDestino) { //Após o backup, a validação do mesmo pode ser realizada usando o método SqlVerify. //Como este é um método da classe Restore, é necessário criar uma instância desta classe. pclsrestore.Devices.AddDevice(strDiretorioDestino, DeviceType.File); pclsrestore.Database = Conexao.CONN.ConnectionString; bool lblnverificaValidacao = pclsrestore.SqlVerify(srvServidor); return(lblnverificaValidacao); }
static void Main(string[] args) { if (args.Length != 3) { return; } string serverName = args[0]; string databaseName = args[1]; string restoreFilePath = args[2]; Restore restoreDB = new Restore(); restoreDB.Database = databaseName; restoreDB.Action = RestoreActionType.Database; restoreDB.Devices.AddDevice(@restoreFilePath, DeviceType.File); restoreDB.ReplaceDatabase = true; /* If you have a differential or log restore after the current restore, * you would need to specify NoRecovery = true, this will ensure no * recovery performed and subsequent restores are allowed. It means it * the database will be in a restoring state. */ restoreDB.NoRecovery = false; restoreDB.PercentComplete += (obj, e) => { Console.WriteLine("Percent completed: {0}%.", e.Percent); }; Server srv = new Server(@serverName); /* Check if database exists, if not, create one. */ Database db = srv.Databases[databaseName]; if (db == null) { db = new Database(srv, databaseName); Console.WriteLine("Creating database..."); db.Create(); Console.WriteLine("Created {0}.", databaseName); } Console.WriteLine("Verifying backup media..."); bool valid = restoreDB.SqlVerify(srv); if (valid) { Console.WriteLine("Backup media is valid."); Console.WriteLine("Starting restore..."); restoreDB.SqlRestore(srv); } else { Console.WriteLine("Backup media is invalid. Aborting operation..."); } }
static void Main(string[] args) { if (args.Length != 3) return; string serverName = args[0]; string databaseName = args[1]; string restoreFilePath = args[2]; Restore restoreDB = new Restore(); restoreDB.Database = databaseName; restoreDB.Action = RestoreActionType.Database; restoreDB.Devices.AddDevice(@restoreFilePath, DeviceType.File); restoreDB.ReplaceDatabase = true; /* If you have a differential or log restore after the current restore, * you would need to specify NoRecovery = true, this will ensure no * recovery performed and subsequent restores are allowed. It means it * the database will be in a restoring state. */ restoreDB.NoRecovery = false; restoreDB.PercentComplete += (obj, e) => { Console.WriteLine("Percent completed: {0}%.", e.Percent); }; Server srv = new Server(@serverName); /* Check if database exists, if not, create one. */ Database db = srv.Databases[databaseName]; if (db == null) { db = new Database(srv,databaseName); Console.WriteLine("Creating database..."); db.Create(); Console.WriteLine("Created {0}.", databaseName); } Console.WriteLine("Verifying backup media..."); bool valid = restoreDB.SqlVerify(srv); if (valid) { Console.WriteLine("Backup media is valid."); Console.WriteLine("Starting restore..."); restoreDB.SqlRestore(srv); } else { Console.WriteLine("Backup media is invalid. Aborting operation..."); } }
public static void BackupDatabase(string connectionString, string backupSetPath, bool verify) { SqlConnectionStringBuilder cb = new SqlConnectionStringBuilder(connectionString); string database = cb.InitialCatalog; cb.InitialCatalog = "master"; SqlConnection sqlConnection = new SqlConnection(cb.ConnectionString); ServerConnection serverConnection = new ServerConnection(sqlConnection); try { //Make Database Single User serverConnection.ExecuteNonQuery(String.Format(_SingleUserCmd, database)); Server server = new Server(serverConnection); Backup backup = new Backup(); BackupDeviceItem destination = new BackupDeviceItem(backupSetPath, DeviceType.File); backup.Action = BackupActionType.Database; backup.Database = database; backup.Devices.Add(destination); backup.SqlBackup(server); if (verify) { Restore restore = new Restore(); restore.Action = RestoreActionType.Database; restore.Database = database; restore.Devices.Add(destination); restore.ReplaceDatabase = true; string errorMessage; if (!restore.SqlVerify(server, out errorMessage)) { throw new Exception(errorMessage); } } } catch { throw; } finally { //Make Database Multi User serverConnection.ExecuteNonQuery(String.Format(_MultiUserCmd, database)); serverConnection.Disconnect(); } }
/// <summary> /// Verify the selected backup set. /// </summary> /// <param name="BackupDeviceName"></param> private void VerifyBackupSet(string BackupDeviceName) { Cursor csr = null; Boolean verified; BackupDeviceItem backupDeviceItem; try { csr = this.Cursor; // Save the old cursor this.Cursor = Cursors.WaitCursor; // Display the waiting cursor // Create a Restore object // Fire any events sqlRestore = new Restore(); // Create a file backup device backupDeviceItem = new BackupDeviceItem( BackupDeviceName, DeviceType.LogicalDevice); // Add the backup device to the restore object sqlRestore.Devices.Add(backupDeviceItem); // Call the SQLVerify method of the Restore object using the SQLServer object verified = sqlRestore.SqlVerify(SqlServerSelection, true); ExceptionMessageBox emb = new ExceptionMessageBox(); emb.Text = string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.VerifiedResult, verified.ToString(System.Globalization.CultureInfo.InvariantCulture)); emb.Show(this); return; } catch (SmoException ex) { ExceptionMessageBox emb = new ExceptionMessageBox(ex); emb.Show(this); } finally { sqlRestore = null; this.Cursor = csr; // Restore the original cursor } }
public void Verify() { if (string.IsNullOrEmpty(AttachDbFilename)) { MessageBox.Show("Please select file"); return; } try { Mouse.OverrideCursor = Cursors.Wait; var rest = new Restore(); rest.Devices.AddDevice(AttachDbFilename, DeviceType.File); bool verifySuccessful = rest.SqlVerify(Srv); if (verifySuccessful) { MessageBox.Show("Backup Verified!", "SMO Demos"); DataTable dt = rest.ReadFileList(Srv); // this.dataGridView1.DataSource = dt; } else { MessageBox.Show("Backup NOT Verified!", "SMO Demos"); } } catch (SmoException exSMO) { MessageBox.Show(exSMO.ToString()); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { Mouse.OverrideCursor = null; } }
private void btnVerify_Click(object sender, EventArgs e) { Restore rest = new Restore(); string fileName = this.txtFileName.Text; this.Cursor = Cursors.WaitCursor; this.dataGridView1.DataSource = string.Empty; try { rest.Devices.AddDevice(fileName, DeviceType.File); bool verifySuccessful = rest.SqlVerify(srv); if (verifySuccessful) { MessageBox.Show("Backup Verified!", "SMO Demos"); DataTable dt = rest.ReadFileList(srv); this.dataGridView1.DataSource = dt; } else { MessageBox.Show("Backup NOT Verified!", "SMO Demos"); } } catch (SmoException exSMO) { MessageBox.Show(exSMO.ToString()); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { this.Cursor = Cursors.Default; } }
private void VerifyBackup() { if (this.DataFilePath == null) { this.Log.LogError("DataFilePath is required"); return; } if (!File.Exists(this.DataFilePath.GetMetadata("FullPath"))) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "DataFilePath not found: {0}", this.DataFilePath.GetMetadata("FullPath"))); return; } this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Verifying Backup: {0}", this.DataFilePath.GetMetadata("FullPath"))); Restore sqlRestore = new Restore(); sqlRestore.Devices.AddDevice(this.DataFilePath.GetMetadata("FullPath"), DeviceType.File); string error; bool verified = sqlRestore.SqlVerify(this.sqlServer, out error); if (!verified) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Verification failed for: {0}. Error: {1}", this.DataFilePath.GetMetadata("FullPath"), error)); return; } this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Backup successfully verified: {0}", this.DataFilePath.GetMetadata("FullPath"))); }
private void Button_Click_2(object sender, RoutedEventArgs e) { Restore rest = new Restore(); string PathtobackUp =""; OpenFileDialog dlg = new OpenFileDialog(); dlg.InitialDirectory = "c:\\"; dlg.Filter = "Backup Files (*.bak)|*.bak|All Files (*.*)|*.*"; dlg.RestoreDirectory = true; if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) { PathtobackUp = dlg.FileName.ToString(); } else { return; } string fileName = PathtobackUp; //this.Cursor = Cursors.WaitCursor; //this.dataGridView1.DataSource = string.Empty; try { rest.Devices.AddDevice(fileName, DeviceType.File); Server srv = new Server("(localdb)\\v11.0"); bool verifySuccessful = rest.SqlVerify(srv); string databaseName = "LoanManagement.Domain.finalContext"; if (verifySuccessful) { System.Windows.MessageBox.Show("Backup Verified!", "Info"); System.Windows.MessageBoxResult dr = System.Windows.MessageBox.Show("Do you want to restore?","Question",MessageBoxButton.YesNo); if (dr == MessageBoxResult.Yes) { //fileName = dlg.FileName.Replace(Directory.GetCurrentDirectory(), ""); System.Windows.MessageBox.Show(fileName); rest.Database = databaseName; rest.Action = RestoreActionType.Database; BackupDeviceItem bdi = default(BackupDeviceItem); bdi = new BackupDeviceItem(fileName, DeviceType.File); rest.Devices.Add(bdi); //rest.Devices.Add(bdi); rest.ReplaceDatabase = true; srv = new Server("(localdb)\\v11.0"); rest.SqlRestore(srv); srv.Refresh(); System.Windows.MessageBox.Show("Restore of " + databaseName +" Complete!"); } } else { System.Windows.MessageBox.Show("ERROR: Backup not verified!", "Error"); } } catch (Exception ex) { System.Windows.MessageBox.Show("The system has been successfully restored"); } finally { //this.Cursor = Cursors.Default; } }
/// <summary> /// Verify the selected backup set. /// </summary> /// <param name="BackupDeviceName"></param> private void VerifyBackupSet(string BackupDeviceName) { Cursor csr = null; Boolean verified; BackupDeviceItem backupDeviceItem; try { csr = this.Cursor; // Save the old cursor this.Cursor = Cursors.WaitCursor; // Display the waiting cursor // Create a Restore object // Fire any events sqlRestore = new Restore(); // Create a file backup device backupDeviceItem = new BackupDeviceItem( BackupDeviceName, DeviceType.LogicalDevice); // Add the backup device to the restore object sqlRestore.Devices.Add(backupDeviceItem); // Call the SQLVerify method of the Restore object using the SQLServer object verified = sqlRestore.SqlVerify(SqlServerSelection, true); ExceptionMessageBox emb = new ExceptionMessageBox(); emb.Text = string.Format( System.Globalization.CultureInfo.InvariantCulture, Properties.Resources.VerifiedResult, verified.ToString(System.Globalization.CultureInfo.InvariantCulture)); emb.Show(this); return; } catch (SmoException ex) { ExceptionMessageBox emb = new ExceptionMessageBox(ex); emb.Show(this); } finally { sqlRestore = null; this.Cursor = csr; // Restore the original cursor } }
public void DoDataBaseBackup() { string connectionString = ConfigurationManager.ConnectionStrings["Test"].ToString(); SqlConnection connecton = new SqlConnection(connectionString); ServerConnection serverConnection = new ServerConnection(connecton); Server myServer = new Server(serverConnection); //Using windows authentication myServer.ConnectionContext.Connect(); Database myDatabase = myServer.Databases[ConfigurationManager.AppSettings["DatabaseNameToBackup"]]; //Backup operation Backup bkpDBFull = new Backup(); /* Specify whether you want to back up database or files or log */ bkpDBFull.Action = BackupActionType.Database; /* Specify the name of the database to back up */ bkpDBFull.Database = myDatabase.Name; /* You can take backup on several media type (disk or tape), here I am * using File type and storing backup on the file system */ string destinationFolderForDatabase = ConfigurationManager.AppSettings["DestinationFolderForDatabase"]; bkpDBFull.Devices.AddDevice(destinationFolderForDatabase, DeviceType.File); bkpDBFull.BackupSetName = "Test database Backup"; bkpDBFull.BackupSetDescription = "test database - Full Backup"; /* You can specify the expiration date for your backup data * after that date backup data would not be relevant */ bkpDBFull.ExpirationDate = DateTime.Today.AddDays(10); /* You can specify Initialize = false (default) to create a new * backup set which will be appended as last backup set on the media. You * can specify Initialize = true to make the backup as first set on the * medium and to overwrite any other existing backup sets if the all the * backup sets have expired and specified backup set name matches with * the name on the medium */ bkpDBFull.Initialize = false; /* You can specify Incremental = false (default) to perform full backup or Incremental = true to perform differential backup since most recent full backup */ bkpDBFull.Incremental = false; /* Wiring up events for progress monitoring */ bkpDBFull.PercentComplete += CompletionStatusInPercent; bkpDBFull.Complete += Backup_Completed; /* SqlBackup method starts to take back up * You can also use SqlBackupAsync method to perform the backup * operation asynchronously */ bkpDBFull.SqlBackup(myServer); Restore restore = new Restore(); restore.Devices.AddDevice(@"C:\Test.bak", DeviceType.File); restore.Database = "Test2012"; Console.WriteLine(restore.SqlVerify(myServer).ToString()); if (myServer.ConnectionContext.IsOpen) { myServer.ConnectionContext.Disconnect(); } }
/// <summary> /// Returns true if the backup file is passed verification on SQL Server /// </summary> public Boolean VerifyBackup(Server server, String backupFile) { Restore restore = new Restore(); restore.Devices.AddDevice(backupFile, DeviceType.File); return restore.SqlVerify(server); }
public bool ValidateBackup(string path) { if (string.IsNullOrEmpty(path)) throw new RestoreException(RestoreExceptionType.InvalidFullBackupPath); FileInfo file = new FileInfo(path); if (!file.Exists) throw new RestoreException(RestoreExceptionType.NoFullBackupFile); Restore restore = new Restore(); restore.Devices.AddDevice(path, DeviceType.File); return restore.SqlVerify(_server); }