Imports System.Globalization
Imports DevExpress.Utils
Imports DevExpress.XtraGrid.Views.Grid.ViewInfo
Imports DevExpress.XtraGrid.Views.Grid
Imports DevExpress.XtraGrid
Imports DevExpress.XtraNavBar
Imports DevExpress.XtraGrid.Columns
Imports System.Threading
Imports System.ComponentModel
Imports System.IO
Imports DevExpress.XtraPrinting
Imports DigitalData.Modules.EDMI.API.DatabaseWithFallback
Imports DigitalData.Modules.EDMI.API.Constants
Imports DigitalData.Modules.Windream
Imports DigitalData.GUIs.Common
Imports DevExpress.XtraGrid.Views.BandedGrid
Imports DevExpress.XtraBars.Ribbon
Imports DigitalData.Modules.ZooFlow
Imports DevExpress.LookAndFeel
Imports DigitalData.Modules.Base

Public Class frmMain
    Private Property FormHelper As FormHelper

    Private UserLoggedin As Integer = 0
    Private CURR_DT_VWPM_PROFILE_ACTIVE As DataTable
    Private CURR_DT_VWPM_PROFILE_AH_WORKFLOW As DataTable
    Private DT_CURR_WF_ITEMS As DataTable
    Private OVERVIEW_ADDED_WHEN As String
    Private OVERVIEW_CHANGED_WHEN As String
    Private OVERVIEW_COUNT As Integer = 0
    Private RedDocuments As Integer = 0
    Private YellowDocuments As Integer = 0
    Private GreenDocuments As Integer = 0
    Private GridViewItem_Clicked = Nothing
    Private GridCursorLocation As Point
    Private GRID_LOAD_TYPE As String = "OVERVIEW"
    Private GRID_INV_COL_REMOVED As Boolean = False
    Private NO_WORKFLOWITEMS As Boolean = False
    Private InResetlayout As Boolean = False
    Private RefreshHelper As RefreshHelper
    Private _FormValidator As frmValidator
    Private FormOpenClose As Boolean = False
    Private FormShown As Boolean = False
    Private GridIsLoaded As Boolean = False
    Private OverviewOrDEtail As String = "OVERVIEW"
    Private GridBuilder As GridBuilder

    Private allgFunk As New ClassAllgemeineFunktionen
    Private _Init As New ClassInit
    Private CurrNavBarGroup As NavBarGroup
    'Private DataASorDB As ClassDataASorDB

    Private DT_CHECKUSER_MODULE As DataTable
    Private NOTIFICATIONS_DT As DataTable
    Private IsFilterMode As Boolean
    Private DetailLinkActive As Boolean = False
    Private FRONTEND_ACTION As String = "NONE"
    Private Ev_Filter_Panel_Closed As Boolean = False

    Dim omsgOpenWorkflow As String
    Dim omsgTitleWarning As String
    Dim omsgTitleAttention As String

    Private Const FullFilepatColName = "FULL_FILE_PATH"
    Private Const FA_NONE = "NONE"
    Public Const NAVBAR_CLICKED = "NAVBAR LINK CLICKED"


    Private Class S
        Inherits My.Resources.frmMain_Strings
    End Class


    Private Function GET_LAST_ADDED(pDatatable As DataTable) As String
        Dim oADDED As String
        Try
            If IsNothing(pDatatable) Then
                oADDED = "NOTHING"
            ElseIf LAST_ADDED_COLUMN = FA_NONE Then
                oADDED = Now.ToShortTimeString.ToString
            Else
                Dim result As Object
                result = pDatatable.Compute($"MAX({LAST_ADDED_COLUMN})", "")
                oADDED = result
            End If

        Catch ex As Exception
            oADDED = "Exception"
        End Try
        Return oADDED
    End Function
    Private Function GET_LAST_CHANGED(pDatatable As DataTable) As String
        Dim oCHANGED As String
        Try
            If IsNothing(pDatatable) Then
                oCHANGED = "NOTHING"
            ElseIf LAST_EDITED_COLUMN = FA_NONE Then
                oCHANGED = Now.ToShortTimeString.ToString
            Else
                Dim result As Object
                result = pDatatable.Compute($"MAX({LAST_EDITED_COLUMN})", "")
                oCHANGED = result
            End If

        Catch ex As Exception
            oCHANGED = "Exception"
        End Try
        Return oCHANGED
    End Function
    Private Function Free_File()
        Try
            Dim sql = $"UPDATE TBPM_PROFILE_FILES SET EDIT = 0, IN_WORK = 0, IN_WORK_WHEN = NULL, WORK_USER = NULL WHERE GUID = {CURRENT_DOC_GUID}"
            Return DatabaseFallback.ExecuteNonQueryECM(sql)
        Catch ex As Exception
            LOGGER.Error(ex)
            Return False
        End Try
    End Function
    Private Sub frmMain_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        Free_File()

        Try
            FormOpenClose = True
            ' Position und Größe speichern
            My.Settings.frmMainSize = Me.Size
            My.Settings.frmMainPosition = Me.Location
            My.Settings.Save()
        Catch ex As Exception
            LOGGER.Error(ex)
            LOGGER.Info("Error in Save FormLayout: " & ex.Message)
        End Try
        If IDB_ACTIVE = False Then
            Try
                If WINDREAM?.oSession?.aLoggedin = True Then
                    WINDREAM.Stop_WMCC_andCo()
                End If
            Catch ex As Exception

            End Try

        End If
        If INACTIVITYRecognized Then
            Exit Sub
        End If
        Try
            ClassAllgemeineFunktionen.LoginOut("LOGOUT")
            LOGGER.Info("TaskFlow closed - " & Now, False)
        Catch ex As Exception
            LOGGER.Error(ex)
        End Try
    End Sub

    Private Sub frmMain_KeyUp(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyUp
        Select Case e.KeyCode
            Case Keys.F12
                frmLicense.ShowDialog()
        End Select
    End Sub

    Private Sub frmMain_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        FormOpenClose = True
        LOGGER.Debug("Initializing MainForm....")

        GridBuilder = New GridBuilder(GridViewWorkflows)
        GridBuilder.WithFontSizeDelta(CONFIG.Config.GridFontSizeDelta)

        Dim oFontSettings = New List(Of FontSetting) From {
            New FontSetting With {.Title = S.Kleiner, .Value = -2},
            New FontSetting With {.Title = S.Normal, .Value = 0},
            New FontSetting With {.Title = S.Größer, .Value = 2}
        }

        cmbGridFontSize.Items.Clear()
        cmbGridFontSize.Items.AddRange(oFontSettings)
        barItemGridFontSize.EditValue = oFontSettings.
                Where(Function(item) item.Value = CONFIG.Config.GridFontSizeDelta).
                FirstOrDefault()

        ' Create helper to save/load expanded GroupColumns at runtime
        RefreshHelper = New RefreshHelper(LOGCONFIG, GridViewWorkflows, "GUID")

        omsgOpenWorkflow = ClassAllgemeineFunktionen.GUI_LANGUAGE_INFO("WorkflowIsActive1")
        omsgTitleWarning = ClassAllgemeineFunktionen.GUI_LANGUAGE_INFO("MsgboxTitleWarning")
        omsgTitleAttention = ClassAllgemeineFunktionen.GUI_LANGUAGE_INFO("MsgboxTitleAttention")


        Dim oVErsion = My.Application.Info.Version.ToString 'String.Format("{0}.{1}.{2}", My.Application.Info.Version.Major, My.Application.Info.Version.Minor, My.Application.Info.Version.Build)
        BSIVERSION1.Caption = oVErsion
        If ERROR_STATE = "NO DB-CONNECTION" Or ERROR_STATE = "FAILED DBCONNECTION" Then
            MsgBox(S.Bitte_konfigurieren_Sie_eine_Datenbankverbindung_, MsgBoxStyle.Critical, "Fehlende Konfiguration:")
            frmKonfig.ShowDialog()
        End If
        Try
            If CultureInfo.CurrentUICulture.ThreeLetterISOLanguageName = "eng" Then
                LOGGER.Info("## CurrentUICulture.Name: " & CultureInfo.CurrentUICulture.Name, False)
                INDEX_DMS_ERSTELLT = "DMS Created"
                INDEX_DMS_ERSTELLT_ZEIT = "DMS Created Time"
                My.Settings.Save()
            End If
            Try
                Dim oCultureInfo As System.Globalization.CultureInfo
                oCultureInfo = New System.Globalization.CultureInfo(USER_LANGUAGE)
                oCultureInfo.DateTimeFormat.ShortDatePattern = USER_DATE_FORMAT
                Thread.CurrentThread.CurrentCulture = oCultureInfo
                Thread.CurrentThread.CurrentUICulture = oCultureInfo
                CultureInfo.DefaultThreadCurrentCulture = oCultureInfo
                CultureInfo.DefaultThreadCurrentUICulture = oCultureInfo

            Catch ex As Exception

            End Try
        Catch ex As Exception
            LOGGER.Error(ex)
            MessageBox.Show("Error loading CurrentUICulture-Info!", "Attention:", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try

        Try
            'DataASorDB = New ClassDataASorDB
            If User.IsAdmin = True Then
                'Dim oCaption As String = ClassAllgemeineFunktionen.GUI_LANGUAGE_INFO("NumberLicenses")
                'bsiLicenses.Caption = $"{oCaption} {LICENSE_COUNT}"
                Dim oCaption As String = String.Format(S.Anzahl_Lizenzen___0_, LICENSE_COUNT)
                bsiLicenses.Caption = oCaption

                bsiLicenses.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
            Else
                bsiLicenses.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
            End If

            LOGGER.Debug("Initializing MainForm....")

            If ERROR_STATE = "NO USER" Then
                Dim oDT As DataTable = ClassAllgemeineFunktionen.GUI_LANGUAGE_INFO("No Userconfig")
                MsgBox(oDT.Rows(0).Item("STRING1") & vbNewLine & oDT.Rows(0).Item("STRING2"), MsgBoxStyle.Critical, "Exception")
                Me.Close()
            ElseIf USER_IN_MODULE = False Then
                If USER_IS_ADMIN = False Then
                    Dim oDT As DataTable = ClassAllgemeineFunktionen.GUI_LANGUAGE_INFO("No Module Configuration")
                    MsgBox(oDT.Rows(0).Item("STRING1") & vbNewLine & oDT.Rows(0).Item("STRING2"), MsgBoxStyle.Critical, "Exception")
                    Me.Close()
                End If
            ElseIf SYS_LOCKED_MAINTENANCE = True Then
                Dim msg = $"Wegen Wartungsarbeiten ist der Zugriff auf den Workflow aktuell gesperrt!" & vbNewLine & "Vielen Dank für Ihre Geduld!"
                If USER_LANGUAGE <> "de-DE" Then
                    msg = $"Due to maintenance work, access to the workflow is currently blocked!" & vbNewLine & "Thank You for Your patience!"
                End If
                MsgBox(msg, MsgBoxStyle.Exclamation, ADDITIONAL_TITLE)
                Me.Close()
            Else
                LOGGER.Info("Username: " & USER_USERNAME, False)
                'Wenn license abgelaufen und der User nicht admin ist!
                If LICENSE_EXPIRED = True Then
                    If USER_IS_ADMIN = False Then
                        MsgBox("License expired or invalid!" & vbNewLine & "Please contact the AdminTeam!", MsgBoxStyle.Critical, "Attention:")
                        Me.Close()
                    End If
                End If
                If USER_IS_ADMIN = True Then
                    RibbonPageGroup3.Visible = True
                    'Anzahl der eingeloggten User

                    bsiUserLoggedIn.Visibility = DevExpress.XtraBars.BarItemVisibility.Always

                    'Dim oCaption As String = ClassAllgemeineFunktionen.GUI_LANGUAGE_INFO("NumberUserLoggedIn")
                    'bsiUserLoggedIn.Caption = $"{oCaption} {USERCOUNT_LOGGED_IN}"

                    Dim oCaption As String = String.Format(S.Anzahl_angemeldete_Benutzer___0_, USERCOUNT_LOGGED_IN)
                    bsiUserLoggedIn.Caption = oCaption

                    If GHOSTMODE_ACTIVE = True Then
                        bbtnitmGhostMode.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
                    Else
                        bbtnitmGhostMode.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
                    End If

                Else
                    RibbonPageGroup3.Visible = False
                    bsiUserLoggedIn.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
                    bbtnitmGhostMode.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
                End If

                If MONITORING_ACTIVE = False Then
                    RibbonPageGroup2.Visible = False
                Else
                    RibbonPageGroup2.Visible = True
                End If
                Try
                    If SEARCH1 <> String.Empty Then
                        Dim oindex = SEARCH1.IndexOf("~")

                        Dim oCaption = SEARCH1.Substring(0, oindex)

                        Dim oCommand = SEARCH1.Replace(oCaption + "~", "")
                        SearchItem1.Caption = oCaption
                        SearchItem1.Tag = oCommand
                        SearchItem1.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
                        RibbonPageGroup4.Visible = True
                    End If
                Catch ex As Exception

                End Try
                Try
                    If SEARCH2 <> String.Empty Then
                        Dim oindex = SEARCH2.IndexOf("~")

                        Dim oCaption = SEARCH2.Substring(0, oindex)

                        Dim oCommand = SEARCH2.Replace(oCaption + "~", "")
                        SearchItem2.Caption = oCaption
                        SearchItem2.Tag = oCommand
                        SearchItem2.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
                        RibbonPageGroup4.Visible = True
                    End If
                Catch ex As Exception

                End Try
                If START_CW = True Then
                    Dim oPath
                    Select Case START_CW_LOC_VARIANT
                        Case "-1"
                            oPath = Directory.GetParent(Application.StartupPath).ToString
                        Case "0"
                            oPath = Application.StartupPath.ToString
                    End Select

                    oPath &= "\ClipboardWatcher\DD_Clipboard_Watcher.exe"
                    If File.Exists(oPath) Then
                        bbtniCW.Caption = START_CW_CAPTION
                        bbtniCW.Tag = oPath
                        bbtniCW.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
                        RibbonPageGroup4.Visible = True
                    Else
                        LOGGER.Warn($"Error in CW-Button init: Could not find CW.Exe {oPath}")
                    End If


                End If

            End If
        Catch ex As Exception
            LOGGER.Error(ex)
            MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Error in User Check:")
        End Try
        bsiUser.Caption = USER_USERNAME
        GetBaseData("Load")


        Try
            If TimerRefresh.Enabled = False Then
                TimerRefresh.Start()
            End If
            Timer5Mins.Start()
        Catch ex As Exception
            LOGGER.Error(ex)
            MsgBox("Unexpected Error in LoadForm - Step 4: " & vbNewLine & ex.Message, MsgBoxStyle.Critical, "Attention:")
        End Try
        LoadNavBar()
        AddHandler NavBarControl1.LinkClicked, AddressOf navBar_LinkClicked
        If Not IsNothing(CURR_DT_VWPM_PROFILE_AH_WORKFLOW) Then
            If CURR_DT_VWPM_PROFILE_AH_WORKFLOW.Rows.Count > 0 And LIC_MODULES.Contains("MOD_AdhocWorkflow_BlindFile") Then
                RibbonPageGroupAHW.Visible = True
                Dim OCounter As Integer = 1
                For Each oRow As DataRow In CURR_DT_VWPM_PROFILE_AH_WORKFLOW.Rows
                    Select Case OCounter
                        Case 1
                            BbtnitmAHWF1.Caption = oRow.Item("TITLE")
                            BbtnitmAHWF1.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
                            BbtnitmAHWF1.Tag = oRow.Item("GUID")

                        Case 2
                            BbtnitmAHWF2.Caption = oRow.Item("TITLE")
                            BbtnitmAHWF2.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
                            BbtnitmAHWF2.Tag = oRow.Item("GUID")
                        Case 3
                            BbtnitmAHWF3.Caption = oRow.Item("TITLE")
                            BbtnitmAHWF3.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
                            BbtnitmAHWF3.Tag = oRow.Item("GUID")
                        Case 4
                    End Select
                    OCounter += 1
                Next
            Else
                LOGGER.Info($"NO ADHOC-WFs Blindfiles ({CURR_DT_VWPM_PROFILE_AH_WORKFLOW.Rows.Count}) or License AHWF_NoBlindFile not integrated...")
            End If
        Else
            LOGGER.Debug("NO ADHOC-WFs Blindfiles (Nothing)...")
        End If
        Try
            If SHOW_CHARTS = True Then

                If BASEDATA_DT_CHARTS.Rows.Count = 0 Then
                    LOGGER.Debug("No Charts: BASEDATA_DT_CHARTS.RowCount = 0")
                    bbtnitDashboardInv.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
                Else
                    LOGGER.Debug($"We got Charts: {BASEDATA_DT_CHARTS.Rows.Count}")
                    bbtnitDashboardInv.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
                End If
            Else
                LOGGER.Debug("No Charts: SHOW_CHARTS = False")
                bbtnitDashboardInv.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
            End If

        Catch ex As Exception
            LOGGER.Warn($"Could not load Charts: {ex.Message}")
        End Try
        If MONITORING_ACTIVE = False Then
            bbtniMonitor.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
        Else
            bbtniMonitor.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
        End If
        Check_Timer_Notification()
        Timer_Inactivity_Reset_Disable("FormLoad")

        'Restore_Form_Position()
        ScreenEx.RestoreFormPosition(Me, My.Settings.frmMainPosition)
        ScreenEx.RestoreFormState(Me, My.Settings.frmMainWindowState)
        ScreenEx.RestoreFormSize(Me, My.Settings.frmMainSize)

        If IDB_ACTIVE = False And ERROR_STATE = "" Then
            Try
                If Init_windream() = True Then
                    WINDREAM.Start_WMCC_andCo()
                    BarButtonItemFileLink.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
                    If Not IsNothing(WINDREAM.oSession) Then
                        If WINDREAM.oSession.aLoggedin = False Then
                            LOGGER.Warn("You could not be logged in to windream")
                            MsgBox(S.Es_ist_keine_Windream_Session_vorhanden__Bitte_überprüfen_Sie_das_Log_, MsgBoxStyle.Critical)
                        End If
                    Else
                        LOGGER.Warn("Login on windream was not possible.")
                        MsgBox(S.Es_ist_keine_Windream_Session_vorhanden__Bitte_überprüfen_Sie_das_Log_, MsgBoxStyle.Critical)
                    End If
                End If


            Catch ex As Exception
                LOGGER.Error(ex)
                MsgBox("Unexpected Error in windream-login - Step 5: " & vbNewLine & ex.Message, MsgBoxStyle.Critical, "Attention:")
            End Try
        Else
            BarButtonItemFileLink.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
            SOURCE_INIT = Init_IDB()
            If SOURCE_INIT = True Then
                Dim oSQL = $"SELECT SQL_COMMAND FROM TBDD_SQL_COMMANDS WHERE TITLE = 'PM_IDB_DOC_DATA'"

                Dim DTIDB_DOC_DATA_SQL = DatabaseFallback.GetDatatable("TBDD_SQL_COMMANDS", New GetDatatableOptions(oSQL, DatabaseType.ECM) With {
                    .FilterExpression = "TITLE = 'PM_IDB_DOC_DATA'"
                })

                IDB_DOC_DATA_SQL = DTIDB_DOC_DATA_SQL.Rows(0).Item("SQL_COMMAND")
                LOGGER.Debug($"Got the IDB_DOC_DATA_SQL..{IDB_DOC_DATA_SQL}")
            End If

            bsiGeneralInfo.Caption = S.IDB_Aktiv

        End If
        If EDMIAppServerActive = True Then
            BarStaticItemAppServer.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
        Else
            BarStaticItemAppServer.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
        End If
        If BASIC_CONF_VISIBLE = False Then
            RibbonPageGroupBasicConf.Visible = False
            barbtnitmsaveLogfiles.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
        Else
            RibbonPageGroupBasicConf.Visible = True
        End If
        If EXCEL_OVERVIEW = True Then
            BarButtonItemExportExcel.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
        Else
            BarButtonItemExportExcel.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
        End If
        If BASEDATA_DT_LANGUAGE.Rows.Count > 1 Then
            bbtnitmLanguage_Change.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
        Else
            bbtnitmLanguage_Change.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
        End If

        LOGGER.Debug("MainForm initialized!")

        FormOpenClose = False
    End Sub

    Public Class FontSetting
        Public Property Title As String
        Public Property Value As Integer

        Public Overrides Function ToString() As String
            Return Title
        End Function
    End Class

    Sub Check_Timer_Notification()
        Try
            If CONFIG.Config.ReminderTimer <> 0 Then
                TimerReminder.Stop()
                TimerReminder.Interval = CONFIG.Config.ReminderTimer * 60000
                TimerReminder.Start()
            Else
                TimerReminder.Enabled = False
                TimerReminder.Stop()
            End If
        Catch ex As Exception
            LOGGER.Error(ex)

        End Try

    End Sub
    Public Sub Timer_Inactivity_Reset_Disable(pTrigger As String)
        Try
            If Timer5Mins_running = True Or TimerRefresh_running = True Or FormShown = False Then
                Exit Sub
            End If
            If INACTIVITY_DURATION <> 0 Then
                TimerInactivity.Enabled = False
                TimerInactivity.Stop()
                TimerInactivity.Interval = INACTIVITY_DURATION * 60000
                TimerInactivity.Enabled = True
                TimerInactivity.Start()
                bsiInactivityCheck.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
                Dim StartTime As DateTime = #12:00:00 AM#

                Dim oStarttime As DateTime = Now
                oStarttime = oStarttime.AddMinutes(INACTIVITY_DURATION)
                If LOGCONFIG.Debug = False Then
                    pTrigger = ""
                Else
                    pTrigger = $"({pTrigger})"
                End If

                bsiInactivityCheck.Caption = String.Format(S.Nächste_Aktivitätsüberprüfung___0___1_, oStarttime.ToShortTimeString, pTrigger)
            Else
                TimerInactivity.Enabled = False
                TimerInactivity.Stop()
                bsiInactivityCheck.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
            End If
        Catch ex As Exception
            LOGGER.Error(ex)

        End Try

    End Sub
    Sub Restore_Form_Position()
        Try
            'Sind Werte hinterlegt?
            If My.Settings.frmMainPosition.IsEmpty = False Then

                If My.Settings.frmMainPosition.X > 0 And My.Settings.frmMainPosition.Y > 0 Then
                    If Not My.Settings.frmMainSize.IsEmpty Then
                        If My.Settings.frmMainWindowState = "Normal" Then
                            Dim oisonscreen = IsOnScreen(My.Settings.frmMainPosition, My.Settings.frmMainSize)
                            If oisonscreen = False Then
                                Me.StartPosition = FormStartPosition.CenterScreen
                                Exit Sub
                            Else
                                ' Gespeicherte Werte verwenden
                                Me.Location = Screen.AllScreens(UBound(Screen.AllScreens)).Bounds.Location + My.Settings.frmMainPosition
                            End If
                        Else
                            Me.WindowState = FormWindowState.Maximized
                        End If
                    End If
                Else
                    LOGGER.Info("FormPosition is out of range!..Standard will be loaded!")
                    If My.Settings.frmMainWindowState = "Normal" Then
                        Me.StartPosition = FormStartPosition.CenterScreen
                    Else
                        Me.WindowState = FormWindowState.Maximized
                    End If
                End If

            End If
            'Sind Werte hinterlegt?
            'If Not My.Settings.frmMainSize.IsEmpty Then
            '    If My.Settings.frmMainWindowState = "Normal" Then
            '        Dim oisonscreen = IsOnScreen(My.Settings.frmMainPosition, My.Settings.frmMainSize)

            '        If oisonscreen = False Then
            '            Me.StartPosition = FormStartPosition.CenterScreen
            '            Exit Sub
            '        End If
            '        ' Gespeicherte Werte verwenden
            '        Try
            '            Me.Size = My.Settings.frmMainSize
            '        Catch ex As Exception

            '        End Try
            '    Else
            '        Me.WindowState = FormWindowState.Maximized
            '    End If


            'End If
        Catch ex As Exception
            LOGGER.Error(ex)
            LOGGER.Info("Error in Load FormLayout: " & ex.Message)
        End Try
    End Sub
    Function IsOnScreen(ByVal RecLocation As System.Drawing.Point, ByVal RecSize As System.Drawing.Size, Optional MinPercentOnScreen As Double = 0.2)
        Try
            Dim PixelsVisible As Double = 0
            Dim Rec As System.Drawing.Rectangle = New System.Drawing.Rectangle(RecLocation, RecSize)
            For Each Scrn As Screen In Screen.AllScreens
                Dim r As System.Drawing.Rectangle = System.Drawing.Rectangle.Intersect(Rec, Scrn.WorkingArea)
                'intersect rectangle with screen
                If (r.Width <> 0 And r.Height <> 0) Then
                    PixelsVisible += (r.Width * r.Height)
                    'tally visible pixels
                End If

            Next
            Return PixelsVisible >= (Rec.Width * Rec.Height) * MinPercentOnScreen
        Catch ex As Exception
            Return False
        End Try

    End Function

    Private Function GetLayoutName_GridMain()
        Dim Filename As String = String.Format("DevExpressGridViewOverview_UserLayout_{0}_{1}.xml", GRID_LOAD_TYPE, USER_LANGUAGE)
        LOGGER.Debug($"LayoutFilename is: {Filename}")
        Return System.IO.Path.Combine(USER_CONFIG_DIRECTORY, Filename)
    End Function

    Private Sub SaveGridLayout()
        Timer_Inactivity_Reset_Disable("SaveGridLayout")
        If NO_WORKFLOWITEMS = True Then
            Exit Sub
        End If

        Try
            Dim oXmlPath As String = GetLayoutName_GridMain()
            GridViewWorkflows.SaveLayoutToXml(oXmlPath, OptionsLayoutBase.FullLayout)
            LOGGER.Debug("Layout saved successfully!")
        Catch ex As Exception
            LOGGER.Error(ex)
            LOGGER.Info("Error while saving GridLayout MainGrid: " & ex.Message)
        End Try
    End Sub

    Private Sub RestoreLayout()
        If NO_WORKFLOWITEMS = True Then
            Exit Sub
        End If

        Try
            Dim oXmlPath As String = GetLayoutName_GridMain()
            If System.IO.File.Exists(oXmlPath) Then
                GridViewWorkflows.RestoreLayoutFromXml(oXmlPath, OptionsLayoutBase.FullLayout)
            Else
                LOGGER.Info("oXmlPath not existing - Saving Layout")
                COLUMNS_INVISIBLE()
                SaveGridLayout()
            End If

        Catch ex As Exception
            LOGGER.Info("Error while restoring layout MainGrid: " & ex.Message)
        End Try
    End Sub
    Private Sub COLUMNS_INVISIBLE()
        Try
            GridViewWorkflows.Columns.Item("PROFILE_ID").Visible = False
            GridViewWorkflows.Columns.Item("GUID").Visible = False
            Try
                GridViewWorkflows.Columns.Item(FullFilepatColName).Visible = False
            Catch ex As Exception

            End Try
            Try
                'GridViewWorkflows.Columns.Item("DocID").Visible = False
                GridViewWorkflows.Columns.Item("TL_STATE").Visible = False
            Catch ex As Exception

            End Try
            Try
                If Not IsNothing(GridViewWorkflows.Columns("CONV_YN")) Then
                    GridViewWorkflows.Columns.Item("CONV_YN").Visible = False
                End If
            Catch ex As Exception

            End Try
        Catch ex As Exception

        End Try
    End Sub
    Private Sub ResetLayout()
        Try
            Timer_Inactivity_Reset_Disable("ResetLayout")
            Dim xml As String = GetLayoutName_GridMain()
            IO.File.Delete(xml)
            Try
                GridViewWorkflows.Columns.Clear()
            Catch ex As Exception
                If IsNothing(GridViewWorkflows) Then
                    LOGGER.Warn("Somehow GridViewWorkflows is nothing....")
                Else
                    If IsNothing(GridViewWorkflows.Columns) Then
                        LOGGER.Warn("Somehow GridViewWorkflows.Columns is nothing....")

                    End If
                End If
                Exit Sub
            End Try

            GridViewWorkflows.PopulateColumns()
            If GridViewWorkflows.Columns.Count > 0 Then
                Try
                    If TL_ICON = True Then
                        GridViewWorkflows.Columns.Item("ICON").MaxWidth = 24
                        GridViewWorkflows.Columns.Item("ICON").MinWidth = 24
                        GridViewWorkflows.Columns.Item("ICON").AppearanceCell.BackColor = Color.White
                        GridViewWorkflows.Columns.Item("ICON").Fixed = FixedStyle.Left
                    End If
                Catch ex As Exception

                End Try


                'If IDB_ACTIVE = True Then
                '    Try
                '        If GridViewWorkflows.Columns.Item("CONV_YN") IsNot Nothing Then
                '            GridViewWorkflows.Columns.Item("CONV_YN").Visible = False
                '        End If
                '    Catch ex As Exception
                '        LOGGER.Info("ResetLayout - Check wether Column CONV_YN is part of select/view..now checking CONVERSATION")
                '    End Try
                '    Try
                '        GridViewWorkflows.Columns.Item("CONVERSATION").MaxWidth = 24
                '        GridViewWorkflows.Columns.Item("CONVERSATION").MinWidth = 24
                '        GridViewWorkflows.Columns.Item("CONVERSATION").Fixed = FixedStyle.Left
                '    Catch ex As Exception
                '        LOGGER.Info("ResetLayout - Column CONVERSATION obviously is not part of GridViewWorkflows")
                '    End Try
                'End If

                Dim oReducedColName As String
                Try
                    oReducedColName = LAST_EDITED_COLUMN.Replace("[", "")
                    oReducedColName = oReducedColName.Replace("]", "")
                    GridViewWorkflows.Columns(oReducedColName).DisplayFormat.FormatType = FormatType.DateTime
                    GridViewWorkflows.Columns(oReducedColName).DisplayFormat.FormatString = "dd.MM.yyyy HH:MM:ss"
                Catch ex As Exception
                    Try
                        GridViewWorkflows.Columns("Zuletzt bearbeitet").DisplayFormat.FormatType = FormatType.DateTime
                        GridViewWorkflows.Columns("Zuletzt bearbeitet").DisplayFormat.FormatString = "dd.MM.yyyy HH:MM:ss"

                    Catch ex1 As Exception
                        LOGGER.Warn($"(ResetLayout)Column [{oReducedColName}] or [Zuletzt bearbeitet] not part of OverviewSQL")
                    End Try

                End Try

                Try
                    GridViewWorkflows.Columns.Item("GROUP_TEXT").Visible = False
                    GridViewWorkflows.Columns.Item("GROUP_COLOR").Visible = False

                Catch ex As Exception

                End Try
                Try
                    If GridViewWorkflows.Columns.ColumnByFieldName("ROW_COLOR") IsNot Nothing Then
                        GridViewWorkflows.Columns.Item("ROW_COLOR").Visible = False
                    End If
                Catch ex As Exception

                End Try
                ' GridViewWorkflows.OptionsView.ShowIndicator = False
                COLUMNS_INVISIBLE()

            End If

        Catch ex As Exception
            LOGGER.Error(ex)
            LOGGER.Info("Error while resetting layout: " & ex.Message)
        End Try
    End Sub

    Sub LoadNavBar()
        Dim profileGroupOpen As Boolean = False
        If Not IsNothing(CurrNavBarGroup) Then
            Try
                profileGroupOpen = CurrNavBarGroup.Expanded
                Try
                    CurrNavBarGroup.ItemLinks.Clear()
                Catch ex As Exception
                    LOGGER.Error(ex)
                    LOGGER.Info("CurrGroupClear - Error: " & ex.Message)

                End Try

            Catch ex As Exception

            End Try
        End If
        Try



            If Load_Profiles_for_User() = False Then
                Throw New Exception("Could not load Profiles. Datatable is empty")
                Exit Sub
            End If
            If NO_DETAIL_PROFILES = False Then
                NavBarControl1.Visible = True
                Dim oCountItems As Integer = 0
                For Each oProfileRow As DataRow In CURR_DT_VWPM_PROFILE_ACTIVE.Rows
                    Dim oFileCount = CInt(oProfileRow.Item("FILE_COUNT"))
                    Dim ODisplayMode = oProfileRow.Item("DISPLAY_MODE")
                    If oFileCount > 0 And (ODisplayMode = "Overview and Detail" Or ODisplayMode = "Detail") Then

                        oCountItems += 1
                        Dim item1 As NavBarItem = NavBarControl1.Items.Add()
                        item1.Caption = oProfileRow.Item("TITLE")
                        item1.Hint = oProfileRow.Item("TITLE")
                        item1.Appearance.TextOptions.WordWrap = WordWrap.Wrap
                        item1.Tag = "itmProfile#" & oProfileRow.Item("GUID").ToString

                        Dim _image As Image = Nothing
                        _image = DevExpress.Images.ImageResourceCache.Default.GetImage("images/business%20objects/bofileattachment_16x16.png")
                        item1.LargeImage = _image
                        item1.SmallImage = _image

                        NavBarControl1.Groups(1).ItemLinks.Add(item1)


                    End If
                Next
                If oCountItems > 0 Then
                    If NavBarControl1.Groups(1).Visible = False Then
                        NavBarControl1.Groups(1).Visible = True
                    End If
                Else
                    If NavBarControl1.Groups(1).Visible = True Then
                        NavBarControl1.Groups(1).Visible = False
                    End If
                End If

                If Not IsNothing(CurrNavBarGroup) Then
                    CurrNavBarGroup.Expanded = profileGroupOpen
                Else
                    NavBarControl1.Groups(1).Expanded = True
                End If
            Else
                LOGGER.Debug("NavBarControl - No Detail Profiles")
                NavBarControl1.Visible = False
            End If

        Catch ex As Exception
            LOGGER.Error(ex)
            LOGGER.Info("Load_Profile_items - Error: " & ex.Message)
            'MsgBox("Unexpected Error in Load_Profile_items - Error: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub
    Private Async Sub navBar_LinkClicked(ByVal sender As Object, ByVal e As NavBarLinkEventArgs)
        If Not Application.OpenForms().OfType(Of frmValidator).Any Then
        Else
            'FormHelper.ShowInfoMessage(omsgOpenWorkflow, omsgTitleWarning)
            FormHelper.ShowInfoMessage(S.Bitte_schließen_Sie_den_offenen_Workflow_, omsgTitleWarning)
            Exit Sub
        End If

        FRONTEND_ACTION = NAVBAR_CLICKED

        Dim _tag = e.Link.Item.Tag
        Timer_Inactivity_Reset_Disable("navBar_LinkClicked")

        If Not IsNothing(_tag) Then
            If _tag.ToString.Contains("itmProfile#") Then
                _tag = _tag.ToString.Replace("itmProfile#", "")
                If IsNumeric(_tag) Then
                    If CURRENT_CLICKED_PROFILE_ID <> _tag Then
                        OverviewOrDEtail = "DETAIL"
                        If Not Application.OpenForms().OfType(Of frmValidator).Any Then
                            CURRENT_CLICKED_PROFILE_ID = _tag
                            CURRENT_CLICKED_PROFILE_TITLE = e.Link.Item.Caption
                        End If


                        GRID_LOAD_TYPE = "PROFILE#" & _tag.ToString
                        TimerRefresh.Stop()
                        GridViewWorkflows.ShowLoadingPanel()
                        DetailLinkActive = True
                        Await Load_single_Profile(True)
                        GridViewWorkflows.HideLoadingPanel()
                        TimerRefresh.Start()
                    Else
                        CURRENT_CLICKED_PROFILE_TITLE = Nothing
                        CURRENT_CLICKED_PROFILE_ID = Nothing
                    End If
                End If
            ElseIf _tag = "OVERVIEW" Then
                OverviewOrDEtail = "OVERVIEW"
                GRID_LOAD_TYPE = "OVERVIEW"
                GridViewWorkflows.ShowLoadingPanel()
                TimerRefresh.Stop()
                Dim oForce As Boolean = False
                If DetailLinkActive = True Then
                    oForce = True
                    DetailLinkActive = False
                    OVERVIEW_ADDED_WHEN = ""
                End If
                Await Load_Grid_Overview(False, True, True)
                GridViewWorkflows.HideLoadingPanel()
                TimerRefresh.Start()
                RefreshHelper.LoadViewInfo()
                If GridViewWorkflows.GroupCount = 0 And Not IsNothing(GridViewWorkflows.Columns("GROUP_TEXT")) Then
                    LOGGER.Info("NO GROUPS AFTER CLICK OVERVIEW...CREATING GROUPS NEW...")
                    Await Load_Grid_Overview(False, True, True)
                    GridViewWorkflows.HideLoadingPanel()
                    TimerRefresh.Start()
                    RefreshHelper.LoadViewInfo()
                End If
            End If
        End If

        FRONTEND_ACTION = FA_NONE
    End Sub
    Function Load_Profiles_for_User() As Boolean
        Try

            If IsNothing(CURR_DT_VWPM_PROFILE_ACTIVE) Then
                Return False
            End If

            Return True
        Catch ex As Exception
            LOGGER.Error(ex)
            LOGGER.Info("Load_Profiles_for_User - Error: " & ex.Message)
            Return False
        End Try
    End Function
    Sub GridControlWorkflows_Visible()
        Try
            If GridControlWorkflows.Visible = False Then
                GridControlWorkflows.Visible = True
            End If
        Catch ex As Exception
            LOGGER.Error(ex)
        End Try
    End Sub

    Async Function Load_single_Profile(Optional ForceReload As Boolean = False) As Tasks.Task
        Try
            FRONTEND_ACTION = "Load_single_Profile"
            Load_Profiles_for_User()
            GridControlWorkflows_Visible()
            Dim expression As String
            expression = "GUID = " & CURRENT_CLICKED_PROFILE_ID
            Dim TEMP_TABLE = CURR_DT_VWPM_PROFILE_ACTIVE
            Dim foundRows() As DataRow
            foundRows = TEMP_TABLE.Select(expression)
            Dim result = 0
            For i = 0 To foundRows.GetUpperBound(0)
                result += 1
            Next

            If result = 1 Then


                Dim oSQL = foundRows(0)("SQL_VIEW")

                oSQL = clsPatterns.ReplaceInternalValues(oSQL)
                oSQL = clsPatterns.ReplaceUserValues(oSQL)

                oSQL = oSQL.Replace("@USER_ID", USER_ID)
                oSQL = oSQL.Replace("@USERNAME", USER_USERNAME)
                oSQL = oSQL.Replace("@MACHINE_NAME", System.Environment.MachineName)
                oSQL = oSQL.Replace("@DATE", Now.ToShortDateString)
                oSQL = oSQL.Replace("@PROFILE_ID", CURRENT_CLICKED_PROFILE_ID)

                DT_CURR_WF_ITEMS = Await DatabaseFallback.GetDatatableECMAsync(oSQL)
                If ForceReload = True Then
                    LOGGER.Info("ForceReload is true!")
                End If
                If Not IsNothing(DT_CURR_WF_ITEMS) Then
                    Dim oADDED = GET_LAST_ADDED(DT_CURR_WF_ITEMS)
                    Dim oChanged = GET_LAST_CHANGED(DT_CURR_WF_ITEMS)
                    Dim oCOUNT = DT_CURR_WF_ITEMS.Rows.Count
                    If oADDED = OVERVIEW_ADDED_WHEN And oChanged = OVERVIEW_CHANGED_WHEN And OVERVIEW_COUNT = oCOUNT Then
                        If ForceReload = False Then
                            LOGGER.Info("No changes on OverviewHash - so exit Refresh")
                            Exit Function
                        End If

                    Else
                        OVERVIEW_ADDED_WHEN = oADDED
                        OVERVIEW_CHANGED_WHEN = oChanged
                        OVERVIEW_COUNT = oCOUNT
                    End If

                    If DT_CURR_WF_ITEMS.Rows.Count = 0 Then
                        NO_WORKFLOWITEMS = True
                        lblCaptionMainGrid.Text = String.Format(S.Aktuell_keine_Workflowdaten_vorhanden___0_, CURRENT_CLICKED_PROFILE_TITLE)
                        GridControlWorkflows.Visible = False
                        bindsourcegrid.DataSource = Nothing
                        GridControlWorkflows.DataSource = Nothing
                    Else
                        NO_WORKFLOWITEMS = False

                        lblCaptionMainGrid.Text = CURRENT_CLICKED_PROFILE_TITLE
                    End If
                    Create_Basic_View()

                    RestoreLayout()

                End If

            End If

        Catch ex As Exception
            LOGGER.Error(ex)
            LOGGER.Info("Load_single_Profile - Error: " & ex.Message)
        End Try
        FRONTEND_ACTION = FA_NONE
    End Function
    Sub Create_Basic_View()
        Try
            FRONTEND_ACTION = "Create_Basic_View"
            GridControlWorkflows.DataSource = Nothing
            Try
                GridViewWorkflows.Columns.Clear()
            Catch ex As Exception
                LOGGER.Error(ex)
                LOGGER.Warn("Could not clear GridViewWorkflows.Columns")
            End Try
            If TL_ICON = True Then
                ' Spalte für Status Icon erstellen
                Dim columnStateIcon As New DataColumn()
                columnStateIcon.DataType = GetType(Image)
                columnStateIcon.ColumnName = "ICON"
                columnStateIcon.Caption = ""
                DT_CURR_WF_ITEMS.Columns.Add(columnStateIcon)
            End If


            RedDocuments = 0
            YellowDocuments = 0
            GreenDocuments = 0
            If TL_ICON = True Then
                For Each row As DataRow In DT_CURR_WF_ITEMS.Rows
                    Dim State As Integer = row.Item("TL_STATE")
                    Select Case State
                        Case 1
                            RedDocuments += 1
                            row.Item("ICON") = My.Resources.bullet_red
                        Case 2
                            YellowDocuments += 1
                            row.Item("ICON") = My.Resources.bullet_orange
                        Case 3
                            GreenDocuments += 1
                            row.Item("ICON") = My.Resources.bullet_green
                    End Select
                Next
            End If

            'If IDB_ACTIVE = True Then
            '    ' Spalte für Conversation erstellen
            '    Dim columnConvIcon As New DataColumn()
            '    columnConvIcon.DataType = GetType(Image)
            '    columnConvIcon.ColumnName = "CONVERSATION"
            '    columnConvIcon.Caption = ""
            '    DT_CURR_WF_ITEMS.Columns.Add(columnConvIcon)
            'End If
            'For Each oRow As DataRow In DT_CURR_WF_ITEMS.Rows
            '    Try
            '        Dim oCONVYN As Boolean
            '        Try
            '            oCONVYN = oRow.Item("CONV_YN")
            '        Catch ex As Exception
            '            LOGGER.Warn($"Please check Your select/view Config - Column CONV_YN is missing [{ex.Message}]")
            '            Exit For
            '        End Try

            '        Select Case oCONVYN
            '            Case True
            '                oRow.Item("CONVERSATION") = My.Resources.conversation
            '        End Select
            '    Catch ex As Exception
            '        LOGGER.Warn("Create_Basic_View1 - Column CONVERSATION obviously is not part of GridViewWorkflows")
            '    End Try

            'Next
            bindsourcegrid.DataSource = DT_CURR_WF_ITEMS
            GridControlWorkflows.DataSource = bindsourcegrid
            Dim objectCount_Descr = GridViewWorkflows.RowCount.ToString

            'Dim ocapt = ClassAllgemeineFunktionen.GUI_LANGUAGE_INFO("DescItems")

            Dim ocapt = String.Format(S._0__Vorgänge, objectCount_Descr)
            objectCount_Descr = $"{objectCount_Descr} {ocapt}"

            'tslblObjectCount.Text = objectCount_Descr

            'GridControlDocRow.ForceInitialize()

            RestoreLayout()

            COLUMNS_INVISIBLE()

            Try
                If TL_ICON = True Then
                    GridViewWorkflows.Columns.Item("ICON").MaxWidth = 24
                    GridViewWorkflows.Columns.Item("ICON").MinWidth = 24
                    GridViewWorkflows.Columns.Item("ICON").AppearanceCell.BackColor = Color.White
                    GridViewWorkflows.Columns.Item("ICON").Fixed = FixedStyle.Left
                End If
            Catch ex As Exception

            End Try



            'If IDB_ACTIVE = True Then
            '    Try
            '        GridViewWorkflows.Columns.Item("CONVERSATION").MaxWidth = 24
            '        GridViewWorkflows.Columns.Item("CONVERSATION").MinWidth = 24
            '        GridViewWorkflows.Columns.Item("CONVERSATION").Fixed = FixedStyle.Left
            '    Catch ex As Exception
            '        LOGGER.Info("Create_Basic_View2 - Column CONVERSATION obviously is not part of GridViewWorkflows - Trying to Rest Layout")
            '        ResetLayout()
            '        FRONTEND_ACTION = FA_NONE
            '        Exit Sub
            '    End Try
            'End If


            ' GridViewWorkflows.OptionsView.ShowIndicator = False
            Try
                Dim oReducedColName = LAST_EDITED_COLUMN.Replace("[", "")
                oReducedColName = oReducedColName.Replace("]", "")
                GridViewWorkflows.Columns(oReducedColName).DisplayFormat.FormatType = FormatType.DateTime
                GridViewWorkflows.Columns(oReducedColName).DisplayFormat.FormatString = "dd.MM.yyyy HH:MM:ss"
            Catch ex As Exception
                Try
                    GridViewWorkflows.Columns("Zuletzt bearbeitet").DisplayFormat.FormatType = FormatType.DateTime
                    GridViewWorkflows.Columns("Zuletzt bearbeitet").DisplayFormat.FormatString = "dd.MM.yyyy HH:MM:ss"
                Catch ex1 As Exception
                    LOGGER.Warn("(CreateBasicView)Column [Last edited] or [Zuletzt bearbeitet] not part of OverviewSQL")
                End Try

            End Try

            LOGGER.Debug("All columns in CreateBasicView created")
            Try
                GridViewWorkflows.Columns.Item("GROUP_TEXT").Visible = False
                GridViewWorkflows.Columns.Item("GROUP_COLOR").Visible = False
            Catch ex As Exception
                If OverviewOrDEtail = "OVERVIEW" Then
                    LOGGER.Warn("ATTENTION: GROUP COLUMNS NOT PART OF GRID")
                End If

            End Try
            LOGGER.Debug("All columns in CreateBasicView created")
        Catch ex As Exception
            LOGGER.Error(ex)
        End Try
        FRONTEND_ACTION = FA_NONE
    End Sub
    Private Function GridLayoutChanged() As Boolean
        Try
            For Each oViewColumn As DataColumn In DT_CURR_WF_ITEMS.Columns
                If oViewColumn.Caption = "" Then
                    Continue For
                End If
                Dim oViewColumn_exists As Boolean = False
                For Each oActGridColumn As GridColumn In GridViewWorkflows.Columns
                    Dim oGridDXFieldName = oActGridColumn.FieldName
                    Dim GridDXColumnEditName = oActGridColumn.ColumnEditName
                    Dim GridDXFieldName = oActGridColumn.FieldName
                    If oViewColumn.Caption = oGridDXFieldName Then
                        If oActGridColumn.Visible = False Then
                            If oViewColumn.Caption <> "GUID" And oViewColumn.Caption <> "TL_STATE" And oViewColumn.Caption <> "PROFILE_ID" And oViewColumn.Caption <> "DocID" And
                               oViewColumn.Caption <> "GROUP_COLOR" And oViewColumn.Caption <> "GROUP_TEXT" Then 'And oViewColumn.Caption <> "CONV_YN"
                                Console.WriteLine($"ViewColumn  [{oViewColumn.Caption}] is invisible")
                            Else
                                oViewColumn_exists = True
                            End If
                        Else
                            oViewColumn_exists = True
                        End If
                    End If
                Next
                If oViewColumn_exists = False Then
                    If oViewColumn.Caption = FullFilepatColName And IDB_ACTIVE = False Then
                        LOGGER.Info($"Following ViewColumn no longer exists in the view: [{oViewColumn.Caption}]")
                        Return True
                    End If
                End If
            Next
            For Each oActGridColumn As GridColumn In GridViewWorkflows.Columns
                If oActGridColumn.Caption = "" Then
                    Continue For
                End If
                Dim oGridColumn_exists As Boolean = False
                Dim oGridDXFieldName = oActGridColumn.FieldName
                For Each oViewColumn As DataColumn In DT_CURR_WF_ITEMS.Columns
                    If oViewColumn.Caption = oGridDXFieldName Then
                        oGridColumn_exists = True
                    End If
                Next
                If oGridColumn_exists = False Then
                    LOGGER.Info($"Following GridColumn no longer exists in the View: [{oGridDXFieldName}]")
                    Return True
                End If
            Next
        Catch ex As Exception
            LOGGER.Error(ex)
            LOGGER.Info("Unexpected Error in GridLayoutChanged: " & ex.Message)
            Return False
        End Try
    End Function
    Private Function Column_inGridViewLayout(Col2bChecked As String) As Boolean
        Try
            Dim oGridView As New GridView
            Dim oXml As String = GetLayoutName_GridMain()
            oGridView.RestoreLayoutFromXml(oXml, OptionsLayoutBase.FullLayout)
            Dim oViewColumn_exists As Boolean = False
            For Each oActGridColumn As GridColumn In oGridView.Columns
                Dim oGridDXFieldName = oActGridColumn.FieldName
                Dim GridDXColumnEditName = oActGridColumn.ColumnEditName
                Dim GridDXFieldName = oActGridColumn.FieldName
                If Col2bChecked = oGridDXFieldName Then
                    oViewColumn_exists = True
                    Exit For
                End If
            Next
            If oViewColumn_exists = False Then
                LOGGER.Info($"Following ViewColumn is not existing in the view: [{Col2bChecked}]")
                Return Not False
            End If

        Catch ex As Exception
            LOGGER.Info("Unexpected Error in Column_inGridViewLayout: " & ex.Message)
            Return Not False
        End Try
    End Function

    Private Sub NotifyIcon1_MouseDoubleClick(sender As System.Object, e As MouseEventArgs) Handles NotifyIcon1.MouseDoubleClick
        BringMonitor2Front()
    End Sub
    Sub BringMonitor2Front()
        Me.BringToFront()
        Visible = True
    End Sub
    Private Async Sub TimerRefresh_Tick(sender As System.Object, e As EventArgs) Handles TimerRefresh.Tick
        Try
            If TimerRefresh.Enabled = False Then
                Exit Sub
            End If
            If bwBasicData.IsBusy Then
                LOGGER.Info("backGroundWorker BasicData in Action - no Client-Sync")
                bsiMessage.Caption = "bwBasicData is busy - no Refreshing"
                bsiMessage.ItemAppearance.Normal.BackColor = Color.Yellow
                bsiMessage.ItemAppearance.Normal.ForeColor = Color.Black
                Exit Sub
            End If

            TimerRefresh_running = True

            ' Cancel Refresh if a Validator Form or an Admin Form is opened
            If Application.OpenForms().OfType(Of frmMassValidator).Any() Or
                Application.OpenForms().OfType(Of frmValidator).Any() Or
                Application.OpenForms().OfType(Of frmAdministration).Any() Or
                Application.OpenForms().OfType(Of frmAdmin2).Any() Then
                Exit Sub
            End If

            'bsilastsync.Caption = $"{ClassAllgemeineFunktionen.GUI_LANGUAGE_INFO("CaptLastSync")}: " & Now.ToLongTimeString
            bsilastsync.Caption = String.Format(S.Letzte_Synchronisation___0_, Now.ToLongTimeString)

            If GridControlWorkflows.Visible = True And FormOpenClose = False Then
                RefreshHelper.SaveViewInfo()
            End If

            If bwSync.IsBusy Then
                TimerRefresh_running = False
                Exit Sub
            End If

            Try
                'bwSync.ReportProgress(10)
                LoadNavBar()
                'bwSync.ReportProgress(60)
                Dim oStopWatch As New RefreshHelper.SW("Decide_Load")
                Await Decide_Load(False)
                oStopWatch.Done()
                'bwSync.ReportProgress(95)

                If GridControlWorkflows.Visible = True And FormOpenClose = False Then RefreshHelper.LoadViewInfo()

                Handling_DEBUG_USER()
            Catch ex As Exception
                LOGGER.Error(ex)
            End Try
        Catch ex As Exception
            LOGGER.Error(ex)
        End Try
        TimerRefresh_running = False
        'BarEditItem1.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
        '' call this method to start your asynchronous Task.
        'bwSync.RunWorkerAsync()


    End Sub

    Private Sub NotifyIcon1_Click(sender As System.Object, e As EventArgs) Handles NotifyIcon1.Click
        BringMonitor2Front()
    End Sub
    Private Async Function Decide_Load(pIsFormLoad As Boolean, Optional ForceReload As Boolean = False) As Tasks.Task
        Try
            If pIsFormLoad = True Then
                FormShown = False
            End If
            GridIsLoaded = False

            If USER_EXISTS = False Then
                Exit Function
            End If
            If TimerRefresh.Enabled = True Then
                TimerRefresh.Enabled = False
            End If

            GridViewWorkflows.ShowLoadingPanel()
            TimerRefresh.Stop()
            FRONTEND_ACTION = "DECIDE_LOAD"
            If GRID_LOAD_TYPE = "OVERVIEW" Then

                Await Load_Grid_Overview(pIsFormLoad, ForceReload, False)
            ElseIf GRID_LOAD_TYPE.StartsWith("PROFILE#") Then
                Await Load_single_Profile(ForceReload)
            End If
            FRONTEND_ACTION = FA_NONE
            GridViewWorkflows.HideLoadingPanel()
            TimerRefresh.Start()

            If SHOW_MASS_VALIDATOR = False Then
                GridViewWorkflows.OptionsSelection.MultiSelect = False
                GridViewWorkflows.OptionsSelection.MultiSelectMode = GridMultiSelectMode.RowSelect
                BarButtonItemMassValidation.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
            Else
                BarButtonItemMassValidation.Visibility = DevExpress.XtraBars.BarItemVisibility.Always

                GridViewWorkflows.OptionsSelection.MultiSelect = True
                GridViewWorkflows.OptionsSelection.MultiSelectMode = GridMultiSelectMode.CheckBoxRowSelect
            End If
            If GridViewWorkflows.OptionsView.ShowAutoFilterRow = True Then
                BarCheckItemAutofilter.Checked = True
            End If
            If GridViewWorkflows.OptionsFind.AlwaysVisible Then
                BarCheckItemShowSearch.Checked = True
            End If
            COLUMNS_INVISIBLE()
            GridIsLoaded = True
        Catch ex As Exception
            GridIsLoaded = True
            LOGGER.Error(ex)
            LOGGER.Info("Unexpected error in Decide_load: " & ex.Message)
        End Try
        If TimerRefresh.Enabled = False Then
            TimerRefresh.Enabled = True
        End If
        If pIsFormLoad = True Then
            FormShown = True
        End If
    End Function

    Private Sub ToolStripButton2_Click_2(sender As Object, e As EventArgs)
        frmAdminPasswort.ShowDialog()
    End Sub

    Public Sub New()
        Dim splash As New frmSplash()
        Try
            splash.ShowDialog()
        Catch ex As Exception
            LOGGER.Error(ex)
            LOGGER.Info($"Error in Splash: {ex.Message}")
        End Try
        Try
            If USER_LANGUAGE <> "" Then
                Dim cultureInfo As New System.Globalization.CultureInfo(USER_LANGUAGE)
                cultureInfo.DateTimeFormat.ShortDatePattern = USER_DATE_FORMAT
                Thread.CurrentThread.CurrentCulture = cultureInfo
                Thread.CurrentThread.CurrentUICulture = cultureInfo
                CultureInfo.DefaultThreadCurrentCulture = cultureInfo
                CultureInfo.DefaultThreadCurrentUICulture = cultureInfo
            End If
        Catch ex As Exception
            LOGGER.Error(ex)
        End Try
        Try
            InitializeComponent()
            FormHelper = New FormHelper(LOGCONFIG, Me)
            ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.
        Catch ex As Exception
            LOGGER.Error(ex)
            LOGGER.Info($"Error in InitializeComponent: {ex.Message}")
        End Try
    End Sub

    Private Sub TimerReminder_Tick(sender As Object, e As EventArgs) Handles TimerReminder.Tick
        Try

            If Application.OpenForms().OfType(Of frmValidator).Any Then
                Exit Sub
            End If

            If DT_CURR_WF_ITEMS.Rows.Count > 0 And POPUP_REMINDER_ACTIVE = True Then
                Dim oMessage As String = ClassAllgemeineFunktionen.GUI_LANGUAGE_INFO("App.ReminderPipeline")
                NotifyIcon1.ShowBalloonTip(30000, $"Reminder {ADDITIONAL_TITLE}", oMessage, ToolTipIcon.Info)
            End If
        Catch ex As Exception
            LOGGER.Warn($"Unexpected error in TimerReminderTick:  {ex.Message}")
        End Try

    End Sub
    Public Function GetEnvironment() As Environment
        Return New Environment With {
            .Database = DatabaseECM,
            .DatabaseIDB = DatabaseIDB,
            .Service = EDMIService,
            .User = User
        }
    End Function

    Sub Load_Profil_from_Grid(pProfilID As Integer)
        Try
            CURRENT_ProfilGUID = pProfilID
            WM_AHWF_docPath = String.Empty



            ' Dim th As System.Threading.Thread
            If Not Application.OpenForms().OfType(Of frmValidator).Any Then
                If TimerRefresh.Enabled Then
                    TimerRefresh.Enabled = False
                End If

                If CHANGES_FORM_DESIGN = True Then
                    LoadCURRENT_DT_PROFILES()
                    LoadVWPM_CONTROL_INDEX()
                    CHANGES_FORM_DESIGN = False
                End If

                Dim oExpression = $"GUID = {CURRENT_ProfilGUID}"
                CURRENT_DT_PROFILE = Nothing '.Clear()
                CURRENT_DT_PROFILE = CURRENT_DT_PROFILES.Clone
                CURRENT_DT_PROFILES.Select(oExpression).CopyToDataTable(CURRENT_DT_PROFILE, LoadOption.PreserveChanges)
                If CURRENT_DT_PROFILE.Rows.Count = 1 Then
                    CURRENT_ProfilName = CURRENT_DT_PROFILE.Rows(0).Item("NAME")
                    CURRENT_WMObjecttype = CURRENT_DT_PROFILE.Rows(0).Item("WD_OBJECTTYPE")
                    PROFILE_SHOW_DOCUMENT = Convert.ToBoolean(CURRENT_DT_PROFILE.Rows(0).Item("SHOW_DOCUMENT"))
                    ActiveWorkflowType = 1
                Else
                    MsgBox("Could not get a Profile - Check Your log!", MsgBoxStyle.Exclamation, ADDITIONAL_TITLE)
                    Exit Sub
                End If

                DT_FILTERED_PROFILE_SEARCHES_DOC = Nothing
                DT_FILTERED_PROFILE_SEARCHES_DOC = BASEDATA_DT_PROFILES_SEARCHES_DOC.Copy
                DT_FILTERED_PROFILE_SEARCHES_DOC.Clear()
                oExpression = $"PROFILE_ID = {CURRENT_ProfilGUID}"
                BASEDATA_DT_PROFILES_SEARCHES_DOC.Select(oExpression, "TAB_INDEX").CopyToDataTable(DT_FILTERED_PROFILE_SEARCHES_DOC, LoadOption.PreserveChanges)

                BASEDATA_DT_PROFILE_SEARCHES_SQL = Nothing
                BASEDATA_DT_PROFILE_SEARCHES_SQL = BASEDATA_DT_PROFILES_SEARCHES_SQL.Copy
                BASEDATA_DT_PROFILE_SEARCHES_SQL.Clear()
                BASEDATA_DT_PROFILES_SEARCHES_SQL.Select(oExpression, "TAB_INDEX").CopyToDataTable(BASEDATA_DT_PROFILE_SEARCHES_SQL, LoadOption.PreserveChanges)

                Try
                    Dim oEnvironment = GetEnvironment()
                    _FormValidator = New frmValidator(oEnvironment)
                    AddHandler _FormValidator.FormClosed, AddressOf ValidatorClosed
                    _FormValidator.Show()
                Catch ex As Exception
                    LOGGER.Warn($"Error opening Form frmValidator [{ex.Message}]")
                    If Not IsNothing(ex.InnerException) Then
                        LOGGER.Warn($"ex.InnerException.Message [{ex.InnerException.Message}]")
                        LOGGER.Warn($"ex.InnerException.Source [{ex.InnerException.Source}]")
                        LOGGER.Error(ex.InnerException)
                    End If

                    MsgBox(ex.Message, MsgBoxStyle.Critical, ADDITIONAL_TITLE)
                End Try

                Try
                    Dim iterateIndex As Integer = 0
                    Dim oNewDataTable As DataTable = DT_CURR_WF_ITEMS.Copy
                    For Each row As DataRow In oNewDataTable.Rows
                        If row("GUID") = CURRENT_DOC_GUID Then
                            DT_CURR_WF_ITEMS.Rows.RemoveAt(iterateIndex)
                            Exit For
                        Else
                            iterateIndex += 1
                        End If
                    Next
                Catch ex As Exception
                    LOGGER.Warn("Unexpected Error in Removing Row after Loading Record from Grid: " & ex.Message)
                End Try
                TimerRefresh.Enabled = True
                ' th = New Threading.Thread(AddressOf Task_A)
                ' th.SetApartmentState(ApartmentState.STA)
                '  th.Start()
            Else
                LOGGER.Debug("Validator is already open...")

                Dim omsg = ClassAllgemeineFunktionen.GUI_LANGUAGE_INFO("WorkflowIsActive2")
                FormHelper.ShowInfoMessage(S.Es_existiert_bereits_ein_aktiver_Workflow_, omsgTitleAttention)
                'FormHelper.ShowInfoMessage(omsg, omsgTitleAttention)

            End If




        Catch ex As Exception
            LOGGER.Error(ex)
            MsgBox("Unexpected error in Load_Profil_from_Grid: " & ex.Message & vbNewLine & ADDITIONAL_TITLE & " will try to reload the overview - Please try again!", MsgBoxStyle.Information, ADDITIONAL_TITLE)
            Dim task = Decide_Load(False, True)
        End Try
        'Me.Visible = True
        'Decide_Load()

    End Sub

    'Public Sub Task_A()
    '    Dim frmA = New frmValidator() ' Must be created on this thread!
    '    Application.Run(frmA)
    'End Sub
    Private Sub Item_Scope(startedFrom As String)
        Try

            LOGGER.Info("Starting Profile Loading")

            If Application.OpenForms().OfType(Of frmValidator).Any Then
                bsiMessage.Caption = S.Es_existiert_bereits_ein_aktiver_Workflow_
                LOGGER.Info("Item Scope - Workflow open! - Exit")
                bsiMessage.ItemAppearance.Normal.BackColor = Color.Red
                bsiMessage.ItemAppearance.Normal.ForeColor = Color.Black
                Exit Sub
            End If
            Dim hitInfo As GridHitInfo = GridViewWorkflows.CalcHitInfo(GridCursorLocation)
            bsiMessage.Caption = ""
            bsiMessage.ItemAppearance.Normal.BackColor = Color.Transparent
            Dim OItemScopeInfo = "No Item so far"
            If startedFrom = "DOUBLECLICK" Then
                If hitInfo.InGroupRow Then
                    LOGGER.Debug("User clicked group row.")
                    startedFrom = "CMGROUP"
                Else
                    LOGGER.Debug("User clicked normal row.")
                    startedFrom = "CMROW"
                End If
            End If
            Dim oHitProfilID
            If hitInfo.InGroupRow Then
                oHitProfilID = GridViewWorkflows.GetRowCellValue(GridViewWorkflows.GetDataRowHandleByGroupRowHandle(hitInfo.RowHandle), GridViewWorkflows.Columns("PROFILE_ID"))
            ElseIf hitInfo.InDataRow Then
                oHitProfilID = GridViewWorkflows.GetRowCellValue(GridViewWorkflows.GetDataRowHandleByGroupRowHandle(GridViewWorkflows.GetParentRowHandle(hitInfo.RowHandle)), GridViewWorkflows.Columns("PROFILE_ID"))
            End If

            LOGGER.Debug("Clicked ProfileId: [{0}]", oHitProfilID)
            LOGGER.Debug("Started From: [{0}]", startedFrom)

            If Len(oHitProfilID) > 0 Then
                If oHitProfilID > 0 Then
                    If oHitProfilID <> CURRENT_CLICKED_PROFILE_ID Then
                        LOGGER.Debug($"Item_Scope: oHitProfilID {oHitProfilID} <> CURRENT_CLICKED_PROFILE_ID {CURRENT_CLICKED_PROFILE_ID} ")
                        CURRENT_CLICKED_PROFILE_ID = oHitProfilID
                    End If

                End If
            End If

            If startedFrom = "CMGROUP" Then

                LOGGER.Debug("Loading Child DocIds..")

                Dim oIds As New List(Of Integer)
                Dim oGroupRowHandle = hitInfo.RowHandle
                Dim oChildRowCount = GridViewWorkflows.GetChildRowCount(oGroupRowHandle)

                For index = 0 To oChildRowCount - 1
                    Dim oChildRowHandle = GridViewWorkflows.GetChildRowHandle(oGroupRowHandle, index)
                    Dim oRow = GridViewWorkflows.GetRow(oChildRowHandle)
                    Dim oDocId = oRow.Item("DocId")
                    oIds.Add(oDocId)
                Next

                LOGGER.Debug("[{0}] DocIds loaded", oIds.Count)

                If oIds.Count = 0 Then
                    For index = 0 To GridViewWorkflows.RowCount
                        Dim oRow = GridViewWorkflows.GetRow(index)

                        If oRow Is Nothing Then
                            Continue For
                        End If

                        Dim oProfileId = oRow.row.item("PROFILE_ID")

                        If oProfileId = CURRENT_CLICKED_PROFILE_ID Then
                            oIds.Add(oRow.item("DocId"))
                        End If
                    Next
                End If

                ' -----------------------------

                If oIds.Count = 0 Then
                    Dim omsg = String.Format(S.System_konnte_die_Profilworkflows_nicht_auswerten_, vbNewLine)
                    FormHelper.ShowInfoMessage(omsg, omsgTitleAttention)
                    'MsgBox("System konnte die Profilworkflows nicht auswerten!" & vbNewLine & "Bitte wählen Sie ein Profil durch Klicken auf einen Beleg oder eine Überschrift!", MsgBoxStyle.Information, ADDITIONAL_TITLE)
                    Exit Sub
                End If
                LOGGER.Debug("Cleaning up queued DocIds..")
                Dim oDelete = $"DELETE FROM TBPM_VALIDATION_PROFILE_GROUP_USER WHERE UserID = {USER_ID}"
                If DatabaseFallback.ExecuteNonQueryECM(oDelete) = True Then
                    LOGGER.Debug("Adding [{0}] queued DocIds..", oIds.Count)
                    For Each oID As Integer In oIds
                        Dim oInsert = $"INSERT INTO TBPM_VALIDATION_PROFILE_GROUP_USER ([PROFIL_ID] ,[DocID]
                        ,[UserID] ,[ADDED_WHO]) VALUES ({CURRENT_CLICKED_PROFILE_ID},{oID},{USER_ID},'{USER_USERNAME}')"
                        DatabaseFallback.ExecuteNonQueryECM(oInsert)
                    Next
                End If

            End If

            'GridViewWorkflows.EndSelection()
            CURRENT_JUMP_DOC_GUID = 0

            If IsNothing(hitInfo) Then
                bsiMessage.Caption = "Could not specify hitinfo via click event (CalcHitInfo)"
                LOGGER.Info("Could not specify hitinfo via click event (CalcHitInfo)")
                bsiMessage.ItemAppearance.Normal.BackColor = Color.Red
                bsiMessage.ItemAppearance.Normal.ForeColor = Color.Black
                Exit Sub
            End If
            Dim groupRowText = ""

            If hitInfo.InGroupRow Then
                GridViewItem_Clicked = "GROUP"
                startedFrom = "CMGROUP"
                LOGGER.Debug($"Item_Scope: InGroupRow")
                OItemScopeInfo = "InGroupRow"
                groupRowText = GridViewWorkflows.GetGroupRowDisplayText(hitInfo.RowHandle)
                OItemScopeInfo = $"groupRowText {groupRowText}"
                LOGGER.Debug($"Item_Scope: groupRowText {groupRowText}")
                ' oHitProfilID = GridViewWorkflows.GetRowCellValue(GridViewWorkflows.GetDataRowHandleByGroupRowHandle(hitInfo.RowHandle), GridViewWorkflows.Columns("PROFILE_ID"))
            ElseIf hitInfo.InDataRow Then
                GridViewItem_Clicked = "ROW"
                OItemScopeInfo = "InDataRow"
                LOGGER.Debug($"Item_Scope: InDataRow")
                If GRID_LOAD_TYPE = "OVERVIEW" Then
                    OItemScopeInfo = $"GRID_LOAD_TYPE = OVERVIEW"
                    LOGGER.Debug($"Item_Scope: GRID_LOAD_TYPE = OVERVIEW")
                    groupRowText = GridViewWorkflows.GetGroupRowDisplayText(GridViewWorkflows.GetParentRowHandle(hitInfo.RowHandle))
                    OItemScopeInfo = $"OVERVIEWgroupRowText {groupRowText}"
                    LOGGER.Debug($"Item_Scope: OVERVIEWgroupRowText {groupRowText}")
                    ' oHitProfilID = GridViewWorkflows.GetRowCellValue(GridViewWorkflows.GetDataRowHandleByGroupRowHandle(GridViewWorkflows.GetParentRowHandle(hitInfo.RowHandle)), GridViewWorkflows.Columns("PROFILE_ID"))
                Else
                    OItemScopeInfo = $"NOT GRID_LOAD_TYPE = OVERVIEW"
                    LOGGER.Debug($"Item_Scope: NOT GRID_LOAD_TYPE = OVERVIEW")
                    If IsNothing(CURRENT_CLICKED_PROFILE_ID) = False Then
                        If CURRENT_CLICKED_PROFILE_ID = 0 Then
                            LOGGER.Info("ItemScope: CURRENT_CLICKED_PROFILE_ID = 0!!!")
                        End If
                        LOGGER.Debug($"Item_Scope: CURRENT_CLICKED_PROFILE_ID [{CURRENT_CLICKED_PROFILE_ID}]")
                        oHitProfilID = CURRENT_CLICKED_PROFILE_ID
                    Else
                        LOGGER.Warn("ItemScope: CURRENT_CLICKED_PROFILE_ID is nothing!!!")
                        Exit Sub
                    End If

                End If

            Else
                Exit Sub
            End If
            Dim PROFIL_TITLE
            If GRID_LOAD_TYPE = "OVERVIEW" Then
                Try
                    groupRowText = groupRowText.ToString.Replace("Profile (Fixed): ", "").Trim()
                Catch ex As Exception

                End Try

                Dim _SPLIT As String()
                _SPLIT = groupRowText.Split("|")
                PROFIL_TITLE = _SPLIT(0).ToString.Trim()
            Else

            End If
            If Len(PROFIL_TITLE) > 0 Then
                CURRENT_CLICKED_PROFILE_TITLE = PROFIL_TITLE
            End If


            If Not IsNothing(CURRENT_CLICKED_PROFILE_ID) And IsNumeric(CURRENT_CLICKED_PROFILE_ID) Then
                LOGGER.Debug($"Item_Scope: Not IsNothing(PROFIL_ID) And IsNumeric(PROFIL_ID)")
                Dim oExpression As String
                oExpression = "PROFILE_ID = " & CURRENT_CLICKED_PROFILE_ID
                If hitInfo.InGroupRow Or (startedFrom = "CMGROUP" And hitInfo.InDataRow) Then
                    CURRENT_JUMP_DOC_GUID = 0
                    CURRENT_DOC_GUID = 0
                    CURRENT_ProfilGUID = CURRENT_CLICKED_PROFILE_ID
                    LOGGER.Debug($"Item_Scope: hitInfo.InGroupRow...CURRENT_CLICKED_PROFILE_ID [{CURRENT_CLICKED_PROFILE_ID}]")
                    Load_Profil_from_Grid(CURRENT_CLICKED_PROFILE_ID)
                ElseIf hitInfo.InDataRow Then
                    LOGGER.Debug($"Item_Scope: hitInfo.InDataRow...")
                    Dim oFocusedDocGUID
                    Try
                        oFocusedDocGUID = GridViewWorkflows.GetFocusedRowCellValue(GridViewWorkflows.Columns("GUID"))
                    Catch ex As Exception
                        FormHelper.ShowInfoMessage("Could not get DocGUID. Inform Your admin-team: Check Your View-Config", omsgTitleWarning)

                    End Try
                    Dim oFocusedDocID
                    Try
                        oFocusedDocID = GridViewWorkflows.GetFocusedRowCellValue(GridViewWorkflows.Columns("DocID"))
                    Catch ex As Exception
                        FormHelper.ShowInfoMessage("Could not get DocID. Inform Your admin-team: Check Your View-Config", omsgTitleWarning)
                    End Try

                    If IsNothing(oFocusedDocID) Then
                        LOGGER.Warn("In hitInfo.InDataRow: DocID is nothing!!!")
                        bsiMessage.Caption = "Error getting DocID!"
                        bsiMessage.ItemAppearance.Normal.BackColor = Color.Red
                        bsiMessage.ItemAppearance.Normal.ForeColor = Color.Black
                        Exit Sub
                    End If
                    If IsNothing(oFocusedDocGUID) Then
                        LOGGER.Warn("In hitInfo.InDataRow: oFocusedDocGUID is nothing!!!")
                        bsiMessage.Caption = "Error getting DocGUID!"
                        bsiMessage.ItemAppearance.Normal.BackColor = Color.Red
                        bsiMessage.ItemAppearance.Normal.ForeColor = Color.Black
                        Exit Sub
                    End If
                    LOGGER.Debug($"Item_Scope: GotDocID {oFocusedDocID} and DocGUID {oFocusedDocGUID}")
                    If Not IsNothing(GridViewWorkflows.Columns(FullFilepatColName)) Then
                        Dim DOC_PATH = GridViewWorkflows.GetFocusedRowCellValue(GridViewWorkflows.Columns(FullFilepatColName))
                        If IsNothing(DOC_PATH) Then
                            LOGGER.Warn("In hitInfo.InDataRow: FULL_FILE_PATH is nothing!!!")
                            Exit Sub
                        End If
                        DOC_PATH = DOC_PATH.Replace("W:\", "\\windream\objects\")
                        DOC_PATH = DOC_PATH.Replace("K:\", "\\windream\objects\")
                        ' CURRENT_DOC_PATH = DOC_PATH
                    End If

                    'Checking if table really contains one record with profile-id and docid
                    oExpression = oExpression & " AND DocID = " & oFocusedDocID
                    'Dim TEMP_TABLE = CURR_DT_OVERVIEW
                    'Dim foundRows() As DataRow
                    'foundRows = TEMP_TABLE.Select(expression)
                    'Dim result = 0
                    'For i = 0 To foundRows.GetUpperBound(0)
                    'result += 1
                    'Next
                    'If result = 1 Then
                    CURRENT_DOC_ID = oFocusedDocID
                    CURRENT_JUMP_DOC_GUID = oFocusedDocGUID
                    CURRENT_DOC_GUID = CURRENT_JUMP_DOC_GUID

                    Dim oSQL = $"SELECT [dbo].[FNPM_CHECK_DocGUID_Valid] ({CURRENT_DOC_GUID})"
                    Dim oResult = DatabaseFallback.GetScalarValueECM(oSQL)
                    Try
                        If CBool(oResult) = True Then
                            Load_Profil_from_Grid(CURRENT_CLICKED_PROFILE_ID)
                        Else

                            'Dim omsg = ClassAllgemeineFunktionen.GUI_LANGUAGE_INFO("WFInWork")
                            Dim omsg = S.Der_gewählte_Beleg_ist_durch_einen_anderen_Benutzer_bereits_in_Bearbeitung_oder_anderweitig_gesperrt_
                            FormHelper.ShowInfoMessage(omsg, omsgTitleAttention)

                        End If
                    Catch ex As Exception
                        LOGGER.Warn($"Uenxpected error in Checking freefile - sql so far: {oSQL} - ")
                    End Try

                    'Else
                    'LOGGER.Warn($"Unable to load Object DocID {CURRENT_DOC_ID} and DocGUID {CURRENT_JUMP_DOC_GUID}: Expression returned 0 [{expression}]")
                    'Exit Sub
                    'End If

                End If
            Else
                FormHelper.ShowInfoMessage("Could not get the ProfileID of file! - Check Your configuration of MainView!", omsgTitleWarning)
            End If
        Catch ex As Exception
            LOGGER.Error(ex)
            bsiMessage.Caption = "Warning in Item_Scope: " & ex.Message
            bsiMessage.ItemAppearance.Normal.BackColor = Color.Red
            bsiMessage.ItemAppearance.Normal.ForeColor = Color.Black

        End Try
    End Sub
    Private Async Sub ValidatorClosed(sender As Object, e As FormClosedEventArgs)
        Try
            Await Decide_Load(False, True)
            If GridControlWorkflows.Visible = True And FormOpenClose = False Then RefreshHelper.LoadViewInfo()
        Catch ex As Exception
            LOGGER.Error(ex)
        End Try
    End Sub
    Private Function Init_IDB()
        Try
            IDBData = New ClassIDBData()

            Return True
        Catch ex As Exception
            LOGGER.Error(ex)
            MsgBox("Error Init_IDB:" & vbNewLine & ex.Message, MsgBoxStyle.Critical, "Attention:")
            LOGGER.Info("Unexpected error in Init_IDB: " & ex.Message, True)
            Return False
        End Try
    End Function
    Private Function Init_windream()
        Try
            WINDREAM = New ClassPMWindream()
            WINDREAM_MOD = New Windream(LOGCONFIG, False, WMDRIVE_LETTER, WMSUFFIX, True, "", "", "", "")

            WINDREAM.Create_Session()
            WINDREAM_ALLG = New ClassWindream_allgemein
            Return WINDREAM.IsLoggedIn
        Catch ex As Exception
            LOGGER.Error(ex)
            MsgBox("Error Init_windream:" & vbNewLine & ex.Message, MsgBoxStyle.Critical, "Attention:")
            LOGGER.Info("Unexpected error in Init_windream: " & ex.Message, True)
            Return False
        End Try
    End Function
    Private Sub Create_GroupBy_Parts()
        Try
            LOGGER.Debug("Now Create_GroupBy_Parts ...")
            GridViewWorkflows.OptionsView.ShowGroupPanel = False
            Dim oindex As Integer = 0
            If Not IsNothing(BASEDATA_DTGRID_GROUPS) Then
                For Each oGridGroup As DataRow In BASEDATA_DTGRID_GROUPS.Rows

                    Dim oGroupName = oGridGroup.Item("GROUPNAME")

                    LOGGER.Debug($"Adding group [{oGroupName}] for Grid...")
                    Try
                        Dim oGroupColumn As GridColumn = GridViewWorkflows.Columns.Item(oGroupName)

                        If oGroupColumn IsNot Nothing Then
                            oGroupColumn.GroupIndex = oindex
                            oGroupColumn.Group()
                            oGroupColumn.OptionsColumn.AllowGroup = DefaultBoolean.False
                            oGroupColumn.OptionsColumn.AllowMove = False
                            oGroupColumn.OptionsColumn.AllowShowHide = False
                            oGroupColumn.Caption = "Profile (Fixed)"
                        End If
                    Catch ex As Exception

                    End Try

                    oindex += 1
                Next
            End If

            Try
                GridViewWorkflows.Columns.Item("GROUP_TEXT").Visible = False
                GridViewWorkflows.Columns.Item("GROUP_COLOR").Visible = False
            Catch ex As Exception
            End Try
            For index = 0 To GridViewWorkflows.GroupCount - 1
                'Dim v = GridViewWorkflows.GroupedColumns(index).ToString
                LOGGER.Debug($"Adding tag [{GridViewWorkflows.Columns.Item("PROFILE_ID")}] for group...")
                Dim sd = GridViewWorkflows.GroupedColumns(index).GetTextCaption
                GridViewWorkflows.GroupedColumns(index).Tag = GridViewWorkflows.Columns.Item("PROFILE_ID")
            Next
            GridViewWorkflows.CollapseAllGroups()
            LOGGER.Debug("finished Grouping!")
        Catch ex As Exception
            LOGGER.Error(ex)
        End Try
    End Sub
    Async Function Load_Grid_Overview(pFormLoad As Boolean, pForceReload As Boolean, pNavbarClick As Boolean) As Tasks.Task
        Dim oStopWatch As New RefreshHelper.SW("Load_Grid_Overview(LGO)")
        GridControlWorkflows_Visible()
        GRID_LOAD_TYPE = "OVERVIEW"
        CURRENT_CLICKED_PROFILE_ID = 0

        Try
            bsiMessage.Caption = ""

            If BASEDATA_DT_VW_PROFILE_USER.Rows.Count = 0 Then
                LOGGER.Info("no profiles for user: '" & USER_USERNAME & "' configured!", False)
                NO_WORKFLOWITEMS = True
                bsiMessage.Caption = "NO PROFILES FOR USER"
                bsiMessage.ItemAppearance.Normal.BackColor = Color.Red
                bsiMessage.ItemAppearance.Normal.ForeColor = Color.Black
                If GridControlWorkflows.Visible = True Then
                    GridControlWorkflows.Visible = False
                End If
                oStopWatch.Done()
                Exit Function
            End If
            Dim oStopWatch1 As New RefreshHelper.SW("LGO#Load_Profiles_for_User")
            Load_Profiles_for_User()
            oStopWatch1.Done()
            'ClassInit.InitBasics()
            Dim oStopWatch2 As New RefreshHelper.SW("LGO#build CURR_DT_OVERVIEW")
            Dim oSQLOverview = BASEDATA_DT_CONFIG.Rows(0).Item("SQL_PROFILE_MAIN_VIEW")
            If IsDBNull(oSQLOverview) Then
                bsiMessage.Caption = "No SQL_PROFILE_MAIN_VIEW in Baseconfig"
                oStopWatch.Done()
                oStopWatch2.Done()
                Exit Function
            End If
            If oSQLOverview.ToString.Contains("GROUP_TEXT") = False Then
                LOGGER.Info($"SQL SO FAR: {oSQLOverview} ")
                FormHelper.ShowInfoMessage("Incomplete Overview-Source (No Group-Columns). Please reload manually!", omsgTitleWarning)

                NO_WORKFLOWITEMS = True
                GridControlWorkflows.Visible = False
                bindsourcegrid.DataSource = Nothing
                GridControlWorkflows.DataSource = Nothing
                Try
                    GridViewWorkflows.Columns.Clear()
                Catch ex As Exception
                    LOGGER.Error(ex)

                End Try

                Exit Function
            End If

            oSQLOverview = clsPatterns.ReplaceInternalValues(oSQLOverview)
            oSQLOverview = clsPatterns.ReplaceUserValues(oSQLOverview)

            oSQLOverview = oSQLOverview.Replace("@USER_ID", USER_ID)
            oSQLOverview = oSQLOverview.Replace("@USERNAME", USER_USERNAME)
            oSQLOverview = oSQLOverview.Replace("@MACHINE_NAME", System.Environment.MachineName)
            oSQLOverview = oSQLOverview.Replace("@DATE", Now.ToShortDateString)
            oSQLOverview = oSQLOverview.Replace("@PROFILE_ID", CURRENT_CLICKED_PROFILE_ID)

            DT_CURR_WF_ITEMS = Await DatabaseFallback.GetDatatableECMAsync(oSQLOverview)
            oStopWatch2.Done()

            If Not IsNothing(DT_CURR_WF_ITEMS) Then
                LOGGER.Debug($"Datatable CURR_DT_OVERVIEW loaded: {DT_CURR_WF_ITEMS.Rows.Count} rows")
                If GridControlWorkflows.Visible = False Then
                    GridControlWorkflows.Visible = True
                End If

                Dim oADDED = GET_LAST_ADDED(DT_CURR_WF_ITEMS)
                Dim oChanged = GET_LAST_CHANGED(DT_CURR_WF_ITEMS)
                Dim oCOUNT = DT_CURR_WF_ITEMS.Rows.Count
                If pForceReload = False Then
                    If oADDED = OVERVIEW_ADDED_WHEN And oChanged = OVERVIEW_CHANGED_WHEN And oCOUNT = OVERVIEW_COUNT Then
                        If pForceReload = False Then
                            LOGGER.Debug("No changes on OverviewHash - so exit Load_Grid_overview")
                            Exit Function
                        End If
                    Else
                        LOGGER.Info("Differences on OverviewHash")
                        LOGGER.Debug($"oADDED/OVERVIEW_ADDED_WHEN: {oADDED}/{OVERVIEW_ADDED_WHEN}#oADDED/OVERVIEW_ADDED_WHEN: {oChanged}/{OVERVIEW_CHANGED_WHEN}")
                        OVERVIEW_ADDED_WHEN = oADDED
                        OVERVIEW_CHANGED_WHEN = oChanged
                        OVERVIEW_COUNT = oCOUNT
                    End If
                End If

                NO_WORKFLOWITEMS = False
                If DT_CURR_WF_ITEMS.Rows.Count = 0 Then
                    NO_WORKFLOWITEMS = True
                    lblCaptionMainGrid.Text = String.Format(S.Aktuell_keine_Workflowdaten_vorhanden___0_, "")

                    GridControlWorkflows.Visible = False
                    bindsourcegrid.DataSource = Nothing
                    GridControlWorkflows.DataSource = Nothing
                    Try
                        GridViewWorkflows.Columns.Clear()
                    Catch ex As Exception
                        LOGGER.Error(ex)
                    End Try
                    Exit Function
                End If


                GridControlWorkflows.Visible = True
                If TL_ICON = True Then
                    'Spalte für Status Icon erstellen
                    Dim columnStateIcon As New DataColumn()
                    columnStateIcon.DataType = GetType(Image)
                    columnStateIcon.ColumnName = "ICON"
                    columnStateIcon.Caption = ""
                    DT_CURR_WF_ITEMS.Columns.Add(columnStateIcon)
                End If
                RedDocuments = 0
                YellowDocuments = 0
                GreenDocuments = 0
                If TL_ICON = True Then
                    For Each row As DataRow In DT_CURR_WF_ITEMS.Rows
                        Dim State As Integer = row.Item("TL_STATE")
                        Select Case State
                            Case 1
                                RedDocuments += 1
                                row.Item("ICON") = My.Resources.bullet_red
                            Case 2
                                YellowDocuments += 1
                                row.Item("ICON") = My.Resources.bullet_orange
                            Case 3
                                GreenDocuments += 1
                                row.Item("ICON") = My.Resources.bullet_green
                        End Select
                    Next
                End If

                'If IDB_ACTIVE = True Then
                '    ' Spalte für Conversation erstellen
                '    Dim columnConvIcon As New DataColumn()
                '    columnConvIcon.DataType = GetType(Image)
                '    columnConvIcon.ColumnName = "CONVERSATION"
                '    columnConvIcon.Caption = ""
                '    DT_CURR_WF_ITEMS.Columns.Add(columnConvIcon)
                '    For Each oRow As DataRow In DT_CURR_WF_ITEMS.Rows
                '        Try
                '            Dim oCONVYN As Boolean
                '            Try
                '                oCONVYN = oRow.Item("CONV_YN")
                '            Catch ex As Exception
                '                LOGGER.Warn("Load_Grid_Overview - Column CONV_YN obviously is not part of CURR_DT_OVERVIEW")
                '                Exit For
                '            End Try
                '            Select Case oCONVYN
                '                Case True
                '                    oRow.Item("CONVERSATION") = My.Resources.conversation
                '            End Select
                '        Catch ex As Exception
                '            LOGGER.Warn("Load_Grid_Overview - Column CONVERSATION obviously is not part of GridViewWorkflows")
                '            Exit For
                '        End Try

                '    Next
                'End If


                bindsourcegrid.DataSource = DT_CURR_WF_ITEMS
                GridControlWorkflows.DataSource = bindsourcegrid
                GridControlWorkflows.ForceInitialize()

                Create_View_Caption()
                Dim oColNotPartofLayout As Boolean
                oColNotPartofLayout = False
                'GridControlDocRow.ForceInitialize()
                '  GridControl1.DataSource = CURR_DT_PROFILEGRID
                'If pFormLoad = True Then
                '    If IDB_ACTIVE = True Then
                '        oColNotPartofLayout = Column_inGridViewLayout("CONV_YN")
                '    End If
                'End If
                If pNavbarClick = False Then
                    If pForceReload = True And (GridLayoutChanged() = True Or oColNotPartofLayout = True) Then
                        'ResetLayout()
                        'SaveGridLayout()
                        LOGGER.Debug("Now GridLayout_Reset..")
                        Await GridLayout_Reset(False)
                    Else
                        If oColNotPartofLayout = False Then
                            RestoreLayout()
                        End If
                    End If
                Else
                    RestoreLayout()
                End If


                Try
                    If pForceReload = True And (GridLayoutChanged() = True Or oColNotPartofLayout = True) Then
                        Create_GroupBy_Parts()
                        COLUMNS_INVISIBLE()
                    End If




                    If TL_ICON = True Then
                        Try
                            GridViewWorkflows.Columns.Item("ICON").MaxWidth = 24
                            GridViewWorkflows.Columns.Item("ICON").MinWidth = 24
                            GridViewWorkflows.Columns.Item("ICON").AppearanceCell.BackColor = Color.White
                            GridViewWorkflows.Columns.Item("ICON").Fixed = DevExpress.XtraGrid.Columns.FixedStyle.Left
                        Catch ex As Exception

                        End Try

                    End If


                    LOGGER.Debug("GridViewWorkflows.Columns loaded...")
                    Try
                        Dim oReducedColName = LAST_EDITED_COLUMN.Replace("[", "")
                        oReducedColName = oReducedColName.Replace("]", "")
                        If Not IsNothing(GridViewWorkflows.Columns(oReducedColName)) Then
                            GridViewWorkflows.Columns(oReducedColName).DisplayFormat.FormatType = FormatType.DateTime
                            GridViewWorkflows.Columns(oReducedColName).DisplayFormat.FormatString = "dd.MM.yyyy HH:MM:ss"
                        ElseIf Not IsNothing(GridViewWorkflows.Columns("Zuletzt bearbeitet")) Then
                            GridViewWorkflows.Columns("Zuletzt bearbeitet").DisplayFormat.FormatType = FormatType.DateTime
                            GridViewWorkflows.Columns("Zuletzt bearbeitet").DisplayFormat.FormatString = "dd.MM.yyyy HH:MM:ss"
                        End If

                    Catch ex As Exception
                        LOGGER.Warn("(Warning LoadGridOverview)Column [Last edited] or [Zuletzt bearbeitet] not part of OverviewSQL")

                    End Try

                    LOGGER.Debug("finished Formatting Grid!")
                Catch ex As Exception
                    LOGGER.Error(ex)
                    LOGGER.Info("Unexpected Error in Formatting Grid: " & ex.Message)
                End Try
                If GridViewWorkflows.Columns.Count <= 5 Then
                    LOGGER.Info("GridViewWorkflows.Columns.Count <= 2 - Reset_Gridlayout will be forced...", False)
                    Await Reset_GridLayout(pFormLoad)
                End If
            Else
                NO_WORKFLOWITEMS = True
                GridControlWorkflows.Visible = False
                'BindingNavigator1.Dock = DockStyle.None


                GridControlWorkflows.DataSource = Nothing


                Try
                    GridViewWorkflows.Columns.Clear()
                Catch ex As Exception
                    LOGGER.Error(ex)
                End Try
            End If
            RestoreLayout()
            oStopWatch.Done()
        Catch ex As Exception
            LOGGER.Error(ex)
            LOGGER.Info("Load_Grid_Overview - Fehler: " & ex.Message)
        End Try
    End Function
    Private Sub tsmiValidationProfil_Click(sender As Object, e As EventArgs) Handles tsmiValidationProfil.Click
        If CURRENT_CLICKED_PROFILE_ID <> 0 Then
            Load_Profil_from_Grid(CURRENT_CLICKED_PROFILE_ID)
        Else
            FormHelper.ShowInfoMessage(S.Bitte_wählen_Sie_ein_Profil_aus_, omsgTitleWarning)
        End If
    End Sub

    Private Async Function GridLayout_Reset(Also_decideload As Boolean) As Tasks.Task

        FRONTEND_ACTION = "RESET_LAYOUT"
        Await Reset_GridLayout(False)
        If Also_decideload Then
            Await Decide_Load(False, True)
        End If

        GridViewWorkflows.OptionsView.ShowViewCaption = False
        SaveGridLayout()
        If GridViewWorkflows.GroupCount = 0 And Not IsNothing(GridViewWorkflows.Columns("GROUP_TEXT")) Then
            LOGGER.Info("NO GROUPS AFTER GridLayout_Reset Load...")
            Create_GroupBy_Parts()
        End If
        GridBuilder.WithFontSizeDelta(CONFIG.Config.GridFontSizeDelta)
        If GridControlWorkflows.Visible = True And FormOpenClose = False Then RefreshHelper.LoadViewInfo()
        FRONTEND_ACTION = FA_NONE
    End Function

    Async Function Reset_GridLayout(FormLoad As Boolean) As Tasks.Task

        If GridControlWorkflows.Visible = True And FormOpenClose = False Then
            RefreshHelper.SaveViewInfo()
        End If

        InResetlayout = True
        ' Layout zurücksetzen
        ResetLayout()

        ' Ansicht neu laden
        LoadNavBar()
        Await Decide_Load(FormLoad)
        InResetlayout = False
    End Function

    Private Sub GridViewWorkflows_DoubleClick(sender As Object, e As EventArgs) Handles GridViewWorkflows.DoubleClick
        Item_Scope("DOUBLECLICK")
    End Sub

    Private Sub GridViewWorkflows_CustomDrawGroupRow(sender As Object, e As Views.Base.RowObjectCustomDrawEventArgs) Handles GridViewWorkflows.CustomDrawGroupRow
        Try
            ' Added
            If FormOpenClose = True And GridIsLoaded = False Then
                Exit Sub
            End If

            Dim info As GridGroupRowInfo = TryCast(e.Info, GridGroupRowInfo)
            Dim view As GridView = sender

            If info.Column.FieldName = "GROUP_TEXT" Then
                info.GroupText = info.GroupValueText

                Dim oColorString As String = "LightGray"
                Dim oFontColorString As String = "Black"
                Dim oFoundConfig As Boolean = False
                Dim oGROUP_TEXT_COL As String
                If USER_LANGUAGE = "de-DE" Then
                    oGROUP_TEXT_COL = "GROUP_TEXT"
                Else
                    oGROUP_TEXT_COL = "GROUP_TEXT_LANG"
                End If


                For Each oProfileRow As DataRow In CURR_DT_VWPM_PROFILE_ACTIVE.Rows
                    If oProfileRow.Item(oGROUP_TEXT_COL) = info.GroupValueText Then
                        oFoundConfig = True
                        oColorString = oProfileRow.Item("GROUP_COLOR")
                        oFontColorString = oProfileRow.Item("GROUP_FONT_COLOR")
                        ' Added
                        Exit For
                    End If
                Next
                If oFoundConfig = False Then
                    LOGGER.Info($"CustomDrawGroupRow: Could not find a ColorConfig for ProfileGroupValueText [{info.GroupValueText}]...")
                    ' Added
                    Exit Sub
                End If

                Dim oColor As Color = ParseColorString(oColorString, Color.LightGray, "Background Color")
                Dim oFontColor As Color = ParseColorString(oFontColorString, Color.Black, "Font Color")

                info.Appearance.BackColor = oColor
                info.Appearance.ForeColor = oFontColor
            End If
        Catch ex As Exception
            LOGGER.Error(ex)
        End Try
    End Sub

    Private Function ParseColorString(ColorString As String, DefaultColor As Color, ColorDescription As String) As Color
        Dim oResultColor As Color

        If ColorString.Contains(";") Or ColorString.Contains(".") Then
            Dim oSplitColorString As String()

            If ColorString.Contains(";") Then
                oSplitColorString = ColorString.Split(";")
            Else
                oSplitColorString = ColorString.Split(".")
            End If

            Try
                oResultColor = Color.FromArgb(oSplitColorString(0), oSplitColorString(1), oSplitColorString(2))
            Catch ex As Exception
                oResultColor = DefaultColor
                LOGGER.Info("ParseColorString: Could not get Color.FromArgb [{0}] for {1}", ColorString, ColorDescription)
            End Try
        Else
            Try
                oResultColor = Color.FromName(ColorString)
            Catch ex As Exception
                LOGGER.Info("ParseColorString: Could not get Color.FromArgb [{0}] for {1}", ColorString, ColorDescription)
                oResultColor = DefaultColor
            End Try
        End If

        Return oResultColor
    End Function


    Private Sub GridViewWorkflows_MouseDown(sender As Object, e As MouseEventArgs) Handles GridViewWorkflows.MouseDown
        Dim view As GridView = sender
        Dim hi As GridHitInfo = view.CalcHitInfo(e.Location)
        Dim groupRowButtonClicked = (hi.HitTest = GridHitTest.RowGroupButton)
        GridCursorLocation = e.Location

        'If e.Button = MouseButtons.Left Then
        ' wenn in eine Group Row Doppelt geklickt wurde..
        If hi.InGroupRow And Not groupRowButtonClicked Then
            ' Ein/Ausklappen verhindern
            DXMouseEventArgs.GetMouseArgs(e).Handled = True
            GridViewItem_Clicked = "GROUP"
            If Not Application.OpenForms().OfType(Of frmValidator).Any Then
                CURRENT_CLICKED_PROFILE_ID = GridViewWorkflows.GetRowCellValue(GridViewWorkflows.GetDataRowHandleByGroupRowHandle(hi.RowHandle), GridViewWorkflows.Columns("PROFILE_ID"))
            End If

        ElseIf hi.InDataRow Then
            GridViewItem_Clicked = "ROW"
            If Not Application.OpenForms().OfType(Of frmValidator).Any Then
                CURRENT_CLICKED_PROFILE_ID = GridViewWorkflows.GetRowCellValue(GridViewWorkflows.GetDataRowHandleByGroupRowHandle(hi.RowHandle), GridViewWorkflows.Columns("PROFILE_ID"))
            End If

        Else
            GridViewItem_Clicked = Nothing
            If hi.HitTest = GridHitTest.FilterPanelCloseButton Then
                Ev_Filter_Panel_Closed = True
                Grid_Reset_Filter()
                Ev_Filter_Panel_Closed = False
            End If
        End If
        If Not IsNothing(CURRENT_CLICKED_PROFILE_ID) Then
            If IsNumeric(CURRENT_CLICKED_PROFILE_ID) Then
                If CURRENT_CLICKED_PROFILE_ID > 0 Then
                    For Each orow As DataRow In CURRENT_DT_PROFILES.Rows
                        If orow.Item("GUID") = CURRENT_CLICKED_PROFILE_ID Then
                            If Not Application.OpenForms().OfType(Of frmValidator).Any Then
                                CURRENT_CLICKED_PROFILE_TITLE = orow.Item("TITLE")
                            End If

                            Exit For
                        End If
                    Next
                End If
            End If
        End If

    End Sub

    Private Sub GridViewWorkflows_ColumnWidthChanged(sender As Object, e As Views.Base.ColumnEventArgs) Handles GridViewWorkflows.ColumnWidthChanged
        GridLayout_Changed("ColumnWidthChanged")
    End Sub
    Private Sub GridViewWorkflows_EndSorting(sender As Object, e As EventArgs) Handles GridViewWorkflows.EndSorting
        GridLayout_Changed("EndSorting")
    End Sub

    Private Sub GridViewWorkflows_LostFocus(sender As Object, e As EventArgs) Handles GridViewWorkflows.LostFocus
        ' Save expanded GroupRows
        If GridControlWorkflows.Visible = True And FormOpenClose = False Then
            RefreshHelper.SaveViewInfo()
        End If
    End Sub
    Sub LoadCURRENT_DT_PROFILES()
        Dim oSQL = $"select * from TBPM_PROFILE where ACTIVE = 1"
        CURRENT_DT_PROFILES = DatabaseFallback.GetDatatable("TBPM_PROFILE", New GetDatatableOptions(oSQL, DatabaseType.ECM))
        oSQL = $"select * from TBDD_GUI_LANGUAGE_PHRASE where LANGUAGE = '{USER_LANGUAGE}' AND MODULE = 'PM' AND TITLE LIKE 'PROFILE_%'"
        CURRENT_DT_PROFILE_LANGUAGE = DatabaseFallback.GetDatatable("TBPMPROFILE_LANGUAGE_TERMS", New GetDatatableOptions(oSQL, DatabaseType.ECM) With {
                .FilterExpression = $"LANGUAGE = '{USER_LANGUAGE}'"
            })
    End Sub
    Sub LoadVWPM_CONTROL_INDEX()
        Dim oSQL = $"SELECT * FROM VWPM_CONTROL_INDEX ORDER BY PROFIL_ID,Y_LOC, X_LOC"
        'DTVWCONTROLS_INDEX = DataASorDB.GetDatatable("DD_ECM", oSQL, "VWPM_CONTROL_INDEX", "")
        DTVWCONTROLS_INDEX = DatabaseFallback.GetDatatable("VWPM_CONTROL_INDEX", New GetDatatableOptions(oSQL, DatabaseType.ECM))
    End Sub
    Sub GetBaseData(pMode As String)
        Dim oStopWatch As New RefreshHelper.SW("GetBaseData")
        Try
            Dim oSQL = String.Format("SELECT * FROM [dbo].[FNDD_LOGIN_USER_MODULE] ('{0}','PM',{1})", USER_USERNAME, CLIENT_SELECTED)
            Dim DT_CHECKUSER_MODULE As DataTable
            DT_CHECKUSER_MODULE = DatabaseFallback.GetDatatable("TBDD_USER_MODULE", New GetDatatableOptions(oSQL, DatabaseType.ECM) With {
                                .FilterExpression = $"USERNAME = '{USER_USERNAME.ToLower}' AND MODULE_SHORT = 'PM'"
                            })

            If pMode = "bwBasicData" Then bwBasicData.ReportProgress(10)
            If pMode <> "Load" Then
                ClassParamRefresh.Refresh_Params(DT_CHECKUSER_MODULE)
            End If

            If pMode = "bwBasicData" Then bwBasicData.ReportProgress(20)
            If SQL_PROFILES_USER <> "" Then
                oSQL = SQL_PROFILES_USER.Replace("@USER_ID", USER_ID)
                LOGGER.Debug($"VWPM_PROFILE_ACTIVE-SELECT used from DD-SQL-Config..")
            Else
                oSQL = $"SELECT [dbo].[FNDD_LANGUAGE_PHRASE] ('PROFILE_TITLE' + CONVERT(VARCHAR(4),T.GUID),'{USER_LANGUAGE}','PM') as GROUP_TEXT_LANG, T.* 
FROM VWPM_PROFILE_ACTIVE T WHERE T.FILE_COUNT > 0 AND T.GUID IN (SELECT PROFILE_ID FROM [dbo].[FNPM_GET_ACTIVE_PROFILES_USER] ({USER_ID}))"

            End If

            CURR_DT_VWPM_PROFILE_ACTIVE = DatabaseFallback.GetDatatableECM(oSQL)
            CURR_DT_VWPM_PROFILE_AH_WORKFLOW = CURR_DT_VWPM_PROFILE_ACTIVE.Copy
            CURR_DT_VWPM_PROFILE_AH_WORKFLOW.Clear()
            Dim AHWFRows As DataRow() = CURR_DT_VWPM_PROFILE_ACTIVE.Select($"TYPE = {ConstAHWorkflow_BlindFile}", "PRIORITY")
            If AHWFRows.Length > 0 Then
                LOGGER.Info($"...NUMBER OF ADHOC-WORKFLOW PROFILES ({AHWFRows.Length})")
                CURR_DT_VWPM_PROFILE_AH_WORKFLOW = AHWFRows.CopyToDataTable()
            Else
                LOGGER.Debug($"...NO ADHOC-WORKFLOW PROFILES!")
            End If

            If pMode = "bwBasicData" Then bwBasicData.ReportProgress(30)
            LoadCURRENT_DT_PROFILES()

            If pMode = "Load" Then
                CURRENT_DT_PROFILE = CURRENT_DT_PROFILES.Clone()
            End If
            If pMode = "bwBasicData" Then bwBasicData.ReportProgress(40)
            oSQL = "select * from TBPM_PROFILE_SEARCH where TYPE = 'DOC' AND ACTIVE = 1 ORDER BY PROFILE_ID,TAB_INDEX"
            If SQL_VALIDATOR_SEARCHES <> String.Empty Then
                SQL_VALIDATOR_SEARCHES = SQL_VALIDATOR_SEARCHES.Replace("@USR_LANG_CODE", User.Language)
                oSQL = SQL_VALIDATOR_SEARCHES
            End If
            'BASEDATA_DT_PROFILES_SEARCHES_DOC = DataASorDB.GetDatatable("DD_ECM", oSQL, "TBPM_PROFILE_SEARCH", "TYPE = 'DOC'", "PROFILE_ID,TAB_INDEX")
            BASEDATA_DT_PROFILES_SEARCHES_DOC = DatabaseECM.GetDatatable(oSQL)
            '.GetDatatable("TBPM_PROFILE_SEARCH", New GetDatatableOptions(oSQL, DatabaseType.ECM) With {
            '    .FilterExpression = "TYPE = 'DOC'",
            '    .SortByColumn = "PROFILE_ID,TAB_INDEX"
            '})
            If pMode = "Load" Then
                DT_FILTERED_PROFILE_SEARCHES_DOC = BASEDATA_DT_PROFILES_SEARCHES_DOC.Clone()
            End If
            If pMode = "bwBasicData" Then bwBasicData.ReportProgress(50)
            oSQL = "select * from TBPM_PROFILE_SEARCH where TYPE = 'SQL' AND ACTIVE = 1 ORDER BY PROFILE_ID,TAB_INDEX"
            'BASEDATA_DT_PROFILES_SEARCHES_SQL = DataASorDB.GetDatatable("DD_ECM", oSQL, "TBPM_PROFILE_SEARCH", "TYPE = 'SQL'", "PROFILE_ID,TAB_INDEX")
            BASEDATA_DT_PROFILES_SEARCHES_SQL = DatabaseFallback.GetDatatable("TBPM_PROFILE_SEARCH", New GetDatatableOptions(oSQL, DatabaseType.ECM) With {
                .FilterExpression = "TYPE = 'SQL'",
                .SortByColumn = "PROFILE_ID,TAB_INDEX"
            })
            If pMode = "Load" Then
                BASEDATA_DT_PROFILE_SEARCHES_SQL = BASEDATA_DT_PROFILES_SEARCHES_SQL.Clone()
            End If
            If pMode = "bwBasicData" Then bwBasicData.ReportProgress(60)
            LoadVWPM_CONTROL_INDEX()
            If pMode = "bwBasicData" Then bwBasicData.ReportProgress(80)
            If pMode = "Load" Then
                DTVWCONTROL_INDEX = DTVWCONTROLS_INDEX.Clone()
            End If
            oSQL = $"SELECT * FROM TBPM_PROFILE_CONTROLS WHERE LEN(ISNULL(SQL_UEBERPRUEFUNG,'')) > 0 AND CTRL_TYPE <> 'BUTTON'"
            'DTCONTROLS_WITH_SQL = DataASorDB.GetDatatable("DD_ECM", oSQL, "DTCONTROLS_WITH_SQL", "", "")
            DTCONTROLS_WITH_SQL = DatabaseFallback.GetDatatable("DTCONTROLS_WITH_SQL", New GetDatatableOptions(oSQL, DatabaseType.ECM))

            If pMode = "bwBasicData" Then bwBasicData.ReportProgress(85)
            If pMode = "bwBasicData" Then bwBasicData.ReportProgress(100)
        Catch ex As Exception
            LOGGER.Warn($"Error in GetBaseData - Error: [{ex.Message}]")
        End Try
        oStopWatch.Done()
    End Sub
    Private Async Sub frmMain_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        If RIBBON_COLOR_SCHEME <> "" Then
            Me.LookAndFeel.UseDefaultLookAndFeel = False
            If RIBBON_COLOR_SCHEME = "Blue".ToUpper Then
                LookAndFeel.SetSkinStyle(SkinStyle.Office2019White, SkinSvgPalette.Office2019White.Yale)
            ElseIf RIBBON_COLOR_SCHEME = "Green".ToUpper Then
                LookAndFeel.SetSkinStyle(SkinStyle.Office2019White, SkinSvgPalette.Office2019White.Pine)
            ElseIf RIBBON_COLOR_SCHEME = "Purple".ToUpper Then
                LookAndFeel.SetSkinStyle(SkinStyle.Office2019White, SkinSvgPalette.Office2019White.Plum)
            ElseIf RIBBON_COLOR_SCHEME = "Red".ToUpper Then
                LookAndFeel.SetSkinStyle(SkinStyle.Office2019White, SkinSvgPalette.Office2019White.FireBrick)
            Else
                RibbonControl1.ColorScheme = DevExpress.XtraBars.Ribbon.RibbonControlColorScheme.Default
            End If
            LOGGER.Debug($" RibbonControl1.ColorScheme [{RIBBON_COLOR_SCHEME}]")
        End If

        Me.Text = ADDITIONAL_TITLE
        CurrNavBarGroup = NavBarControl1.Groups(1)

        FormShown = True
        Timer_Inactivity_Reset_Disable("Decide_Load")
        Await Decide_Load(True)
        If GridViewWorkflows.GroupCount = 0 And Not IsNothing(GridViewWorkflows.Columns("GROUP_TEXT")) Then
            LOGGER.Info("NO GROUPS AFTER SHOWN_Decide Load...")
            Create_GroupBy_Parts()
        End If

        Handling_DEBUG_USER()

        Dim oSQL = $"SELECT * FROM TBDD_NOTIFICATIONS_SYSTEM NOTE
            INNER JOIN (SELECT * FROM TBDD_NOTIFICATIONS_SYSTEM WHERE LANG_CODE = '{USER_LANGUAGE}' OR LANG_CODE = 'ALL') LANG ON NOTE.GUID = LANG.GUID
                where (CONVERT(DATE,GETDATE()) <= NOTE.DISPLAY_UNTIL or NOTE.DISPLAY_UNTIL IS NULL) AND NOTE.MODULE = 'PM' 
            AND NOTE.GUID NOT IN (SELECT NOTIFY_ID FROM TBDD_NOTIFICATIONS_USER_HISTORY WHERE USR_ID = {USER_ID})"
        Dim oDT As DataTable = DatabaseFallback.GetDatatable("TBDD_NOTIFICATIONS_SYSTEM", New GetDatatableOptions(oSQL, DatabaseType.ECM))

        If Not IsNothing(oDT) Then
            If oDT.Rows.Count > 0 Then
                NOTIFICATIONS_DT = oDT
                BBtnItmNotfications.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
                Open_Notifications_Form()
            End If

        End If

    End Sub
    Sub Open_Notifications_Form()
        Try
            Dim oEnvironment = GetEnvironment()
            Dim oNForm As New frmNotification_Startup(NOTIFICATIONS_DT, LOGCONFIG, GDPICTURE_LICENSE, TITLE_NOTIFICATIONS, oEnvironment)
            oNForm.ShowDialog()
        Catch ex As Exception
            LOGGER.Error(ex)
        End Try
    End Sub
    Sub Handling_DEBUG_USER()
        If DEBUG = True Then
            'bsiDebug.Caption = ClassAllgemeineFunktionen.GUI_LANGUAGE_INFO("DebugModeActive")
            bsiDebug.Caption = S.HINWEIS__Debug_Modus_ist_eingeschaltet_
            bsiDebug.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
        Else
            bsiDebug.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
        End If
    End Sub

    Sub DebuglogBackgroundthread()
        Dim oSQL As String = FA_NONE
        Try
            For Each oSLogstring As String In LOGCONFIG.Logs
                Dim oLogSplit As String() = oSLogstring.Split("|")
                Dim oMessage = PrepareLogMessage(oSLogstring)
                Dim oDateTime As Date = CDate(oLogSplit(0))
                oSQL = $"INSERT INTO [dbo].[TBPM_LOG_DEBUG] ([USERID] , [LOGMSG], [ADDED_WHEN],DATE_STR) VALUES({USER_ID},'{oMessage}',GetDate(),'{oDateTime}')"
                DatabaseFallback.ExecuteNonQueryECM(oSQL)
            Next
            LOGCONFIG.ClearLogs()
        Catch ex As Exception
            LOGGER.Error(ex)
            LOGGER.Warn($"oSQL so far [{oSQL}]")
        End Try
    End Sub
    Private Sub tsslblDEBUG_LOG_MouseHover(sender As Object, e As EventArgs)
        MsgBox("UserDebugMode is activated remotely. Debugdata will be transferred to database and will be deleted after 10 days!!", MsgBoxStyle.Information, ADDITIONAL_TITLE)

    End Sub

    Private Sub frmMain_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing
        If Application.OpenForms().OfType(Of frmValidator).Any Then
            _FormValidator.Close()
        End If
    End Sub


    Sub Grid_Reset_Filter()
        Timer_Inactivity_Reset_Disable("LöscheAlleFilterToolStripMenuItem")

        Try
            GridViewWorkflows.ClearFindFilter()
            GridViewWorkflows.ClearColumnsFilter()
            SaveGridLayout()
        Catch ex As Exception

        End Try
    End Sub

    Private Sub ContextMenuNotifyIcon_Opening(sender As Object, e As CancelEventArgs) Handles ContextMenuNotifyIcon.Opening
        If CONFIG.Config.ReminderTimer <> 0 Then
            PopupErinnerungInaktivierenToolStripMenuItem.Text = "Popup Erinnerung inaktivieren"
        Else
            PopupErinnerungInaktivierenToolStripMenuItem.Text = $"Popup Erinnerung aktivieren ({CONFIG.Config.ReminderTimer} min)"
        End If
    End Sub

    Private Sub PopupErinnerungInaktivierenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles PopupErinnerungInaktivierenToolStripMenuItem.Click
        If CONFIG.Config.ReminderTimer <> 0 Then
            CONFIG.Config.ReminderTimer = 0
            CONFIG.Save()
            Check_Timer_Notification()
        Else
            CONFIG.Config.ReminderTimer = 5
            CONFIG.Save()
            Check_Timer_Notification()

        End If
    End Sub
    Private Sub AnzeigenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AnzeigenToolStripMenuItem.Click
        BringMonitor2Front()
    End Sub

    Private Sub frmMain_Resize(sender As Object, e As EventArgs) Handles Me.Resize
        Try
            If FormShown = False Then
                Exit Sub
            End If

            If WindowState = FormWindowState.Maximized Then
                My.Settings.frmMainWindowState = "Maximized"
            ElseIf WindowState = FormWindowState.Normal Then
                My.Settings.frmMainWindowState = "Normal"
            End If
            My.Settings.Save()
        Catch ex As Exception
            LOGGER.Error(ex)
        End Try
    End Sub
    Private Sub BarButtonItem3_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbtniGrundeinstellung.ItemClick
        Try
            frmKonfig.ShowDialog()

            '  Load_Profil()
            Check_Timer_Notification()
        Catch ex As Exception
            LOGGER.Error(ex)
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler beim Laden Grundeinstellungen:")
        End Try
    End Sub


    Private Async Sub bbtniRefresh_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbtniRefresh.ItemClick
        If Application.OpenForms().OfType(Of frmValidator).Any Then
            'FormHelper.ShowInfoMessage(omsgOpenWorkflow, omsgTitleWarning)
            FormHelper.ShowInfoMessage(S.Bitte_schließen_Sie_den_offenen_Workflow_, omsgTitleWarning)
            Exit Sub
        End If
        Timer_Inactivity_Reset_Disable("OverviewRefreshClick")
        'If GridControlWorkflows.Visible = True And FormOpenClose = False Then
        '    RefreshHelper.SaveViewInfo()
        '    SaveGridLayout()
        'End If
        Await Decide_Load(False, True)
        LoadNavBar()
        If GridControlWorkflows.Visible = True And FormOpenClose = False Then
            RefreshHelper.LoadViewInfo()
        End If
    End Sub

    Private Sub bbtniMonitor_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbtniMonitor.ItemClick
        If Not Application.OpenForms().OfType(Of frmMonitor).Any Then
            frmMonitor.Show()
        End If
    End Sub

    Private Sub bbiProfilverwaltung_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbiProfilverwaltung.ItemClick
        'Dim AdminSecurity As Boolean = False
        'AdminSecurity = TBPM_KONFIGURATIONTableAdapter.cmdGetAdminSecurity()
        'If AdminSecurity = True Then
        '    frmLoginAdmin.ShowDialog()
        'Else
        frmAdministration.Show()
        ' End If

    End Sub

    Private Sub bbiKonfiguration_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbiKonfiguration.ItemClick
        frmAdmin2.ShowDialog()
    End Sub

    Private Sub bbtniMetadataFile_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbtniMetadataFile.ItemClick
        frmDesignerLayout.Show()
    End Sub

    Private Sub bwSync_DoWork(sender As Object, e As DoWorkEventArgs) Handles bwSync.DoWork

    End Sub

    Private Sub bwSync_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles bwSync.ProgressChanged
        BarEditItem1.EditValue = e.ProgressPercentage
    End Sub


    Private Sub Timer5Mins_Tick(sender As Object, e As EventArgs) Handles Timer5Mins.Tick

        Try
            Timer5Mins_running = True
            If Not bwBasicData.IsBusy Then
                BarEditItem1.Caption = "Get BasicData"
                BarEditItem1.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
                bwBasicData.RunWorkerAsync()
            End If

            If DEBUG = True Then
                '    'Jetzt der insert der Inhalte
                If Not IsNothing(LOGCONFIG.Logs) Then
                    If LOGCONFIG.Logs.Count > 0 Then
                        Dim thread As New Thread(AddressOf DebuglogBackgroundthread)
                        thread.Start()

                    End If

                End If
            End If
        Catch ex As Exception
            LOGGER.Warn($"Timer5Mins Error: {ex.Message}")
        End Try
        Timer5Mins_running = False
    End Sub
    Private Sub bwBasicData_DoWork(sender As Object, e As DoWorkEventArgs) Handles bwBasicData.DoWork
        GetBaseData("bwBasicData")
    End Sub

    Private Sub bwBasicData_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles bwBasicData.RunWorkerCompleted
        If USER_IS_ADMIN Then
            'bsiDebug.Caption = $"{ClassAllgemeineFunktionen.GUI_LANGUAGE_INFO("LicenseCountCaption")}: {USERCOUNT_LOGGED_IN}"
            bsiDebug.Caption = String.Format(S.Anzahl_Lizenzen___0_, USERCOUNT_LOGGED_IN)
        End If
        BarEditItem1.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
    End Sub

    Private Sub bwBasicData_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles bwBasicData.ProgressChanged
        BarEditItem1.EditValue = e.ProgressPercentage
    End Sub

    Private Sub BarButtonItem2_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbtnitDashboardInv.ItemClick
        If Application.OpenForms().OfType(Of frmInvDashboard).Any Then
            Exit Sub
        End If

        frmInvDashboard.Show()
    End Sub

    Private Sub OutOfRangePMFixierenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OutOfRangePMFixierenToolStripMenuItem.Click
        Dim myPoint As Point = New Point(50, 50)
        Me.Location = Screen.AllScreens(UBound(Screen.AllScreens)).Bounds.Location + myPoint
        BringMonitor2Front()
    End Sub

    Private Sub GridViewWorkflows_RowStyle(sender As Object, e As RowStyleEventArgs) Handles GridViewWorkflows.RowStyle
        If FormShown = False Then
            Exit Sub
        End If
        If e.RowHandle = -1 Then
            IsFilterMode = True
            Exit Sub
        End If
        If e.RowHandle = DevExpress.XtraGrid.GridControl.AutoFilterRowHandle Then
            IsFilterMode = True
            ' e.Appearance.BackColor = Color.Yellow
        Else
            IsFilterMode = False
            Try
                Dim oRowColorCellValue = GridViewWorkflows.GetRowCellValue(e.RowHandle, "ROW_COLOR")
                If Not IsNothing(oRowColorCellValue) Then
                    Dim oColor As Color
                    Try
                        If oRowColorCellValue.ToString.Contains(";") Or oRowColorCellValue.ToString.Contains(".") Then
                            Dim oColorSplit As String()
                            If oRowColorCellValue.Contains(";") Then
                                oColorSplit = oRowColorCellValue.Split(";")
                            ElseIf oRowColorCellValue.Contains(".") Then
                                oColorSplit = oRowColorCellValue.Split(".")
                            End If


                            Try
                                oColor = Color.FromArgb(oColorSplit(0), oColorSplit(1), oColorSplit(2))
                            Catch ex As Exception
                                LOGGER.Info($"RowColorHandler: Could not get Color.FromArgb [{oRowColorCellValue}]")
                                oColor = Color.LightGray
                            End Try
                        Else
                            Try
                                oColor = Color.FromName(oRowColorCellValue)
                            Catch ex As Exception
                                LOGGER.Info($"RowColorHandler: Could not get Color.FromName [{oRowColorCellValue}]")
                            End Try


                        End If
                    Catch ex As Exception
                        LOGGER.Info("RowBackColor: " & ex.Message, False)
                        Exit Sub
                    End Try
                    e.Appearance.BackColor = oColor
                    e.HighPriority = True
                End If
            Catch ex As Exception
                LOGGER.Info("Unexpected Error in RowStyle: " & ex.Message, False)
            End Try

        End If
    End Sub

    Private Async Sub BarButtonItem2_ItemClick_1(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbtnitmGhostMode.ItemClick
        frmGhostMode.ShowDialog()
        If USER_GHOST_MODE_ACTIVE = True And USER_GHOST_MODE_USRNAME <> String.Empty Then
            LOGGER.Info($"GHOST MODE for User {USER_GHOST_MODE_USRNAME} will now be initialized!")
            Dim oUserLanguage = User.Language
            USER_USERNAME_ORG = USER_USERNAME
            BarButtonItemGhostMode.Caption = String.Format(S.Ghost_Modus___0___deaktivieren, USER_GHOST_MODE_USRNAME)
            BarButtonItemGhostMode.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
            _Init.InitBasics()
            _Init.InitUserLogin()
            _Init.InitBasics2()
            Dim onewUserLanguage = User.Language
            GetBaseData("Load")
            LoadNavBar()
            If oUserLanguage <> onewUserLanguage Then
                MsgBox($"Layout will be reset as language changed from {oUserLanguage} to {onewUserLanguage}", MsgBoxStyle.Exclamation, ADDITIONAL_TITLE)
                Await GridLayout_Reset(True)
            Else
                Await Decide_Load(False)
            End If


            If GridControlWorkflows.Visible = True And FormOpenClose = False Then RefreshHelper.LoadViewInfo()
        End If
    End Sub

    Private Async Sub BarButtonItem2_ItemClick_2(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemGhostMode.ItemClick
        USER_GHOST_MODE_ACTIVE = False
        USER_GHOST_MODE_USRNAME = String.Empty
        USER_ID = 0
        USER_USERNAME = USER_USERNAME_ORG

        BarButtonItemGhostMode.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
        _Init.InitUserLogin()
        GetBaseData("InactivateGM")
        LoadNavBar()
        Await Decide_Load(False)
        If GridControlWorkflows.Visible = True And FormOpenClose = False Then RefreshHelper.LoadViewInfo()
    End Sub

    Private Sub GridViewWorkflows_ColumnFilterChanged(sender As Object, e As EventArgs) Handles GridViewWorkflows.ColumnFilterChanged
        Try
            If FormShown = False Or FRONTEND_ACTION = NAVBAR_CLICKED Then
                Exit Sub
            End If

            Timer_Inactivity_Reset_Disable("GridViewWorkflows.ColumnFilterChanged")
            If DetailLinkActive = False Then
                Create_View_Caption()
            End If

            If GridViewWorkflows.ActiveFilterEnabled Then

            End If
            If Ev_Filter_Panel_Closed = False Then
                Dim oTermFilterActive As String = S.Filter_aktiv
                If GridViewWorkflows.ActiveFilterString <> String.Empty Then
                    If Not lblCaptionMainGrid.Text.Contains(oTermFilterActive) Then
                        lblCaptionMainGrid.Text += $"|{oTermFilterActive}"
                    Else
                        Ev_Filter_Panel_Closed = False
                    End If
                End If

            End If
            GridLayout_Changed("ColumnFilterChanged")
        Catch ex As Exception
            LOGGER.Error(ex.Message)
        End Try
    End Sub

    Sub Create_View_Caption()
        Try
            lblCaptionMainGrid.Text = S.Gesamtübersicht

        Catch ex As Exception

        End Try
    End Sub
    Sub Grid_Export()
        XtraSaveFileDialog1.FileName = "Overview.xlsx"
        XtraSaveFileDialog1.DefaultExt = ".xlsx"

        If XtraSaveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            Dim oOptions As New XlsxExportOptions() With {
                    .ExportMode = XlsxExportMode.SingleFile
                }
            GridViewWorkflows.ExportToXlsx(XtraSaveFileDialog1.FileName, oOptions)
        End If
    End Sub



    Private Sub TimerInactivity_Tick(sender As Object, e As EventArgs) Handles TimerInactivity.Tick
        Try
            If Application.OpenForms().OfType(Of frmValidator).Any Then
                bsiMessage.Caption = "Validation Active - no Inactivity-Logout"
                bsiMessage.ItemAppearance.Normal.BackColor = Color.Yellow
                bsiMessage.ItemAppearance.Normal.ForeColor = Color.Black
                Timer_Inactivity_Reset_Disable("frmValidator")
                Exit Sub
            End If
            If Application.OpenForms().OfType(Of frmAdministration).Any Then
                bsiMessage.Caption = "Administration Active - no Inactivity-Logout"
                bsiMessage.ItemAppearance.Normal.BackColor = Color.Yellow
                bsiMessage.ItemAppearance.Normal.ForeColor = Color.Black
                Timer_Inactivity_Reset_Disable("frmAdministration")
                Exit Sub
            End If
            If Application.OpenForms().OfType(Of frmAdmin2).Any Then
                bsiMessage.Caption = "Administration2 Active - no Inactivity-Logout"
                bsiMessage.ItemAppearance.Normal.BackColor = Color.Yellow
                bsiMessage.ItemAppearance.Normal.ForeColor = Color.Black
                Timer_Inactivity_Reset_Disable("frmAdmin2")
                Exit Sub
            End If
            If Application.OpenForms().OfType(Of frmMonitor).Any Then
                bsiMessage.Caption = "Monitoring open - no Inactivity-Logout"
                bsiMessage.ItemAppearance.Normal.BackColor = Color.Yellow
                bsiMessage.ItemAppearance.Normal.ForeColor = Color.Black
                Timer_Inactivity_Reset_Disable("frmMonitor")
                Exit Sub
            End If
            If GHOSTMODE_ACTIVE And USER_GHOST_MODE_ACTIVE Then
                bsiMessage.Caption = "GhostMode Active - no Inactivity-Logout"
                bsiMessage.ItemAppearance.Normal.BackColor = Color.Yellow
                bsiMessage.ItemAppearance.Normal.ForeColor = Color.Black
                Timer_Inactivity_Reset_Disable("USER_GHOST_MODE_ACTIVE")
                Exit Sub
            End If
            INACTIVITYRecognized = True

            'Dim omsg As String = ClassAllgemeineFunktionen.GUI_LANGUAGE_INFO("INACTIVITYRecognized")
            Dim omsg As String = S.Sie_wurden_aufgrund_von_Inaktivität_automatisch_abgemeldet_

            Timer5Mins.Stop()
            TimerRefresh.Stop()
            TimerReminder.Stop()
            LOGGER.Info("Inactivity recognized. Automatic Logout in process!")
            Hide()
            ClassAllgemeineFunktionen.LoginOut("LOGOUT")
            TimerInactivity.Stop()
            MsgBox(omsg, MsgBoxStyle.Information, ADDITIONAL_TITLE)
            Application.Exit()
        Catch ex As Exception
            LOGGER.Error(ex.Message)
        End Try
    End Sub

    Private Sub BarButtonItem3_ItemClick_1(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles SearchItem1.ItemClick
        Try
            Dim oTag = SearchItem1.Tag
            Dim _SPLIT As String()
            _SPLIT = oTag.Split("%")
            Dim oPath = LTrim(RTrim(_SPLIT(0).ToString))
            Dim MyProcess As New Process()
            MyProcess.StartInfo.FileName = oPath
            MyProcess.StartInfo.Arguments = LTrim(RTrim(_SPLIT(1).ToString))
            MyProcess.Start() 'Startet den Prozess
        Catch ex As Exception
            LOGGER.Error(ex.Message)
        End Try


    End Sub

    Private Sub bbtniCW_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbtniCW.ItemClick
        Try
            If File.Exists(bbtniCW.Tag) Then
                Dim MyProcess As New Process()
                MyProcess.StartInfo.FileName = bbtniCW.Tag
                MyProcess.Start()
            Else
                LOGGER.Warn($"Clipboardwatcher-Exe not found [{bbtniCW.Tag}]")
                FormHelper.ShowInfoMessage("Clipboard Watcher could not be started!", omsgTitleWarning)
            End If

        Catch ex As Exception
            LOGGER.Error(ex.Message)
        End Try
    End Sub

    Private Sub GridViewWorkflows_ColumnPositionChanged(sender As Object, e As EventArgs) Handles GridViewWorkflows.ColumnPositionChanged
        GridLayout_Changed("ColumnPositionChanged")
    End Sub
    Private Sub GridLayout_Changed(oEvent As String)
        If FormShown = False Or Ev_Filter_Panel_Closed Then
            Exit Sub
        End If
        If FRONTEND_ACTION <> FA_NONE Then
            Exit Sub
        End If
        SaveGridLayout()
    End Sub


    Private Sub GridViewWorkflows_EndGrouping(sender As Object, e As EventArgs) Handles GridViewWorkflows.EndGrouping
        GridLayout_Changed("EndGrouping")
    End Sub

    Private Sub bsilastsync_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles bsilastsync.ItemClick

    End Sub

    Private Sub GridViewWorkflows_KeyDown(sender As Object, e As KeyEventArgs) Handles GridViewWorkflows.KeyDown
        Dim view As GridView = CType(sender, GridView)
        If e.Control AndAlso e.KeyCode = Keys.C Then
            If view.GetRowCellValue(view.FocusedRowHandle, view.FocusedColumn) IsNot Nothing AndAlso view.GetRowCellValue(view.FocusedRowHandle, view.FocusedColumn).ToString() <> [String].Empty Then
                Clipboard.SetText(view.GetRowCellValue(view.FocusedRowHandle, view.FocusedColumn).ToString())
            End If
            e.Handled = True
        End If
    End Sub

    Private Sub BarCheckItem1_CheckedChanged(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarCheckItemAutofilter.CheckedChanged
        If GridIsLoaded = True Then
            GridViewWorkflows.OptionsView.ShowAutoFilterRow = BarCheckItemAutofilter.Checked
        End If

    End Sub
    Private Sub BarCheckItem1_CheckedChanged_1(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarCheckItemShowSearch.CheckedChanged
        If GridIsLoaded = True Then
            GridViewWorkflows.OptionsFind.AlwaysVisible = BarCheckItemShowSearch.Checked
        End If
    End Sub

    Private Sub BarButtonItem4_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem4.ItemClick
        Grid_Layout_Save()
    End Sub
    Sub Grid_Layout_Save()
        FRONTEND_ACTION = "SAVE GRID LAYOUT"
        GridViewWorkflows.OptionsView.ShowViewCaption = False
        GridLayout_Changed("Grid_Layout_Save")
        FRONTEND_ACTION = FA_NONE
    End Sub

    Private Sub BarButtonItem5_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemExportExcel.ItemClick
        Grid_Export()
    End Sub

    Private Sub BarButtonItem6_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem6.ItemClick
        Grid_Reset_Filter()
    End Sub

    Private Sub BarButtonItem7_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem7.ItemClick
        GridViewWorkflows.ShowCustomization()
    End Sub

    Private Sub BarButtonItem8_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemWFSingle.ItemClick
        Item_Scope("CMROW")
    End Sub

    Private Sub BarButtonItemWFGroup_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemWFGroup.ItemClick
        Item_Scope("CMGROUP")
    End Sub

    Private Sub BarButtonItemFileLink_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemFileLink.ItemClick
        Dim oReceipiant = ""
        Dim oFocusedDocGUID = GridViewWorkflows.GetFocusedRowCellValue(GridViewWorkflows.Columns("GUID"))
        Dim oSQL = $"SELECT [dbo].[FNPM_GET_FILEPATH] ({oFocusedDocGUID},1)"
        Dim oFilePath = DatabaseFallback.GetScalarValueECM(oSQL)
        If File.Exists(oFilePath) Then
            Dim oLink = "<HTML><body><p><a href=" + "file:///" + oFilePath + ">Link zur Datei</a></p></body></HTML>"
            Dim oLink2 = "<a href=" + "file:///" + oFilePath + ">Link zur Datei</a>"
            If Not IsNothing(oFilePath) Then
                Process.Start($"mailto:{oReceipiant}?subject=Link aus TaskFlow Manager&body={oLink}")
            End If
        End If

    End Sub

    Private Async Sub BarButtonItemMassValidation_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemMassValidation.ItemClick
        Try
            Dim oSelectedRows As Integer() = GridViewWorkflows.GetSelectedRows()
            Dim oHitInfo As GridHitInfo = GridViewWorkflows.CalcHitInfo(GridCursorLocation)
            Dim oSelectedRowHandle As Integer = oHitInfo.RowHandle
            Dim oWorkedFiles As Integer = 0

            Dim oProfileId = 0

            If oSelectedRows.Count = 0 Then
                'Dim omsg = ClassAllgemeineFunktionen.GUI_LANGUAGE_INFO("MASS_NO_WF_SELECTED")
                Dim omsg = S.Bitte_wählen_Sie_ein_Profil_aus_

                FormHelper.ShowInfoMessage(omsg, omsgTitleWarning)
                Exit Sub
            End If

            oProfileId = GridViewWorkflows.GetRowCellValue(oSelectedRows.Last(), GridViewWorkflows.Columns("PROFILE_ID"))

            If oProfileId = 0 Then
                FormHelper.ShowInfoMessage("Could not select a profile!", omsgTitleWarning)
                Exit Sub
            End If


            If SOURCE_INIT = True Then
                CURRENT_ProfilGUID = oProfileId
                Dim oSQL = $"select * from TBPM_PROFILE_FINAL_INDEXING where PROFIL_ID = {CURRENT_ProfilGUID} ORDER BY [SEQUENCE]"

                'CURRENT_DT_FINAL_INDEXING = DataASorDB.GetDatatable("DD_ECM", oSQL, "TBPM_PROFILE_FINAL_INDEXING", $"PROFIL_ID = {CURRENT_ProfilGUID}", "SEQUENCE")
                CURRENT_DT_FINAL_INDEXING = DatabaseFallback.GetDatatable("TBPM_PROFILE_FINAL_INDEXING", New GetDatatableOptions(oSQL, DatabaseType.ECM) With {
                    .FilterExpression = $"PROFIL_ID = {CURRENT_ProfilGUID}",
                    .SortByColumn = "SEQUENCE"
                })

                CURRENT_DT_PROFILE = Nothing '.Clear
                CURRENT_DT_PROFILE = CURRENT_DT_PROFILES.Clone
                Dim oExpression = $"GUID = {CURRENT_ProfilGUID}"
                CURRENT_DT_PROFILES.Select(oExpression).CopyToDataTable(CURRENT_DT_PROFILE, LoadOption.PreserveChanges)
                If CURRENT_DT_PROFILE.Rows.Count = 1 Then
                    CURRENT_ProfilName = CURRENT_DT_PROFILE.Rows(0).Item("NAME")
                    PROFILE_SHOW_DOCUMENT = CURRENT_DT_PROFILE.Rows(0).Item("SHOW_DOCUMENT")
                    ActiveWorkflowType = 1
                Else
                    Exit Sub
                End If

                CURRENT_PROFILE_LOG_INDEX = CURRENT_DT_PROFILE.Rows(0).Item("PM_VEKTOR_INDEX")
                If CURRENT_PROFILE_LOG_INDEX = "" Then
                    CURRENT_PROFILE_LOG_INDEX = CURRENT_DT_PROFILE.Rows(0).Item("LOG_INDEX")
                End If


                Dim NewDatatable As New DataTable
                NewDatatable.Columns.Add("DocID")
                NewDatatable.Columns.Add("DOC_GUID")
                NewDatatable.Columns.Add("FULL_PATH")

                For Each oRowHandle As Integer In oSelectedRows

                    Dim oDocID = GridViewWorkflows.GetRowCellValue(oRowHandle, "DocID")
                    If IsNothing(oDocID) Then
                        Continue For
                    End If
                    Dim R As DataRow = NewDatatable.NewRow
                    CURRENT_DOC_ID = oDocID
                    Dim DOC_PATH = GridViewWorkflows.GetRowCellValue(oRowHandle, FullFilepatColName)
                    ' CURRENT_DOC_PATH = DOC_PATH
                    CURRENT_DOC_GUID = GridViewWorkflows.GetRowCellValue(oRowHandle, "GUID")
                    R("DocID") = CURRENT_DOC_ID
                    R("FULL_PATH") = DOC_PATH
                    R("DOC_GUID") = GridViewWorkflows.GetRowCellValue(oRowHandle, "GUID")
                    NewDatatable.Rows.Add(R)
                Next

                CURRENT_DT_MASS_CHANGE_DOCS = Nothing
                CURRENT_DT_MASS_CHANGE_DOCS = NewDatatable
                TimerRefresh.Enabled = False
                frmMassValidator.ShowDialog()
                LoadNavBar()
                Await Decide_Load(False)
            Else
                'Dim oMSG = ClassAllgemeineFunktionen.GUI_LANGUAGE_INFO("MASS_ERROR_WINDREAM")
                Dim oMSG = S.Massenabschluss_konnte_nicht_ausgeführt_werden__weil_windream_nicht_initialisiert_werden_konnte_
                MsgBox(oMSG, MsgBoxStyle.Critical, "Unexpected Error Massvalidation")
            End If
        Catch ex As Exception
            LOGGER.Error(ex)
            MsgBox("Unhandled Error in tsmiMarkedFilesFinish_Click: " & ex.Message)
        End Try
    End Sub

    Private Sub RibbonControl1_SelectedPageChanged(sender As Object, e As EventArgs) Handles RibbonControl1.SelectedPageChanged
        Dim ribbon As RibbonControl = TryCast(sender, RibbonControl)
        Timer_Inactivity_Reset_Disable("RibbonControl1_SelectedPageChanged")
        If ribbon.SelectedPage Is RibbonPageAktionen Then
            If USER_GHOST_MODE_ACTIVE = True And USER_GHOST_MODE_USRNAME <> String.Empty Then
                LOGGER.Debug("Ghostmode is active...")
                bbtnitmLanguage_Change.Enabled = False
            Else
                bbtnitmLanguage_Change.Enabled = True
            End If
            Select Case GridViewItem_Clicked
                Case "GROUP"
                    If SHOW_MASS_VALIDATOR = True Then
                        BarButtonItemMassValidation.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
                    End If
                Case "ROW"
                    '        If selectedRows.Count > 1 Then
                    '            CMFileStart.Enabled = False
                    '        Else
                    '            CMFileStart.Enabled = True
                    '        End If
                    '        If CURRENT_CLICKED_PROFILE_ID > 0 Then
                    '            CMGroupStart.Enabled = True
                    '        End If
            End Select
        End If
    End Sub

    Private Sub barItemGridFontSize_EditValueChanged(sender As Object, e As EventArgs) Handles barItemGridFontSize.EditValueChanged
        Try
            CONFIG.Config.GridFontSizeDelta = DirectCast(barItemGridFontSize.EditValue, FontSetting).Value
            CONFIG.Save()
            GridBuilder.WithFontSizeDelta(CONFIG.Config.GridFontSizeDelta)
        Catch ex As Exception
        End Try
    End Sub

    Private Sub GridViewWFItems_SelectionChanged(sender As Object, e As DevExpress.Data.SelectionChangedEventArgs) Handles GridViewWorkflows.SelectionChanged
        Timer_Inactivity_Reset_Disable("GridViewWFItems_SelectionChanged")
    End Sub

    Private Sub GridViewWFItems_Click(sender As Object, e As MouseEventArgs) Handles GridViewWorkflows.Click
        Try
            If e.Button = Windows.Forms.MouseButtons.Right Then
                RibbonControl1.SelectedPage = RibbonPageTabelle
            Else
                RibbonControl1.SelectedPage = RibbonPageStart
            End If
        Catch ex As Exception
            LOGGER.Error(ex)
        End Try
    End Sub

    Private Sub frmMain_FormClosed(sender As Object, e As FormClosedEventArgs) Handles Me.FormClosed
        Try
            'System.Diagnostics.Process.GetCurrentProcess().Kill()
        Catch ex As Exception

        End Try

    End Sub

    Private Sub GridViewWFItems_SubstituteFilter(sender As Object, e As DevExpress.Data.SubstituteFilterEventArgs) Handles GridViewWorkflows.SubstituteFilter
        GridLayout_Changed("GridViewWFItems_SubstituteFilter")
    End Sub

    Private Sub BbtnitmAHWF1_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BbtnitmAHWF1.ItemClick, BbtnitmAHWF2.ItemClick, BbtnitmAHWF3.ItemClick, BbtnitmAHWF4.ItemClick
        Dim obutton As DevExpress.XtraBars.BarButtonItem = TryCast(e.Item, DevExpress.XtraBars.BarButtonItem)
        AdHocWorkflow_BlindFile(obutton.Tag)
    End Sub
    Private Sub AdHocWorkflow_BlindFile(pProfileID As Int16)
        Try
            If Not Application.OpenForms().OfType(Of frmValidator).Any Then
                Dim oExpression = $"GUID = {pProfileID}"
                LOGGER.Debug($"Starting AHWFNoFile for ProfileID: {pProfileID}...")
                CURRENT_DT_PROFILE = Nothing
                CURRENT_DT_PROFILE = CURRENT_DT_PROFILES.Clone
                CURRENT_DT_PROFILES.Select(oExpression).CopyToDataTable(CURRENT_DT_PROFILE, LoadOption.PreserveChanges)
                If CURRENT_DT_PROFILE.Rows.Count = 1 Then
                    CURRENT_ProfilGUID = pProfileID
                    Dim sGUID As String
                    sGUID = System.Guid.NewGuid.ToString()
                    Dim oTargetPath = CURRENT_DT_PROFILE.Rows(0).Item("TARGET_PATH_BLIND_FILE")
                    Dim oSourcePath = CURRENT_DT_PROFILE.Rows(0).Item("WD_SEARCH")
                    Dim oWMObjecttype = CURRENT_DT_PROFILE.Rows(0).Item("WD_OBJECTTYPE")
                    LOGGER.Debug($"oTargetPath: {oTargetPath}")
                    LOGGER.Debug($"oSourcePath: {oSourcePath}")
                    If oTargetPath = String.Empty Or oSourcePath = String.Empty Then
                        Exit Sub
                    End If
                    oTargetPath = $"{oTargetPath}\{Now.Year}\{Now.Month}\{Now.Day}"
                    oTargetPath = oTargetPath & "\" & sGUID & ".pdf"

                    LOGGER.Debug($"oTargetPath with NowParams: {oTargetPath}")

                    Dim oResult = WINDREAM_MOD.NewFileStream(oSourcePath, oTargetPath, oWMObjecttype)
                    If oResult = True Then
                        WM_AHWF_docPath = oTargetPath
                        Dim oDocID = WINDREAM_MOD.NewDocumentID
                        CURRENT_CLICKED_PROFILE_ID = pProfileID
                        PROFILE_SHOW_DOCUMENT = CURRENT_DT_PROFILE.Rows(0).Item("SHOW_DOCUMENT")
                        CURRENT_CLICKED_PROFILE_TITLE = CURRENT_DT_PROFILE.Rows(0).Item("TITLE")

                        CURRENT_WMObjecttype = CURRENT_DT_PROFILE.Rows(0).Item("WD_OBJECTTYPE")
                        CURRENT_DOC_ID = oDocID
                        CURRENT_DOC_GUID = 99123456789
                        ActiveWorkflowType = ConstAHWorkflow_BlindFile
                        CURRENT_JUMP_DOC_GUID = CURRENT_DOC_GUID
                        DT_FILTERED_PROFILE_SEARCHES_DOC = Nothing
                        DT_FILTERED_PROFILE_SEARCHES_DOC = BASEDATA_DT_PROFILES_SEARCHES_DOC.Copy
                        DT_FILTERED_PROFILE_SEARCHES_DOC.Clear()
                        oExpression = $"PROFILE_ID = {CURRENT_ProfilGUID}"
                        BASEDATA_DT_PROFILES_SEARCHES_DOC.Select(oExpression, "TAB_INDEX").CopyToDataTable(DT_FILTERED_PROFILE_SEARCHES_DOC, LoadOption.PreserveChanges)

                        BASEDATA_DT_PROFILE_SEARCHES_SQL = Nothing
                        BASEDATA_DT_PROFILE_SEARCHES_SQL = BASEDATA_DT_PROFILES_SEARCHES_SQL.Copy
                        BASEDATA_DT_PROFILE_SEARCHES_SQL.Clear()
                        BASEDATA_DT_PROFILES_SEARCHES_SQL.Select(oExpression, "TAB_INDEX").CopyToDataTable(BASEDATA_DT_PROFILE_SEARCHES_SQL, LoadOption.PreserveChanges)

                        Try
                            Dim oEnvironment = GetEnvironment()

                            _FormValidator = New frmValidator(oEnvironment)
                            AddHandler _FormValidator.FormClosed, AddressOf ValidatorClosed
                            _FormValidator.Show()
                        Catch ex As Exception
                            LOGGER.Warn($"Error opening Form frmValidator [{ex.Message}]")
                            LOGGER.Warn($"ex.InnerException.Message [{ex.InnerException.Message}]")
                            LOGGER.Warn($"ex.InnerException.Source [{ex.InnerException.Source}]")
                            LOGGER.Error(ex.InnerException)
                            MsgBox(ex.Message, MsgBoxStyle.Critical, ADDITIONAL_TITLE)
                        End Try


                    End If
                Else
                    LOGGER.Info("Attention: CURRENT_DT_PROFILE.Rows.Count <> 1")
                End If

            Else
                FormHelper.ShowInfoMessage(S.Bitte_schließen_Sie_den_offenen_Workflow_, omsgTitleWarning)
                Exit Sub
            End If

        Catch ex As Exception
            LOGGER.Error(ex)
        End Try
    End Sub

    Private Sub bbtnitmLanguage_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbtnitmLanguage_Change.ItemClick
        Dim oNForm As New frmLanguage_Select(LOGCONFIG, CONNECTION_STRING_ECM, USER_USERNAME, BASEDATA_DT_LANGUAGE, "TF")
        oNForm.ShowDialog()

        If oNForm.pChanged = True Then
            MsgBox("For the changes to take effect, the program must now be closed. Restart it afterwards.", MsgBoxStyle.Exclamation, "Restart:")
            Me.Close()
        End If
    End Sub

    Private Sub BBtnItmNotfications_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BBtnItmNotfications.ItemClick
        Open_Notifications_Form()
    End Sub

    Private Sub GridViewWFItems_Click(sender As Object, e As EventArgs) Handles GridViewWorkflows.Click

    End Sub

    Private Async Sub BarButtonItem3_ItemClick_2(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemResetLayout.ItemClick
        LOGGER.Info("User clicked reset layout")
        Await GridLayout_Reset(True)
    End Sub

    Private Sub barbtnitmsaveLogfiles_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles barbtnitmsaveLogfiles.ItemClick
        ClassAllgemeineFunktionen.Save_Logfiles()
    End Sub
End Class