Imports System.ComponentModel
Imports System.IO
Imports System.Net.Mail
Imports System.Text.RegularExpressions
Imports System.Windows.Forms.VisualStyles.VisualStyleElement.Tab
Imports DevExpress.XtraPrinting.Export
Imports DigitalData.GUIs.Common
Imports DigitalData.Modules.Config
Imports DigitalData.Modules.Database
Imports DigitalData.Modules.Logging
Imports DigitalData.Modules.Messaging
Imports DigitalData.Modules.Messaging.Mail
Imports EmailProfiler.Common

Public Class frmMain
    Private Logger As Logger
    Private LogConfig As LogConfig
    Private ConfigManager As ConfigManager(Of Config)
    Private _database As MSSQLServer
    Private _Encryption As clsEncryption
    Private _windream As clsWindream_allgemein
    Private _LoadInProgress As Boolean = True
    Private _RunwithLocalemail As Boolean = False
    Private _SQLServerConString As String
    Private _Worklist As List(Of String)
    Private _limilab As Limilab
    Private _DBConfig As ClassDBConfig.Config
    Private MyConnectionString As String

    Private _MailSender As Mail.MailSender

    Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles Me.Load
        Try
            LogConfig = New LogConfig(LogConfig.PathType.CustomPath, Path.Combine(My.Application.Info.DirectoryPath, "Log"), Nothing, My.Application.Info.CompanyName, My.Application.Info.ProductName)
            Logger = LogConfig.GetLogger()

            _limilab = New Limilab(LogConfig)
            Dim oUserAppDataPath As String = Application.UserAppDataPath
            Dim oCommonAppDataPath = Application.CommonAppDataPath
            Dim oStartupPath = Application.StartupPath

            Dim oAppconfig As String = "AppConfig.xml"
            Dim oAppConfigFilePath As String = Path.Combine(oStartupPath, oAppconfig)
            If File.Exists(oAppConfigFilePath) Then
                Logger.Info("Die Datei AppConfig.xml ist im StartUp-Path vorhanden.")
                ' UserAppDataPath = StartupPath
                oCommonAppDataPath = oStartupPath
            Else
                Logger.Info("Keine AppConfig.xml-Konfiguration!")
            End If


            ConfigManager = New ConfigManager(Of Config)(LogConfig, oUserAppDataPath, oCommonAppDataPath, oStartupPath)
            ConfigManager.Save()
            LogConfig.Debug = ConfigManager.Config.Debug
            If ConfigManager.Config.Debug = True Then
                Logger.Info("!! DEBUG is ACTIVE !!")
            End If

            InitDatabase()
            ToolStripProgressBar2.Visible = False
            Logger.Debug($"AppConfig is located at: [{AppDomain.CurrentDomain.SetupInformation.ConfigurationFile}]")
            Try
                If ConfigManager.Config.UseWindream Then
                    _windream = New clsWindream_allgemein(LogConfig)
                End If
            Catch ex As Exception
                Logger.Error(ex)
                ConfigManager.Save()
            End Try

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error in FormLoad")
        End Try

        If Set_ConnectionStrings() Then
            Load_AllData()
            Check_Steps()
            Active_Color(ACTIVECheckBox)
            Active_Color(ACTIVECheckBox1)
            Active_Color(ACTIVECheckBox2)
            Active_Color(ACTIVECheckBox3)
            Active_Color(ACTIVECheckBox4)
        End If
        Try
            If ConfigManager.Config.UseWindream Then
                ObjektTypenEintragen()
            End If
        Catch ex As Exception
            Logger.Error(ex)
            ConfigManager.Save()
        End Try


        _Encryption = New clsEncryption("!35452didalog=", LogConfig)

        If String.IsNullOrWhiteSpace(txtMonitoringConfig.Text) OrElse Not IsNumeric(txtMonitoringConfig.Text) OrElse CInt(txtMonitoringConfig.Text) <= 0 Then
            txtMonitoringConfig.Text = "500"
        End If
        LoadMonitoringIntoGrid()
    End Sub

    Private Sub frmMain_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        If ConfigManager.Config.UseWindream Then
            Load_Indexdata()
        End If
    End Sub

    Private Function Set_ConnectionStrings()
        Try

            Me.TBEMLP_POLL_PROFILESTableAdapter.Connection.ConnectionString = _SQLServerConString
            Me.TBEMLP_POLL_PROCESSTableAdapter.Connection.ConnectionString = _SQLServerConString
            Me.TBEMLP_POLL_STEPSTableAdapter.Connection.ConnectionString = _SQLServerConString
            Me.TBEMLP_POLL_INDEXING_STEPSTableAdapter.Connection.ConnectionString = _SQLServerConString
            Me.TBDD_EMAIL_ACCOUNTTableAdapter.Connection.ConnectionString = _SQLServerConString
            Me.TBEMLP_HISTORYTableAdapter.Connection.ConnectionString = _SQLServerConString
            Me.TBEMLP_CONFIGTableAdapter.Connection.ConnectionString = _SQLServerConString

            Return True
        Catch ex As Exception
            MsgBox("Unexpected Error in Set ConnectionStrings: " & ex.Message, MsgBoxStyle.Critical)
            Return False
        End Try
    End Function
    Sub Load_AllData()
        Try
            Me.TBDD_EMAIL_ACCOUNTTableAdapter.Fill(Me.MyDataset.TBDD_EMAIL_ACCOUNT)
            Me.TBEMLP_POLL_PROFILESTableAdapter.Fill(Me.MyDataset.TBEMLP_POLL_PROFILES)
            Me.TBEMLP_POLL_PROCESSTableAdapter.Fill(Me.MyDataset.TBEMLP_POLL_PROCESS)
            Me.TBEMLP_POLL_STEPSTableAdapter.Fill(Me.MyDataset.TBEMLP_POLL_STEPS)
            Me.TBEMLP_POLL_INDEXING_STEPSTableAdapter.Fill(Me.MyDataset.TBEMLP_POLL_INDEXING_STEPS)
        Catch ex As Exception
            MsgBox("Unexpected Error in Load_AllData: " & ex.Message, MsgBoxStyle.Critical)
            ConfigManager.Save()
        End Try
    End Sub
    Sub Load_Profiles()
        Try
            Me.TBEMLP_POLL_PROFILESTableAdapter.Fill(Me.MyDataset.TBEMLP_POLL_PROFILES)
        Catch ex As Exception
            MsgBox("Unexpected Error in Load_Profiles: " & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Sub Load_Processes()
        Try
            Me.TBEMLP_POLL_PROCESSTableAdapter.Fill(Me.MyDataset.TBEMLP_POLL_PROCESS)
        Catch ex As Exception
            MsgBox("Unexpected Error in Load_Processes: " & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Sub Load_Steps()
        Try
            Me.TBEMLP_POLL_STEPSTableAdapter.Fill(Me.MyDataset.TBEMLP_POLL_STEPS)
        Catch ex As Exception
            MsgBox("Unexpected Error in Load_Steps: " & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Sub Load_History()
        Try
            TBEMLP_HISTORYTableAdapter.Fill(MyDataset.TBEMLP_HISTORY)
        Catch ex As Exception
            MsgBox("Error in Load History: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Sub Load_indexingSteps()
        Try
            TBEMLP_POLL_INDEXING_STEPSTableAdapter.Fill(MyDataset.TBEMLP_POLL_INDEXING_STEPS)
        Catch ex As Exception
            MsgBox("Unexpected Error in Load_indexingSteps: " & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Sub Load_Config()
        Try
            _LoadInProgress = True
            TBEMLP_CONFIGTableAdapter.Fill(MyDataset.TBEMLP_CONFIG)

            txtConnectionString.Text = _database.MaskedConnectionString
        Catch ex As Exception
            MsgBox("Unexpected Error in Load_Config: " & ex.Message, MsgBoxStyle.Critical)
        End Try

        Try
            Dim osql = "SELECT * FROM TBDD_FUNCTION_REGEX WHERE UPPER(FUNCTION_NAME) IN (UPPER('EMAIL_PROFILER - RemoveHTMLText'),UPPER('EMAIL_PROFILER - RemoveHTMLText1'))"
            Dim oDTFunctionRegex As DataTable = _database.GetDatatable(osql)

            If oDTFunctionRegex?.Rows.Count > 0 Then
                txtRegex1.Text = oDTFunctionRegex.Rows(0).Item("REGEX")
                txtRegex2.Text = oDTFunctionRegex.Rows(1).Item("REGEX")
                txthtmlEmail.BackColor = Color.Wheat
            End If
        Catch ex As Exception
            MsgBox("Error in Load Regex: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

        _LoadInProgress = False
    End Sub

    Private Sub Load_Email()
        SetEmailTextboxLabels()
    End Sub

    Private Sub SetEmailTextboxLabels()
        Select Case AUTH_TYPEComboBox.Text
            Case "OAUTH2"
                EMAIL_SMTPLabel.Text = "Anwendungs-ID (Client):"
                EMAIL_PWLabel.Text = "Geheimnis ID Value"
                ARCHIVE_FOLDERLabel.Text = "Verzeichnis-ID (Mandant):"
            Case Else
                EMAIL_SMTPLabel.Text = "Server:"
                EMAIL_PWLabel.Text = "Passwort:"
                ARCHIVE_FOLDERLabel.Text = "Archive Ordner:"
        End Select
    End Sub

    Private Sub ObjektTypenEintragen()
        Try
            If IsNothing(_windream) Then
                Exit Sub
            End If
            ' Combobox leeren
            Me.WM_OBJEKTTYPEComboBox.Items.Clear()
            Dim result = _windream.GetObjecttypesAsStrings
            ' alle Objekttypen durchlaufen
            For Each oStr In result
                ' und in die Combobox eintragen
                Me.WM_OBJEKTTYPEComboBox.Items.Add(oStr)
            Next
        Catch ex As Exception
            MsgBox("Unexpected error in ObjektTypenEintragen", MsgBoxStyle.Critical)
        End Try

    End Sub

    Public Function InitDatabase()
        Try
            tslblstatus.BackColor = Color.Transparent
            If ConfigManager.Config.ConnectionString <> String.Empty Then
                _SQLServerConString = MSSQLServer.DecryptConnectionString(ConfigManager.Config.ConnectionString)
                If _SQLServerConString.Contains("LOGIT_DMS") Then
                    _SQLServerConString.Replace("LOGIT_DMS", "DD_ECM")
                    Logger.Debug($"Replaced wrong Database in ConString ... ")
                End If
                Logger.Debug($"SQL-Server ConnString is [{_SQLServerConString}]")

                _database = New MSSQLServer(LogConfig, _SQLServerConString)

                Logger.Debug("Inititalizing Configuration")
                Dim oConfigManager As ClassDBConfig = New ClassDBConfig(LogConfig, _database)
                _DBConfig = oConfigManager.GetConfig()

                If _DBConfig Is Nothing Then
                    MsgBox("Configuration could not be loaded. Please check the Logfile.", MsgBoxStyle.Critical, Text)
                End If

            Else
                MsgBox("No Databaseconnection configured. (First Start or Appdata not accessible)" & vbNewLine & "Basic-Config will be loaded.", MsgBoxStyle.Information)

                TabControl1.SelectedIndex = 1
                tslblstatus.Text = "Please add a connection!"
                tslblstatus.BackColor = Color.Red
            End If
            If _database?.DBInitialized = False Then
                MsgBox("Error in init database. (Connection failed) More information in the logfile.", MsgBoxStyle.Critical, Text)
                Return False
            Else
                Return True
            End If
        Catch ex As Exception
            Logger.Error(ex)
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error in Init Database:")
            Return False
        End Try

    End Function
    Private Sub cmbDatenbank_Click(sender As Object, e As EventArgs) Handles cmbDatenbank.Click

        Try
            Me.Cursor = Cursors.WaitCursor
            Dim csb As New SqlClient.SqlConnectionStringBuilder
            csb.DataSource = Me.txtServer.Text
            csb.IntegratedSecurity = False
            csb.UserID = Me.txtUser.Text
            csb.Password = Me.txtPasswort.Text

            Dim con As String
            If chkbxUserAut.Checked Then
                con = "Data Source=" & Me.txtServer.Text & ";Trusted_Connection=True;"
            Else
                con = "Server=" & Me.txtServer.Text & ";User Id=" & Me.txtUser.Text & ";Password=" & Me.txtPasswort.Text & ";"
            End If
            Dim connection As New SqlClient.SqlConnection(con) 'csb.ConnectionString)
            connection.Open()
            MyConnectionString = con
            ConfigManager.Save()
            Dim cmd As New SqlClient.SqlCommand("sp_databases", connection)
            cmd.CommandType = CommandType.StoredProcedure
            ' Ausführen und Ergebnis in einer ListBox anzeigen
            Dim dr As SqlClient.SqlDataReader = cmd.ExecuteReader
            If dr.HasRows Then
                cmbDatenbank.Items.Clear()
                Do While dr.Read
                    cmbDatenbank.Items.Add(dr("Database_Name"))
                Loop
                cmbDatenbank.DroppedDown = True
            Else
                MsgBox("The standard-databases could not be retrieved. The default database will be set!" & vbNewLine & "Check rights in sql-server for user: " & Me.txtUser.Text, MsgBoxStyle.Exclamation)
                cmbDatenbank.Text = "DD_ECM"
            End If
            connection.Close()
        Catch ex As Exception
            If ex.Message.ToLower.Contains("he standard-databases") Or ex.Message.ToLower.Contains("ie standard-datenbanken") Then
                cmbDatenbank.Text = "DD_ECM"
            End If
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error in Load Databases:")
        End Try
        Cursor = Cursors.Default
    End Sub
    Private Sub BtnConnect_Click_1(sender As Object, e As EventArgs) Handles BtnConnect.Click
        Try
            Dim con As String
            If chkbxUserAut.Checked Then
                con = "Server=" & Me.txtServer.Text & ";Database=" & Me.cmbDatenbank.Text & ";Trusted_Connection=True;Application Name=EMLProfiler_Client"
            Else
                con = "Server=" & Me.txtServer.Text & ";Database=" & Me.cmbDatenbank.Text & ";User Id=" & Me.txtUser.Text & ";Password=" & Me.txtPasswort.Text & ";Application Name=EMLProfiler_Client"
            End If


            Dim connection As New SqlClient.SqlConnection(con) 'csb.ConnectionString)
            'während Verbindungsaufbau Sanduhr-Mauszeiger
            Cursor = Cursors.WaitCursor
            connection.Open()
            Cursor = Cursors.Default
            'DialogResult = Windows.Forms.DialogResult.OK
            Dim result As MsgBoxResult
            Dim msg = "Die Verbindung wurde erfolgreich aufgebaut!" & vbNewLine & "Möchten Sie diese Verbindung nun in der Anwendung speichern?"
            result = MessageBox.Show(msg, "Database-Connection", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
            If result = MsgBoxResult.Yes Then
                'Set the construction string
                MyConnectionString = con
                ConfigManager.Config.ConnectionString = MyConnectionString

                _database = New MSSQLServer(LogConfig, MyConnectionString)
                Dim oConfigManager As ClassDBConfig = New ClassDBConfig(LogConfig, _database)

                'csb.ConnectionString
                '_database.Init(MyConnectionString)

                ConfigManager.Save()

                If chkbxUserAut.Checked = False Then
                    Dim cipherText As String = _Encryption.EncryptData(Me.txtPasswort.Text)
                    Dim pw As String = cipherText
                    con = "Server=" & Me.txtServer.Text & ";Database=" & Me.cmbDatenbank.Text & ";User Id=" & Me.txtUser.Text & ";Password=" & pw & ";"
                End If

                Dim csb As New SqlClient.SqlConnectionStringBuilder
                csb.ConnectionString = MyConnectionString
                Dim constr = connection.ConnectionString
                If chkbxUserAut.Checked = False Then
                    constr = constr.Replace(csb.Password, "XXXXX")
                End If
            End If
        Catch ex As Exception
            Cursor = Cursors.Default
            MsgBox("Error in Connectionbuild: " & vbNewLine & ex.Message, MsgBoxStyle.Exclamation)
        End Try
    End Sub

    Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork

        ConfigManager.Config.EmailTitlePrefix = "EmailProfilerTestClient"
        ConfigManager.Config.EmailAccountId = ToolStripEmailAccountID2.Text
        ConfigManager.Config.GDPictureVersion = "11.2024"

        If _RunwithLocalemail = False Then

            LogConfig.Debug = True
            Dim _work As New clsWorker(LogConfig, _SQLServerConString, _DBConfig.WindreamConnectionString, GUIDTextBox.Text, ConfigManager.Config)
            _work.Start_WorkingProfiles()

        Else
            For Each ofile As String In _Worklist
                Logger.Info($"## Manual working on file {ofile} ... ")
                Dim _work As New clsWorker(LogConfig, _SQLServerConString, _DBConfig.WindreamConnectionString, GUIDTextBox.Text, ConfigManager.Config, ofile.ToString)
                _work.Start_WorkingProfiles(True)
            Next

        End If
        Try
            'Delete all Tempfiles
            For Each _file In ClassCurrent.TEMP_FILES
                File.Delete(_file)
            Next
            Try
                Dim oDiTempPath As New DirectoryInfo(Path.GetTempPath)
                Dim oaryFi As FileInfo() = oDiTempPath.GetFiles()

                For Each fi In oaryFi
                    fi.Delete()
                Next
            Catch ex As Exception
                If LogConfig.Debug = True Then
                    Logger.Warn($"Could not delete the tempfile: {ex.Message}")
                End If
            End Try
        Catch ex As Exception

        End Try
    End Sub

    Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
        If e.Error IsNot Nothing Then
            MessageBox.Show(e.Error.Message, Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
        ElseIf e.Cancelled Then
            MessageBox.Show("Task cancelled!", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        Else
            MessageBox.Show("Manual Run completed!", Text, MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If

        tsbtnRunProfiles2.Enabled = True
        tsbtnRunLocalMail2.Enabled = True
        ToolStripProgressBar2.Visible = False
    End Sub

    Private Sub tsbtnRunProfiles_Click(sender As Object, e As EventArgs) Handles tsbtnRunProfiles2.Click
        If IsNumeric(ToolStripEmailAccountID2.Text) = False Then
            MsgBox("Choose an email-Profile before running processes!", MsgBoxStyle.Exclamation, Text)
            Exit Sub
        End If
        _RunwithLocalemail = False
        If Not BackgroundWorker1.IsBusy Then
            tsbtnRunProfiles2.Enabled = False
            tsbtnRunLocalMail2.Enabled = False
            ToolStripProgressBar2.Visible = True
            BackgroundWorker1.RunWorkerAsync()
        End If
    End Sub
    Private Sub ToolStripButton28_Click(sender As Object, e As EventArgs) Handles tsbtnRunLocalMail2.Click
        If IsNumeric(ToolStripEmailAccountID2.Text) = False Then
            MsgBox("Choose an email-Profile before running processes!", MsgBoxStyle.Exclamation)
            Exit Sub
        End If

        If Not BackgroundWorker1.IsBusy Then
            Dim openFileDialog1 As New OpenFileDialog With {
                .Filter = "Emails (*.eml)|*.eml|All files (*.*)|*.*",
                .FilterIndex = 2,
                .RestoreDirectory = True,
                .Multiselect = True
            }

            If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
                For Each oFile As String In openFileDialog1.FileNames
                    Dim oList As New List(Of String) From {oFile}
                    _Worklist = oList
                Next
                _RunwithLocalemail = True
                tsbtnRunLocalMail2.Enabled = False
                tsbtnRunProfiles2.Enabled = False
                ToolStripProgressBar2.Visible = True
                BackgroundWorker1.RunWorkerAsync()
            End If
        End If
    End Sub
    Private Sub mWorker_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
        ToolStripProgressBar2.Value = e.ProgressPercentage
    End Sub

    Private Sub btnShowLogpath_Click(sender As Object, e As EventArgs) Handles btnShowLogpath.Click
        Process.Start(LogConfig.LogDirectory)
    End Sub

    Private Sub TBEMLP_POLL_PROFILESBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs)
        Validate()
        TBEMLP_POLL_PROFILESBindingSource.EndEdit()
        TableAdapterManager.UpdateAll(MyDataset)

    End Sub

    Private Sub ToolStripButton9_Click(sender As Object, e As EventArgs) Handles ToolStripButton9.Click
        Load_AllData()
    End Sub

    Private Sub ToolStripButton10_Click(sender As Object, e As EventArgs) Handles ToolStripButton10.Click
        Load_Processes()
    End Sub

    Private Sub ToolStripButton8_Click(sender As Object, e As EventArgs) Handles ToolStripButton8.Click
        Try
            TBEMLP_POLL_PROCESSBindingSource.EndEdit()
            If MyDataset.TBEMLP_POLL_PROCESS.GetChanges Is Nothing = False Then
                CHANGED_WHOProcessTextBox.Text = Environment.UserName
                TBEMLP_POLL_PROCESSBindingSource.EndEdit()
                TBEMLP_POLL_PROCESSTableAdapter.Update(MyDataset.TBEMLP_POLL_PROCESS)
            End If
        Catch ex As Exception
            MsgBox("Error in Save Process: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub

    Private Sub WM_OBJEKTTYPEComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles WM_OBJEKTTYPEComboBox.SelectedIndexChanged
        If ConfigManager.Config.UseWindream Then
            Load_Indexdata()
        End If

    End Sub
    Sub Load_Indexdata()
        Try
            If Not IsNothing(WM_OBJEKTTYPEComboBox.Text) Then
                If WM_OBJEKTTYPEComboBox.Text = String.Empty Then
                    Exit Sub
                End If
                WM_VECTOR_LOGComboBox.Items.Clear()
                WM_IDX_BODY_TEXTComboBox.Items.Clear()
                INDEXNAMEIndexStepsComboBox.Items.Clear()

                WM_VECTOR_LOGComboBox.Items.Add("")
                WM_IDX_BODY_TEXTComboBox.Items.Add("")
                INDEXNAMEIndexStepsComboBox.Items.Add("")

                Dim indexe = _windream.GetIndicesByObjecttype(WM_OBJEKTTYPEComboBox.Text)
                If indexe IsNot Nothing Then
                    For Each index As String In indexe
                        Me.WM_VECTOR_LOGComboBox.Items.Add(index)
                        WM_IDX_BODY_TEXTComboBox.Items.Add(index)
                        INDEXNAMEIndexStepsComboBox.Items.Add(index)
                    Next
                End If
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Error in load_WDIndices: ")
        End Try
    End Sub
    Private Sub ToolStripButton18_Click(sender As Object, e As EventArgs) Handles ToolStripButton18.Click
        Load_Steps()
    End Sub

    Private Sub WM_IMPORTCheckBox_CheckedChanged(sender As Object, e As EventArgs) Handles WM_IMPORTCheckBox.CheckedChanged
        If WM_IMPORTCheckBox.Checked Then
            GroupBox2.Enabled = True
        Else
            GroupBox2.Enabled = False
        End If
    End Sub

    Private Sub TBEMLP_POLL_PROFILESBindingSource_AddingNew(sender As Object, e As AddingNewEventArgs) Handles TBEMLP_POLL_PROFILESBindingSource.AddingNew
        MyDataset.TBEMLP_POLL_PROFILES.ADDED_WHOColumn.DefaultValue = Environment.UserName
    End Sub

    Private Sub TBEMLP_POLL_PROCESSBindingSource_AddingNew(sender As Object, e As AddingNewEventArgs) Handles TBEMLP_POLL_PROCESSBindingSource.AddingNew
        MyDataset.TBEMLP_POLL_PROCESS.ADDED_WHOColumn.DefaultValue = Environment.UserName
    End Sub

    Private Sub TBEMLP_POLL_STEPSBindingSource_AddingNew(sender As Object, e As AddingNewEventArgs) Handles TBEMLP_POLL_STEPSBindingSource.AddingNew
        MyDataset.TBEMLP_POLL_STEPS.ADDED_WHOColumn.DefaultValue = Environment.UserName
    End Sub
    Private Sub TBDD_EMAIL_ACCOUNTBindingSource_AddingNew(sender As Object, e As AddingNewEventArgs) Handles TBDD_EMAIL_ACCOUNTBindingSource.AddingNew
        MyDataset.TBDD_EMAIL_ACCOUNT.ADDED_WHOColumn.DefaultValue = Environment.UserName
    End Sub

    Private Sub TBEMLP_POLL_PROCESSBindingSource_PositionChanged(sender As Object, e As EventArgs) Handles TBEMLP_POLL_PROCESSBindingSource.PositionChanged
        Check_Steps()
    End Sub
    Sub Check_Steps()
        If IsNumeric(GUIDProcessTextBox.Text) Then
            Dim oItemCount = TBEMLP_POLL_STEPSBindingSource.Count
            XtraTabPage2.Text = $"Working Steps ({oItemCount})"
        End If
    End Sub
    Sub Check_IndexingSteps()
        If IsNumeric(GUIDPollStepsTextBox.Text) Then
            Dim oItemCount = TBEMLP_POLL_INDEXING_STEPSBindingSource.Count
            XtraTabPage3.Text = $"Indexing Steps ({oItemCount})"
        End If
    End Sub
    Private Sub ToolStripButton27_Click(sender As Object, e As EventArgs) Handles ToolStripButton27.Click
        Save_email_Profile()
    End Sub
    Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs) Handles ToolStripButton1.Click
        Try
            TBEMLP_POLL_PROFILESBindingSource.EndEdit()
            If MyDataset.TBEMLP_POLL_PROFILES.GetChanges Is Nothing = False Then
                CHANGED_WHOProfilesTextBox.Text = Environment.UserName
                TBEMLP_POLL_PROFILESBindingSource.EndEdit()
                TBEMLP_POLL_PROFILESTableAdapter.Update(MyDataset.TBEMLP_POLL_PROFILES)
            End If
        Catch ex As Exception
            MsgBox("Error in Save Process: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub ToolStripButton17_Click(sender As Object, e As EventArgs) Handles ToolStripButton17.Click
        Try
            TBEMLP_POLL_STEPSBindingSource.EndEdit()
            If MyDataset.TBEMLP_POLL_STEPS.GetChanges Is Nothing = False Then
                CHANGED_WHOStepsTextBox.Text = Environment.UserName
                TBEMLP_POLL_STEPSBindingSource.EndEdit()
                TBEMLP_POLL_STEPSTableAdapter.Update(MyDataset.TBEMLP_POLL_STEPS)
            End If
        Catch ex As Exception
            MsgBox("Error in Save Steps: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub TBEMLP_POLL_STEPSBindingSource_PositionChanged(sender As Object, e As EventArgs) Handles TBEMLP_POLL_STEPSBindingSource.PositionChanged
        Check_IndexingSteps()
    End Sub
    Private Sub ToolStripButton25_Click(sender As Object, e As EventArgs) Handles ToolStripButton25.Click
        Try
            TBEMLP_POLL_INDEXING_STEPSBindingSource.EndEdit()
            If MyDataset.TBEMLP_POLL_INDEXING_STEPS.GetChanges Is Nothing = False Then
                CHANGED_WHOIndexingStepsTextBox.Text = Environment.UserName
                TBEMLP_POLL_INDEXING_STEPSBindingSource.EndEdit()
                TBEMLP_POLL_INDEXING_STEPSTableAdapter.Update(MyDataset.TBEMLP_POLL_INDEXING_STEPS)
            End If
        Catch ex As Exception
            MsgBox("Error in Save Indexing Steps: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub ToolStripButton26_Click(sender As Object, e As EventArgs) Handles ToolStripButton26.Click
        Load_indexingSteps()
    End Sub

    Private Sub XtraTabControl1_SelectedPageChanged(sender As Object, e As DevExpress.XtraTab.TabPageChangedEventArgs) Handles XtraTabControl1.SelectedPageChanged
        Select Case XtraTabControl1.SelectedTabPageIndex
            Case 0
                Check_Steps()
                If ConfigManager.Config.UseWindream Then
                    Load_Indexdata()
                End If

            Case 1
                Check_IndexingSteps()
            Case 2

        End Select
    End Sub



    Private Sub TabControl1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles TabControl1.SelectedIndexChanged
        tslblRefresh.BackColor = Color.Transparent
        tslblRefresh.Text = ""
        If TabControl1.SelectedTab.Equals(tabConfig) Then
            Load_Config()
        End If
        If TabControl1.SelectedTab.Equals(tabEmail) Then
            Load_Email()
        End If
    End Sub

    Sub Active_Color(pCheckBox As CheckBox)
        If pCheckBox.Checked Then
            pCheckBox.BackColor = Color.LimeGreen

        Else
            pCheckBox.BackColor = Color.IndianRed
        End If
    End Sub

    Private Sub PROCESS_NAMEComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles PROCESS_NAMEComboBox.SelectedIndexChanged
        If PROCESS_NAMEComboBox.SelectedIndex <> -1 Then
            Select Case PROCESS_NAMEComboBox.Text
                Case "ProcessManager"
                    txtSubjectExample.Text = "[ProcessManager][EA][DID#[%Dokument-ID]]"
                    cbAllowXMLReceipt.Enabled = False
                    cbAllowXMLReceipt.Checked = False
                Case "Attachment Sniffer"
                    lblDownloadPath.Text = "Download-Path Attachments:"
                    cbAllowXMLReceipt.Enabled = True
                Case "ZugFeRD-Parser"
                    lblDownloadPath.Text = "Download-Path Attachments:"
                    cbAllowXMLReceipt.Enabled = False
                    cbAllowXMLReceipt.Checked = False
                Case Else
                    txtSubjectExample.Text = ""
                    lblDownloadPath.Text = "Download-Path:"
                    cbAllowXMLReceipt.Enabled = False
                    cbAllowXMLReceipt.Checked = False
            End Select
        End If
    End Sub

    Private Sub ToolStripButton34_Click(sender As Object, e As EventArgs)
        Load_History()
    End Sub

    Private Sub LOG_ERRORS_ONLYCheckBox_CheckedChanged(sender As Object, e As EventArgs) Handles LOG_ERRORS_ONLYCheckBox.CheckedChanged
        If _LoadInProgress = True Then Exit Sub
        LogConfig.Debug = LOG_ERRORS_ONLYCheckBox.Checked
        ConfigManager.Save()
        Dim upd = $"UPDATE TBEMLP_CONFIG SET CHANGED_WHO = '{Environment.UserName}',LOG_ERRORS_ONLY = '{LOG_ERRORS_ONLYCheckBox.Checked}' WHERE GUID = 1"
        _database.ExecuteNonQuery(upd)
        Load_Config()

    End Sub

    Sub Save_Config()
        Try
            TBEMLP_CONFIGBindingSource.EndEdit()
            If MyDataset.TBEMLP_CONFIG.GetChanges Is Nothing = False Then
                Me.CHANGED_WHOTextBox.Text = Environment.UserName
                TBEMLP_CONFIGBindingSource.EndEdit()
                TBEMLP_CONFIGTableAdapter.Update(MyDataset.TBEMLP_CONFIG)

            End If
        Catch ex As Exception
            MsgBox("Error in Save_Config: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Sub Save_email_Profile()
        Try
            TBDD_EMAIL_ACCOUNTBindingSource.EndEdit()
            If MyDataset.TBDD_EMAIL_ACCOUNT.GetChanges Is Nothing = False Then
                Me.CHANGED_WHOTextBox1.Text = Environment.UserName
                TBDD_EMAIL_ACCOUNTBindingSource.EndEdit()
                TBDD_EMAIL_ACCOUNTTableAdapter.Update(MyDataset.TBDD_EMAIL_ACCOUNT)
                ToolStripStatusLabel1.Text = $"Email-Profil gespeichert [{Now.ToString}]"
            End If
        Catch ex As Exception
            MsgBox("Error in Save_EmailAccount: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub CHECK_INTERVALL_MINUTESNumericUpDown_ValueChanged(sender As Object, e As EventArgs) Handles CHECK_INTERVALL_MINUTESNumericUpDown.ValueChanged
        If _LoadInProgress = True Then Exit Sub
        Dim upd = $"UPDATE TBEMLP_CONFIG SET CHANGED_WHO = '{Environment.UserName}',CHECK_INTERVALL_MINUTES = {CHECK_INTERVALL_MINUTESNumericUpDown.Value} WHERE GUID = 1"
        _database.ExecuteNonQuery(upd)
        Load_Config()
    End Sub
    Private Sub STEP_NAMEComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles STEP_NAMEComboBox.SelectedIndexChanged
        Label9.Visible = False
        txtSubjectExample.Visible = False
        Select Case STEP_NAMEComboBox.Text
            Case "Easy Approval"
                Label9.Visible = True
                txtSubjectExample.Visible = True
            Case "Download Mail"
                COPY_2_HDDCheckBox.Checked = True
            Case Else

        End Select
    End Sub

    Private Sub btnFBD_DonwloadPath_Click(sender As Object, e As EventArgs) Handles btnFBD_DonwloadPath.Click
        If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
            PATH_EMAIL_TEMPTextBox.Text = FolderBrowserDialog1.SelectedPath
        End If
    End Sub

    Private Sub btnFBD_ErrorPath_Click(sender As Object, e As EventArgs) Handles btnFBD_ErrorPath.Click
        If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
            PATH_EMAIL_ERRORSTextBox.Text = FolderBrowserDialog1.SelectedPath
        End If
    End Sub

    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        Dim pwencrypted = _Encryption.EncryptData(txtnewpasswort.Text)
        EMAIL_PWTextBox.Text = pwencrypted
        Save_email_Profile()
        MsgBox("Passwort was encrypted!")
    End Sub

    Private Sub btnsendtestmail_Click(sender As Object, e As EventArgs) Handles btnsendtestmail.Click
        If txtTestmail.Text <> String.Empty Then
            ConfigManager.Save()
            My.Settings.Save()
            Cursor = Cursors.WaitCursor
            Dim PWPlain = _Encryption.DecryptData(EMAIL_PWTextBox.Text)
            'NEW
            _MailSender = New Mail.MailSender(LogConfig)
            Dim oDefault As Boolean = True
            If CheckBoxEnableTls1_1.Checked Or CheckBoxEnableTls1_2.Checked Then
                oDefault = False
            End If
            Dim oOptions As New Mail.MailSession.MailSessionOptions() With {
                        .EnableTls1_1 = CheckBoxEnableTls1_1.Checked,
                        .EnableTls1_2 = CheckBoxEnableTls1_2.Checked,
                        .EnableDefault = oDefault
                    }
            Logger.Debug($"oOptions: oOptions.EnableTls1_1: {oOptions.EnableTls1_1}, oOptions.EnableTls1_2: {oOptions.EnableTls1_2}, oOptions.EnableDefault: {oOptions.EnableDefault}")
            Dim oResult As Mail.MailSession.SessionInfo = _MailSender.Connect(EMAIL_SMTPTextBox.Text, PORTTextBox.Text, EMAIL_USERTextBox.Text, PWPlain, AUTH_TYPEComboBox.Text, oOptions)

            If oResult.Connected = False Then
                Cursor = Cursors.Default
                MsgBox("Could not create a MailSession / connect to server. Please check the log.", MsgBoxStyle.Exclamation)
                Exit Sub
            End If
            Dim oAddresses As List(Of String) = txtTestmail.Text.Split(";").ToList()
            Dim oAddedWhen = Now
            Dim oAttachments As New List(Of String)
            Dim oBody As String = $"This is just a template body (text will be replaced within the run) - ProfileID: {EMAILIDTextBox.Text}"
            Dim oMessageSent = _MailSender.SendMail(oAddresses, EMAIL_FROMTextBox.Text, "Testmail from EmailProfilerConfig", oBody, oAddedWhen, oAttachments, False)
            Cursor = Cursors.Default
            If oMessageSent = True Then
                MsgBox("Email has been send successfully.", MsgBoxStyle.Information)
            Else
                MsgBox("Could not send the testmail. Please check the log.", MsgBoxStyle.Exclamation)
            End If
            'NEW END

            'If _limilab.NewSMTPEmail(txtTestmail.Text, "Testmail", "This is the body (text will be replaced within profile)", EMAIL_FROMTextBox.Text, EMAIL_SMTPTextBox.Text, PORTTextBox.Text,
            '                     EMAIL_USERTextBox.Text, PWPlain, AUTH_TYPEComboBox.Text, "frmMain-Test", "", "", True) = True Then


            '    MsgBox("Email has been send successfully.", MsgBoxStyle.Information)
            'Else
            '    MsgBox("Could not send the testmail. Please check the log.", MsgBoxStyle.Exclamation)
            'End If
        End If
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btntestImap.Click
        ConfigManager.Save()
        Dim oSQL = $"SELECT * FROM TBDD_EMAIL_ACCOUNT WHERE GUID = {EMAILIDTextBox.Text}"
        Dim oDT As DataTable = _database.GetDatatable(oSQL)
        If Not IsNothing(oDT) Then

            If oDT.Rows.Count = 1 Then

                Dim oRow As DataRow = oDT.Rows.Item(0)

                Dim PWPlain = _Encryption.DecryptData(oRow.Item("EMAIL_PW"))
                Dim oServer = oRow.Item("EMAIL_SMTP")
                Dim oPortIn = oRow.Item("PORT_IN")
                Dim oUser = oRow.Item("EMAIL_USER")
                Dim oAuthType = oRow.Item("AUTH_TYPE")
                Dim oArchiveFolder = oRow.Item("ARCHIVE_FOLDER")

                Dim oFetcher As New MailFetcher(LogConfig)
                Dim oSession As MailSession.SessionInfo

                If oAuthType = MailSession.AUTH_OAUTH2 Then
                    ' These Variables from the DB are reused for the OAuth credentials
                    Dim oClientId = oServer
                    Dim oClientSecret = PWPlain
                    Dim oTenantId = oArchiveFolder
                    oSession = oFetcher.ConnectToO365(oUser, oClientId, oTenantId, oClientSecret)
                Else
                    oSession = oFetcher.Connect(oServer, oPortIn, oUser, PWPlain, oAuthType, New MailSession.MailSessionOptions() With {
                        .EnableTls1_1 = True,
                        .EnableTls1_2 = True
                    })
                End If

                If oSession.Connected = True Then
                    ' Unseen check will be done automatically
                    'btnCheckIMAPObjects.Visible = True

                    Dim oMailIds = oFetcher.ListUnseenMails()
                    If oMailIds Is Nothing Then
                        MsgBox("Could not get unseen Objects from IMAP-Folder!", MsgBoxStyle.Critical, Text)
                    Else
                        MsgBox($"IMAP-Folder contained [{oMailIds.Count}] unseen Objects!", MsgBoxStyle.Information, Text)
                    End If

                    oFetcher.Disconnect()
                Else
                    MsgBox($"Imap Login NOT successful: {vbNewLine}{oSession.Error?.Message}", MsgBoxStyle.Critical, Text)
                End If

                '_limilab.InitIMAP(True, oDT.Rows(0).Item("EMAIL_SMTP"), oDT.Rows(0).Item("PORT_IN"), oDT.Rows(0).Item("EMAIL_USER"), PWPlain, oDT.Rows(0).Item("AUTH_TYPE"))
                'Dim oResult = _limilab.IMAPTestLogin()

                'If oResult = False Then
                '    MsgBox("Access Imap NOT successfull", MsgBoxStyle.Critical)
                'Else
                '    MsgBox("IMAP-Test Successful!", MsgBoxStyle.Information)
                '    btnCheckIMAPObjects.Visible = True
                'End If
            End If
        End If
    End Sub

    Private Sub btnCheckIMAPObjects_Click(sender As Object, e As EventArgs) Handles btnCheckIMAPObjects.Click

        Dim oListuids As List(Of Long) = _limilab.IMAPGetUnseenMessageIDs()
        If IsNothing(oListuids) Then
            MsgBox("Something went wrong! - Check Your log.", MsgBoxStyle.Critical)
        Else
            _limilab.CloseImap()
            MsgBox($"IMAP-Folder contained [{oListuids.Count}] unseen Objects!", MsgBoxStyle.Information)
        End If
    End Sub

    Private Sub btnTestRegEx_Click(sender As Object, e As EventArgs)
        txtResultRegEx.Text = ""
        Try
            ConfigManager.Save()
            txtResultRegEx.BackColor = Color.WhiteSmoke
            ' Instantiate the regular expression object.
            Dim oReg As Regex = New Regex(txtRegex1.Text, RegexOptions.IgnoreCase)
            Dim oMatch As Match = oReg.Match(txthtmlEmail.Text)
            Dim oClearedBodyText = txthtmlEmail.Text
            Do While oMatch.Success
                oClearedBodyText = oClearedBodyText.Replace(oMatch.Value, "")
                'Dim g As Group = m.Groups(1)
                'If g.ToString.StartsWith("&") = False Then
                '    TEMP_HTML_RESULTS.Add(g.ToString())
                'End If

                oMatch = oMatch.NextMatch()
            Loop
            Logger.Info($"Cleared bodytext after Regex1 is: {oClearedBodyText}")
            Dim oReg2 As Regex = New Regex(txtRegex2.Text, RegexOptions.IgnoreCase)
            Dim oMatch2 As Match = oReg2.Match(oClearedBodyText)

            Do While oMatch2.Success
                oClearedBodyText = oClearedBodyText.Replace(oMatch2.Value, "")
                'Dim g As Group = m.Groups(1)
                'If g.ToString.StartsWith("&") = False Then
                '    TEMP_HTML_RESULTS.Add(g.ToString())
                'End If

                oMatch2 = oMatch2.NextMatch()
            Loop
            Logger.Info($"Cleared bodytext after Regex2 is: {oClearedBodyText}")
            txtResultRegEx.Text = oClearedBodyText
            txtResultRegEx.BackColor = Color.Yellow
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub

    Private Sub btnsaveRegex_Click_1(sender As Object, e As EventArgs)
        tslblRefresh.BackColor = Color.Transparent
        Dim upd = $"UPDATE TBDD_FUNCTION_REGEX SET REGEX = '{txtRegex1.Text}' WHERE UPPER(FUNCTION_NAME) = UPPER('EMAIL_PROFILER - RemoveHTMLText')"
        If _database.ExecuteNonQuery(upd) = True Then
            tslblRefresh.Text = "Regex1 saved - " & Now.ToString
            tslblRefresh.BackColor = Color.Yellow
        Else
            tslblRefresh.Text = "Regex1 NOT saved - Check Your log: " & Now.ToString
            tslblRefresh.BackColor = Color.Transparent
        End If
    End Sub

    Private Sub Button5_Click(sender As Object, e As EventArgs)
        tslblRefresh.BackColor = Color.Transparent
        Dim upd = $"UPDATE TBDD_FUNCTION_REGEX SET REGEX = '{txtRegex2.Text}' WHERE UPPER(FUNCTION_NAME) = UPPER('EMAIL_PROFILER - RemoveHTMLText1')"
        If _database.ExecuteNonQuery(upd) = True Then
            tslblRefresh.Text = "Regex2 saved - " & Now.ToString
            tslblRefresh.BackColor = Color.Yellow
        Else
            tslblRefresh.Text = "Regex2 NOT saved - Check Your log: " & Now.ToString
            tslblRefresh.BackColor = Color.Transparent
        End If
    End Sub

    Private Sub COPY_2_HDDCheckBox_CheckedChanged(sender As Object, e As EventArgs) Handles COPY_2_HDDCheckBox.CheckedChanged
        If COPY_2_HDDCheckBox.Checked Then
            PATH_ORIGINALTextBox.Enabled = True
        Else
            PATH_ORIGINALTextBox.Enabled = False
        End If
    End Sub

    Private Sub EMAILIDTextBox_TextChanged(sender As Object, e As EventArgs) Handles EMAILIDTextBox.TextChanged
        If IsNumeric(EMAILIDTextBox.Text) Then
            ToolStripEmailAccountID2.Text = EMAILIDTextBox.Text
        Else
            ToolStripEmailAccountID2.Text = "Choose Email-Config"
        End If
        btnCheckIMAPObjects.Visible = False
    End Sub

    Private Sub AUTH_TYPEComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles AUTH_TYPEComboBox.SelectedIndexChanged
        If AUTH_TYPEComboBox.SelectedIndex <> -1 Then
            Select Case AUTH_TYPEComboBox.SelectedIndex
                Case 0 'Start TLS
                    PORT_INTextBox.Enabled = False
                Case 1 'SSL/TLS
                    PORT_INTextBox.Enabled = True
            End Select
        End If
        SetEmailTextboxLabels()
    End Sub

    Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
        Try
            If ComboBox1.SelectedIndex <> -1 Then
                ToolStripEmailAccountID2.Text = ComboBox1.SelectedValue
            End If
        Catch ex As Exception
            Logger.Error(ex)
        End Try
    End Sub

    Private Sub PasswortAnzeigenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles PasswortAnzeigenToolStripMenuItem.Click
        Try
            Dim oPW = EMAIL_PWTextBox.Text
            Dim pwdecrypted = _Encryption.DecryptData(oPW)
            MsgBox(pwdecrypted, MsgBoxStyle.Information, "Current PW")
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "")
        End Try
    End Sub

    Private Sub btnAktualisieren_Click(sender As Object, e As EventArgs) Handles btnAktualisieren.Click
        Me.TBDD_EMAIL_ACCOUNTTableAdapter.Fill(Me.MyDataset.TBDD_EMAIL_ACCOUNT)
    End Sub

    Private Sub ACTIVECheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles ACTIVECheckBox.CheckedChanged, ACTIVECheckBox1.CheckedChanged, ACTIVECheckBox2.CheckedChanged, ACTIVECheckBox3.CheckedChanged, ACTIVECheckBox4.CheckedChanged
        Dim oCheckBox As CheckBox = sender
        Active_Color(oCheckBox)
    End Sub

    Private Sub GridView6_FocusedRowChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs) Handles GridView6.FocusedRowChanged
        SetEmailTextboxLabels()
    End Sub

    Private Sub btnValidationSQL_Click(sender As Object, e As EventArgs) Handles btnValidationSQL.Click
        Dim oForm As New frmSQLEditor(LogConfig, _database) With {
            .SQLConnection = 1,
            .SQLCommand = txtSQLValidation.EditValue,
            .PlaceholdersManual = New Dictionary(Of String, String) From {
                {"EMAIL", "EMAIL"},
                {"DOMAIN", "DOMAIN"}
            },
            .PlaceholdersManualPrefix = "CUST"
        }
        If oForm.ShowDialog() = DialogResult.OK Then
            txtSQLValidation.EditValue = oForm.SQLCommand
        End If

    End Sub

    Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
        If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
            PATH_ORIGINALTextBox.Text = FolderBrowserDialog1.SelectedPath
        End If
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        ConfigManager.Save()
    End Sub

    Private Sub PATH_EMAIL_ERRORSTextBox_TextChanged(sender As Object, e As EventArgs) Handles PATH_EMAIL_ERRORSTextBox.TextChanged

    End Sub

    Private Sub PATH_ORIGINALTextBox_TextChanged(sender As Object, e As EventArgs) Handles PATH_ORIGINALTextBox.TextChanged

    End Sub

    Private Sub COMMENT_PROFILESTextBox_TextChanged(sender As Object, e As EventArgs) Handles COMMENT_PROFILESTextBox.TextChanged

    End Sub

    Private Sub LoadMonitoringIntoGrid()
        Try

            Dim emailAmount As Integer
            If txtMonitoringConfig.Text = Nothing OrElse Not IsNumeric(txtMonitoringConfig.Text) Then
                emailAmount = 500
            Else
                emailAmount = Convert.ToInt32(txtMonitoringConfig.Text)
            End If

            Dim oSQL = $"SELECT TOP ({emailAmount}) GUID, PROFILE_ID, EMAIL_MSGID, EMAIL_FROM, EMAIL_SUBJECT, EMAIL_DATE, ADDED_WHEN, STATUS FROM [dbo].[TBEMLP_HISTORY] (nolock) order by GUID DESC"
            Dim oDT As DataTable = _database.GetDatatable(oSQL)

            Me.gridMonitoring.DataSource = oDT

            Dim gridView = TryCast(Me.GridViewMonitoring, DevExpress.XtraGrid.Views.Grid.GridView)
            If gridView IsNot Nothing Then

                gridView.OptionsView.ColumnAutoWidth = True
                gridView.BestFitColumns()
                gridView.OptionsBehavior.Editable = False

                LoadLayoutMonitoring()
            End If

        Catch ex As Exception
            If Logger IsNot Nothing Then Logger.Error(ex) Else Debug.WriteLine(ex.ToString())
        End Try
    End Sub

    Private Sub txtMonitoringConfig_LostFocus(sender As Object, e As EventArgs) Handles txtMonitoringConfig.LostFocus
        If Not IsNumeric(txtMonitoringConfig.Text) OrElse CInt(txtMonitoringConfig.Text) <= 0 Then
            txtMonitoringConfig.Text = "500"
        End If
        LoadMonitoringIntoGrid()
    End Sub

    Private Sub btnRefresh_Click(sender As Object, e As EventArgs) Handles btnRefresh.Click
        LoadMonitoringIntoGrid()
    End Sub

    Private Sub btnSaveLayout_Click(sender As Object, e As EventArgs) Handles btnSaveLayout.Click
        Dim layoutPath As String = System.IO.Path.Combine(Application.UserAppDataPath, "gridMonitoringLayout.xml")
        GridViewMonitoring.SaveLayoutToXml(layoutPath)
        MessageBox.Show("Layout gespeichert!")
    End Sub

    Private Sub btnRestoreDefaultLayout_Click(sender As Object, e As EventArgs) Handles btnRestoreDefaultLayout.Click
        Dim layoutPath As String = System.IO.Path.Combine(Application.UserAppDataPath, "gridMonitoringLayout.xml")
        If System.IO.File.Exists(layoutPath) Then
            System.IO.File.Delete(layoutPath)
        End If
        GridViewMonitoring.Columns.Clear()
        gridMonitoring.DataSource = Nothing
        LoadMonitoringIntoGrid()
        MessageBox.Show("Standardlayout wurde wiederhergestellt!")
    End Sub

    Private Sub LoadLayoutMonitoring()
        Dim layoutPath As String = System.IO.Path.Combine(Application.UserAppDataPath, "gridMonitoringLayout.xml")
        If System.IO.File.Exists(layoutPath) Then
            GridViewMonitoring.RestoreLayoutFromXml(layoutPath)
        End If
    End Sub

End Class
