0

I'm trying to restore a SQL database backup with this code

private void btnRestore_Click(object sender, EventArgs e)
{
    string dbName = "BakodahDB";
    try
    {
        Server dbServer = new Server(); //local using windows athuentication 
        Restore dbRestore = new Restore() { Database = dbName, Action = RestoreActionType.Database, ReplaceDatabase = true, NoRecovery = false };
        dbRestore.Devices.AddDevice(@"C:\WorkHours\dbBackup.bak", DeviceType.File);
        dbRestore.PercentComplete += DbRestore_PercentComplete;
        dbRestore.Complete += DbRestore_Complete;
        dbRestore.SqlRestoreAsync(dbServer);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

When I click the button nothing happens, not even an error message... What's the right way to do it?

5
  • 1
    Possible duplicate of Restoring a DB using C# Commented Jan 3, 2017 at 22:26
  • In order to further assist, I have a couple of questions. Have you tried moving the dbRestore out to a higher scope such as the class? What do your delegates' DbRestore_PercentComplete and DbRestore_Complete implementations look like? Is it possible that the work is just long running? Commented Jan 3, 2017 at 22:26
  • 1
    Try the non-async version; does that throw? Alternatively, handle the Information event - anything reported? Commented Jan 3, 2017 at 22:32
  • @Cameron just tried it it didn't work, 'DbRestore_PercentComplete' and 'DbRestore_Complete' just updates a progress bar and a status text label. Commented Jan 3, 2017 at 23:21
  • @Blorgbeard just tried it, at least now there's an error message Failed to Restore.... before it was no response. Commented Jan 3, 2017 at 23:25

1 Answer 1

3

I just needed to kill all process before restoring

            // Kill all processes
            dbServer.KillAllProcesses(dbRestore.Database);
            // Set single-user mode
            Database db = dbServer.Databases[dbRestore.Database];
            // db.DatabaseOptions.UserAccess=true;
            db.Alter(TerminationClause.RollbackTransactionsImmediately);
            // Detach database
            dbServer.DetachDatabase(dbRestore.Database, false);

it worked!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.