Imports System.ComponentModel
Imports DigitalData.Modules.Logging
Public Class ClassInitLoader
Private _Worker As BackgroundWorker
Private _Logger As Logger
Private _CurrentStep As InitStep
Public Steps As New List(Of InitStep)
Public Event ProgressChanged As EventHandler(Of InitProgress)
Public Event InitCompleted As EventHandler(Of RunWorkerCompletedEventArgs)
Public Sub New()
_Logger = My.LogConfig.GetLogger()
End Sub
Public Sub AddStep(Name As String, Action As Action, Optional Fatal As Boolean = False)
Steps.Add(New InitStep() With {
.Name = Name,
.Action = Action,
.Fatal = Fatal
})
End Sub
Public Function Run() As Boolean
_Worker = New BackgroundWorker()
_Worker.WorkerReportsProgress = True
AddHandler _Worker.DoWork, AddressOf DoWork
AddHandler _Worker.ProgressChanged, Sub(sender As Object, e As ProgressChangedEventArgs)
Dim oProgress As New InitProgress() With {
.CurrentStep = _CurrentStep,
.CurrentPercent = e.ProgressPercentage
}
RaiseEvent ProgressChanged(sender, oProgress)
End Sub
AddHandler _Worker.RunWorkerCompleted, Sub(sender As Object, e As RunWorkerCompletedEventArgs)
RaiseEvent InitCompleted(sender, e)
End Sub
_Worker.RunWorkerAsync()
Return True
End Function
Private Sub DoWork(sender As Object, e As DoWorkEventArgs)
Dim oStepCounter = 0
For Each oStep In Steps
_CurrentStep = oStep
Try
oStep.Action.Invoke()
Catch ex As Exception
_Logger.Error(ex)
_Logger.Warn("Init Step '{0}' failed!", oStep.Name)
If oStep.Fatal Then
_Logger.Warn("Fatal error in '{0}'. Init will be aborted!", oStep.Name)
e.Cancel = True
End If
End Try
oStepCounter += 1
Dim oPercentComplete As Integer = CInt(Math.Truncate(oStepCounter / Steps.Count * 100))
_Worker.ReportProgress(oPercentComplete)
Threading.Thread.Sleep(600)
Next
End Sub
Public Class InitProgress
Public CurrentStep As InitStep
Public CurrentPercent As Integer
End Class
Public Class InitStep
'''
''' Human Readable Name of init step
'''
Public Name As String
'''
''' The function to execute
'''
Public Action As Action
'''
''' Should init be aborted if this step fails?
'''
Public Fatal As Boolean
End Class
End Class