Imports System.ComponentModel
Imports System.Data.SqlClient
Imports System.IO
Imports System.Runtime.InteropServices
Imports DevExpress.Utils
Imports DevExpress.XtraGrid
Imports DevExpress.XtraGrid.Columns
Imports DevExpress.XtraGrid.Views.Base
Imports DevExpress.XtraGrid.Views.Grid
Imports DevExpress.XtraTab
Imports DigitalData.GUIs.Common
Imports DigitalData.GUIs.Common.DocumentResultList
Imports DigitalData.Modules.Base
Imports DigitalData.Modules.EDMI.API.Constants
Imports DigitalData.Modules.EDMI.API.DatabaseWithFallback
Imports DigitalData.Modules.ZooFlow
Imports DigitalData.Modules.ZooFlow.Constants

Public Class frmValidatorSearch
    <DllImport("Shell32", CharSet:=CharSet.Auto, SetLastError:=True)>
    Public Shared Function ShellExecuteEx(ByRef lpExecInfo As SHELLEXECUTEINFO) As Boolean
    End Function
    Public Structure SHELLEXECUTEINFO
        Public cbSize As Integer
        Public fMask As Integer
        Public hwnd As IntPtr
        <MarshalAs(UnmanagedType.LPTStr)> Public lpVerb As String
        <MarshalAs(UnmanagedType.LPTStr)> Public lpFile As String
        <MarshalAs(UnmanagedType.LPTStr)> Public lpParameters As String
        <MarshalAs(UnmanagedType.LPTStr)> Public lpDirectory As String
        Dim nShow As Integer
        Dim hInstApp As IntPtr
        Dim lpIDList As IntPtr
        <MarshalAs(UnmanagedType.LPTStr)> Public lpClass As String
        Public hkeyClass As IntPtr
        Public dwHotKey As Integer
        Public hIcon As IntPtr
        Public hProcess As IntPtr
    End Structure
#Region "Laufzeitvariablen & Konstanten"
    Private Const SEE_MASK_INVOKEIDLIST = &HC
    Private Const SEE_MASK_NOCLOSEPROCESS = &H40
    Private Const SEE_MASK_FLAG_NO_UI = &H400
    Public Const SW_SHOW As Short = 5
#End Region
    Public formLoaded As Boolean = False
    Public _DTDocSearches As DataTable
    Public _DTDATASearches As DataTable
    Private _frmValidator As frmValidator 'You need a reference to Form1
    Private Shared BW_DocPath As String
    Private Shared BW_DocID As Integer
    Private LastDocID As Int64 = 0
    Private Documentloader As Loader
    Private Property OperationMode As OperationMode
    Private ReadOnly Environment As Environment
    Private _documentPathHandler As DocumentPathHandler
    Private _suppressTabEvents As Boolean = False

    Public Sub New(pfrmValidator As frmValidator, pEnvironment As Environment)

        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()
        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.
        _frmValidator = pfrmValidator
        Environment = pEnvironment
    End Sub
    Private Function GetOperationMode() As OperationMode
        Dim oOperationMode As OperationMode
        If Environment.Service.Client Is Nothing Then
            Return OperationMode.NoAppServer
        End If

        If Environment.Service.Client.IsOnline AndAlso Environment.Service.Client.ServerAddress <> String.Empty And IDB_USES_WMFILESTORE = False Then
            oOperationMode = OperationMode.WithAppServer
        Else
            oOperationMode = OperationMode.NoAppServer
        End If
        If OPERATION_MODE_FS = ClassConstants.OpModeFS_ZF Then
            oOperationMode = OperationMode.ZooFlow
        End If

        Return oOperationMode
    End Function
    Public Sub TabPreload(TabCountSQL As Integer, TabCountDoc As Integer, DTSQL As DataTable, DTDOC As DataTable)
        Try
            LOGGER.Debug("=== TabPreload START ===")
            LOGGER.Debug($"Parameters: TabCountSQL={TabCountSQL}, TabCountDoc={TabCountDoc}, DTSQL.Rows={If(DTSQL?.Rows.Count, 0)}, DTDOC.Rows={If(DTDOC?.Rows.Count, 0)}")

            ' Validierung der Parameter
            If DTSQL Is Nothing Then
                LOGGER.Warn("⚠️ DTSQL ist Nothing")
                DTSQL = New DataTable()
            End If
            If DTDOC Is Nothing Then
                LOGGER.Warn("⚠️ DTDOC ist Nothing")
                DTDOC = New DataTable()
            End If

            ' Thread-Synchronisation
            If Me.InvokeRequired() Then
                LOGGER.Debug("InvokeRequired=True, rufe auf UI-Thread auf")
                Me.Invoke(Sub() TabPreload(TabCountSQL, TabCountDoc, DTSQL, DTDOC))
                Return
            End If

            LOGGER.Debug("Ausführung auf UI-Thread")

            ' ============================================================
            ' WICHTIG: Variablen VOR Try-Block deklarieren
            ' ============================================================
            Dim hasSQLData As Boolean = False
            Dim hasDocData As Boolean = False
            Dim actualSQLTabCount As Integer = 0
            Dim actualDocTabCount As Integer = 0

            ' ============================================================
            ' KRITISCH: Events DEAKTIVIEREN während der Rekonfiguration
            ' ============================================================
            _suppressTabEvents = True
            LOGGER.Debug("🚫 Tab-Events deaktiviert")

            Try
                ' KRITISCH: DataTables SOFORT zuweisen
                _DTDATASearches = DTSQL
                _DTDocSearches = DTDOC
                LOGGER.Debug($"✓ _DTDATASearches und _DTDocSearches zugewiesen: SQL={_DTDATASearches.Rows.Count}, Doc={_DTDocSearches.Rows.Count}")

                ' TabCount-Validierung
                actualSQLTabCount = Math.Min(TabCountSQL, DTSQL.Rows.Count)
                actualDocTabCount = Math.Min(TabCountDoc, DTDOC.Rows.Count)

                If actualSQLTabCount <> TabCountSQL Then
                    LOGGER.Warn($"⚠️ TabCountSQL korrigiert: {TabCountSQL} → {actualSQLTabCount}")
                End If
                If actualDocTabCount <> TabCountDoc Then
                    LOGGER.Warn($"⚠️ TabCountDoc korrigiert: {TabCountDoc} → {actualDocTabCount}")
                End If

                ' Panel-Sichtbarkeit
                hasSQLData = DTSQL.Rows.Count > 0 AndAlso actualSQLTabCount > 0
                hasDocData = DTDOC.Rows.Count > 0 AndAlso actualDocTabCount > 0

                SplitContainerSearches.Panel1Collapsed = Not hasSQLData
                SplitContainerSearches.Panel2Collapsed = Not hasDocData

                LOGGER.Debug($"Panel1Collapsed (SQL)={SplitContainerSearches.Panel1Collapsed}, Panel2Collapsed (Doc)={SplitContainerSearches.Panel2Collapsed}")

                ' ============================================================
                ' KRITISCH: DocumentViewer nur bei Doc-Searches sichtbar
                ' ============================================================
                If hasDocData Then
                    If Not DocumentViewer1.Visible Then
                        DocumentViewer1.Visible = True
                        LOGGER.Debug("✓ DocumentViewer1 sichtbar gemacht (Doc-Searches vorhanden)")
                    End If
                Else
                    If DocumentViewer1.Visible Then
                        DocumentViewer1.Visible = False
                        LOGGER.Debug("✓ DocumentViewer1 ausgeblendet (keine Doc-Searches)")
                    End If
                End If

                ' #### SQL Tabs konfigurieren
                If hasSQLData Then
                    LOGGER.Debug($"Konfiguriere SQL-Tabs: {DTSQL.Rows.Count} Definitionen")

                    ' ALLE Tabs unsichtbar machen
                    For p As Integer = 0 To XtraTabControlSQL.TabPages.Count - 1
                        XtraTabControlSQL.TabPages(p).PageVisible = False
                    Next
                    LOGGER.Debug($"Alle {XtraTabControlSQL.TabPages.Count} SQL-Tabs auf PageVisible=False gesetzt")

                    ' Nur benötigte Tabs sichtbar machen
                    Dim processedTabs As Integer = 0
                    For p As Integer = 0 To Math.Min(actualSQLTabCount - 1, XtraTabControlSQL.TabPages.Count - 1)
                        If p < DTSQL.Rows.Count Then
                            Try
                                Dim tabTitle As String = If(DTSQL.Rows(p).Item("TAB_TITLE")?.ToString(), $"Tab {p + 1}")
                                XtraTabControlSQL.TabPages(p).Text = tabTitle
                                XtraTabControlSQL.TabPages(p).PageVisible = True
                                processedTabs += 1
                                LOGGER.Debug($"SQL-Tab {p}: Text='{tabTitle}', PageVisible=True")
                            Catch ex As Exception
                                LOGGER.Error($"❌ Fehler beim Konfigurieren von SQL-Tab {p}", ex)
                            End Try
                        End If
                    Next

                    LOGGER.Info($"✓ {processedTabs} SQL-Tabs konfiguriert")
                Else
                    LOGGER.Debug("Keine SQL-Daten, alle Tabs ausblenden")
                    For p As Integer = 0 To XtraTabControlSQL.TabPages.Count - 1
                        XtraTabControlSQL.TabPages(p).PageVisible = False
                    Next
                End If

                ' #### Doc Tabs konfigurieren
                If hasDocData Then
                    LOGGER.Debug($"Konfiguriere Doc-Tabs: {DTDOC.Rows.Count} Definitionen")

                    ' ALLE Tabs unsichtbar machen
                    For p As Integer = 0 To XtraTabControlDocs.TabPages.Count - 1
                        XtraTabControlDocs.TabPages(p).PageVisible = False
                    Next
                    LOGGER.Debug($"Alle {XtraTabControlDocs.TabPages.Count} Doc-Tabs auf PageVisible=False gesetzt")

                    ' Nur benötigte Tabs sichtbar machen
                    Dim processedTabs As Integer = 0
                    For p As Integer = 0 To Math.Min(actualDocTabCount - 1, XtraTabControlDocs.TabPages.Count - 1)
                        If p < DTDOC.Rows.Count Then
                            Try
                                Dim tabTitle As String = If(DTDOC.Rows(p).Item("TAB_TITLE")?.ToString(), $"Tab {p + 1}")
                                XtraTabControlDocs.TabPages(p).Text = tabTitle
                                XtraTabControlDocs.TabPages(p).PageVisible = True
                                processedTabs += 1
                                LOGGER.Debug($"Doc-Tab {p}: Text='{tabTitle}', PageVisible=True")
                            Catch ex As Exception
                                LOGGER.Error($"❌ Fehler beim Konfigurieren von Doc-Tab {p}", ex)
                            End Try
                        End If
                    Next

                    LOGGER.Info($"✓ {processedTabs} Doc-Tabs konfiguriert")
                Else
                    LOGGER.Debug("Keine Doc-Daten, alle Tabs ausblenden")
                    For p As Integer = 0 To XtraTabControlDocs.TabPages.Count - 1
                        XtraTabControlDocs.TabPages(p).PageVisible = False
                    Next
                End If

            Finally
                ' ============================================================
                ' KRITISCH: Events REAKTIVIEREN nach Rekonfiguration
                ' ============================================================
                _suppressTabEvents = False
                LOGGER.Debug("✓ Tab-Events reaktiviert")
            End Try

            ' JETZT manuell den ersten sichtbaren Tab aktivieren
            ' ERSETZE im unteren Teil von TabPreload den SQL-Block:
            If hasSQLData AndAlso XtraTabControlSQL.TabPages.Count > 0 Then
                Dim firstVisibleSqlIndex As Integer = -1
                For i As Integer = 0 To XtraTabControlSQL.TabPages.Count - 1
                    If XtraTabControlSQL.TabPages(i).PageVisible Then
                        firstVisibleSqlIndex = i
                        Exit For
                    End If
                Next

                If firstVisibleSqlIndex >= 0 AndAlso _DTDATASearches IsNot Nothing AndAlso firstVisibleSqlIndex < _DTDATASearches.Rows.Count Then
                    LOGGER.Debug($"Setze SQL SelectedTabPageIndex manuell auf {firstVisibleSqlIndex}")

                    Dim prevSuppress As Boolean = _suppressTabEvents
                    _suppressTabEvents = True
                    XtraTabControlSQL.SelectedTabPageIndex = firstVisibleSqlIndex
                    _suppressTabEvents = prevSuppress

                    Try
                        Dim selectedRow As DataRow = _DTDATASearches.Rows(firstVisibleSqlIndex)
                        Dim oConID As Integer = If(IsDBNull(selectedRow.Item("CONN_ID")), 1, CInt(selectedRow.Item("CONN_ID")))
                        Dim oCommand As String = selectedRow.Item("SQL_COMMAND")?.ToString()
                        Dim oTabCaption As String = If(selectedRow.Item("TAB_TITLE")?.ToString(), $"Tab {firstVisibleSqlIndex}")

                        If Not String.IsNullOrEmpty(oCommand) Then
                            oCommand = clsPatterns.ReplaceAllValues(oCommand, _frmValidator.PanelValidatorControl, True)
                            LOGGER.Debug($"SQL-Tab {firstVisibleSqlIndex}: erzwungener Initial-Refresh")
                            RefreshTabSQL(oConID, oCommand, firstVisibleSqlIndex, oTabCaption)
                        End If
                    Catch ex As Exception
                        LOGGER.Error("❌ Fehler beim SQL-Initial-Refresh in TabPreload", ex)
                    End Try
                End If
            End If

            ' ERSETZE im unteren Teil von TabPreload den Doc-Block:
            If hasDocData AndAlso XtraTabControlDocs.TabPages.Count > 0 Then
                Dim firstVisibleDocIndex As Integer = -1
                For i As Integer = 0 To XtraTabControlDocs.TabPages.Count - 1
                    If XtraTabControlDocs.TabPages(i).PageVisible Then
                        firstVisibleDocIndex = i
                        Exit For
                    End If
                Next

                If firstVisibleDocIndex >= 0 AndAlso _DTDocSearches IsNot Nothing AndAlso firstVisibleDocIndex < _DTDocSearches.Rows.Count Then
                    LOGGER.Debug($"Setze Doc SelectedTabPageIndex manuell auf {firstVisibleDocIndex}")

                    Dim prevSuppress As Boolean = _suppressTabEvents
                    _suppressTabEvents = True
                    XtraTabControlDocs.SelectedTabPageIndex = firstVisibleDocIndex
                    _suppressTabEvents = prevSuppress

                    Try
                        Dim selectedRow As DataRow = _DTDocSearches.Rows(firstVisibleDocIndex)
                        Dim oConID As Integer = If(IsDBNull(selectedRow.Item("CONN_ID")), 1, CInt(selectedRow.Item("CONN_ID")))
                        Dim oCommand As String = selectedRow.Item("SQL_COMMAND")?.ToString()
                        Dim oTabCaption As String = If(selectedRow.Item("TAB_TITLE")?.ToString(), $"Tab {firstVisibleDocIndex}")

                        If Not String.IsNullOrEmpty(oCommand) Then
                            oCommand = clsPatterns.ReplaceAllValues(oCommand, _frmValidator.PanelValidatorControl, True)
                            LOGGER.Debug($"Doc-Tab {firstVisibleDocIndex}: erzwungener Initial-Refresh")
                            RefreshTabDoc(oConID, oCommand, firstVisibleDocIndex, oTabCaption)
                        End If
                    Catch ex As Exception
                        LOGGER.Error("❌ Fehler beim Doc-Initial-Refresh in TabPreload", ex)
                    End Try
                End If
            End If

            LOGGER.Debug("=== TabPreload END ===")

        Catch ex As Exception
            LOGGER.Error("❌ Fehler in TabPreload", ex)
            LOGGER.Error($"Stack Trace: {ex.StackTrace}")
            _suppressTabEvents = False ' Sicherstellung

            Try
                SplitContainerSearches.Panel1Collapsed = True
                SplitContainerSearches.Panel2Collapsed = True
                DocumentViewer1.Visible = False
            Catch collapseEx As Exception
                LOGGER.Error("❌ Fehler beim Kollabieren der Panels", collapseEx)
            End Try
        End Try
    End Sub
    Private Sub XtraTabControlSQL_SelectedPageChanged(sender As Object, e As TabPageChangedEventArgs) Handles XtraTabControlSQL.SelectedPageChanged
        Try
            ' KRITISCH: Event unterdrücken während TabPreload läuft
            If _suppressTabEvents Then
                LOGGER.Debug($"🚫 XtraTabControlSQL_SelectedPageChanged unterdrückt (SelectedTabPageIndex={XtraTabControlSQL.SelectedTabPageIndex})")
                Exit Sub
            End If

            LOGGER.Debug($"=== XtraTabControlSQL_SelectedPageChanged START - SelectedTabPageIndex={XtraTabControlSQL.SelectedTabPageIndex} ===")

            If _DTDATASearches Is Nothing Then
                LOGGER.Warn("⚠️ _DTDATASearches ist Nothing - Exit Sub")
                Exit Sub
            End If
            If XtraTabControlSQL.SelectedTabPageIndex >= 0 AndAlso
                Not XtraTabControlSQL.TabPages(XtraTabControlSQL.SelectedTabPageIndex).PageVisible Then
                LOGGER.Debug("SQL-Tab ist nicht sichtbar - Exit Sub")
                Exit Sub
            End If

            If XtraTabControlSQL.SelectedTabPageIndex >= _DTDATASearches.Rows.Count Then
                LOGGER.Error($"❌ SelectedTabPageIndex ({XtraTabControlSQL.SelectedTabPageIndex}) >= _DTDATASearches.Rows.Count ({_DTDATASearches.Rows.Count}) - Exit Sub")
                Exit Sub
            End If

            Dim selectedRow As DataRow = _DTDATASearches.Rows(XtraTabControlSQL.SelectedTabPageIndex)
            Dim oConID As Integer = If(IsDBNull(selectedRow.Item("CONN_ID")), 1, CInt(selectedRow.Item("CONN_ID")))
            Dim oCommand As String = selectedRow.Item("SQL_COMMAND")?.ToString()
            Dim oTabIndex As Integer = XtraTabControlSQL.SelectedTabPageIndex
            Dim oTabCaption As String = If(selectedRow.Item("TAB_TITLE")?.ToString(), $"Tab {oTabIndex}")

            LOGGER.Debug($"Tab-Info: '{oTabCaption}', ConID={oConID}, TabIndex={oTabIndex}")

            If String.IsNullOrEmpty(oCommand) Then
                LOGGER.Warn($"⚠️ SQL_COMMAND ist leer für Tab '{oTabCaption}' - Exit Sub")
                Exit Sub
            End If

            oCommand = clsPatterns.ReplaceAllValues(oCommand, _frmValidator.PanelValidatorControl, True)
            LOGGER.Debug($"SQL ersetzt, Länge={oCommand.Length} Zeichen")

            ' ============================================================
            ' KRITISCH: RefreshTabSQL aufrufen!
            ' ============================================================
            LOGGER.Debug($"Rufe RefreshTabSQL auf für Tab '{oTabCaption}'")
            RefreshTabSQL(oConID, oCommand, oTabIndex, oTabCaption)

            LOGGER.Debug("=== XtraTabControlSQL_SelectedPageChanged END ===")

        Catch ex As Exception
            LOGGER.Error("❌ Fehler in XtraTabControlSQL_SelectedPageChanged", ex)
            LOGGER.Error($"Details: SelectedTabPageIndex={XtraTabControlSQL.SelectedTabPageIndex}, _DTDATASearches.Rows.Count={If(_DTDATASearches?.Rows.Count, 0)}")
        End Try
    End Sub

    Private Sub XtraTabControlDocs_SelectedPageChanged_1(sender As Object, e As TabPageChangedEventArgs) Handles XtraTabControlDocs.SelectedPageChanged
        Try
            ' KRITISCH: Event unterdrücken während TabPreload läuft
            If _suppressTabEvents Then
                LOGGER.Debug($"🚫 XtraTabControlDocs_SelectedPageChanged unterdrückt (SelectedTabPageIndex={XtraTabControlDocs.SelectedTabPageIndex})")
                Exit Sub
            End If

            LOGGER.Debug($"=== XtraTabControlDocs_SelectedPageChanged START - SelectedTabPageIndex={XtraTabControlDocs.SelectedTabPageIndex} ===")

            If _DTDocSearches Is Nothing Then
                LOGGER.Warn("⚠️ _DTDocSearches ist Nothing - Exit Sub")
                Exit Sub
            End If

            If XtraTabControlDocs.SelectedTabPageIndex < 0 Then
                LOGGER.Debug("SelectedTabPageIndex < 0 - Exit Sub")
                Exit Sub
            End If

            If XtraTabControlDocs.SelectedTabPageIndex >= _DTDocSearches.Rows.Count Then
                LOGGER.Error($"❌ SelectedTabPageIndex ({XtraTabControlDocs.SelectedTabPageIndex}) >= _DTDocSearches.Rows.Count ({_DTDocSearches.Rows.Count}) - Exit Sub")
                Exit Sub
            End If

            Dim selectedRow As DataRow = _DTDocSearches.Rows(XtraTabControlDocs.SelectedTabPageIndex)
            Dim oConID As Integer = If(IsDBNull(selectedRow.Item("CONN_ID")), 1, CInt(selectedRow.Item("CONN_ID")))
            Dim oCommand As String = selectedRow.Item("SQL_COMMAND")?.ToString()
            Dim oTabIndex As Integer = XtraTabControlDocs.SelectedTabPageIndex
            Dim oTabCaption As String = If(selectedRow.Item("TAB_TITLE")?.ToString(), $"Tab {oTabIndex}")

            LOGGER.Debug($"Tab-Info: '{oTabCaption}', ConID={oConID}, TabIndex={oTabIndex}")

            If String.IsNullOrEmpty(oCommand) Then
                LOGGER.Warn($"⚠️ SQL_COMMAND ist leer für Tab '{oTabCaption}' - Exit Sub")
                Exit Sub
            End If

            oCommand = clsPatterns.ReplaceAllValues(oCommand, _frmValidator.PanelValidatorControl, True)
            LOGGER.Debug($"SQL ersetzt, Länge={oCommand.Length} Zeichen")

            ' ============================================================
            ' KRITISCH: RefreshTabDoc aufrufen!
            ' ============================================================
            LOGGER.Debug($"Rufe RefreshTabDoc auf für Tab '{oTabCaption}'")
            RefreshTabDoc(oConID, oCommand, oTabIndex, oTabCaption)

            LOGGER.Debug("=== XtraTabControlDocs_SelectedPageChanged END ===")

        Catch ex As Exception
            LOGGER.Error("❌ Fehler in XtraTabControlDocs_SelectedPageChanged", ex)
            LOGGER.Error($"Details: SelectedTabPageIndex={XtraTabControlDocs.SelectedTabPageIndex}, _DTDocSearches.Rows.Count={If(_DTDocSearches?.Rows.Count, 0)}")
        End Try
    End Sub
    Public Sub RefreshTabSQL(ConID As Integer, SQLCommand As String, TabIndex As Integer, TabCaption As String)
        If Me.InvokeRequired() Then
            Me.Invoke(Sub() RefreshTabSQL(ConID, SQLCommand, TabIndex, TabCaption))
        Else
            'Code to refresh your textbox here
            Refresh_Load_GridSQL(ConID, SQLCommand, TabIndex, TabCaption)
        End If
    End Sub
    Public Sub RefreshTabDoc(ConID As Integer, SQLCommand As String, TabIndex As Integer, TabCaption As String)
        If Me.InvokeRequired() Then
            Me.Invoke(Sub() RefreshTabDoc(ConID, SQLCommand, TabIndex, TabCaption))
        Else
            'Code to refresh your textbox here
            Refresh_Load_GridDoc(ConID, SQLCommand, TabIndex, TabCaption)
        End If
    End Sub
    Sub Refresh_Load_GridSQL(ConID As Integer, SQLCommand As String, TabIndex As Integer, TabCaption As String)
        Try
            Dim myGridControl As DevExpress.XtraGrid.GridControl
            Dim myGridview As DevExpress.XtraGrid.Views.Grid.GridView
            Select Case TabIndex
                Case 0
                    GridControlSearch1.DataSource = Nothing
                    GridViewSearch1.Columns.Clear()
                    myGridview = GridViewSearch1
                    myGridControl = GridControlSearch1
                Case 1
                    GridControlSearch2.DataSource = Nothing
                    GridViewSearch2.Columns.Clear()
                    myGridview = GridViewSearch2
                    myGridControl = GridControlSearch2
                Case 2
                    GridControlSearch3.DataSource = Nothing
                    GridViewSearch3.Columns.Clear()
                    myGridview = GridViewSearch3
                    myGridControl = GridControlSearch3
                Case 3
                    GridControlSearch4.DataSource = Nothing
                    GridViewSearch4.Columns.Clear()
                    myGridview = GridViewSearch4
                    myGridControl = GridControlSearch4
                Case 4
                    GridControlSearch5.DataSource = Nothing
                    GridViewSearch5.Columns.Clear()
                    myGridview = GridViewSearch5
                    myGridControl = GridControlSearch5
            End Select
            myGridControl.ContextMenuStrip = ContextMenuStripSQL
            'Dim oDatatable As DataTable = ClassDatabase.Return_Datatable_ConId(SQLCommand, ConID)
            Dim oDatatable As DataTable = DatabaseFallback.GetDatatable(New GetDatatableOptions(SQLCommand, DatabaseType.ECM) With {
                .ConnectionId = ConID
            })

            If Not IsNothing(oDatatable) Then
                XtraTabControlSQL.TabPages(TabIndex).Text = $"{TabCaption} ({oDatatable.Rows.Count})"
                Select Case TabIndex
                    Case 0
                        GridControlSearch1.DataSource = oDatatable
                        GridViewSearch1.BestFitColumns(True)
                    Case 1
                        GridControlSearch2.DataSource = oDatatable
                        GridViewSearch2.BestFitColumns(True)
                    Case 2
                        GridControlSearch3.DataSource = oDatatable
                        GridViewSearch3.BestFitColumns(True)
                    Case 3
                        GridControlSearch4.DataSource = oDatatable
                        GridViewSearch4.BestFitColumns(True)
                    Case 4
                        GridControlSearch5.DataSource = oDatatable
                        GridViewSearch5.BestFitColumns(True)

                End Select
                tsslblSQL.Text = $"Tab [{TabCaption}] refreshed - {Now}"
            End If
        Catch ex As Exception
            LOGGER.Error(ex)
        End Try
    End Sub
    Sub Refresh_Load_GridDoc(ConID As Integer, SQLCommand As String, TabIndex As Integer, TabCaption As String)
        Try
            Dim myGridControl As DevExpress.XtraGrid.GridControl
            Dim myGridview As DevExpress.XtraGrid.Views.Grid.GridView
            Select Case TabIndex
                Case 0
                    GridControlDocSearch1.DataSource = Nothing
                    GridViewDocSearch1.Columns.Clear()
                    myGridview = GridViewDocSearch1
                    myGridControl = GridControlDocSearch1
                Case 1
                    GridControlDocSearch2.DataSource = Nothing
                    GridViewDocSearch2.Columns.Clear()
                    myGridview = GridViewDocSearch2
                    myGridControl = GridControlDocSearch2
                Case 2
                    GridControlDocSearch3.DataSource = Nothing
                    GridViewDocSearch3.Columns.Clear()
                    myGridview = GridViewDocSearch3
                    myGridControl = GridControlDocSearch3
                Case 3
                    GridControlDocSearch4.DataSource = Nothing
                    GridViewDocSearch4.Columns.Clear()
                    myGridControl = GridControlDocSearch4
                    myGridview = GridViewDocSearch4
                Case 4
                    GridControlDocSearch5.DataSource = Nothing
                    GridViewDocSearch5.Columns.Clear()
                    myGridControl = GridControlDocSearch5
                    myGridview = GridViewDocSearch5
            End Select
            myGridControl.ContextMenuStrip = ContextMenuStripWMFile

            Dim oDatatable As DataTable = DatabaseFallback.GetDatatable(New GetDatatableOptions(SQLCommand, DatabaseType.ECM) With {
            .ConnectionId = ConID
        })

            If Not IsNothing(oDatatable) Then
                XtraTabControlDocs.TabPages(TabIndex).Text = $"{TabCaption} ({oDatatable.Rows.Count})"

                ' FIX: Nicht jedes Doc-Tab liefert echte Dokumentspalten
                Dim hasDocId As Boolean = oDatatable.Columns.Contains("DocID")
                Dim hasFullFilename As Boolean = oDatatable.Columns.Contains("FULL_FILENAME")

                If Not hasDocId OrElse Not hasFullFilename Then
                    LOGGER.Warn($"⚠️ Refresh_Load_GridDoc: Tab [{TabCaption}] liefert kein Dokument-Schema (DocID/FULL_FILENAME fehlt). Fallback auf Standard-Grid.")
                    myGridControl.DataSource = oDatatable
                    myGridview.BestFitColumns(True)
                    clsWMDocGrid.DTDocuments = Nothing
                    ToolStripDropDownButtonFile.Visible = False
                    tslblState.Text = $"Tab [{TabCaption}] refreshed (fallback grid) - {Now}"
                    Exit Sub
                End If

                clsWMDocGrid.DTDocuments = oDatatable
                Create_GridControl(myGridview, oDatatable)

                Dim oxmlPath As String = ""
                oxmlPath = Get_DocGrid_Layout_Filename(XtraTabControlDocs.SelectedTabPageIndex)

                If File.Exists(oxmlPath) Then
                    myGridview.RestoreLayoutFromXml(oxmlPath)
                    myGridview.GuessAutoFilterRowValuesFromFilter()
                End If
                tslblState.Text = $"Tab [{TabCaption}] refreshed - {Now}"
            Else
                clsWMDocGrid.DTDocuments = Nothing
            End If
        Catch ex As Exception
            LOGGER.Error(ex)
        End Try
    End Sub
    Private Function Create_GridControl(MyGridView As GridView, _datatable As DataTable) As GridView
        Dim oMyDocDatatable As New DataTable
        Try
            'Die Icon Colum erstellen und konfigurieren
            Dim oColIcon As New System.Data.DataColumn()
            oColIcon.DataType = GetType(Image)
            oColIcon.ColumnName = "ICON"
            oColIcon.Caption = ""
            oMyDocDatatable.Columns.Add(oColIcon)

            Dim oColPath As New System.Data.DataColumn()
            oColPath.DataType = GetType(String)
            oColPath.ColumnName = "FULL_FILENAME"
            oColPath.Caption = "Fullpath"
            oMyDocDatatable.Columns.Add(oColPath)
            Dim oColDocID As New System.Data.DataColumn()
            oColDocID.DataType = GetType(Int32)
            oColDocID.ColumnName = "DocID"
            oColDocID.Caption = "DocID"
            oMyDocDatatable.Columns.Add(oColDocID)
            Dim oRestColArray As New List(Of String)
            For Each oCol As DataColumn In _datatable.Columns
                Dim onewColumn As New System.Data.DataColumn()
                If oCol.ColumnName <> "DocID" And oCol.ColumnName <> "FULL_FILENAME" And oCol.ColumnName <> "Filename" Then

                    onewColumn.DataType = GetType(String)
                    onewColumn.ColumnName = oCol.ColumnName
                    onewColumn.Caption = oCol.Caption
                    oMyDocDatatable.Columns.Add(onewColumn)
                    oRestColArray.Add(onewColumn.ColumnName)
                End If

            Next
            For Each FILE_ROW As DataRow In _datatable.Rows
                Dim oFullpath = FILE_ROW.Item("FULL_FILENAME")
                Dim oDocID = FILE_ROW.Item("DocID")
                'Dim Folderpath = Path.GetDirectoryName(fullpath)
                Dim oFilename = Path.GetFileName(oFullpath)
                Dim oFileextension = Path.GetExtension(oFullpath)
                Dim oNewRow As DataRow
                oNewRow = oMyDocDatatable.NewRow()
                'Icon zuweisen
                Select Case oFileextension.ToUpper
                    Case ".csv".ToUpper
                        oNewRow.Item(0) = My.Resources.doc_excel_csv
                    Case ".txt".ToUpper
                        oNewRow.Item(0) = My.Resources.txt
                    Case ".pdf".ToUpper
                        oNewRow.Item(0) = My.Resources.pdf
                    Case ".doc".ToUpper
                        oNewRow.Item(0) = My.Resources.doc
                    Case ".docx".ToUpper
                        oNewRow.Item(0) = My.Resources.doc
                    Case ".xls".ToUpper
                        oNewRow.Item(0) = My.Resources.xls
                    Case ".xlsx".ToUpper
                        oNewRow.Item(0) = My.Resources.xls
                    Case ".xlsm".ToUpper
                        oNewRow.Item(0) = My.Resources.xls
                    Case ".ppt".ToUpper
                        oNewRow.Item(0) = My.Resources.ppt
                    Case ".pptx".ToUpper
                        oNewRow.Item(0) = My.Resources.ppt
                    Case ".dwg".ToUpper
                        oNewRow.Item(0) = My.Resources.dwg
                    Case ".dxf".ToUpper
                        oNewRow.Item(0) = My.Resources.dxf
                    Case ".msg".ToUpper
                        oNewRow.Item(0) = My.Resources.email_go
                    Case ".msg".ToUpper
                        oNewRow.Item(0) = My.Resources.email_go
                    Case Else
                        oNewRow.Item(0) = My.Resources._blank
                End Select
                'Den Filepath mitgeben
                oNewRow.Item(1) = oFullpath
                oNewRow.Item(2) = oDocID

                Dim i = 3 'Fängt bei 3 an, um die definierten Spalten zu überspringen
                For Each Colname As String In oRestColArray
                    Dim oRowValue
                    oRowValue = FILE_ROW.Item(Colname)
                    oNewRow.Item(i) = oRowValue.ToString
                    i += 1
                Next
                oMyDocDatatable.Rows.Add(oNewRow)
            Next
            Dim sdsd As String = ""






            Dim oGridControl As GridControl = MyGridView.GridControl
            oGridControl.DataSource = oMyDocDatatable
            oGridControl.ForceInitialize()
            Try
                MyGridView.Columns.Item("DocID").Visible = False
            Catch ex As Exception
            End Try
            Try
                MyGridView.Columns.Item("FULL_FILENAME").Visible = False
            Catch ex As Exception
            End Try

            Dim created, changed As String
            If USER_LANGUAGE <> "de-DE" Then
                changed = "Changed"
                created = "Created"
            Else
                changed = "Geändert"
                created = "Erstellt"
            End If

            Dim createdColumn = MyGridView.Columns(created)
            If Not IsNothing(createdColumn) Then
                createdColumn.DisplayFormat.FormatType = FormatType.DateTime
                createdColumn.DisplayFormat.FormatString = USER_DATE_FORMAT & " HH:MM:ss"
            End If

            Dim changedColumn = MyGridView.Columns(changed)
            If Not IsNothing(changedColumn) Then
                changedColumn.DisplayFormat.FormatType = FormatType.DateTime
                changedColumn.DisplayFormat.FormatString = USER_DATE_FORMAT & " HH:MM:ss"
            End If
            ' Alle Spalten aus ReadOnly setzen, danach werden alle passenden auf nicht ReadOnly gesetzt
            For Each column As GridColumn In MyGridView.Columns
                column.OptionsColumn.AllowEdit = False
            Next
            MyGridView.Columns.Item("ICON").MaxWidth = 24
            MyGridView.Columns.Item("ICON").MinWidth = 24
            MyGridView.OptionsView.BestFitMaxRowCount = -1
            MyGridView.BestFitColumns(True)
            Return MyGridView
        Catch ex As Exception
            LOGGER.Error(ex)
            Return Nothing
        End Try
    End Function
    Private Sub frmValidatorSearch_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        Try
            DocumentViewer1.Done()
        Catch ex As Exception
            LOGGER.Warn($"Unexpected error in DocumentViewerValSearch.Done: {ex.Message}")
        End Try
        Try
            ' Position und Größe speichern
            My.Settings.frmValidatorSearchSize = Me.Size
            My.Settings.frmValidatorSearchPosition = Me.Location
            My.Settings.frmValSearchSplitterDistance = SplitContainerSearches.SplitterDistance
            My.Settings.Save()
        Catch ex As Exception
            LOGGER.Error(ex)
            LOGGER.Info("Error in Save FormLayout: " & ex.Message)
        End Try

    End Sub

    Private Sub frmValidatorSearch_Load(sender As Object, e As EventArgs) Handles Me.Load
        Try
            DocumentViewer1.Init(LOGCONFIG, GDPICTURE_LICENSE, New DigitalData.Controls.DocumentViewer.DocumentViewer.ToolbarSettings() With {
            .ShowPrintButton = True,
            .ShowRotateButton = True,
            .ShowFlipButton = True,
            .ShowSettingButton = True
        })
        Catch ex As Exception
            LOGGER.Warn("⚠️ Error initializing DocViewDocsValdiatorSearch: " & ex.Message)
        End Try

        OperationMode = GetOperationMode()
        Documentloader = New Loader(LOGCONFIG, OperationMode, Environment.Service.Client, Environment.User)


        SplitContainerSearches.Panel1Collapsed = True
        If My.Settings.frmValidatorSearchPosition.IsEmpty = False Then
            If My.Settings.frmValidatorSearchPosition.X > 0 And My.Settings.frmValidatorSearchPosition.Y > 0 Then
                Location = My.Settings.frmValidatorSearchPosition
            End If
        End If
        If My.Settings.frmValidatorSearchSize.IsEmpty = False Then
            If My.Settings.frmValidatorSearchSize.Height > 120 And My.Settings.frmValidatorSearchSize.Width > 120 Then
                Me.Size = My.Settings.frmValidatorSearchSize
            End If
        End If
        If My.Settings.frmValSearchSplitterDistance > 20 Then
            SplitContainerSearches.SplitterDistance = My.Settings.frmValSearchSplitterDistance
        End If
        ' DocumentPathHandler initialisieren
        _documentPathHandler = New DocumentPathHandler(LOGCONFIG)

        ToolStripDropDownButtonFile.Visible = False
    End Sub

    Private Sub EnsureFormIsVisible()
        Try
            ' Aktuellen Bildschirm basierend auf der Formularposition ermitteln
            Dim currentScreen As Screen = Screen.FromPoint(Me.Location)
            Dim workingArea As Rectangle = currentScreen.WorkingArea

            ' Prüfen ob das Formular vollständig außerhalb des sichtbaren Bereichs liegt
            Dim formBounds As New Rectangle(Me.Location, Me.Size)

            ' Wenn das Formular nicht mit dem Arbeitsbereich überschneidet
            If Not workingArea.IntersectsWith(formBounds) Then
                CenterFormOnScreen()
                Exit Sub
            End If

            ' Optional: Prüfen ob das Formular zu weit außerhalb liegt (z.B. nur 20% sichtbar)
            Dim visibleArea As Rectangle = Rectangle.Intersect(workingArea, formBounds)
            Dim visiblePercentage As Double = (visibleArea.Width * visibleArea.Height) / (formBounds.Width * formBounds.Height)

            If visiblePercentage < 0.2 Then ' Weniger als 20% sichtbar
                CenterFormOnScreen()
            End If

        Catch ex As Exception
            LOGGER.Error(ex)
            ' Bei Fehler sicherheitshalber zentrieren
            CenterFormOnScreen()
        End Try
    End Sub

    Private Sub CenterFormOnScreen()
        Try
            ' Formular auf dem primären Bildschirm zentrieren
            Me.StartPosition = FormStartPosition.CenterScreen

            ' Alternative: Auf aktuellem Bildschirm zentrieren
            Dim currentScreen As Screen = Screen.PrimaryScreen
            Dim x As Integer = currentScreen.WorkingArea.Left + (currentScreen.WorkingArea.Width - Me.Width) \ 2
            Dim y As Integer = currentScreen.WorkingArea.Top + (currentScreen.WorkingArea.Height - Me.Height) \ 2
            Me.Location = New Point(x, y)

            LOGGER.Info("Formular wurde zentriert, da es außerhalb des sichtbaren Bereichs lag")
        Catch ex As Exception
            LOGGER.Error(ex)
        End Try
    End Sub
    Private Sub frmValidatorSearch_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        ' Prüfen ob das Formular im sichtbaren Bereich liegt
        EnsureFormIsVisible()
        formLoaded = True
    End Sub



    Private Sub EigenschaftenDateiToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles EigenschaftenDateiToolStripMenuItem.Click
        Show_File_Properties()
    End Sub
    Sub Show_File_Properties()
        If IsNothing(clsWMDocGrid.DTDocuments) Then
            MsgBox("Could not read file Parameters!", MsgBoxStyle.Exclamation)
            Exit Sub
        End If
        For Each oRow As DataRow In clsWMDocGrid.DTDocuments.Rows
            If oRow.Item("DOC_PATH") <> "" Then
                Cursor = Cursors.WaitCursor
                Dim sei As New SHELLEXECUTEINFO
                sei.cbSize = Marshal.SizeOf(sei)
                sei.lpVerb = "properties"
                sei.lpFile = oRow.Item("DOC_PATH")
                sei.nShow = SW_SHOW
                sei.fMask = SEE_MASK_INVOKEIDLIST
                If Not ShellExecuteEx(sei) Then
                    Dim ex As New System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error())
                    MsgBox("Error in Open file propertys: " & ex.Message, MsgBoxStyle.Critical)
                    LOGGER.Error(ex)
                End If
            End If
            Cursor = Cursors.Default
        Next
    End Sub
    Sub Refresh_DocID(myGrid As GridView)
        If myGrid Is Nothing Then
            LOGGER.Warn("⚠️ Refresh_DocID: myGrid is Nothing - Exit Sub")
            Return
        End If

        Try
            myGrid.ShowLoadingPanel()
            clsWMDocGrid.ActiveDocGrid = myGrid
            clsWMDocGrid.ActiveDocGrid.EndSelection()
            clsWMDocGrid.GetDocItems()

            If ToolStripDropDownButtonFile.Visible = False Then
                ToolStripDropDownButtonFile.Visible = True
            End If

            If clsWMDocGrid.SELECTED_DOC_ID = 0 Then
                tslblDocID.Text = "DocRow not selected"
                ToolStripDropDownButtonFile.Enabled = False
                Return
            End If

            If LastDocID = clsWMDocGrid.SELECTED_DOC_ID Then
                Return
            End If

            tslblDocID.Text = "DocID: " & clsWMDocGrid.SELECTED_DOC_ID.ToString
            ToolStripDropDownButtonFile.Enabled = True
            LOGGER.Debug($"✓ DocID aktualisiert: {clsWMDocGrid.SELECTED_DOC_ID}")
            If IsNothing(Documentloader) Then
                If OperationMode = Nothing Then
                    OperationMode = GetOperationMode()
                End If
                Documentloader = New Loader(LOGCONFIG, OperationMode, Environment.Service.Client, Environment.User)
            End If

            If _documentPathHandler Is Nothing Then
                _documentPathHandler = New DocumentPathHandler(LOGCONFIG)
            End If

            Dim oDocument As DocumentResultList.Document = Documentloader.Load(clsWMDocGrid.SELECTED_DOC_ID, clsWMDocGrid.SELECTED_DOC_PATH)

            If IsNothing(oDocument) Then
                LOGGER.Warn($"⚠️ Refresh_DocID: Documentloader.Load lieferte Nothing (DocID={clsWMDocGrid.SELECTED_DOC_ID})")
                statlbl.Text = "Dokument konnte nicht geladen werden."
                Return
            Else
                LOGGER.Debug($"✓ Documentloader.Load erfolgreich für DocID={clsWMDocGrid.SELECTED_DOC_ID}, Pfad: {clsWMDocGrid.SELECTED_DOC_PATH}")
            End If

            If Not IsNothing(DocumentViewer1) AndAlso Not IsNothing(oDocument.Contents) Then
                Dim options As New DocumentPathHandler.DocumentPathOptions With {
                    .EnableMapping = COPY_WMFILE_2TEMP AndAlso Not String.IsNullOrWhiteSpace(WMSUFFIX),
                    .WMSuffix = WMSUFFIX,
                    .SpecificDrive = If(Len(MAP_SHARE_DRIVE) = 1, MAP_SHARE_DRIVE, ""),
                    .DriveBlacklist = MAP_BLACKLIST,
                    .CopyToTemp = COPY_WMFILE_2TEMP,
                    .TempFolder = TEMP_DOCUMENT_FOLDER,
                    .UnmapAfterCopy = True
                }

                Dim result = _documentPathHandler.ProcessDocumentPath(clsWMDocGrid.SELECTED_DOC_PATH, options)

                If result.Success Then
                    DocumentViewer1.LoadFile_FromPath(result.FinalPath)
                    LastDocID = clsWMDocGrid.SELECTED_DOC_ID
                    DocumentViewer1.RightViewOnly(USER_RIGHT_VIEW_ONLY)
                    LOGGER.Debug($"✓ [ValidatorSearch] Dokument geladen: [{Path.GetFileName(result.FinalPath)}]")
                Else
                    LOGGER.Error($"❌ [ValidatorSearch] {result.ErrorMessage}")
                    statlbl.Text = $"Fehler: {result.ErrorMessage}"
                End If
            Else
                statlbl.Text = "Dokumentinhalt ist leer."
            End If

        Catch ex As Exception
            LOGGER.Error(ex)
        Finally
            Try
                myGrid.HideLoadingPanel()
            Catch
            End Try
        End Try
    End Sub
    Private Sub GridViewDocSearch_FocusedRowChanged(sender As Object, e As FocusedRowChangedEventArgs) Handles GridViewDocSearch1.FocusedRowChanged,
    GridViewDocSearch2.FocusedRowChanged,
    GridViewDocSearch3.FocusedRowChanged,
    GridViewDocSearch4.FocusedRowChanged,
    GridViewDocSearch5.FocusedRowChanged

        If Not Me.Visible Then
            Return
        End If

        Dim activeGrid As GridView = TryCast(sender, GridView)
        If activeGrid Is Nothing Then
            Return
        End If

        LOGGER.Debug($"FocusedRowChanged ausgelöst: [{activeGrid.Name}]")
        Refresh_DocID(activeGrid)
    End Sub

    Private Sub GridViewDocSearch_FocusedColumnChanged(sender As Object, e As FocusedColumnChangedEventArgs) Handles GridViewDocSearch1.FocusedColumnChanged,
    GridViewDocSearch2.FocusedColumnChanged,
    GridViewDocSearch3.FocusedColumnChanged,
    GridViewDocSearch4.FocusedColumnChanged,
    GridViewDocSearch5.FocusedColumnChanged

        If Not Me.Visible Then
            Return
        End If

        Dim activeGrid As GridView = TryCast(sender, GridView)
        If activeGrid Is Nothing Then
            Return
        End If

        LOGGER.Debug($"FocusedColumnChanged ausgelöst: [{activeGrid.Name}]")
        Refresh_DocID(activeGrid)
    End Sub

    Private Sub DateiÖffnenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles DateiÖffnenToolStripMenuItem.Click
        FileShow()

    End Sub
    Sub FileShow()
        Try
            If IsNothing(clsWMDocGrid.SELECTED_DOC_PATH) Then
                MsgBox("Could not read fileparameters(5)!", MsgBoxStyle.Exclamation)
                Exit Sub
            End If
            File_SYSOPEN(clsWMDocGrid.SELECTED_DOC_PATH, clsWMDocGrid.SELECTED_DOC_ID)
        Catch ex As Exception

        End Try
    End Sub
    Private Shared Sub File_SYSOPEN(RESULT_DOC_PATH As Object, DocID As String)
        Try
            If RESULT_DOC_PATH <> Nothing Then
                If File.Exists(RESULT_DOC_PATH) Then
                    BW_DocPath = RESULT_DOC_PATH
                    BW_DocID = DocID

                    Dim BWFileHandler As New BackgroundWorker
                    AddHandler BWFileHandler.DoWork, AddressOf BWFileHandler_DoWork
                    BWFileHandler.RunWorkerAsync()
                Else
                    MsgBox("Document is not existing or accessible!", MsgBoxStyle.Exclamation)

                End If

            Else
                LOGGER.Warn("⚠️ Attention: RESULT_DOC_PATH is nothing")
            End If
        Catch ex As Exception
            MsgBox("Unexpected Error in File_SYSOPEN:" & vbNewLine & ex.Message & vbNewLine & RESULT_DOC_PATH & vbNewLine & "DocID: " & DocID, MsgBoxStyle.Critical)
            LOGGER.Error(ex)
        End Try
    End Sub
    Private Shared Sub BWFileHandler_DoWork()
        Try

            Dim oMyProcess = New Process()

            Try
                'Dim oPSI As New ProcessStartInfo(BW_DocPath)
                oMyProcess.StartInfo.FileName = BW_DocPath
                oMyProcess.StartInfo.UseShellExecute = True
                oMyProcess.StartInfo.RedirectStandardOutput = False
                oMyProcess.Start()

                'oMyProcess.WaitForExit()
            Catch ex As Exception
                LOGGER.Error(ex)
                Exit Sub
            End Try

        Catch ex As Exception
            LOGGER.Error(ex)

            Try
                Process.Start(BW_DocPath)
            Catch ex1 As Exception
                LOGGER.Error(ex)

            End Try
        End Try
    End Sub
    Private Sub DateiÖffnenToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles DateiÖffnenToolStripMenuItem1.Click
        FileShow()
    End Sub

    Private Sub EigenschaftenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles EigenschaftenToolStripMenuItem.Click
        Show_File_Properties()
    End Sub
    Private Function Get_DocGrid_Layout_Filename(oIndex As Integer)
        Dim oUserConfigPath = USER_CONFIG_DIRECTORY
        Dim oFilename As String = String.Format("GridViewDoc_Search-{0}-{1}-{2}-UserLayout.xml", oIndex, CURRENT_ProfilGUID, USER_LANGUAGE)
        Dim oPath = System.IO.Path.Combine(oUserConfigPath, oFilename)
        Return oPath
    End Function
    Private Sub GridControlDocSearch_Leave(sender As Object, e As EventArgs) Handles GridControlDocSearch1.Leave, GridControlDocSearch2.Leave, GridControlDocSearch3.Leave, GridControlDocSearch4.Leave, GridControlDocSearch5.Leave
        SaveDocGridLayout()
    End Sub

    Sub SaveDocGridLayout()
        Dim oXMLPath = Get_DocGrid_Layout_Filename(XtraTabControlDocs.SelectedTabPageIndex)
        If File.Exists(oXMLPath) Then
            clsWMDocGrid.ActiveDocGrid.SaveLayoutToXml(oXMLPath)
        End If


    End Sub
    Private Sub ToolStripButtonRefreshSearches_Click(sender As Object, e As EventArgs) Handles ToolStripButtonRefreshSearches.Click
        If DT_FILTERED_PROFILE_SEARCHES_DATA.Rows.Count > 0 Then
            LOGGER.Debug($"There are [{DT_FILTERED_PROFILE_SEARCHES_DATA.Rows.Count}] DATASearches configured!")
            _DTDATASearches = DT_FILTERED_PROFILE_SEARCHES_DATA
            Dim oConID = DT_FILTERED_PROFILE_SEARCHES_DATA.Rows(0).Item("CONN_ID")
            Dim oCommand = DT_FILTERED_PROFILE_SEARCHES_DATA.Rows(0).Item("SQL_COMMAND")
            oCommand = clsPatterns.ReplaceAllValues(oCommand, _frmValidator.PanelValidatorControl, True)
            XtraTabControlSQL.SelectedTabPageIndex = 0
            Refresh_Load_GridSQL(oConID, oCommand, 0, DT_FILTERED_PROFILE_SEARCHES_DATA.Rows(0).Item("TAB_TITLE"))
        Else
            LOGGER.Debug("No DATASearches configured for this profile!")
        End If
        If DT_FILTERED_PROFILE_SEARCHES_DOC.Rows.Count > 0 Then
            LOGGER.Debug($"There are [{DT_FILTERED_PROFILE_SEARCHES_DOC.Rows.Count}] DocSearches configured!")
            _DTDocSearches = DT_FILTERED_PROFILE_SEARCHES_DOC
            Dim oConID = DT_FILTERED_PROFILE_SEARCHES_DOC.Rows(0).Item("CONN_ID")
            Dim oCommand = DT_FILTERED_PROFILE_SEARCHES_DOC.Rows(0).Item("SQL_COMMAND")
            oCommand = clsPatterns.ReplaceAllValues(oCommand, _frmValidator.PanelValidatorControl, True)
            XtraTabControlDocs.SelectedTabPageIndex = 0
            RefreshTabDoc(oConID, oCommand, 0, DT_FILTERED_PROFILE_SEARCHES_DOC.Rows(0).Item("TAB_TITLE"))
        Else
            LOGGER.Debug("No DocSearches configured for this profile!")
        End If
    End Sub

    Private Sub GridViewDocSearch_ColumnWidthChanged(sender As Object, e As ColumnEventArgs) Handles GridViewDocSearch1.ColumnWidthChanged, GridViewDocSearch2.ColumnWidthChanged, GridViewDocSearch3.ColumnWidthChanged, GridViewDocSearch4.ColumnWidthChanged, GridViewDocSearch5.ColumnWidthChanged
        SaveDocGridLayout()
    End Sub

    Private Sub ToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem1.Click
        ReLoad_Active_DocTab()
    End Sub
    Sub ReLoad_Active_DocTab()
        Dim oTabIndex = XtraTabControlDocs.SelectedTabPageIndex
        Dim oConID = DT_FILTERED_PROFILE_SEARCHES_DOC.Rows(oTabIndex).Item("CONN_ID")
        Dim oCommand = DT_FILTERED_PROFILE_SEARCHES_DOC.Rows(oTabIndex).Item("SQL_COMMAND")
        oCommand = clsPatterns.ReplaceAllValues(oCommand, _frmValidator.PanelValidatorControl, True)
        RefreshTabDoc(oConID, oCommand, oTabIndex, DT_FILTERED_PROFILE_SEARCHES_DOC.Rows(oTabIndex).Item("TAB_TITLE"))
    End Sub

    Private Sub LayoutZurücksetzenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles LayoutZurücksetzenToolStripMenuItem.Click
        Set_DoclayoutBack()

    End Sub
    Sub Set_DoclayoutBack()
        Dim oXMLPath = Get_DocGrid_Layout_Filename(XtraTabControlDocs.SelectedTabPageIndex)
        Try
            If File.Exists(oXMLPath) Then
                File.Delete(oXMLPath)
                ReLoad_Active_DocTab()
                tslblState.Text = "Layout has been set back!"
            Else
                tslblState.Text = ""
            End If

        Catch ex As Exception
            tslblState.Text = ""
        End Try


    End Sub
    Private Sub ToolStripMenuItem4_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem4.Click
        ReLoad_Active_SQLTab()
    End Sub
    Sub ReLoad_Active_SQLTab()
        Dim oTabIndex = XtraTabControlSQL.SelectedTabPageIndex
        Dim oConID = DT_FILTERED_PROFILE_SEARCHES_DATA.Rows(oTabIndex).Item("CONN_ID")
        Dim oCommand = DT_FILTERED_PROFILE_SEARCHES_DATA.Rows(oTabIndex).Item("SQL_COMMAND")
        oCommand = clsPatterns.ReplaceAllValues(oCommand, _frmValidator.PanelValidatorControl, True)
        RefreshTabSQL(oConID, oCommand, oTabIndex, DT_FILTERED_PROFILE_SEARCHES_DATA.Rows(oTabIndex).Item("TAB_TITLE"))
    End Sub

    Private Sub GridControlDocSearch1_DoubleClick(sender As Object, e As EventArgs) Handles GridControlDocSearch1.DoubleClick
        If Not Me.Visible Then Return
        Refresh_DocID(GridViewDocSearch1)
        FileShow()
    End Sub
    Private Sub GridControlDocSearch2_DoubleClick(sender As Object, e As EventArgs) Handles GridControlDocSearch2.DoubleClick
        If Not Me.Visible Then Return
        Refresh_DocID(GridViewDocSearch2)
        FileShow()
    End Sub
    Private Sub GridControlDocSearch3_DoubleClick(sender As Object, e As EventArgs) Handles GridControlDocSearch3.DoubleClick
        If Not Me.Visible Then Return
        Refresh_DocID(GridViewDocSearch3)
        FileShow()
    End Sub
    Private Sub GridControlDocSearch4_DoubleClick(sender As Object, e As EventArgs) Handles GridControlDocSearch4.DoubleClick
        If Not Me.Visible Then Return
        Refresh_DocID(GridViewDocSearch4)
        FileShow()
    End Sub
    Private Sub GridControlDocSearch5_DoubleClick(sender As Object, e As EventArgs) Handles GridControlDocSearch5.DoubleClick
        If Not Me.Visible Then Return
        Refresh_DocID(GridViewDocSearch5)
        FileShow()
    End Sub

    Private Sub GridControlDocSearch1_Click(sender As Object, e As EventArgs) Handles GridControlDocSearch1.Click
        If Not Me.Visible Then Return
        Refresh_DocID(GridViewDocSearch1)

    End Sub
    Private Sub GridControlDocSearch2_Click(sender As Object, e As EventArgs) Handles GridControlDocSearch2.Click
        If Not Me.Visible Then Return
        Refresh_DocID(GridViewDocSearch2)
    End Sub
    Private Sub GridControlDocSearch3_Click(sender As Object, e As EventArgs) Handles GridControlDocSearch3.Click
        If Not Me.Visible Then Return
        Refresh_DocID(GridViewDocSearch3)
    End Sub
    Private Sub GridControlDocSearch4_Click(sender As Object, e As EventArgs) Handles GridControlDocSearch4.Click
        If Not Me.Visible Then Return
        Refresh_DocID(GridViewDocSearch4)
    End Sub
    Private Sub GridControlDocSearch5_Click(sender As Object, e As EventArgs) Handles GridControlDocSearch5.Click
        If Not Me.Visible Then Return
        Refresh_DocID(GridViewDocSearch5)
    End Sub

    Private Sub ContextMenuStripWMFile_Opening(sender As Object, e As CancelEventArgs) Handles ContextMenuStripWMFile.Opening

    End Sub
End Class