Imports System.ComponentModel
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.DocumentResultList
Imports DigitalData.Modules.EDMI.API.Constants
Imports DigitalData.Modules.EDMI.API.DatabaseWithFallback
Imports DigitalData.Modules.ZooFlow.Constants
Imports DigitalData.Modules.ZooFlow
Imports DigitalData.GUIs.Common

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 _DTSQLSearches 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 Documentloader As Loader
    Private Property OperationMode As OperationMode
    Private ReadOnly Environment As Environment

    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(Panel1Collapsed As Boolean, Panel2Collapsed As Boolean, TabCountSQL As Integer, TabCountDoc As Integer, DTSQL As DataTable, DTDOC As DataTable)
        Try
            If Me.InvokeRequired() Then
                Me.Invoke(Sub() TabPreload(Panel1Collapsed, Panel2Collapsed, TabCountSQL, TabCountDoc, DTSQL, DTDOC))
            Else
                '#### SQL Tabs Design Laden
                SplitContainerSearches.Panel1Collapsed = Panel1Collapsed
                SplitContainerSearches.Panel2Collapsed = Panel2Collapsed
                If DTSQL.Rows.Count > 0 Then
                    For p As Integer = 0 To XtraTabControlSQL.TabPages.Count - 1
                        If XtraTabControlSQL.TabPages(p).TabIndex >= TabCountSQL Then
                            XtraTabControlSQL.TabPages(p).PageVisible = False
                        End If
                    Next
                    For p As Integer = 0 To XtraTabControlSQL.TabPages.Count - 1
                        If XtraTabControlSQL.TabPages(p).TabIndex >= TabCountSQL Then
                            Exit For
                        End If
                        XtraTabControlSQL.TabPages(p).Text = DTSQL.Rows(p).Item("TAB_TITLE")

                    Next
                End If

                If DTDOC.Rows.Count > 0 Then
                    '#### Doc Tabs Design Laden
                    For p As Integer = 0 To XtraTabControlDocs.TabPages.Count - 1
                        If XtraTabControlDocs.TabPages(p).TabIndex >= TabCountDoc Then
                            XtraTabControlDocs.TabPages(p).PageVisible = False
                        End If
                    Next
                    For p As Integer = 0 To XtraTabControlDocs.TabPages.Count - 1
                        If XtraTabControlDocs.TabPages(p).TabIndex >= TabCountDoc Then
                            Exit For
                        End If
                        XtraTabControlDocs.TabPages(p).Text = DTDOC.Rows(p).Item("TAB_TITLE")
                    Next

                End If


            End If
        Catch ex As Exception
            LOGGER.Error(ex)
        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 = 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
                XtraTabControlDocs.TabPages(TabIndex).Text = $"{TabCaption} ({oDatatable.Rows.Count})"
                clsWMDocGrid.DTDocuments = oDatatable
                'Select Case TabIndex
                '    Case 0
                '        GridControlDocSearch1.DataSource = oDatatable
                '    Case 1
                '        GridControlDocSearch2.DataSource = oDatatable
                '    Case 2
                '        GridControlDocSearch3.DataSource = oDatatable
                '    Case 3
                '        GridControlDocSearch4.DataSource = oDatatable
                '    Case 4
                '        GridControlDocSearch5.DataSource = oDatatable

                'End Select
                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)
        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
            Size = My.Settings.frmValidatorSearchSize
        End If
        SplitContainerSearches.SplitterDistance = My.Settings.frmValSearchSplitterDistance

        ToolStripDropDownButtonFile.Visible = False
    End Sub

    Private Sub frmValidatorSearch_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        formLoaded = True
    End Sub

    Private Sub XtraTabControlSQL_SelectedPageChanged(sender As Object, e As TabPageChangedEventArgs) Handles XtraTabControlSQL.SelectedPageChanged
        If IsNothing(_DTSQLSearches) Then Exit Sub
        Dim oConID = _DTSQLSearches.Rows(XtraTabControlSQL.SelectedTabPageIndex).Item("CONN_ID")
        Dim oCommand = _DTSQLSearches.Rows(XtraTabControlSQL.SelectedTabPageIndex).Item("SQL_COMMAND")
        oCommand = clsPatterns.ReplaceAllValues(oCommand, _frmValidator.PanelValidatorControl, True)
        Dim oTabIndex = _DTSQLSearches.Rows(XtraTabControlSQL.SelectedTabPageIndex).Item("TAB_INDEX")
        Dim oTabCaption = _DTSQLSearches.Rows(XtraTabControlSQL.SelectedTabPageIndex).Item("TAB_TITLE")
        RefreshTabSQL(oConID, oCommand, oTabIndex, oTabCaption)
    End Sub
    Private Sub XtraTabControlDocs_SelectedPageChanged_1(sender As Object, e As TabPageChangedEventArgs) Handles XtraTabControlDocs.SelectedPageChanged
        If IsNothing(_DTDocSearches) Then Exit Sub
        Dim oConID = _DTDocSearches.Rows(XtraTabControlDocs.SelectedTabPageIndex).Item("CONN_ID")
        Dim oCommand = _DTDocSearches.Rows(XtraTabControlDocs.SelectedTabPageIndex).Item("SQL_COMMAND")
        oCommand = clsPatterns.ReplaceAllValues(oCommand, _frmValidator.PanelValidatorControl, True)
        Dim oTabIndex = _DTDocSearches.Rows(XtraTabControlDocs.SelectedTabPageIndex).Item("TAB_INDEX")
        Dim oTabCaption = _DTDocSearches.Rows(XtraTabControlDocs.SelectedTabPageIndex).Item("TAB_TITLE")
        RefreshTabDoc(oConID, oCommand, oTabIndex, oTabCaption)
    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)
        Try
            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
                Dim msg = "DocID: " & clsWMDocGrid.SELECTED_DOC_ID.ToString
                tslblDocID.Text = msg
                ToolStripDropDownButtonFile.Enabled = True
                Dim oDocument As DocumentResultList.Document = Nothing
                ' Load DocumentInfo 
                oDocument = Documentloader.Load(clsWMDocGrid.SELECTED_DOC_ID, clsWMDocGrid.SELECTED_DOC_PATH)

                If Not IsNothing(DocumentViewer1) Then
                    ' DocumentViewer1.LoadFile(clsWMDocGrid.SELECTED_DOC_PATH)
                    Dim oFileName = $"{clsWMDocGrid.SELECTED_DOC_ID}.{oDocument.Extension}"
                    If Not IsNothing(oDocument.Contents) Then
                        DocumentViewer1.LoadFile(oFileName, New MemoryStream(oDocument.Contents))

                        DocumentViewer1.RightViewOnly(USER_RIGHT_VIEW_ONLY)
                        If USER_RIGHT_VIEW_ONLY = True Then
                            ToolStripDropDownButtonFile.Visible = False
                        Else
                            ToolStripDropDownButtonFile.Visible = True
                        End If
                    Else
                        statlbl.Text = "odocument.content is nothing, Check Your log"
                    End If


                End If

            Else
                tslblDocID.Text = "DocRow not selected"
                ToolStripDropDownButtonFile.Enabled = False
            End If
        Catch ex As Exception
            LOGGER.Error(ex)
        End Try

    End Sub
    Private Sub GridViewDocSearch1_FocusedRowChanged(sender As Object, e As Views.Base.FocusedRowChangedEventArgs) Handles GridViewDocSearch1.FocusedRowChanged
        Refresh_DocID(GridViewDocSearch1)
    End Sub

    Private Sub GridViewDocSearch2_FocusedRowChanged(sender As Object, e As FocusedRowChangedEventArgs) Handles GridViewDocSearch2.FocusedRowChanged
        Refresh_DocID(GridViewDocSearch2)
    End Sub
    Private Sub GridViewDocSearch3_FocusedRowChanged(sender As Object, e As FocusedRowChangedEventArgs) Handles GridViewDocSearch3.FocusedRowChanged
        Refresh_DocID(GridViewDocSearch3)
    End Sub
    Private Sub GridViewDocSearch4_FocusedRowChanged(sender As Object, e As FocusedRowChangedEventArgs) Handles GridViewDocSearch4.FocusedRowChanged
        Refresh_DocID(GridViewDocSearch4)
    End Sub
    Private Sub GridViewDocSearch5_FocusedRowChanged(sender As Object, e As FocusedRowChangedEventArgs) Handles GridViewDocSearch5.FocusedRowChanged
        Refresh_DocID(GridViewDocSearch5)
    End Sub

    Private Sub GridViewDocSearch1_FocusedColumnChanged(sender As Object, e As FocusedColumnChangedEventArgs) Handles GridViewDocSearch1.FocusedColumnChanged
        Refresh_DocID(GridViewDocSearch1)
    End Sub

    Private Sub GridViewDocSearch2_FocusedColumnChanged(sender As Object, e As FocusedColumnChangedEventArgs) Handles GridViewDocSearch2.FocusedColumnChanged
        Refresh_DocID(GridViewDocSearch2)
    End Sub
    Private Sub GridViewDocSearch3_FocusedColumnChanged(sender As Object, e As FocusedColumnChangedEventArgs) Handles GridViewDocSearch3.FocusedColumnChanged
        Refresh_DocID(GridViewDocSearch3)
    End Sub
    Private Sub GridViewDocSearch4_FocusedColumnChanged(sender As Object, e As FocusedColumnChangedEventArgs) Handles GridViewDocSearch4.FocusedColumnChanged
        Refresh_DocID(GridViewDocSearch4)
    End Sub
    Private Sub GridViewDocSearch5_FocusedColumnChanged(sender As Object, e As FocusedColumnChangedEventArgs) Handles GridViewDocSearch5.FocusedColumnChanged
        Refresh_DocID(GridViewDocSearch5)
    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 BASEDATA_DT_PROFILE_SEARCHES_SQL.Rows.Count > 0 Then
            _DTSQLSearches = BASEDATA_DT_PROFILE_SEARCHES_SQL
            Dim oConID = BASEDATA_DT_PROFILE_SEARCHES_SQL.Rows(0).Item("CONN_ID")
            Dim oCommand = BASEDATA_DT_PROFILE_SEARCHES_SQL.Rows(0).Item("SQL_COMMAND")
            oCommand = clsPatterns.ReplaceAllValues(oCommand, _frmValidator.PanelValidatorControl, True)
            XtraTabControlSQL.SelectedTabPageIndex = 0
            Refresh_Load_GridSQL(oConID, oCommand, 0, BASEDATA_DT_PROFILE_SEARCHES_SQL.Rows(0).Item("TAB_TITLE"))
        End If
        If DT_FILTERED_PROFILE_SEARCHES_DOC.Rows.Count > 0 Then
            _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"))
        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 = BASEDATA_DT_PROFILE_SEARCHES_SQL.Rows(oTabIndex).Item("CONN_ID")
        Dim oCommand = BASEDATA_DT_PROFILE_SEARCHES_SQL.Rows(oTabIndex).Item("SQL_COMMAND")
        oCommand = clsPatterns.ReplaceAllValues(oCommand, _frmValidator.PanelValidatorControl, True)
        RefreshTabSQL(oConID, oCommand, oTabIndex, BASEDATA_DT_PROFILE_SEARCHES_SQL.Rows(oTabIndex).Item("TAB_TITLE"))
    End Sub

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

    Private Sub GridControlDocSearch1_Click(sender As Object, e As EventArgs) Handles GridControlDocSearch1.Click
        Refresh_DocID(GridViewDocSearch1)

    End Sub
    Private Sub GridControlDocSearch2_Click(sender As Object, e As EventArgs) Handles GridControlDocSearch2.Click
        Refresh_DocID(GridViewDocSearch2)
    End Sub
    Private Sub GridControlDocSearch3_Click(sender As Object, e As EventArgs) Handles GridControlDocSearch3.Click
        Refresh_DocID(GridViewDocSearch3)
    End Sub
    Private Sub GridControlDocSearch4_Click(sender As Object, e As EventArgs) Handles GridControlDocSearch4.Click
        Refresh_DocID(GridViewDocSearch4)
    End Sub
    Private Sub GridControlDocSearch5_Click(sender As Object, e As EventArgs) Handles GridControlDocSearch5.Click

        Refresh_DocID(GridViewDocSearch5)
    End Sub

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

    End Sub
End Class