Schema Object Restore from Backup SDK 8
From RedGateWiki
This example demonstrates restoring schema objects from a backup file to a live database. The backup can be either a native SQL Server backup (MTF format) or a Red Gate SQL Backup file that has been compressed and/or encrypted. For these two functions, two support files are needed: zlib1.dll and RedGate.BackupReader.CryptoHelper.dll need to be copied to the application directory. Note, the files do not need to be “referenced” in the Visual Studio environment, but need to be copied to the output folder.
Referenced assemblies:
- RedGate.BackupReader.dll
- RedGate.BackupReader.SqbReader.dll
- RedGate.Shared.SQL.dll
- RedGate.Shared.Utils.dll
- RedGate.SQLCompare.Engine.dll
C#
- using System;
- using System.Collections.Generic;
- using System.Text;
- using RedGate.BackupReader;
- using RedGate.BackupReader.SqbReader;
- using RedGate.SQLCompare.Engine.ReadFromBackup;
- using RedGate.Shared.Utils;
- using RedGate.Shared.SQL;
- using RedGate.SQLCompare.Engine;
- using RedGate.Shared.SQL.ExecutionBlock;
- namespace Schema_Sync_To_Backup
- {
- class Program
- {
- static void Main(string[] args)
- {
- /* Backup reader can support combinations of FULL and DIFFERENTIAL
- * backup files. Put these in a generic string list. For our
- * demonstration purposes, we are using only one full backup.*/
- List<string> files = new List<string>(1);
- files.Add(@"c:\WidgetStaging.bak");
- BackupDatabaseSource backupDatabaseSource = new BackupDatabaseSource();
- backupDatabaseSource.Files = files;
- BackupSetDatabase backupDatabase = new BackupSetDatabase();
- backupDatabase.Status += new StatusEventHandler(StatusCallback);
- Console.WriteLine("Registering backup " + files[0]);
- try
- {
- backupDatabase.Register(backupDatabaseSource.ToConnectionProperties(), Options.Default);
- }
- catch (RedGate.BackupReader.SqbReader.PasswordProtectedException)
- {
- /* If we have reached this block, the backup is an encrypted
- * SQL Backup file and we must ask for the password!
- * NB the decryption requires RedGate.BackupReader.CryptoHelper.dll
- * and zlib1.dll to be copied into your output directory */
- Console.WriteLine("This SQL Backup file is password protected.\r\nPlease enter the password:");
- string sqbPassword = Console.ReadLine();
- backupDatabaseSource.Passwords.Add(sqbPassword);
- backupDatabase.Register(backupDatabaseSource.ToConnectionProperties(), Options.Default);
- }
- catch (RedGate.BackupReader.BackupReaderException brx)
- {
- // If we have reached this block, something generally bad has happened.
- Console.WriteLine("Could not register backup: " + brx.Message);
- }
- /* Now, to register the live database */
- Database liveDatabase = new Database();
- liveDatabase.Status += new StatusEventHandler(StatusCallback);
- Console.WriteLine("Registering live database WidgetProduction");
- liveDatabase.Register(new ConnectionProperties(".", "WidgetProduction"),Options.Default);
- /* Compare the backup to the live database */
- Differences schemaDifferences=backupDatabase.CompareWith(liveDatabase, Options.Default);
- foreach (Difference schemaDifference in schemaDifferences)
- {
- /*Select only schema objects that exist exclusively in the backup.
- * Note that with Options.Default, any dependent objects are included
- * by default. To stop this, unset Options.IncludeDependencies */
- if (schemaDifference.Type == DifferenceType.OnlyIn1)
- {
- Console.WriteLine(
- "\r\nMigrating {0}:{1}",schemaDifference.Type.ToString(),
- schemaDifference.Name);
- schemaDifference.Selected = true;
- }
- else schemaDifference.Selected = false;
- }
- /*Create migration SQL script */
- Work work = new Work();
- work.BuildFromDifferences(schemaDifferences, Options.Default, true);
- ExecutionBlock eb = work.ExecutionBlock;
- /* Write SQL script to console */
- Console.WriteLine(eb.GetString());
- /* Execute the migration script */
- BlockExecutor executor = new BlockExecutor();
- executor.ExecuteBlock(eb, liveDatabase.ConnectionProperties.ToDBConnectionInformation());
- /* Cleanup */
- eb.Dispose();
- liveDatabase.Dispose();
- backupDatabase.Dispose();
- }
- /// <summary>
- /// Example callback function matching the StatusEventHandler delegate.
- /// </summary>
- /// <remarks>
- /// This reports on SQL Compare's progress by displaying any messages or percentage
- /// notifications on the console.
- /// </remarks>
- private static void StatusCallback(object sender, StatusEventArgs e)
- {
- // Fired by the SqlProvider to indicate events
- if (e.Message != null)
- {
- Console.WriteLine("\r{0}",e.Message);
- }
- if (e.Percentage != -1)
- {
- Console.Write("\r \r{0}%",e.Percentage);
- }
- }
- }
- }
VB
- Imports System
- Imports System.Collections.Generic
- Imports System.Text
- Imports RedGate.BackupReader
- Imports RedGate.BackupReader.SqbReader
- Imports RedGate.SQLCompare.Engine.ReadFromBackup
- Imports RedGate.Shared.Utils
- Imports RedGate.Shared.SQL
- Imports RedGate.SQLCompare.Engine
- Imports RedGate.Shared.SQL.ExecutionBlock
- Module Module1
- Sub Main(ByVal args As String())
- ' Backup reader can support combinations of FULL and DIFFERENTIAL
- ' * backup files. Put these in a generic string list. For our
- ' * demonstration purposes, we are using only one full backup.
- Dim files As New List(Of String)(1)
- files.Add("c:\WidgetStaging.bak")
- Dim backupDatabaseSource As New BackupDatabaseSource()
- backupDatabaseSource.Files = files
- Dim backupDatabase As New BackupSetDatabase()
- backupDatabase.Status = New StatusEventHandler(AddressOf StatusCallback)
- Console.WriteLine("Registering backup " & files(0))
- Try
- backupDatabase.Register(backupDatabaseSource.ToConnectionProperties(), Options.[Default])
- Catch generatedExceptionName As RedGate.BackupReader.SqbReader.PasswordProtectedException
- ' If we have reached this block, the backup is an encrypted
- ' SQL Backup file and we must ask for the password!
- ' NB the decryption requires RedGate.BackupReader.CryptoHelper.dll
- ' and zlib1.dll to be copied into your output directory
- Console.WriteLine("This SQL Backup file is password protected." & vbCr & vbLf & "Please enter the password:")
- Dim sqbPassword As String = Console.ReadLine()
- backupDatabaseSource.Passwords.Add(sqbPassword)
- backupDatabase.Register(backupDatabaseSource.ToConnectionProperties(), Options.[Default])
- Catch brx As RedGate.BackupReader.BackupReaderException
- ' If we have reached this block, something generally bad has happened.
- Console.WriteLine("Could not register backup: " & brx.Message)
- End Try
- ' Now, to register the live database
- Dim liveDatabase As New Database()
- liveDatabase.Status = New StatusEventHandler(AddressOf StatusCallback)
- Console.WriteLine("Registering live database WidgetProduction")
- liveDatabase.Register(New ConnectionProperties(".", "WidgetProduction"), Options.Default)
- ' Compare the backup to the live database
- Dim schemaDifferences As Differences = backupDatabase.CompareWith(liveDatabase, Options.[Default])
- For Each schemaDifference As Difference In schemaDifferences
- 'Select only schema objects that exist exclusively in the backup.
- 'Note that with Options.Default, any dependent objects are included
- 'by default. To stop this, unset Options.IncludeDependencies
- If schemaDifference.Type = DifferenceType.OnlyIn1 Then
- Console.WriteLine(vbCr & vbLf & "Migrating {0}:{1}", schemaDifference.Type.ToString(), schemaDifference.Name)
- schemaDifference.Selected = True
- Else
- schemaDifference.Selected = False
- End If
- Next
- 'Create migration SQL script
- Dim work As New Work()
- work.BuildFromDifferences(schemaDifferences, Options.[Default], True)
- Dim eb As ExecutionBlock = work.ExecutionBlock
- ' Write SQL script to console
- Console.WriteLine(eb.GetString())
- ' Execute the migration script
- 'Uncomment the next two lines to synchronize the live database
- 'Dim executor As New BlockExecutor()
- 'executor.ExecuteBlock(eb, liveDatabase.ConnectionProperties.ToDBConnectionInformation())
- ' Cleanup
- eb.Dispose()
- liveDatabase.Dispose()
- backupDatabase.Dispose()
- End Sub
- ''' <summary>
- ''' Example callback function matching the StatusEventHandler delegate.
- ''' </summary>
- ''' <remarks>
- ''' This reports on SQL Compare's progress by displaying any messages or percentage
- ''' notifications on the console.
- ''' </remarks>
- Private Sub StatusCallback(ByVal sender As Object, ByVal e As StatusEventArgs)
- ' Fired by the SqlProvider to indicate events
- If e.Message IsNot Nothing Then
- Console.WriteLine(vbCr & "{0}", e.Message)
- End If
- If e.Percentage <> -1 Then
- Console.Write(vbCr & " " & vbCr & "{0}%", e.Percentage)
- End If
- End Sub
- End Module