Imports System.ComponentModel
Imports System.IO
Imports Independentsoft.Email.Mime
Imports DigitalData.EMLProfiler
Imports DigitalData.EMLProfiler.ClassCurrent
Imports DigitalData.Modules.Logging
Public Class MyService
#Region "+++++ variables +++++"
    Private _threadRunner As BackgroundWorker
    Private MyLogger As LogConfig
    Private Logger As Logger
    Private _database As clsDatabase
    Private _email As clsEmail
    Private _windream As clsWindream_allgemein
    Private _workmail As clsWorkEmail
#End Region
    Public Sub New()
        MyBase.New()
        InitializeComponent()
    End Sub
    Protected Overrides Sub OnStart(ByVal args() As String)
        ' Code zum Starten des Dienstes hier einfügen. Diese Methode sollte Vorgänge
        ' ausführen, damit der Dienst gestartet werden kann.
        Try
            MyLogger = New LogConfig(LogConfig.PathType.CustomPath, Path.Combine(My.Application.Info.DirectoryPath, "Log"), Nothing, "Digital Data", "DD EmailProfiler")
            Logger = MyLogger.GetLogger

            Try
                Dim directory As New IO.DirectoryInfo(MyLogger.LogDirectory)

                For Each file As IO.FileInfo In directory.GetFiles
                    If (Now - file.CreationTime).Days > 29 Then
                        file.Delete()
                    Else
                        Exit For
                    End If
                Next
            Catch ex As Exception

            End Try

            Logger.Info("## Service started  ## ")

            If My.Settings.MyConnectionString = String.Empty Then
                Logger.Warn("NO CONNECTIONSTRING CONFIGURED.")
            Else
                If My.Settings.DEBUG = True Then
                    Logger.Info("DEBUG ACTIVATED")
                    MyLogger.Debug = True
                Else
                    MyLogger.Debug = False
                End If

                _database = New clsDatabase(MyLogger, My.Settings.MyConnectionString)
                _email = New clsEmail(MyLogger)
                Logger.Debug("_database and _email initialized")
                _workmail = New clsWorkEmail(MyLogger, My.Settings.MyConnectionString, My.Settings.FB_DATASOURCE, My.Settings.FB_DATABASE, My.Settings.FB_USER, My.Settings.FB_PW, My.Settings.USE_WM)
                Logger.Debug("_workmail initialized")
                If _database.Init(My.Settings.MyConnectionString) = False Then
                    Logger.Warn("ATTENTION: No Connection was established '" & My.Settings.MyConnectionString & "'!")
                Else
                    '### Thread für das nachträgliche Setzen von Rechten generieren
                    _threadRunner = New BackgroundWorker()
                    _threadRunner.WorkerReportsProgress = True
                    _threadRunner.WorkerSupportsCancellation = True
                    AddHandler _threadRunner.DoWork, AddressOf RUN_THREAD
                    AddHandler _threadRunner.RunWorkerCompleted, AddressOf Thread1_Completed
                    '### Den Timer generieren
                    Dim Timer_Durchlauf As New System.Timers.Timer()
                    'Das Event hinterlegen welches bei "Tick" ausgelöst wird
                    AddHandler Timer_Durchlauf.Elapsed, AddressOf Thread_Run
                    ' Set the Interval
                    Timer_Durchlauf.Interval = (TIMER_INTERVALL * 60000)
                    Timer_Durchlauf.Enabled = True
                    Logger.Debug("...Timer started.")
                    ' Und den Durchlauf das erste Mal starten
                    _threadRunner.RunWorkerAsync()
                End If
            End If
        Catch ex As Exception
            Logger.Error(ex)
        End Try
    End Sub
    Public Sub Thread_Run()
        If Not _threadRunner.IsBusy Then
            _threadRunner.RunWorkerAsync()
        End If
    End Sub
    Public Sub RUN_THREAD(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs)
        Try
            Dim notcompleted As Boolean = False
            Dim _work As New clsWorker(MyLogger, My.Settings.MyConnectionString, 0, My.Settings.FB_DATASOURCE, My.Settings.FB_DATABASE, My.Settings.FB_USER, My.Settings.FB_PW, My.Settings.USE_WM)
            _work.Start_WorkingProfiles()
        Catch ex As Exception
            Logger.Error(ex)
        End Try
    End Sub
    Protected Overrides Sub OnStop()
        ' Hier Code zum Ausführen erforderlicher Löschvorgänge zum Beenden des Dienstes einfügen.
        Logger.Info("## Service was stopped manually. ##")
    End Sub
    Private Sub Thread1_Completed(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) 'Handles threadDateiimport.RunWorkerCompleted
        'This event fires when the DoWork event completes
        Try
            Dim result As String = ""
            If e.Cancelled Then
                EventLog.WriteEntry("DD EmailProfiler", "The thread was cancelled!", EventLogEntryType.Error)
                Logger.Warn("## The thread was cancelled.")
            ElseIf e.Error IsNot Nothing Then
                EventLog.WriteEntry("DD EmailProfiler", "Unexpected error in thread!", EventLogEntryType.Error)
                Logger.Warn("Unexpected error in thread: " & e.Error.Message)
            End If
        Catch ex As Exception
            Logger.Error(ex)
        End Try
    End Sub
End Class
