views:

51

answers:

1

I'm using the below to restore a database in VB.NET. This works but causes the interface to lockup if the user clicks anything. Also, I cannot get the progress label to update incrementally, it's blank until the backup is complete then displays 100%

Sub DoRestore()
    Dim svr As Server = New Server("Server\SQL2008")
    Dim res As Restore = New Restore()
    res.Devices.AddDevice("C:\MyDB.bak", DeviceType.File)
    res.Database = "MyDB"
    res.RelocateFiles.Add(New RelocateFile("MyDB_Data", "C:\MyDB.mdf"))
    res.RelocateFiles.Add(New RelocateFile("MyDB_Log", "C:\MyDB.ldf"))
    res.PercentCompleteNotification = 1
    AddHandler res.PercentComplete, AddressOf ProgressEventHandler
    res.SqlRestore(svr)
End Sub

Is this change correct?:

Private Sub ProgressEventHandler(ByVal sender As Object, ByVal e As PercentCompleteEventArgs)
    UpdateProgressBar(e.Percent)
End Sub

Private Sub UpdateProgressBar(ByVal e As String)
    ProgressBar.Value = e
    Status.Text = e.ToString
End Sub
A: 

You need to use SqlRestoreAsync not SqlRestore to prevent it tying up your main thread.

Then to avoid the Cross Thread Operation error when updating the UI you can use the approach here. Where you create a method on the form that will update the UI elements and call that from your asynch handler using Invoke.

Martin Smith
Hi Martin, the SqlRestoreAsync prevents the progress handler from updating the label and progress bar:Cross-thread operation not valid: Control 'Label3' accessed from a thread other than the thread it was created on.
madlan
@madlan see edit.
Martin Smith
Is the above change correct?I've added an update sub on the main UI thread which is being passed the percent complete from the progress event handler sub.The progress bar seems to finish way before the restore process is complete and the label is not updated at all.
madlan
No I don't think that's right but I'm surprised it didn't give you any errors. I thought you had to use `Invoke` or a `backgroundworker`. It's not something I know about off the top of my head. Maybe have a look at this project which seems very similar to yours http://www.shabdar.org/sql-server-backup-utility.html
Martin Smith