Imports DevExpress.XtraTreeList
Imports DevExpress.XtraTreeList.Columns
Imports DevExpress.XtraTreeList.Nodes.Operations
Imports DevExpress.XtraTreeList.Nodes
Imports DevExpress.XtraSplashScreen
Imports DevExpress.XtraScheduler
Imports DevExpress.Data
Imports DevExpress.XtraEditors
Imports DevExpress.XtraGrid.Views.Grid
Imports DevExpress.XtraPrinting
Imports System.Threading
Imports System.Text
Imports System.IO
Imports DD_LIB_Standards
Imports DigitalData.Modules.Base
Imports DigitalData.Modules.Logging
Imports DigitalData.Modules.Database

Public Class frmNodeNavigation
#Region "Laufzeitvariablen & Konstanten"
    Private DT_STRUCTURE_NODES As DataTable
    Private DT_ADDING_USERS As DataTable
    Private DT_VWPMO_CONSTRUCTOR_FORMS As DataTable
    Private RunningTask As Task
    Private RunningTaskTokenSource As New CancellationTokenSource
    Private RunningTaskToken = RunningTaskTokenSource.Token
    Private _EntityId As Short
    Private oConstructID As Short
    Private CONSTRUCTORID As Integer
    Private CONSTRUCTOR_DETAIL_ID As Short
    Private _FilterActive As Boolean = False
    Private _RowReadOnly As Boolean = False
    Private ADD_RECORDS_CONSTR As Boolean = True
    Private TV_Collapse_ExpandState = "Collapse"

    Private WindowsEx As WindowsEx

    Private DT_CONTROLS_ENTITY As DataTable
    Private DT_COLUMNS_GRID_ENTITY As DataTable
    Private DT_DOCRESULT_DROPDOWN_ITEMS As DataTable
    Private DT_RESULTLIST_OPTIONS As DataTable
    Private DT_RESULTLIST_VARIABLE_VALUE As DataTable
    Private DT_ENTITY_DATA As DataTable
    Private DT_TBPMO_FORM_VIEW As DataTable
    Private DT_CONSTRUCT_VIEW As DataTable
    Private COUNT_RO_CONTROLS As Integer = 0
    Private SELECTED_NODE_RECORD_ID As Integer
    Private SELECTED_NODE_CAPTION As String
    Private ENTITY_RECORD_COUNT As Integer = 0
    Private FORMVIEW_ID As Integer
    Private FORM_LOADED As Boolean = False
    Private FORM_SHOWN As Boolean = False
    Private SAVE_ROUTINE_ACTIVE As Boolean = False

    Private ENTITY_LOADING_PROCESS As Boolean = False
    Private RECORD_ENABLED As Boolean = False
    Private BACKGROUND_HELPER As ClassBackgroundHelper
    Private Node_AfterSelect As Boolean = False
    Private EDIT_STATE As EditState = EditState.None
    Private POS_ENABLED As Boolean = False
    Private ERROR_WHILE_SAVING As Boolean = False
    Private taskToken As CancellationTokenSource
    Private IW_USER As String
    Private IW_COMMENT As String
    Private INWORK_FILE As Boolean
    Private CONTROL_DOCTYPE_MATCH As Integer = 0
    Private FocusedNode As TreeListNode
    Private MyTreeListViewState As ClassTreeListViewState

    Private AvailableConfigNodes As New List(Of frmNewNode.NodeConfig)
    Private CurrentNodeConfigId As Integer = 0

    Private DocList As ClassWindreamDocGrid

    Public CtrlBuilder As ClassControlBuilder
    Public CtrlCommandUI As ClassControlCommandsUI

    Private ClassNodeCommands As ClassNodeCommands

    Private Debug As Boolean = False

    Public Enum EditState
        None
        Insert
        Update
        Delete
    End Enum

#End Region

    Public Sub New(pEntityID As Int16, pConstructID As Int16)
        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()
        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.
        _EntityId = pEntityID
        oConstructID = pConstructID

        DocList = New ClassWindreamDocGrid(GridViewDoc_Search)
        WindowsEx = New WindowsEx(LOGCONFIG)

        ClassNodeCommands = New ClassNodeCommands(LOGCONFIG, MYDB_ECM)
    End Sub

    Private Function Get_Splitter_Layout_Filename()
        Dim Filename As String = String.Format("{0}-{1}-SplitterLayout.xml", CONSTRUCTOR_DETAIL_ID, CONSTRUCTOR_DETAIL_ID.ToString)
        Return Path.Combine(Application.UserAppDataPath(), Filename)
    End Function

    Sub Save_Splitter_Layout()
        Try
            Dim XMLPath = Get_Splitter_Layout_Filename()
            Dim layout As New ClassLayout(XMLPath)
            Dim settings As New List(Of ClassSetting) From {
                New ClassSetting("SplitViewDetailsSplitterPosition", SplitContainer1.SplitterDistance),
                New ClassSetting("SplitViewMainSplitterPosition", SplitContainerMain.SplitterPosition)
            }
            layout.Save(settings)
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", ex.Message, ex.StackTrace)
        End Try
    End Sub

    Sub Load_Splitter_Layout()
        Try
            Dim XMLPath As String = Get_Splitter_Layout_Filename()
            Dim layout As New ClassLayout(XMLPath)
            Dim settings As System.Collections.Generic.List(Of ClassSetting)
            settings = layout.Load()

            'If settings.Count = 0 Then
            '    settings.Add(New ClassSetting("SplitViewTopSplitterPosition", SplitContainerTop.SplitterPosition))
            '    If CONSTRUCTOR_DETAIL_ID > 0 Then
            '        settings.Add(New ClassSetting("SplitViewMainSplitterPosition_" & CONSTRUCTOR_DETAIL_ID.ToString, SplitContainerMain.SplitterPosition))
            '    Else
            '        settings.Add(New ClassSetting("SplitViewMainSplitterPosition_0", SplitContainerMain.SplitterPosition))
            '    End If

            '    settings.Add(New ClassSetting("SplitViewDetailsSplitterPosition_" & CONSTRUCTOR_DETAIL_ID.ToString, SplitContainerDetails.SplitterPosition))
            '    layout.Save(settings)
            'End If

            For Each setting As ClassSetting In settings
                Select Case setting._name
                    Case "SplitViewMainSplitterPosition"
                        SplitContainerMain.SplitterPosition = Integer.Parse(setting._value)
                    Case "SplitViewDetailsSplitterPosition"
                        SplitContainer1.SplitterDistance = Integer.Parse(setting._value)
                End Select
            Next
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", ex.Message, ex.StackTrace)
        End Try
    End Sub
    Private Async Function frmNodeNavigation_Load(sender As Object, e As EventArgs) As Task Handles Me.Load
        CONSTRUCTORID = CURRENT_CONSTRUCTOR_ID

        DT_VWPMO_CONSTRUCTOR_FORMS = ClassFormCommands.LoadConstructorForms(CURRENT_SCREEN_ID, oConstructID, USER_LANGUAGE)

        'Dim Sql = String.Format("SELECT *, [dbo].[FNPMO_GETOBJECTCAPTION]('{0}','FORMVIEW_TITLE' + CONVERT(VARCHAR(5), FORM_VIEW_ID), {1}) AS 'CAPTION' " &
        '    "FROM VWPMO_CONSTRUCTOR_FORMS WHERE SCREEN_ID = {2} AND  CONSTRUCT_ID = {3} ORDER BY SEQUENCE", USER_LANGUAGE, CURRENT_SCREEN_ID, CURRENT_SCREEN_ID, oConstructID)
        'DT_VWPMO_CONSTRUCTOR_FORMS = MYDB_ECM.GetDatatable(Sql)

        CURRENT_DT_TBPMO_ENTITY_RIGHT_CONTROLS = MYDB_ECM.GetDatatable(String.Format("SELECT T.* FROM TBPMO_ENTITY_RIGHT_CONTROLS T INNER JOIN VWPMO_CONSTRUCTOR_FORMS T1 ON T.ENTITY_ID = T1.FORM_ID where T1.CONSTRUCT_ID = {0}", CONSTRUCTORID))

        Dim oGDPictureLicenseKey = MYDB_ECM.GetScalarValue(Queries.DD_ECM.ThirdPartyModules.GdPictureLicense)
        DocumentViewer.Init(LOGCONFIG, oGDPictureLicenseKey)

        ' Hintergrund Bild initialisieren
        'If (System.IO.File.Exists(Application.StartupPath + "\Resources\windream-portrait_col_RGB_Wordpress.png")) Then
        '    WM_LOGO = New Bitmap(Application.StartupPath + "\Resources\windream-portrait_col_RGB_Wordpress.png")
        '    BACKGROUND_HELPER = New ClassBackgroundHelper(GridViewDoc_Search, WM_LOGO) '
        '    ' MessageBox.Show("File: " & Application.StartupPath + "\Resources\Pic1.png" & " doesn't exist. Check file and try again.")
        '    End
        'End If
        ClassWindowLocation.LoadFormLocationSize(Me, CONSTRUCTORID, CURRENT_SCREEN_ID, "NODE_NAVIGATION")
        Try
            DT_CONSTRUCT_VIEW = MYDB_ECM.GetDatatable("SELECT * FROM TBPMO_FORM_CONSTRUCTOR WHERE GUID = " & CONSTRUCTORID)
            Dim SEL1 = String.Format("SELECT * FROM TBPMO_FORM WHERE GUID IN (SELECT FORM_ID FROM VWPMO_CONSTRUCTOR_FORMS WHERE SCREEN_ID = {0} AND  CONSTRUCT_ID = {1})", CURRENT_SCREEN_ID, CONSTRUCTORID)
            DT_ENTITY_DATA = MYDB_ECM.GetDatatable(SEL1)

            SEL1 = String.Format("SELECT *, dbo.FNPMO_GET_CONTROL_CAPTION ('{0}', 1, CONTROL_ID) AS 'CAPTION' FROM VWPMO_CONTROL_SCREEN", USER_LANGUAGE)
            DT_VWPMO_CONTROL_SCREEN = MYDB_ECM.GetDatatable(SEL1)

            If DT_CONSTRUCT_VIEW.Rows.Count = 1 Then
                'Load Input Grid
                Me.Text = DT_CONSTRUCT_VIEW.Rows(0).Item("FORM_TITLE")
                'Die Standards ein/ausblenden
            End If

            'Dim sql_ResultList = "select T1.ENTITY_ID,T.GUID,T.TITLE,T.MANUALLY,T.CREATE_ON_REC_CREATE,T.CREATE_ON_FOLL_UP " &
            '            "FROM TBPMO_WORKFLOW T,TBPMO_WORKFLOW_ENTITY_STATE T1 " &
            '            "WHERE T.GUID = T1.WF_ID " &
            '            "GROUP BY T1.ENTITY_ID,T.GUID,T.TITLE,T.MANUALLY,T.CREATE_ON_REC_CREATE,T.CREATE_ON_FOLL_UP"
            'DT_WORKFLOWS_MANUAL = MYDB_ECM.GetDatatable(sql_ResultList)
            Load_Datafor_Entity()

            FORM_LOADED = True
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", ex.Message, "Error in Loading Form part 4")
        End Try

        Await Load_nodes()
    End Function
    Private Async Function Load_nodes() As Task
        Dim oHandle = SplashScreenManager.ShowOverlayForm(Me)
        Try
            Dim oTable = Await ClassNodeCommands.LoadNodes(CURRENT_ENTITY_ID)
            DT_STRUCTURE_NODES = oTable
            'Dim oToken = RunningTaskTokenSource.Token
            'Dim oStructureNodeSql = $"SELECT 
            '    T.GUID,
            '    T.RECORD_ID,
            '    T.NODE_CONFIG_ID,
            '    T.NODE_CAPTION,
            '    T.ID1, 
            '    T.BACK_COLOR,
            '    T.PARENT_GUID,
            '    T.SEQUENCE,
            '    T.TYPE_NODE
            ' FROM 
            '    VWPMO_STRUCTURE_NODES T 
            'INNER JOIN VWPMO_CONSTRUCTOR_FORMS T1 ON T.ENTITY_ID = T1.FORM_ID 
            'WHERE T.ENTITY_ID = {CURRENT_ENTITY_ID}"
            'DT_STRUCTURE_NODES = MYDB_ECM.GetDatatable(oStructureNodeSql)

            Dim oNodeConfigSql = String.Format("select T.* from TBPMO_STRUCTURE_NODES_CONFIGURATION T INNER JOIN VWPMO_CONSTRUCTOR_FORMS T1 ON T.ENTITY_ID = T1.FORM_ID WHERE T.ENTITY_ID = {0}", CURRENT_ENTITY_ID)
            Dim DT_TREEVIEW_CONFIGURATION = MYDB_ECM.GetDatatable(oNodeConfigSql)
            For Each row As DataRow In DT_TREEVIEW_CONFIGURATION.Rows
                Try
                    Dim bimage = row.ItemEx(Of Object)("NODE_IMAGE", Nothing)
                    If bimage Is Nothing Then
                        Continue For
                    End If

                    Dim oNodeImage = ByteArrayToBitmap(bimage)
                    ImageCollection1.AddImage(oNodeImage, row.Item("GUID"))
                Catch ex As Exception
                End Try
            Next

            TreeListDevexpress.DataSource = DT_STRUCTURE_NODES
            TreeListDevexpress.KeyFieldName = "GUID"
            TreeListDevexpress.ParentFieldName = "PARENT_GUID"
            TreeListDevexpress.Columns("SEQUENCE").SortOrder = SortOrder.Ascending
            TreeListDevexpress.StateImageList = ImageCollection1

            Dim oVisibleColumns = New List(Of String) From {"NODE_CAPTION"}
            For Each oColumn In TreeListDevexpress.Columns
                If oVisibleColumns.Contains(oColumn.FieldName) = False Then
                    oColumn.Visible = False
                End If
            Next


        Catch ex As Exception
            LOGGER.Error(ex)
        Finally
            SplashScreenManager.CloseOverlayForm(oHandle)
        End Try
    End Function
    Private Sub TreeListDevexpress_ColumnFilterChanged(sender As Object, e As EventArgs)
        Dim tree As TreeList = TryCast(sender, TreeList)
        Dim filteredColumns As List(Of TreeListColumn) = tree.Columns.Cast(Of TreeListColumn)().Where(Function(c) c.FilterInfo.AutoFilterRowValue IsNot Nothing).ToList()
        If filteredColumns.Count = 0 Then
            tree.CollapseAll()
            Return
        End If

        tree.BeginUpdate()
        For Each col As TreeListColumn In filteredColumns
            Dim op As New CollapseChildrenOperation(col.FilterInfo.AutoFilterRowValue.ToString(), col)
            tree.NodesIterator.DoOperation(op)
        Next col
        tree.EndUpdate()
    End Sub
    Public Class CollapseChildrenOperation
        Inherits TreeListOperation

        Private filterValue As String
        Private column As TreeListColumn

        Public Sub New(ByVal filter As String, ByVal col As TreeListColumn)
            filterValue = filter
            column = col
        End Sub

        Private Function IsNodeMatchFilter(ByVal node As TreeListNode, ByVal column As TreeListColumn) As Boolean
            Return node.GetDisplayText(column).Contains(filterValue)
        End Function
        Public Overrides Sub Execute(ByVal node As TreeListNode)
            If IsNodeMatchFilter(node, column) Then
                node.TreeList.MakeNodeVisible(node)
                CollapseChildren(node)
            End If
        End Sub

        Public Sub CollapseChildren(ByVal node As TreeListNode)
            'node.Visible = true;
            For Each childNode As TreeListNode In node.Nodes
                CollapseChildren(childNode)
            Next childNode
            node.Expanded = False
        End Sub
    End Class

    Private Async Sub TreeListDevexpress_FocusedNodeChanged(sender As Object, e As FocusedNodeChangedEventArgs) Handles TreeListDevexpress.FocusedNodeChanged
        FocusedNode = Nothing

        btnCreateNewNode.Enabled = False

        If _FilterActive Then
            Exit Sub
        End If

        If e.Node Is Nothing Then
            Exit Sub
        End If

        'For Each treeListNode As TreeListNode In TreeListDevexpress.Selection
        'FocusedNode = TreeListNode

        FocusedNode = e.Node

        RPGNodes.Enabled = True

        Dim oNodeId = e.Node.Id
        Console.Write($"Node ID: {oNodeId}")

        Dim oRowObject = TreeListDevexpress.GetRow(oNodeId)

        If TypeOf oRowObject IsNot DataRowView Then
            Exit Sub
        End If

        'If oNodeId = 0 Then
        '    Exit Sub
        'End If

        Dim oRowView As DataRowView = oRowObject
        Dim oRow As DataRow = oRowView.Row
        Dim oGuid = oRow.Item("GUID")
        Dim oNodeCaption = oRow.Item("NODE_CAPTION")
        Dim oNodeConfigId = oRow.Item("NODE_CONFIG_ID")
        Dim oRecordId = oRow.ItemEx("RECORD_ID", 0)
        Dim oHasRecordId = (oRecordId > 0)
        Dim oIsConfigNode = (oNodeConfigId = 1000)
        Dim oParentNode = e.Node.ParentNode

        ' BEGIN NEW NODE
        Dim oConfigNodeChildren = FocusedNode.Nodes.Where(Function(n) n.Item("TYPE_NODE") = 1000)
        Dim oHasConfigNodeChildren = oConfigNodeChildren.Any()
        Dim oConfigNodeChildrenList = oConfigNodeChildren.ToList()

        CurrentNodeConfigId = oNodeConfigId

        AvailableConfigNodes.Clear()
        Dim oNodeConfigList = NODE_CONFIGURABLE_NODES_DT.Select($"PARENT_NODE = {oNodeConfigId}").
            Cast(Of DataRow).
            Select(Function(row) New frmNewNode.NodeConfig() With {
                       .Id = row.Item("GUID"),
                       .Name = row.Item("NAME")
                   }).ToList()
        AvailableConfigNodes = oNodeConfigList

        If AvailableConfigNodes.Count > 0 Then
            btnCreateNewNode.Enabled = True
        End If

        ' END NEW NODE

        If oHasRecordId Then
            Update_Status_Label(True, $"NodeGUID {oGuid} - RecordID {oRecordId}", EditState.None)
        Else
            Update_Status_Label(True, $"NodeGUID {oGuid}", EditState.None)
        End If

        If oHasRecordId Then
            'oNodeInfo += $" - RecordID {oRecordId}"
            Node_AfterSelect = True
            'Dim sw As New SW("TreeViewMain_AfterSelect1")
            ' Dim swAll As New SW("TreeViewMain_AfterSelect")
            DisableEditMode()

            ' ClassNodeNavigation.Check_NODE_CONFIG_ID(oEntityID, SelectedNode)

            CURRENT_RECORD_ID = oRecordId
            ClassHelper.GetDocrecordLinks(CURRENT_RECORD_ID)
            CURRENT_ENTITY_ID = _EntityId
            CURRENT_NODE_GUID = oNodeId
            SELECTED_NODE_CAPTION = oNodeCaption
            CURRENT_SEARCH_TYPE = "RECORD"
            DisableEditMode()
            ' muss vor show selected record data kommen,
            ' sodass die datasource für die angehakten werte existiert (checked list box)
            CtrlBuilder.WatchRecordChanges = False
            ClassControlValues.LoadControlValuesListWithPlaceholders(_EntityId, CURRENT_RECORD_ID, 0, CtrlBuilder.AllControls, _EntityId)
            CtrlBuilder.WatchRecordChanges = True
            Await Show_Selected_Record_Data(CURRENT_RECORD_ID)


            ClassRightManagement.Check_Set_Rights(CURRENT_RECORD_ID, _EntityId)
            CONTROL_HANDLING()


            If CURRENT_RECORD_ID > 0 Then
                If RIGHT_RECORD_AND_FILE_READ_ONLY = False And CtrlCommandUI.IsInsert = False Then
                    If DT_CONTROLS_ENTITY.Rows.Count = COUNT_RO_CONTROLS Then
                        bbtnitmRecEdit.Enabled = False
                        bbtnitmRecSave.Enabled = False
                    Else
                        bbtnitmRecEdit.Enabled = True
                        In_Visible_Record_Group(True)
                    End If

                End If
                If RIGHT_RECORD_AND_FILE_READ_ONLY = True Then
                    bbtnitmRecEdit.Enabled = False
                    bbtnitmRecSave.Enabled = False
                Else
                    bbtnitmRecEdit.Enabled = True
                    In_Visible_Record_Group(True)

                End If

            End If
            If RIGHT_READ_ONLY_DOC = False Then
                Doc_ReadOnlyHandler(True)

            End If
            'Liste der geänderten Control Values leeren
            CtrlBuilder.ControlsChanged.Clear()

            Load_DocGrid_Layout()
            'Load_Grid_Layout()
            'Load_Variants_Grid_Layout()

            'swAll.Done()
            Node_AfterSelect = False

        End If
    End Sub

    Public Sub Update_Status_Label(visible As Boolean, Optional text As String = "", Optional state As EditState = EditState.None)
        bsiInfo.Caption = text
        If visible = True Then
            bsiInfo.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
        Else
            bsiInfo.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
        End If


        Select Case state
            Case EditState.Insert
                bsiInfo.ItemAppearance.Normal.BackColor = Color.Yellow
            Case EditState.Update
                bsiInfo.ItemAppearance.Normal.BackColor = Color.LightBlue
            Case Else
                bsiInfo.ItemAppearance.Normal.BackColor = Color.LightGray
        End Select
    End Sub
    Public Sub Update_DocID_Label(visible As Boolean, Optional text As String = "", Optional state As EditState = EditState.None)
        bsiDocID.Caption = text
        If visible = True Then
            bsiDocID.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
        Else
            bsiDocID.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
        End If


        Select Case state
            Case EditState.Insert
                bsiDocID.ItemAppearance.Normal.BackColor = Color.Yellow
            Case EditState.Update
                bsiDocID.ItemAppearance.Normal.BackColor = Color.LightBlue
            Case Else
                bsiDocID.ItemAppearance.Normal.BackColor = Color.LightGray
        End Select
    End Sub
    Private Sub TreeListDevexpress_GetStateImage(sender As Object, e As GetStateImageEventArgs) Handles TreeListDevexpress.GetStateImage
        Dim Column_Config_ID As DevExpress.XtraTreeList.Columns.TreeListColumn = TreeListDevexpress.Columns("NODE_CONFIG_ID")
        Dim configid = e.Node.GetDisplayText(Column_Config_ID)

        e.Node.StateImageIndex = ImageCollection1.Images.Keys.IndexOf(configid)
    End Sub
    Sub Load_Adding_users()
        Try
            Dim oSql = String.Format("SELECT * FROM TBPMO_ENTITY_USERRIGHT_ADDING where ENTITY_ID IN (SELECT FORM_ID FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = {0})", oConstructID)
            DT_ADDING_USERS = MYDB_ECM.GetDatatable(oSql)
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", ex.Message, "Error in Load_Adding_users")
        End Try
    End Sub
    Private Sub Load_Configurable_Nodes()
        Try
            Dim oSql = String.Format("SELECT * FROM TBPMO_STRUCTURE_NODES_CONFIGURATION where TYPE_NODE = 1000 AND ENTITY_ID IN (SELECT FORM_ID FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = {0})", oConstructID)
            NODE_CONFIGURABLE_NODES_DT = MYDB_ECM.GetDatatable(oSql)
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", ex.Message, "Error in Load_Configurable_Nodes")
        End Try
    End Sub
    Sub Load_Datafor_Entity()

        Try

            If _EntityId <> CURRENT_ENTITY_ID Then
                LOGGER.Info("Entity-Data needs to be reloaded...")

                CURRENT_ENTITY_ID = _EntityId
                CURRENT_CONSTRUCTOR_ID = oConstructID
                Load_Adding_users()
                Load_Configurable_Nodes()

            End If


            Dim sw As New SW("Load_Datafor_Entity")


            'If NODE_NAVIGATION = True Then
            '    ENTITY_ID = ClassNodeNavigation.Return_ENTITY_FOR_TAG(SelectedNode.Tag)
            '    CURRENT_ENTITY_ID = ENTITY_ID
            'End If

            Dim result = (From form In DT_VWPMO_CONSTRUCTOR_FORMS.AsEnumerable()
                          Select form
                          Where form.Item("FORM_ID") = _EntityId).Single()
            CONSTRUCTOR_DETAIL_ID = result.Item("GUID")
            ' CONSTRUCT_EXPAND = result.Item("EXPAND")
            Dim FORM_DATE_FORMAT = result.Item("DATE_FORMAT")
            If FORM_DATE_FORMAT <> USER_DATE_FORMAT Then
                CURRENT_DATE_FORMAT = USER_DATE_FORMAT
            Else
                CURRENT_DATE_FORMAT = FORM_DATE_FORMAT
            End If
            'LOCK_CONTROLS_BG_LOAD = result.Item("LOCK_CONTROLS_BG_LOAD")


            FAU_AD_DOMAIN = ""
            FAU_AD_SERVER = ""
            FAU_AD_USER = ""
            FAU_AD_USER_PW = ""
            If IsNothing(DT_ADDING_USERS) Then
                Load_Adding_users()
            End If
            If DT_ADDING_USERS.Rows.Count > 0 Then
                'Überprüfen ob für diese Entität ein spezifischer windream-User verwendet wird, wenn Dateien abgelegt werden?
                Dim query1 = From _user In DT_ADDING_USERS.AsEnumerable()
                             Select _user Where _user.Item("ENTITY_ID") = _EntityId
                Dim Rows1 = query1.ToList()
                For Each _row In Rows1
                    FAU_AD_DOMAIN = _row.Item("AD_DOMAIN").ToString()
                    FAU_AD_SERVER = _row.Item("AD_SERVER").ToString()
                    FAU_AD_USER = _row.Item("AD_USER").ToString()
                    Dim wrapper As New ClassEncryption("!35452didalog=")
                    Dim PWplainText As String
                    ' DecryptData throws if the wrong password is used.
                    Try
                        PWplainText = wrapper.DecryptData(_row.Item("AD_USER_PW").ToString())
                    Catch ex As Exception
                        LOGGER.Warn("- the Password for FileAddingUser '" & FAU_AD_USER & "' could not be decrypted")
                        PWplainText = ""
                    End Try
                    FAU_AD_USER_PW = PWplainText
                Next
            End If
            sw.Done()
            Load_Entity_Data_CONTROLS_RECORDS()

        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", ex.Message, "Load_Datafor_Entity: " & ex.StackTrace)
        End Try

    End Sub
    Sub Load_Entity_Data_CONTROLS_RECORDS()
        Try
            LOGGER.Debug("START Load_Entity_Data")
            Dim sw As New SW("Load_Entity_Data")
            ' Me.Cursor = Cursors.WaitCursor
            RECORD_CHANGED = False
            SELECTED_NODE_RECORD_ID = 0
            Dim expression As String
            Dim sql
            'Dim sql = "SELECT CONTROL_ID, CONTROL_READ_ONLY FROM VWPMO_CONTROL_SCREEN WHERE CTRLTYPE_ID NOT IN (1) AND CONTROL_ENTITY_ID = " & oEntityID
            DT_CONTROLS_ENTITY = ClassHelper.FILTER_DATATABLE(DT_VWPMO_CONTROL_SCREEN, "CTRLTYPE_ID NOT IN (1) AND CONTROL_ENTITY_ID = " & _EntityId, "")


            expression = "CONTROL_READ_ONLY = " & 1
            Dim CONTROLS_ROW() As DataRow
            CONTROLS_ROW = DT_CONTROLS_ENTITY.Select(expression)
            Dim i As Integer
            ' Count the locked controls
            For i = 0 To CONTROLS_ROW.GetUpperBound(0)
                COUNT_RO_CONTROLS += 1
            Next
            If DT_CONTROLS_ENTITY.Rows.Count = COUNT_RO_CONTROLS Then
                bbtnitmRecEdit.Enabled = False
                bbtnitmRecSave.Enabled = False
                'tsButtonDelete.Enabled = False
            Else
                bbtnitmRecEdit.Enabled = True
                bbtnitmRecSave.Enabled = True
                ' tsButtonDelete.Enabled = True
            End If

            Dim oRow = (From form In DT_VWPMO_CONSTRUCTOR_FORMS.AsEnumerable()
                        Select form
                        Where form.Item("FORM_ID") = _EntityId).Single()


            CURRENT_CONSTRUCTOR_DETAIL_ID = oRow.Item("GUID")
            CONTROL_DOCTYPE_MATCH = oRow.Item("CONTROL_DOCTYPE_MATCH")
            SQL_RECORD_AND_FILE_READ_ONLY = oRow.Item("SQL_RIGHT_READ_AND_VIEW_ONLY")
            SQL_DOC_READ_ONLY = oRow.Item("SQL_RIGHT_WINDREAM_VIEW")
            Try
                ADD_RECORDS_CONSTR = oRow.Item("ADD_RECORDS")
            Catch ex As Exception
                ADD_RECORDS_CONSTR = True
            End Try



            expression = String.Format("ENTITY_ID = {0} AND LANGUAGE = '{1}'", _EntityId, USER_LANGUAGE)
            DT_COLUMNS_GRID_ENTITY = ClassHelper.FILTER_DATATABLE(DT_DOCSEARCH_RESULTLIST_CONFIG, expression, "SEQUENCE")
            expression = String.Format("ENTITY_ID = {0} AND TYPE_ID = 10 AND LANGUAGE = '{1}'", _EntityId, USER_LANGUAGE)
            DT_DOCRESULT_DROPDOWN_ITEMS = ClassHelper.FILTER_DATATABLE(CURRENT_TBPMO_DOCRESULT_DROPDOWN_ITEMS, expression, "SEQUENCE")
            LOGGER.Debug($"Found {DT_DOCRESULT_DROPDOWN_ITEMS.Rows.Count} DT_DOCRESULT_DROPDOWN_ITEMS!")
            DT_RESULTLIST_OPTIONS = ClassHelper.FILTER_DATATABLE(CURRENT_VARIABLE_CONTROLS, "ENTITY_ID = " & _EntityId, "")
            expression = String.Format("ENTITY_ID = {0} AND LANGUAGE = '{1}' AND COLUMN_VIEW LIKE 'VALUE%'", _EntityId, USER_LANGUAGE)
            DT_RESULTLIST_VARIABLE_VALUE = ClassHelper.FILTER_DATATABLE(DT_DOCSEARCH_RESULTLIST_CONFIG, expression, "SEQUENCE")
            Dim ENTITY_ROW = (From form In DT_ENTITY_DATA.AsEnumerable()
                              Select form
                              Where form.Item("GUID") = _EntityId).Single()


            'sql = String.Format("select * from TBPMO_RIGHT_USER WHERE USER_ID = {0} AND oEntityID = {1}", USER_GUID, oEntityID)
            DT_RIGHTS_USER = ClassHelper.FILTER_DATATABLE(CURRENT_TBPMO_RIGHT_USER, "ENTITY_ID = " & _EntityId, "")
            expression = String.Format("")
            sql = String.Format("SELECT DISTINCT EDIT_REC,ADD_REC,DELETE_REC,ADD_DOC,VIEW_DOC,DELETE_DOC FROM TBPMO_RIGHT_GROUP WHERE ENTITY_ID = {0} AND GROUP_ID IN (SELECT GROUP_ID FROM TBDD_GROUPS_USER WHERE USER_ID = {1})", _EntityId, USER_GUID)
            DT_RIGHTS_GROUP = MYDB_ECM.GetDatatable(sql)
            sql = String.Format("SELECT VIEW_ID FROM TBPMO_USER_CONSTR_VIEW_TYPE WHERE CONSTRUCTOR_DETAIL_ID = {0} AND [ENTITY_ID] = {1} AND USER_ID = {2}", CURRENT_CONSTRUCTOR_DETAIL_ID, _EntityId, USER_GUID)


            SELECTED_NODE_RECORD_ID = 0

            ' LINQ für Zugriff auf DT_VWPMO_CONSTRUCTOR_FORMS
            Dim result1 = (From form In DT_VWPMO_CONSTRUCTOR_FORMS.AsEnumerable()
                           Select form
                           Where form.Item("FORM_ID") = _EntityId).Single()
            CURRENT_PARENT_ENTITY_ID = 0


            ' LINQ für Zugriff auf DT_VWPMO_CONSTRUCTOR_FORMS
            Dim query = From form In DT_VWPMO_CONSTRUCTOR_FORMS.AsEnumerable()
                        Select form
                        Where form.Item("FORM_ID") = _EntityId

            Dim QuickViewSQL = query.Single().Item("SQL_QUICK_VIEW")

            CURRENT_ENTITYSQL = Get_Grid_Sql_NODE_NAV(CONSTRUCTORID, _EntityId, CURRENT_CONSTRUCTOR_DETAIL_ID, USER_GUID)
            ' CURRENT_ENTITYSQL = GridSQL
            'Anzahl der Datensätze
            ENTITY_RECORD_COUNT = MYDB_ECM.GetScalarValue("SELECT COUNT(*) FROM TBPMO_RECORD where PARENT_RECORD = 0 AND FORM_ID = " & _EntityId)

            ClassDOC_SEARCH.Get_DOC_RESULTTABLE(DT_RESULTLIST_OPTIONS, DT_RESULTLIST_VARIABLE_VALUE, DT_COLUMNS_GRID_ENTITY, _EntityId, SELECTED_NODE_RECORD_ID, True, True)


            DT_TBPMO_FORM_VIEW = ClassHelper.FILTER_DATATABLE(CURRENT_TBPMO_FORM_VIEW, "FORM_ID = " & _EntityId & " AND SCREEN_ID = " & CURRENT_SCREEN_ID, "")
            CURRENT_ENTITYSTRING = DT_TBPMO_FORM_VIEW.Rows(0).Item("FORM_TITLE")

            FORMVIEW_ID = DT_TBPMO_FORM_VIEW.Rows(0).Item("GUID")

            Load_Controls(FORMVIEW_ID)

            Try
                Dim async As New ClassAsyncSQL(CURRENT_ENTITYSQL)
                async.bw.RunWorkerAsync()
                While async.bw.IsBusy
                    Application.DoEvents()
                End While
                CURRENT_DT_ENTITY_RECORDS = async.dt
            Catch ex As Exception
                ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error Async EntitySQL", ex.Message, ex.StackTrace)
            End Try


            If IsNothing(CURRENT_DT_ENTITY_RECORDS) Then
                ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in getting Entity-Data - Check logfile")
            Else
                CURRENT_DT_ENTITY_RECORDS.TableName = "VWPMO_ENTITY_TABLE" & _EntityId
                ' Dim SQL_AutoValues = "SELECT GUID AS CONTROL_ID, CONNECTION_ID_1 AS CONNECTION_ID, SQL_COMMAND_1 AS SQL_COMMAND FROM TBPMO_CONTROL WHERE CONNECTION_ID_1 <> '' AND SQL_COMMAND_1 <> '' AND FORM_ID = " & oEntityID

                Dim DT_AUTOVALUES = ClassHelper.FILTER_DATATABLE(CURRENT_TBPMO_CONTROL, "CONNECTION_ID_1 > 0 AND SQL_COMMAND_1 <> '' AND FORM_ID = " & _EntityId, "")


                CURRENT_SQL_AUTO_VALUES_DT = DT_AUTOVALUES

                If USER_WAN = True Then

                End If
                Try
                    Dim primaryKey(1) As DataColumn
                    primaryKey(0) = CURRENT_DT_ENTITY_RECORDS.Columns("Record-ID")
                    CURRENT_DT_ENTITY_RECORDS.PrimaryKey = primaryKey
                Catch ex As Exception
                    LOGGER.Warn("Could not set the primary Key(Record-ID): " & ex.Message)
                End Try







                CtrlBuilder.WatchRecordChanges = False
                ClassControlValues.LoadControlValuesList(_EntityId, CtrlBuilder.MasterPanel.Controls)
                CtrlBuilder.WatchRecordChanges = True

                'Zurücksetzen
                ENTITY_LOADING_PROCESS = True
                Dim RecLoaded As Boolean = False



            End If
            Load_Splitter_Layout()
            sw.Done()

        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error in Load_Entity_Data", ex.Message, ex.StackTrace)
        Finally
            'Me.Cursor = Cursors.Default
            ENTITY_LOADING_PROCESS = True
        End Try


    End Sub
    Sub Update_Record_Label(RecordId As Integer)
        Try
            Dim oSql As String = $"SELECT 
                ADDED_WHO, 
                CONVERT(VARCHAR(16),ADDED_WHEN,20) AS ADDED_WHEN, 
                COALESCE(CHANGED_WHO,'') AS CHANGED_WHO, 
                COALESCE(CONVERT(VARCHAR(16),CHANGED_WHEN,20),'') AS CHANGED_WHEN 
                FROM TBPMO_RECORD WHERE GUID = {RecordId}"

            Dim oTable As DataTable
            oTable = MYDB_ECM.GetDatatable(oSql)

            If Not IsNothing(oTable) Then
                If oTable.Rows.Count = 0 Then
                    Exit Sub
                End If

                Dim oRow As DataRow = oTable.Rows(0)

                bsitmRecordID.Visibility = DevExpress.XtraBars.BarItemVisibility.Never

                Dim oAddedWho = oRow.Item(0)
                Dim oAddedWhen = oRow.Item(1)
                Dim oChangedWho = oRow.Item(2)
                Dim oChangedWhen = oRow.Item(3)

                Dim CreateChangeString = String.Format("Added by '{0}', when: {1}", oAddedWho, oAddedWhen)

                If CtrlCommandUI.IsInsert = False AndAlso (oRow.ItemEx(2, "") <> "") Then
                    CreateChangeString += String.Format(" - Changed by '{0}', when: {1}", oChangedWho, oChangedWhen)
                End If

                'bsitmRecordID.Caption = String.Format("Record ({0}) - {1}", RecordId, CreateChangeString.ToString)
                bsitmRecordID.Caption = String.Format("{0}", CreateChangeString.ToString)
                bsitmRecordID.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
            End If
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", ex.Message, ex.StackTrace)
        End Try

    End Sub
    Private Async Function Show_Selected_Record_Data(Rec_ID As Integer) As Threading.Tasks.Task
        Dim oHandle = SplashScreenManager.ShowOverlayForm(Me)

        Try
            LOGGER.Debug("Show_Selected_Record_Data: " & Rec_ID.ToString)
            Dim ENTITY_ROW = (From form In DT_ENTITY_DATA.AsEnumerable()
                              Select form
                              Where form.Item("GUID") = _EntityId).Single()

            'Update_Status_Label(False, "")
            LOGGER.Debug("RECORD ID: " & Rec_ID.ToString)
            'Me.pnlControls.Visible = True

            SELECTED_NODE_RECORD_ID = Rec_ID

            CURRENT_PARENT_RECORD_ID = 0


            RIGHT_CONTROL_CHANGED = False

            ENTITY_RELOAD_AFT_CONTROL_LOAD = False
            CtrlBuilder.WatchRecordChanges = False
            If pnlControls.Enabled = False Then pnlControls.Enabled = True
            ClassControlValues.LoadControlValues(SELECTED_NODE_RECORD_ID, 0, _EntityId, CtrlBuilder.AllControls, _EntityId)
            CtrlBuilder.WatchRecordChanges = True

            Dim sw As New SW("Show Selected RecordData 2")
            ' Laden der Daten bedeutet nicht dass Daten vom Benutzer geändert wurden!
            RECORD_CHANGED = False
            'Refresh_Navpane()
            Update_Record_Label(SELECTED_NODE_RECORD_ID)

            Dim oDocumentsFounnd = Await RUN_WDSEARCH_GRID(True)

            If oDocumentsFounnd = 0 Then
                DocumentViewer.CloseDocument()
            End If

            sw.Done()

        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in SelectedRecord_ShowData: ", ex.Message)
        Finally
            SplashScreenManager.CloseOverlayForm(oHandle)
        End Try

    End Function

#Region "Controls"
    Sub Load_Controls(frmview_id As Integer)
        Dim sw As New SW("Load_Controls")
        FORMVIEW_ID = frmview_id
        _EntityId = DT_TBPMO_FORM_VIEW.Rows(0).Item("FORM_ID")
        CURRENT_ENTITY_ID = _EntityId
        CtrlBuilder = New ClassControlBuilder(pnlControls)
        CtrlCommandUI = New ClassControlCommandsUI(CtrlBuilder,
                                                   ContextMenuDetails,
                                                   AddressOf NewEditAppointment)

        CtrlCommandUI.LoadControls(_EntityId)
        Lock_RecordControls(True)

        AddHandler CtrlBuilder.OnRecordChanged, AddressOf OnRecordChanged
        ' AddHandler CtrlBuilder.OnMouseHover, AddressOf HandleToolTip
        sw.Done()
    End Sub
    Private Sub OnRecordChanged(sender As Object, e As System.EventArgs)
        If ENTITY_LOADING_PROCESS Then
            RECORD_CHANGED = True
        End If

    End Sub
    'Private Sub HandleToolTip(sender As Object, e As EventArgs)
    '    Dim control As Windows.Forms.Control = DirectCast(sender, Windows.Forms.Control)
    '    Dim id As Integer = DirectCast(control.Tag, ClassControlMetadata).Id

    '    Dim hint = ClassControlValueCache.LoadHint(id)
    '    If Not IsNothing(hint) Then
    '        'show hint
    '        Console.WriteLine("Showing hint: " & hint)
    '        ToolTipController.ShowHint(hint.ToString, ToolTipLocation.RightCenter)
    '    Else
    '        ToolTipController.HideHint()
    '    End If

    'End Sub
    Sub Lock_RecordControls(state As Boolean)
        Lock_Record_Controls_Recursive(state, pnlControls.Controls)
    End Sub
    Sub Lock_Record_Controls_Recursive(state As Boolean, controls As System.Windows.Forms.Control.ControlCollection)
        For Each Control As System.Windows.Forms.Control In controls
            Dim controlId As Integer = DirectCast(Control.Tag, ClassControlMetadata).Id
            Select Case Control.GetType()
                Case GetType(System.Windows.Forms.GroupBox)
                    Lock_Record_Controls_Recursive(state, DirectCast(Control, GroupBox).Controls)
                Case GetType(System.Windows.Forms.TextBox)
                    Dim txt As TextBox = CType(Control, TextBox)
                    txt.ReadOnly = CHECK_CONTROL_CONFIGURED_RO(controlId, state)
                Case Else
                    Control.Enabled = Not CHECK_CONTROL_CONFIGURED_RO(controlId, state) 'state

            End Select
        Next
    End Sub
    Private Function CHECK_CONTROL_CONFIGURED_RO(CONTROL_ID As Integer, state As Boolean)
        Try
            ' LINQ für Zugriff auf DT_VWPMO_CONSTRUCTOR_FORMS
            Dim result1 = (From form In DT_CONTROLS_ENTITY.AsEnumerable()
                           Select form
                           Where form.Item("CONTROL_ID") = CONTROL_ID).Single()
            Dim locked = result1.Item("CONTROL_READ_ONLY")
            If state = False And locked = True Then
                state = True
            End If
            Return state
        Catch ex As Exception
            Return state
        End Try
    End Function
    Sub CONTROL_HANDLING()
        Dim sw As New SW("CONTROL_HANDLING")
        bbtnitmRecSave.Enabled = True


        bbtnitmRecEdit.Enabled = True
        'tsButtonDelete.Enabled = True

        'tslblLocked.Visible = False
        'tslblFileslocked.Visible = False

        'pnlPositions.Enabled = True


        If SQL_RECORD_AND_FILE_READ_ONLY <> "" Or SQL_DOC_READ_ONLY <> "" Then
            If RIGHT_RECORD_AND_FILE_READ_ONLY = True Then

                bbtnitmRecEdit.Enabled = False
                bbtnitmRecSave.Enabled = False
                'tsButtonDelete.Enabled = False
                'tslblLocked.Visible = True
                'TabFollowUp.PageEnabled = False
                'tsmiMassChanges.Enabled = False

            End If
            If RIGHT_READ_ONLY_DOC = True Then
                '  tslblFileslocked.Visible = True
                Doc_ReadOnlyHandler(False)
            End If

        Else
            If DT_RIGHTS_GROUP.Rows.Count > 0 Or DT_RIGHTS_USER.Rows.Count > 0 Then
                'DATENSATZ-RECHTE
                If RIGHT_ADD_R = False Then
                    ' tsButtonAdd.Enabled = False

                End If
                If RIGHT_EDIT_R = False Then
                    ' tslblLocked.Visible = True
                    bbtnitmRecEdit.Enabled = False
                    bbtnitmRecSave.Enabled = False
                    ' tsButtonDelete.Enabled = False
                    ' tsmiMassChanges.Enabled = False
                    If RIGHT_ADD_R = False Then
                        bbtnitmRecSave.Enabled = False
                    End If
                End If
                If RIGHT_DELETE_R = False Then
                    ' tsButtonDelete.Enabled = False
                End If
                'DATEI-RECHTE
                If RIGHT_READ_ONLY_DOC = True Then
                    ' tslblFileslocked.Visible = True
                End If
            End If
        End If
        sw.Done()
    End Sub
#End Region
#Region "Appointments"
    Sub NewEditAppointment(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
        Try
            Dim ctrl As Windows.Forms.Control = sender
            ClassFunctionCommandsUI.NewEditAppointment(ctrl.Name, _EntityId, SELECTED_NODE_RECORD_ID, pnlControls.Controls)
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", ex.Message, ex.StackTrace)
        End Try
    End Sub

    Sub EditAppointment(ByVal sender As Windows.Forms.Control, FormID As Integer)
        Try
            ' Load All appointments first
            frmCalendar.TBPMO_RESOURCESTableAdapter.Fill(frmCalendar.DD_DMSDataSetCalendar.TBPMO_RESOURCES)
            frmCalendar.TBPMO_APPOINTMENTSTableAdapter.Fill(frmCalendar.DD_DMSDataSetCalendar.TBPMO_APPOINTMENTS)

            Dim apt As Appointment = frmCalendar.SchedulerStorage1.Appointments.Items.Find(AddressOf FindAppointment)
            If apt IsNot Nothing Then
                frmCalendar.SchedulerControl1.ShowEditAppointmentForm(apt)
            End If

        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", ex.Message, ex.StackTrace)
        End Try
    End Sub

    Private Function FindAppointment(ByVal apt As Appointment) As Boolean
        Return Convert.ToInt32(apt.CustomFields("RecordID")) = SELECTED_NODE_RECORD_ID
    End Function
#End Region

    Sub Doc_ReadOnlyHandler(state As Boolean)
        Dim sw As New SW("Doc_ReadOnlyHandler")
        If state = False Then
            GridControlDocSearch.ContextMenuStrip = cmsResultFilesBasic
            'tslblDocViewLocked.Visible = True
        ElseIf state = True Then
            GridControlDocSearch.ContextMenuStrip = cmsResultFileDetail
            ' tslblDocViewLocked.Visible = False
        End If
        sw.Done()
    End Sub

    Private LastFindFilterText As String = ""

    Private Sub TreeListDevexpress_ColumnFilterChanged_1(sender As Object, e As EventArgs) Handles TreeListDevexpress.ColumnFilterChanged
        'oFilterActive = True
        Dim oFilterText As String = TreeListDevexpress.FindFilterText
        Dim oNode = TreeListDevexpress.FocusedNode

        If LastFindFilterText <> "" And oFilterText = "" Then
            TreeListDevexpress.FocusedNode = FocusedNode
            TreeListDevexpress.MakeNodeVisible(FocusedNode)
        End If

        LastFindFilterText = oFilterText
    End Sub
    Private Async Sub LoadRecord(pRecord As Integer)
        Try
            CURRENT_RECORD_ID = pRecord
            CURRENT_SEARCH_TYPE = "RECORD"
            ClassHelper.GetDocrecordLinks(CURRENT_RECORD_ID)

            'Wird jetzt bei BeforeRowChange überprüft

            DisableEditMode()

            ' muss vor show selected record data kommen,
            ' sodass die datasource für die angehakten werte existiert (checked list box)
            CtrlBuilder.WatchRecordChanges = False

            ClassControlValues.LoadControlValuesListWithPlaceholders(CURRENT_ENTITY_ID, CURRENT_RECORD_ID, 0, CtrlBuilder.AllControls, _EntityId)
            CtrlBuilder.WatchRecordChanges = True
            If CURRENT_RECORD_ID > 0 Then
                Await Show_Selected_Record_Data(CURRENT_RECORD_ID)
            End If


            ClassRightManagement.Check_Set_Rights(CURRENT_RECORD_ID, _EntityId)
            CONTROL_HANDLING()



            If CURRENT_RECORD_ID > 0 Then
                If RIGHT_RECORD_AND_FILE_READ_ONLY = False And CtrlCommandUI.IsInsert = False Then
                    If DT_CONTROLS_ENTITY.Rows.Count = COUNT_RO_CONTROLS Then
                        bbtnitmRecEdit.Enabled = False
                        bbtnitmRecSave.Enabled = False
                        'tsButtonDelete.Enabled = False
                    Else
                        ' bbtnitmEditRec.Enabled = True
                    End If

                End If
                If RIGHT_RECORD_AND_FILE_READ_ONLY = True Then
                    ' bbtniCopyRecord.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
                    ' bbtniNewVariant2.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
                    ' bbtniParentLink.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
                    ' bbtniWFTask.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
                Else
                    ' bbtniCopyRecord.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
                    ' bbtniNewVariant2.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
                    ' bbtniParentLink.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
                    ' bbtniWFTask.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
                End If

                'tsButtonAdd.Enabled = False
                'MsgBox(SplitContainerFORM.Collapsed)
                'MsgBox(SplitContainerMain.Collapsed)
                'MsgBox(SplitContainerTop.Collapsed)




            End If
            'Liste der geänderten Control Values leeren
            CtrlBuilder.ControlsChanged.Clear()


        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error:", ex.Message & vbNewLine & ex.StackTrace)
        End Try
    End Sub

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

    Private Sub frmNodeNavigation_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing

        If TrySave_Automatic() = False Then

            e.Cancel = True
        End If

        ClassWindowLocation.SaveFormLocationSize(Me, CONSTRUCTORID, CURRENT_SCREEN_ID, "NODE_NAVIGATION")

        CURRENT_OPEN_CONSTRUCTOR_FORMS.Remove(CONSTRUCTORID)

        ' Verhindert, das noch geöffnete Records für immer gelockt sind
        If Not IsNothing(CURRENT_DOCVIEW) Then
            Try
                CURRENT_DOCVIEW.CloseView(CURRENT_DOCVIEW_PATH, 0)
            Catch ex As Exception

            End Try

        End If
    End Sub

    Private Sub pnlControls_Enter(sender As Object, e As EventArgs) Handles pnlControls.Enter
        In_Visible_Record_Group(True)
    End Sub

    Private Sub pnlControls_Leave(sender As Object, e As EventArgs) Handles pnlControls.Leave
        In_Visible_Record_Group(False)
    End Sub

    Private Sub GridControlDocSearch_MouseDown(sender As Object, e As MouseEventArgs) Handles GridControlDocSearch.MouseDown
        In_Visible_Record_Group(False)
    End Sub
    Private Sub pnlControls_MouseDown(sender As Object, e As MouseEventArgs) Handles pnlControls.MouseDown

    End Sub
    Sub In_Visible_Record_Group(oBool As Boolean)
        RibbonPageGroupRecord.Visible = oBool
        RibbonPageGroupRecord.Enabled = oBool
    End Sub
    Private Sub bbtnitmEditRec_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbtnitmRecEdit.ItemClick
        If RECORD_ENABLED = False Then
            EnableEditMode()
        Else

            If TrySave_Automatic() = True Then
                DisableEditMode()
            End If
        End If
    End Sub
    Sub EnableEditMode()
        Dim EditingUser = ClassRecordState.IsRecordLocked(SELECTED_NODE_RECORD_ID)
        ' Überprüfen, ob der Record gerade bearbeitet wird
        If Not IsNothing(EditingUser) And EditingUser <> USER_USERNAME Then
            If USER_IS_ADMIN = True Then
                Dim msg = "Record is in work: " & vbNewLine & $"Dieser Datensatz wird gerade vom Benutzer '{EditingUser}' bearbeitet. Wollen Sie diesen entsperren?"
                Dim msg1 = "Achtung"
                If USER_LANGUAGE <> "de-DE" Then
                    msg = "Record is in work: " & vbNewLine & $"This Record is currently being edited by User '{EditingUser}'. Do You want to unlock the record?"
                    msg1 = "Attention"
                End If
                Dim result As DialogResult = MessageBox.Show(msg, msg1, MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                If result = System.Windows.Forms.DialogResult.Yes Then
                    ClassRecordState.UnlockRecord(SELECTED_NODE_RECORD_ID)
                    Exit Sub
                End If
                BarStaticItemLocked.Visibility = DevExpress.XtraBars.BarItemVisibility.Never

            Else
                BarStaticItemLocked.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
                If USER_LANGUAGE = "de-DE" Then
                    ClassHelper.MSGBOX_Handler("INFO", "Achtung", "Record is in work: " & vbNewLine & String.Format("Dieser Datensatz wird gerade vom Benutzer '{0}' bearbeitet und kann nur lesend abgerufen werden.", EditingUser))
                Else
                    ClassHelper.MSGBOX_Handler("INFO", "Attention", "Record is in work: " & vbNewLine & String.Format("This Record is currently being edited by User '{0}' and only available in Read-Only mode.", EditingUser))
                End If
                ' Wenn Record bearbeitet wird, EnableEditMode abbrechen!
                Exit Sub
            End If


        Else
            'Wenn Record bearbeitet werden kann, IN_WORK auf 1 setzen, um Bearbeitung durch andere zu verhindern!
            ClassRecordState.LockRecord(SELECTED_NODE_RECORD_ID)
        End If

        ' Alle Tabs außer Detailsicht deaktivieren
        'DeactivateTabs()

        CURRENT_CHANGE_STEP += 1
        Dim del = String.Format("DELETE FROM TBPMO_CONTROL_VALUE_CHANGE_HISTORY WHERE UPPER(ADDED_WHO) = '{0}'", USER_USERNAME.ToUpper)
        MYDB_ECM.ExecuteNonQuery(del)

        Lock_RecordControls(False)
        Me.bbtnitmRecSave.Enabled = True

        Dim stg As String
        If USER_LANGUAGE = "de-DE" Then
            stg = "Bearbeiten beenden"
        Else
            stg = "End Working"
        End If

        If RIGHT_RECORD_AND_FILE_READ_ONLY = False Then
            ' tsButtonDelete.Enabled = True
        End If

        CURRENT_RECORD_ID = SELECTED_NODE_RECORD_ID
        ClassHelper.GetDocrecordLinks(CURRENT_RECORD_ID)
        CtrlCommandUI.IsEdit = True
        ' Abhängige Listen laden
        CtrlBuilder.WatchRecordChanges = False
        'ClassControlValues.LoadControlValuesListWithPlaceholders(ENTITY_ID, RECORD_ID, PARENT_ID, CtrlBuilder.AllControls, ENTITY_ID)
        ClassControlValues.Enable_Depending_Controls(_EntityId, SELECTED_NODE_RECORD_ID, 0, CtrlBuilder.AllControls, _EntityId)
        CtrlBuilder.WatchRecordChanges = True

        RECORD_ENABLED = True
        CURRENT_RECORD_ENABLED = True
        If RIGHT_READ_ONLY_DOC = False Then
            Doc_ReadOnlyHandler(True)
        End If
        pnlControls.Focus()
        'If RECORD_ENABLED = False Then
        '    ClassControlValues.LoadControlValuesList(SELECTED_RECORD_ID, ENTITY_ID, CtrlBuilder.AllControls)
        'End If
    End Sub
    Sub DisableEditMode()
        If SELECTED_NODE_RECORD_ID = 0 Then Exit Sub

        Dim sw As New SW("DisableEditMode")
        ClassRecordState.UnlockRecord(SELECTED_NODE_RECORD_ID)
        Dim isinsert As Boolean
        If IsNothing(CtrlCommandUI) Then
            isinsert = 0
        Else
            isinsert = CtrlCommandUI.IsInsert
        End If
        ClassRecordCommands.CHECK_RECORD_FINAL(SELECTED_NODE_RECORD_ID, isinsert)

        Lock_RecordControls(True)
        RECORD_ENABLED = False
        POS_ENABLED = False
        CURRENT_RECORD_ENABLED = False


        'If ADD_RECORDS_CONSTR = False Then
        '    tsButtonAdd.Enabled = False
        'Else
        '    tsButtonAdd.Enabled = True
        'End If
        bbtnitmRecSave.Enabled = False

        If Not IsNothing(CtrlCommandUI) Then
            'ActivateAllTabs()
        End If
        If RECORD_ENABLED = True Then
            ClassControlValues.UnloadControlValuesList(SELECTED_NODE_RECORD_ID, _EntityId, CtrlBuilder.AllControls)
        End If
        If Not IsNothing(CtrlCommandUI) Then
            'If CtrlCommandUI.IsInsert Then
            '    CtrlCommandUI.IsInsert = False
            'End If
            If CtrlCommandUI.IsEdit Then
                CtrlCommandUI.IsEdit = False
            End If
        End If
        If RIGHT_READ_ONLY_DOC = False Then
            Doc_ReadOnlyHandler(True)
        End If
        sw.Done()
    End Sub

#Region "Record Funktionen"
    Sub Focus_Control(name As String)
        Dim controls As Windows.Forms.Control.ControlCollection = pnlControls.Controls

        For Each c As Windows.Forms.Control In controls

            Dim tag As Object = c.Tag
            Dim controlName As String = DirectCast(tag, ClassControlMetadata).Name
            If controlName = name Then

                c.Focus()
                Exit Sub

            End If

        Next
    End Sub
    Public Function TrySave_RequiredControlsFilled() As Boolean
        Dim missingValues As New List(Of String)
        missingValues = ClassControlValues.CheckRequiredControlValues(CtrlBuilder.MasterPanel.Controls)

        If missingValues.Count > 0 Then
            Dim RequiredControlNames = String.Join(vbNewLine, missingValues)

            If (USER_LANGUAGE = "de-DE") Then
                Dim message = String.Format("Die folgenden Steuerelemente müssen ausgefüllt sein: {0}{1}", vbNewLine, RequiredControlNames)
                MessageBox.Show(message, "Muss-Felder ausfüllen", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            Else
                Dim message = String.Format("The following controls must be filled with values: {0}{1}", vbNewLine, RequiredControlNames)
                MessageBox.Show(message, "Fill Required Controls", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            End If

            Focus_Control(missingValues.First())

            ' Muss-Felder sind noch nicht ausgefüllt worden
            Return False
        Else
            ' Muss-Felder sind alle ausgefüllt
            Return True
        End If
    End Function
    ''' <summary>
    ''' Überprüft beim manuellen Speichern, ob Datensatz verändert wurde und
    ''' ob alle Muss-Felder ausgefüllt wurden
    ''' </summary>
    ''' <returns>
    ''' Gibt False zurück, wenn nicht alle Muss-Felder gefüllt wurde,
    ''' ansonsten True
    ''' </returns>
    Public Function TrySave_User() As Boolean
        Try
            'EDIT_STATE = EditState.None
            Update_Status_Label(False)
            Dim RequiredControlsFilled As Boolean = TrySave_RequiredControlsFilled()

            If RECORD_CHANGED = False And RequiredControlsFilled = True Then
                ' Datensatz wurde nicht verändert
                Return True
            Else
                If RequiredControlsFilled = False Then
                    Return False
                End If
            End If

            If RequiredControlsFilled = True Then
                TrySave_DoSave()

                Return True
            Else
                Return False
            End If
        Catch ex As Exception
            MessageBox.Show("Error in TrySave_User: " & vbNewLine & ex.Message)
            Return False
        End Try
    End Function

    Public Sub TrySave_DoSave()
        ERROR_WHILE_SAVING = False
        ' Record Speichern
        Dim ResultMessage = CtrlCommandUI.SaveRecord(SELECTED_NODE_RECORD_ID, _EntityId)
        If ResultMessage <> "ERROR" Then
            ' Status anzeigen
            Update_Status_Label(True, ResultMessage)
        Else
            ERROR_WHILE_SAVING = True
        End If
        'Jetzt die für die Entität notwendigen Prroceduren ausführen
        Customer_Run_Procedures()
        ' RECORD_CHANGED zurücksetzen
        RECORD_CHANGED = False
        'Liste der geänderten Control Values leeren
        CtrlBuilder.ControlsChanged.Clear()
    End Sub

    ''' <summary>
    ''' Fragt den Benutzer beim Datensatzwechsel, ob Änderungen gespeichert werden sollen. Gibt False zurück, wenn Mussfelder ausgefüllt werden müssen, ansonsten True.
    ''' </summary>
    Public Function TrySave_Automatic() As Boolean
        Try
            EDIT_STATE = EditState.None
            Update_Status_Label(False)

            If RECORD_CHANGED = True Then
                Dim ShouldSave As DialogResult
                If USER_LANGUAGE = "de-DE" Then
                    ShouldSave = MessageBox.Show("Sie haben ungespeicherte Änderungen. Wollen Sie diese speichern?", "Ungespeicherte Änderungen", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                Else
                    ShouldSave = MessageBox.Show("There are unsaved changes. Would You like to save?", "Unsaved changes", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                End If

                ' Änderungen sollen gespeichert werden
                If ShouldSave = DialogResult.Yes Then

                    If CtrlCommandUI.IsInsert Then
                        EDIT_STATE = EditState.None
                    End If

                    Dim RequiredControlsFilled As Boolean = TrySave_RequiredControlsFilled()

                    If RequiredControlsFilled = True Then
                        ' Änderungen sollen gespeichert werden,
                        ' Muss-Felder sind alle ausgefüllt
                        TrySave_DoSave()
                        ' Hinzufügen Button wieder aktivieren
                        'If ADD_RECORDS_CONSTR = False Then
                        '    tsButtonAdd.Enabled = False
                        'Else
                        '    tsButtonAdd.Enabled = True
                        'End If
                        If CtrlCommandUI.IsInsert Then
                            Lock_RecordControls(True)
                        End If
                        Return True
                    Else
                        ' Änderungen sollen gespeichert werden, 
                        ' aber Muss-Felder sind noch nicht ausgefüllt worden
                        Return False
                    End If
                Else ' Änderungen sollen nicht gespeichert werden
                    ' Angelegten Record löschen
                    If CtrlCommandUI.IsInsert Then
                        If ClassHelper.DeleteRecord(SELECTED_NODE_RECORD_ID, "TrySave - UserdecidedNotToSave - ENTITY-ID: " & CURRENT_ENTITY_ID) = True Then
                            CtrlCommandUI.IsInsert = False
                            INSERT_IN_ACTION = False
                        End If
                    End If

                    ' Änderungen sollen nicht gespeichert werden
                    RECORD_CHANGED = False

                    ' Hinzufügen Button wieder aktivieren
                    'If ADD_RECORDS_CONSTR = False Then
                    '    tsButtonAdd.Enabled = False
                    'Else
                    '    tsButtonAdd.Enabled = True
                    'End If

                    Return True
                End If
            Else

                ' Datensatz wurde nicht verändert
                Return True
            End If
        Catch ex As Exception
            MessageBox.Show("Error in TrySave_Automatic: " & vbNewLine & ex.Message)
            Return False
        End Try
    End Function
#End Region
    Private Sub Customer_Run_Procedures()
        Try
            Dim DT As DataTable = MYDB_ECM.GetDatatable("SELECT * FROM TBPMO_RUN_PROCEDURES WHERE FORM_ID = " & _EntityId)
            If Not DT Is Nothing Then
                For Each row As DataRow In DT.Rows
                    Dim prsql As String = row.Item("EXECUTE_COMMAND")
                    prsql = prsql.ToUpper.Replace("@FORM_ID", _EntityId)
                    prsql = prsql.ToUpper.Replace("@ENTITY_ID", _EntityId)
                    prsql = prsql.ToUpper.Replace("@RECORD_ID", SELECTED_NODE_RECORD_ID)
                    MYDB_ECM.ExecuteNonQuery(prsql)
                Next
            End If
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Customer_Run_Procedures: ", ex.Message)
        End Try
    End Sub
    Private Async Function RUN_WDSEARCH_GRID(pShowSplashscreen As Boolean) As Task(Of Integer)
        Dim oHandle As IOverlaySplashScreenHandle
        If pShowSplashscreen Then
            oHandle = SplashScreenManager.ShowOverlayForm(Me)
            taskToken = New CancellationTokenSource()
        End If

        Dim sw As New SW("RUN_WDSEARCH_GRID")
        Dim oFilesFound As Integer = 0

        Try
            bsitmtInfoDoc.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
            If CURRENT_SEARCH_TYPE = "NODE_DOWN" Then

                Dim sql = String.Format("DECLARE @return_value int " & vbNewLine &
                    "EXEC	@return_value = [dbo].[PRPMO_NODES_GET_CHILD_RECORDS] @USER_ID = {0}, @NODE_ID = {1} " & vbNewLine &
                    "SELECT	'Return Value' = @return_value", USER_GUID, CURRENT_NODE_GUID)
                Dim DT_ASYNC As DataTable = Await MYDB_ECM.GetDatatableAsync(sql)

                If Not IsNothing(DT_ASYNC) Then
                    Dim result = DT_ASYNC.Rows(0).Item(0)
                    If result <> 0 Then
                        ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Getting SubNodes-Structure", "Check the logfile")
                    End If
                End If

            End If
            Dim DT_RESULT As DataTable
            DT_RESULT = ClassDOC_SEARCH.Get_DOC_RESULTTABLE(DT_RESULTLIST_OPTIONS, DT_RESULTLIST_VARIABLE_VALUE, DT_COLUMNS_GRID_ENTITY, _EntityId, SELECTED_NODE_RECORD_ID, True)

            If IsNothing(DT_RESULT) Then
                Dim msg = "wrong DocSearch-Configuration or unexpected Error in Get_DOC_RESULTTABLE - Check logfile and contact Digital Data"
                GridViewDoc_Search.ViewCaption = msg
                oFilesFound = 0
            Else
                If DT_RESULT.Rows.Count > 0 Then 'Es gibt Suchergebnisse

                    Dim msg = "Dateien für Record: " & SELECTED_NODE_RECORD_ID
                    If CURRENT_SEARCH_TYPE = "ENTITY" Then

                        msg = "Dateien für Entität: "
                        If USER_LANGUAGE <> "de-DE" Then
                            msg = "files for entity: "
                        End If
                        msg &= " (" & DT_RESULT.Rows.Count.ToString & ")"
                    ElseIf CURRENT_SEARCH_TYPE = "RECORD" Then

                        'If NODE_TEXT.Contains(" (") Then
                        '        NODE_TEXT = NODE_TEXT.Substring(0, NODE_TEXT.IndexOf("(") - 1)
                        '    End If
                        msg = String.Format("Dateien für Objekt '{0}' ", SELECTED_NODE_CAPTION)
                        If USER_LANGUAGE <> "de-DE" Then
                            msg = String.Format("Files for Object  '{0}'", SELECTED_NODE_CAPTION)
                        End If
                        msg &= " (" & DT_RESULT.Rows.Count.ToString & ")"

                    ElseIf CURRENT_SEARCH_TYPE = "NODE_DOWN" Then
                        msg = "Dateien für Knotenunterstruktur"
                        If USER_LANGUAGE <> "de-DE" Then
                            msg = "files found in Node-Substructure"
                        End If
                        msg &= " (" & DT_RESULT.Rows.Count.ToString & ")"
                    Else
                        msg = String.Format("Ergebnis der Volltextsuche")
                        If USER_LANGUAGE <> "de-DE" Then
                            msg = String.Format("Result of Fulltext-Search")
                        End If
                        msg &= " (" & DT_RESULT.Rows.Count.ToString & ")"
                    End If

                    GridViewDoc_Search.ViewCaption = msg

                    If DT_RESULT.Rows.Count > 0 Then
                        If CURRENT_SEARCH_TYPE = "FULLTEXT" Then
                            GridViewDoc_Search.ShowFindPanel()
                            GridViewDoc_Search.FindFilterText = CURRENT_FULLTEXT_PATTERN
                        End If
                        If Not IsNothing(DT_DOCRESULT_DROPDOWN_ITEMS) Then
                            If DT_DOCRESULT_DROPDOWN_ITEMS.Rows.Count > 0 Then
                                LOGGER.Info($"RUN_WDSEARCH_GRID - DT_DOCRESULT_DROPDOWN_ITEMS [{DT_DOCRESULT_DROPDOWN_ITEMS.Rows.Count}]!")
                            End If
                        End If


                        ClassWindreamDocGrid.FillColumns(
                           GridViewDoc_Search,
                           DT_RESULT,
                           DT_COLUMNS_GRID_ENTITY,
                           DT_DOCRESULT_DROPDOWN_ITEMS,
                           AddressOf OnCBSelectedValueChanged,
                           AddressOf OnDateSelectedValueChanged,
                           AddressOf OnTextSelectedValueChanged,
                           AddressOf OnCheckboxValueChanged,
                           CURRENT_SEARCH_TYPE, SELECTED_NODE_RECORD_ID)

                    End If
                    'BbtnitmDocSearch.Enabled = TruefRe

                    oFilesFound = DT_RESULT.Rows.Count
                Else

                    Dim msg = "Keine Dateien für '"
                    If CURRENT_SEARCH_TYPE = "ENTITY" Then
                        msg &= " Entität gefunden"
                        If USER_LANGUAGE <> "de-DE" Then
                            msg = "No files found for entity: "
                        End If
                    ElseIf CURRENT_SEARCH_TYPE = "RECORD" Then

                        'If NODE_TEXT.Contains(" (") Then
                        '        NODE_TEXT = NODE_TEXT.Substring(0, NODE_TEXT.IndexOf("(") - 1)
                        '    End If
                        msg &= SELECTED_NODE_CAPTION & "' gefunden"
                        If USER_LANGUAGE <> "de-DE" Then
                            msg = "No files found for object '" & SELECTED_NODE_CAPTION & "'"
                        End If


                        If USER_LANGUAGE <> "de-DE" Then
                            msg = "No files found for record " & SELECTED_NODE_RECORD_ID
                        End If
                    ElseIf CURRENT_SEARCH_TYPE = "NODE_DOWN" Then
                        msg = "Keine Dateien für Knotenunterstruktur gefunden"
                        If USER_LANGUAGE <> "de-DE" Then
                            msg = "No files found in Node-Substructure"
                        End If
                    Else
                        msg = "Keine Dateien für Volltextsuche (" & CURRENT_FULLTEXT_PATTERN & ") gefunden"
                        If USER_LANGUAGE <> "de-DE" Then
                            msg = "No files found for fulltext-search (" & CURRENT_FULLTEXT_PATTERN & ")"
                        End If
                    End If

                    GridViewDoc_Search.ViewCaption = msg
                    GridControlDocSearch.DataSource = Nothing
                    'Clear_Windream_ResultList()

                    oFilesFound = 0
                End If
            End If


        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Run WD-Search Database: ", ex.Message)
        Finally
            sw.Done()
            bsitmtInfoDoc.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
            If pShowSplashscreen Then
                SplashScreenManager.CloseOverlayForm(oHandle)
            End If

        End Try

        Return oFilesFound
    End Function
    Private Sub RUN_ENTITY_DOC_SEARCH()
        Dim sw As New SW("RUN_ENTITY_DOC_SEARCH")
        Try
            Dim oSQL = $"SELECT ENTITY_DOC_SEARCH FROM TBPMO_FORM WHERE GUID = {_EntityId}"
            CURRENT_DOCSEARCH_SQL = MYDB_ECM.GetScalarValue(oSQL)
            If CURRENT_DOCSEARCH_SQL <> String.Empty Then
                Dim oText = $"Die Entität-weite Suche wird im Hintergrund ausgeführt und in einem separaten Fenster angezeigt sobald sie fertig ist."
                If USER_LANGUAGE <> "de-De" Then
                    oText = $"The entity-wide search will be started in background. The result will be displayed when ready."
                End If
                MsgBox(oText, vbOKOnly, "Information")


                CURRENT_DOCSEARCH_SQL = CURRENT_DOCSEARCH_SQL.Replace("@ENTITY_ID", _EntityId)
                CURRENT_DOCSEARCH_SQL = CURRENT_DOCSEARCH_SQL.Replace("@USER_LANGUAGE", USER_LANGUAGE)
                CURRENT_DOCSEARCH_SQL = CURRENT_DOCSEARCH_SQL.Replace("@USER_ECM_ID", USERID_FK_INT_ECM)
                CURRENT_DOCSEARCH_SQL = CURRENT_DOCSEARCH_SQL.Replace("@USER_ID", USER_GUID)


                If USER_LANGUAGE <> "de-DE" Then
                    CURRENT_DOCSEARCH_CAPTION = "Entity-wide search"
                Else
                    CURRENT_DOCSEARCH_CAPTION = "Entitätssuche"
                End If
                Dim myformThread = New Thread(Sub()
                                                  Using frm As New frmDocSearchResult
                                                      Application.Run(frm)

                                                  End Using
                                              End Sub)
                myformThread.Start()
            Else
                MsgBox("Please config the entity-search properly! " & vbNewLine & oSQL, vbOKOnly, "Information")
            End If


        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error RUN_ENTITY_DOC_SEARCH", ex.Message, ex.StackTrace)
        End Try
        sw.Done()
    End Sub
    Private Sub OnCBSelectedValueChanged(sender As Object, e As EventArgs)
        Try
            Dim docId As Integer = ClassWindreamDocGrid.SELECTED_DOC_ID
            If docId = 0 Then
                MsgBox("Sorry no document was selected! Please try again!", MsgBoxStyle.Exclamation)
                Exit Sub
            End If

            Dim ComboBox As ComboBoxEdit = sender
            'Dim ItemComboBox As RepositoryItemComboBox
            'ItemComboBox = sender
            Dim item As ClassWindreamDocGrid.WindreamDocGridComboboxItem = ComboBox.SelectedItem
            Dim value As String = item.Value
            If value.ToUpper = "Not displayable in Group-Search".ToUpper Then
                Exit Sub
            End If
            Dim configId As Integer = item.ConfigID

            Dim user As String = USER_USERNAME

            Dim Sql As String = String.Format("EXEC PRPMO_DOC_VALUE_UPD_INS {0}, {1}, {2}, '{3}', '{4}'", docId, SELECTED_NODE_RECORD_ID, configId, value, user)
            If MYDB_ECM.ExecuteNonQuery(Sql) = False Then
                MsgBox("The Update-Command was not successful! Check the log!",, MsgBoxStyle.Critical)
            Else
                ClassProxy.PRPROXY_DOC_VALUES_UPD(docId, SELECTED_NODE_RECORD_ID)
            End If

        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in OnCBSelectedValueChanged: ", ex.Message)
        End Try
    End Sub

    Private Sub OnDateSelectedValueChanged(sender As Object, e As EventArgs)
        Try
            Dim DatePicker As DateEdit = sender
            Dim value As DateTime = DatePicker.EditValue

            Dim oldValue As Date
            Dim validDate As Boolean = False

            Try
                validDate = Date.TryParse(DatePicker.OldEditValue, oldValue)
            Catch ex As Exception
                oldValue = Date.MinValue
            End Try

            If Not validDate Then
                oldValue = Date.MinValue
            End If

            If oldValue = DatePicker.EditValue Then
                Exit Sub
            End If
            'Dim colTitle = DirectCast(GridControlDocSearch.MainView, DevExpress.XtraGrid.Views.Grid.GridView).FocusedColumn.FieldName
            'Dim configId As Integer = ClassWindreamDocGrid.RESULT_CONFIG_IDS.Item(colTitle)
            ' Config id über mainView -> detailView herausfinden
            Dim mainView As GridView = GridControlDocSearch.MainView
            Dim detailView As GridView = mainView.GetDetailView(mainView.FocusedRowHandle, mainView.GetRelationIndex(mainView.FocusedRowHandle, "docIdDetails"))
            Dim detailRow As DataRowView = detailView.GetRow(detailView.FocusedRowHandle)
            Dim configid = detailRow.Item("CONFIG_ID")

            Dim docId As Integer = ClassWindreamDocGrid.SELECTED_DOC_ID
            If docId = 0 Then
                MsgBox("Sorry no document was selected! Please try again!", MsgBoxStyle.Exclamation)
                Exit Sub
            End If
            Dim user As String = USER_USERNAME
            Dim dateString = value.ToString("yyyy-MM-dd") 'hh:mm:ss.fff
            Dim Sql As String = String.Format("EXEC PRPMO_DOC_VALUE_UPD_INS {0}, {1}, {2}, '{3}', '{4}'", docId, SELECTED_NODE_RECORD_ID, configid, dateString, user)

            If MYDB_ECM.ExecuteNonQuery(Sql) = False Then
                ClassHelper.MSGBOX_Handler("ERROR", "UnexpectedError:", "Error updating doc-metadata (date): " & vbNewLine & "Check the log for further information!")
            Else
                ClassProxy.PRPROXY_DOC_VALUES_UPD(docId, SELECTED_NODE_RECORD_ID)
            End If
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in OnDateSelectedValueChanged: ", ex.Message)
        End Try
    End Sub

    Private Sub OnTextSelectedValueChanged(sender As Object, e As EventArgs)
        Try
            Dim TextBox As TextEdit = sender
            Dim value = TextBox.EditValue
            If value.ToUpper = "Not displayable in Group-Search".ToUpper Then
                Exit Sub
            End If

            'Dim colTitle = DirectCast(GridControlDocSearch.MainView, DevExpress.XtraGrid.Views.Grid.GridView).FocusedColumn.FieldName
            'Dim configId As Integer = ClassWindreamDocGrid.RESULT_CONFIG_IDS.Item(colTitle)
            ' Config id über mainView -> detailView herausfinden
            Dim mainView As GridView = GridControlDocSearch.MainView
            Dim detailView As GridView = mainView.GetDetailView(mainView.FocusedRowHandle, mainView.GetRelationIndex(mainView.FocusedRowHandle, "docIdDetails"))
            Dim detailRow As DataRowView = detailView.GetRow(detailView.FocusedRowHandle)
            Dim configid = detailRow.Item("CONFIG_ID")

            Dim docId As Integer = ClassWindreamDocGrid.SELECTED_DOC_ID
            If docId = 0 Then
                MsgBox("Sorry no document was selected! Please try again!", MsgBoxStyle.Exclamation)
                Exit Sub
            End If
            Dim user As String = USER_USERNAME

            Dim Sql As String = String.Format("EXEC PRPMO_DOC_VALUE_UPD_INS {0}, {1}, {2},'{3}','{4}'", docId, SELECTED_NODE_RECORD_ID, configid, value, user)
            If MYDB_ECM.ExecuteNonQuery(Sql) = False Then
                ClassHelper.MSGBOX_Handler("ERROR", "UnexpectedError:", "Error updating doc-metadata (textbox): " & vbNewLine & "Check the log for further information!")
            Else
                ClassProxy.PRPROXY_DOC_VALUES_UPD(docId, SELECTED_NODE_RECORD_ID)
            End If
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in OnTextSelectedValueChanged: ", ex.Message)
        End Try
    End Sub

    Private Sub OnCheckboxValueChanged(sender As Object, e As EventArgs)
        'TODO Save Checkboxvalue
        Try
            Dim CheckBox As CheckEdit = sender
            Dim value As Boolean = CheckBox.EditValue

            'Config id über mainView -> detailView herausfinden
            Dim mainView As GridView = GridControlDocSearch.MainView
            Dim detailView As GridView = mainView.GetDetailView(mainView.FocusedRowHandle, mainView.GetRelationIndex(mainView.FocusedRowHandle, "docIdDetails"))
            Dim detailRow As DataRowView = detailView.GetRow(detailView.FocusedRowHandle)
            Dim configid = detailRow.Item("CONFIG_ID")

            Dim docId As Integer = ClassWindreamDocGrid.SELECTED_DOC_ID
            If docId = 0 Then
                MsgBox("Sorry no document was selected! Please try again!", MsgBoxStyle.Exclamation)
                Exit Sub
            End If
            Dim user As String = USER_USERNAME

            Dim Sql As String = String.Format("EXEC PRPMO_DOC_VALUE_UPD_INS {0}, {1}, {2},'{3}','{4}'", docId, SELECTED_NODE_RECORD_ID, configid, value, user)
            If MYDB_ECM.ExecuteNonQuery(Sql) = False Then
                ClassHelper.MSGBOX_Handler("ERROR", "UnexpectedError:", "Error updating doc-metadata (checkbox): " & vbNewLine & "Check the log for further information!")
            Else
                ClassProxy.PRPROXY_DOC_VALUES_UPD(docId, SELECTED_NODE_RECORD_ID)
            End If
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in OnCheckboxValueChanged: ", ex.Message)
        End Try
    End Sub

    Private Sub SplitContainer1_SplitterMoved(sender As Object, e As SplitterEventArgs) Handles SplitContainer1.SplitterMoved
        If FORM_LOADED Then
            Save_Splitter_Layout()
        End If

    End Sub
#Region "GridViewEvents"
    Private Sub GridViewDoc_Search_LayoutSave(sender As Object, e As EventArgs) Handles GridViewDoc_Search.ColumnFilterChanged, GridViewDoc_Search.ColumnWidthChanged, GridViewDoc_Search.ColumnPositionChanged
        Save_DocGrid_Layout()
    End Sub

    Private Sub GridViewDoc_Search_FocusedColumnChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.FocusedColumnChangedEventArgs) Handles GridViewDoc_Search.FocusedColumnChanged
        'ClassWindreamDocGrid.GetDocItems(GridViewDoc_Search)
        Refresh_DocID()
    End Sub
    Private Sub GridViewDoc_Search_FocusedRowChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs) Handles GridViewDoc_Search.FocusedRowChanged
        'ClassWindreamDocGrid.GetDocItems(GridViewDoc_Search)
        Refresh_DocID()
    End Sub


    Private Sub GridViewDoc_Search_MasterRowExpanding(sender As Object, e As MasterRowCanExpandEventArgs) Handles GridViewDoc_Search.MasterRowExpanding
        Refresh_DocID()
    End Sub

    Private Sub GridViewDoc_Search_MasterRowExpanded(sender As Object, e As CustomMasterRowEventArgs) Handles GridViewDoc_Search.MasterRowExpanded
        Refresh_DocID()
    End Sub
    Sub Refresh_DocID()
        If ClassWindreamDocGrid.SELECTED_DOC_ID <> 0 Then
            Dim omsg = "Doc-ID: " & ClassWindreamDocGrid.SELECTED_DOC_ID.ToString
            Update_DocID_Label(True, omsg, EditState.Update)


        Else
            Update_DocID_Label(True, "DocRow not selected", EditState.None)
        End If
    End Sub
    Sub Save_DocGrid_Layout()
        Try
            If FORM_LOADED And Node_AfterSelect = False Then
                Dim XMLPath = Get_DocGrid_Layout_Filename()
                GridViewDoc_Search.SaveLayoutToXml(XMLPath)


                Update_Status_Label(True, "Grid Layout Saved")
            End If

        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", ex.Message, ex.StackTrace)
        End Try
    End Sub
    Sub Load_DocGrid_Layout()
        Try

            Dim XMLPath = Get_DocGrid_Layout_Filename()
            If File.Exists(XMLPath) Then

                GridViewDoc_Search.RestoreLayoutFromXml(XMLPath)
                GridViewDoc_Search.GuessAutoFilterRowValuesFromFilter()
                GridViewDoc_Search.ClearColumnsFilter()
                GridViewDoc_Search.ClearFindFilter()
            End If

        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", ex.Message, ex.StackTrace)
        End Try
    End Sub
    Private Function Get_DocGrid_Layout_Filename()
        Dim EntityRegex As New RegularExpressions.Regex("\s+\(\d+\)")
        Dim Filename As String = String.Format("GridViewDoc_Search_{0}_{1}_UserLayout.xml", "Entity" & _EntityId, CONSTRUCTOR_DETAIL_ID)
        LAYOUT_DOC_GRIDVIEW = System.IO.Path.Combine(Application.UserAppDataPath(), Filename)
        Return LAYOUT_DOC_GRIDVIEW
    End Function
#End Region
    Function GetSafeFilename(filename As String)
        Return String.Join("_", filename.Split(Path.GetInvalidFileNameChars()))
    End Function
    Private Async Function Reset_View_layout() As Task
        Try
            Dim XMLPath = Get_DocGrid_Layout_Filename()
            If File.Exists(XMLPath) Then
                Me.Cursor = Cursors.WaitCursor
                File.Delete(XMLPath)
                GridControlDocSearch.DataSource = Nothing
                GridViewDoc_Search.Columns.Clear()

                Await RUN_WDSEARCH_GRID(True)

            Else
                MsgBox("Resetting the layout was not successful - File not existing!", MsgBoxStyle.Information)
            End If
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Resetting Layout DocGrid: ", ex.Message)
        End Try
        Me.Cursor = Cursors.Default
    End Function

    Private Async Sub bbtnitmDocResultLayoutReset_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbtnitmDocResultLayoutReset.ItemClick
        Await Reset_View_layout()
    End Sub

    Private Sub bbtnitmDocResultLayoutSave_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbtnitmDocResultLayoutSave.ItemClick
        Save_DocGrid_Layout()
    End Sub

    Private Sub GridControlDocSearch_DoubleClick(sender As Object, e As EventArgs) Handles GridControlDocSearch.DoubleClick
        Open_File()
    End Sub
#Region "Dropping Files"
    Sub Drag_Enter(e As DragEventArgs)
        If _EntityId <> 0 Then
            ClassDragDrop.Drag_enter(e)
        Else
            Update_Status_Label(True, "No entity selected", EditState.Insert)
        End If
    End Sub
    Private Async Function Drag_Drop(e As DragEventArgs) As Task
        Try
            If ClassDragDrop.Drop_File(e) = False Then
                Exit Function
            End If
            If USER_PERSONIFIED_TEST = True Then
                ClassHelper.MSGBOX_Handler("INFO", "Attention", "You are using ADDI in personified mode! Adding files is not allowed!")
                Exit Function
            End If
            If clsWindream.Create_Session = False Then
                ClassHelper.MSGBOX_Handler("INFO", "Attention", "Check Your windream-connection and restart ADDI afterwards.", "Could not create a windream session!")
                Exit Function
            End If
            If _EntityId <> 0 And (RIGHT_READ_ONLY_DOC = False And GridControlDocSearch.ContextMenuStrip.Name = "ContextMenuStripResultFiles") Or RIGHT_ADD_DOC = True Then
                Dim sql = "select count(*) from VWPMO_DOKUMENTTYPES where FORMVIEW_ID = " & FORMVIEW_ID
                Dim count_DT = MYDB_ECM.GetScalarValue(sql)
                If count_DT = 0 And CURRENT_ENTITY_REDUNDANT_ID = 0 Then
                    MsgBox("No documenttypes for this entity configured! Indexing is not possible!" & vbNewLine & "Please check the configuration!", MsgBoxStyle.Exclamation)
                    Exit Function
                ElseIf count_DT = 0 And CURRENT_ENTITY_REDUNDANT_ID <> 0 Then
                    sql = "select count(*) from VWPMO_DOKUMENTTYPES where FORM_ID = " & CURRENT_ENTITY_REDUNDANT_ID
                    count_DT = MYDB_ECM.GetScalarValue(sql)
                    If count_DT = 0 Then
                        MsgBox("No documenttypes for this entity configured! Indexing is not possible!" & vbNewLine & "Please check the configuration!", MsgBoxStyle.Exclamation)
                        Exit Function
                    End If
                End If
                If RECORD_CHANGED = True Then
                    If Save_Record() = False Then
                        Exit Function
                    End If
                End If
                CURRENT_CONTROL_DOCTYPE_MATCH = 0
                If CONTROL_DOCTYPE_MATCH <> 0 Then
                    Try
                        CURRENT_CONTROL_DOCTYPE_MATCH = ""
                        CURRENT_CONTROL_DOCTYPE_MATCH = ClassControlValues.GetControlValuesREC_CONTROL(CURRENT_RECORD_ID, CONTROL_DOCTYPE_MATCH)
                    Catch ex As Exception
                        CURRENT_CONTROL_DOCTYPE_MATCH = 0
                        CURRENT_CONTROL_DOCTYPE_MATCH = ""
                    End Try

                End If

                DROPPED_CHECKED = False
                If e.Data.GetDataPresent(DataFormats.StringFormat) Then
                    Dim Wert As String = CType(e.Data.GetData(DataFormats.StringFormat), Object)
                    Console.WriteLine("DragDrop-Wert: " & Wert)
                    If Wert.Contains("SCAN") Then
                        Dim split() = Wert.Split(";")
                        If IsNumeric(split(1)) Then
                            CURRENT_FILEID = split(1)

                            CURRENT_FORMVIEW_ID = FORMVIEW_ID
                            ClassHelper.Create_USER_FILE_TABLE()
                            If Not IsNothing(CURRENT_TBPMO_FILES_USER) Then
                                If CURRENT_TBPMO_FILES_USER.Rows.Count > 0 Then
                                    frmWM_IndexFile.ShowDialog()
                                End If
                            End If

                            'RUN_WD_SEARCH(WD_Suche, "RECORD")
                        End If
                    ElseIf (e.Data.GetDataPresent("FileGroupDescriptor")) AndAlso (e.Data.GetDataPresent("FileContents")) Then
                        If ClassDragDrop.Drop_File(e) = True Then
                            Check_Dropped_Files()
                        End If
                    ElseIf e.Data.GetDataPresent("FileGroupDescriptor") Then
                        If ClassDragDrop.Drop_File(e) = True Then
                            Check_Dropped_Files()
                        End If
                    End If
                Else
                    If ClassDragDrop.Drop_File(e) = True Then
                        Check_Dropped_Files()
                    End If

                End If
                'Nur wenn neue Dateien abgelegt wurden muss die Prozedur zur aktualisierung der windream Dateien ausgeführt werden...ansonsten muss nichts passieren
                If NEW_FILES_ADDED = True Then
                    Me.Cursor = Cursors.WaitCursor
                    Await RUN_WDSEARCH_GRID(True)
                    ClassHelper.GetDocrecordLinks(CURRENT_RECORD_ID)
                    TimerClearResultfiles.Start()
                Else
                    LOGGER.Debug("No new files were added or windream tab is not focused!")
                End If
                Me.Cursor = Cursors.Default
            Else
                'If RIGHT_RECORD_AND_FILE_READ_ONLY = True Then
                '    LOGGER.Warn("RIGHT_RECORD_AND_FILE_READ_ONLY is set! No DragDrop allowed")
                'End If
                If RIGHT_READ_ONLY_DOC = True Then
                    LOGGER.Warn("RIGHT_WD_FORBIDDEN is set! No DragDrop allowed")
                Else
                    LOGGER.Warn("No DragDrop allowed - ELSE")
                End If

            End If
        Catch ex As Exception
            LOGGER.Warn("Unexpected Error in Drag_Drop: " & ex.Message)
            MsgBox("Unexpected Error in DragDrop - Please check the log for further information!", MsgBoxStyle.Exclamation)
        Finally

        End Try
    End Function
    Private DROPPED_CHECKED As Boolean = False
    Sub Check_Dropped_Files()
        Try
            NEW_FILES_ADDED = False
            If RECORD_CHANGED = True Then
                If Save_Record() = False Then
                    Exit Sub
                End If
            End If
            If CURRENT_RECORD_ID = 0 Then
                ClassHelper.MSGBOX_Handler("INFO", "Attention", "Input missing: ", "Please choose a record.")
                Exit Sub
            End If
            If DROPPED_CHECKED = False Then
                For Each Str As Object In ClassDragDrop.files_dropped
                    If Not IsNothing(Str) Then
                        Dim DropType = Str.Substring(0, Str.LastIndexOf("@") + 1)
                        If DropType.ToString.Contains("SCAN") = False Then
                            LOGGER.Info("Check_Dropped_Files:" & Str.ToString)
                            Dim CURRENT_WORKFILE = Str.Substring(Str.LastIndexOf("@") + 1)
                            If CURRENT_WORKFILE.ToString.Contains("@") Then
                                MsgBox("File contains invalid operator @!" & vbNewLine & "Please rename file and try again!", MsgBoxStyle.Exclamation)
                                Continue For
                            End If
                            If CURRENT_WORKFILE.ToString.Contains("'") Then
                                MsgBox("File contains invalid operator '!" & vbNewLine & "Please rename file and try again!", MsgBoxStyle.Exclamation)
                                Continue For
                            End If
                            ClassFolderWatcher.Insert_USER_File(CURRENT_WORKFILE, DropType)
                        End If
                    End If
                Next
                DROPPED_CHECKED = True
            End If

            Dim sql = "select count(*) from VWPMO_DOKUMENTTYPES where FORMVIEW_ID = " & FORMVIEW_ID
            Dim count_DT = MYDB_ECM.GetScalarValue(sql)
            If count_DT = 0 And CURRENT_ENTITY_REDUNDANT_ID = 0 Then
                ClassHelper.MSGBOX_Handler("INFO", "Attention", "Configuration missing: ", "No documenttypes for this entity (" & FORMVIEW_ID.ToString & ") configured! Indexing is not possible! Please check the configuration.")
                Exit Sub
            ElseIf count_DT = 0 And CURRENT_ENTITY_REDUNDANT_ID <> 0 Then
                sql = "select count(*) from VWPMO_DOKUMENTTYPES where FORM_ID = " & CURRENT_ENTITY_REDUNDANT_ID
                count_DT = MYDB_ECM.GetScalarValue(sql)
                If count_DT = 0 Then
                    ClassHelper.MSGBOX_Handler("INFO", "Attention", "Configuration missing: ", "No documenttypes for the redundant entity (" & CURRENT_ENTITY_REDUNDANT_ID.ToString & ") configured! Indexing is not possible! Please check the configuration.")
                    Exit Sub
                End If
            End If
            ClassHelper.Create_USER_FILE_TABLE()
            If Not IsNothing(CURRENT_TBPMO_FILES_USER) Then
                If CURRENT_TBPMO_FILES_USER.Rows.Count > 0 Then
                    For Each Filerow As DataRow In CURRENT_TBPMO_FILES_USER.Rows
                        If CBool(Filerow.Item("WORKED")) = False Then
                            'Dim datei = Str.ToString.Replace("@DROPFROMFSYSTEM@", "")
                            CURRENT_FILEID = Filerow.Item("GUID")
                            ' CURRENT_PARENT_ENTITY_ID = PARENT_ENTITYID
                            'CURRENT_RECORD_ID = RECORD_ID
                            'CURRENT_ENTITY_ID = ENTITY_ID
                            CURRENT_FORMVIEW_ID = FORMVIEW_ID
                            frmWM_IndexFile.ShowDialog()

                        Else

                        End If
                    Next
                End If
            End If

        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Check_Dropped_Files: ", ex.Message)
        End Try

    End Sub
    Private Async Sub GridControlDocSearch_DragDrop(sender As Object, e As DragEventArgs) Handles GridControlDocSearch.DragDrop
        Await Drag_Drop(e)
    End Sub

    Private Sub GridControlDocSearch_DragEnter(sender As Object, e As DragEventArgs) Handles GridControlDocSearch.DragEnter
        Drag_Enter(e)
    End Sub

    Private Async Sub pnlControls_DragDrop(sender As Object, e As DragEventArgs) Handles pnlControls.DragDrop
        Await Drag_Drop(e)
    End Sub

    Private Sub pnlControls_DragEnter(sender As Object, e As DragEventArgs) Handles pnlControls.DragEnter
        Drag_Enter(e)
    End Sub
    Private Sub SplitContainer1_DragEnter(sender As Object, e As DragEventArgs) Handles SplitContainer1.DragEnter
        Drag_Enter(e)
    End Sub

    Private Async Sub SplitContainer1_DragDrop(sender As Object, e As DragEventArgs) Handles SplitContainer1.DragDrop
        Await Drag_Drop(e)
    End Sub
#End Region

    Function Save_Record()
        Try
            Me.Cursor = Cursors.WaitCursor
            SAVE_ROUTINE_ACTIVE = True

            Dim RequiredControlsFilled As Boolean = TrySave_RequiredControlsFilled()
            If RequiredControlsFilled = False Then
                Return False
            End If
            If CtrlCommandUI.IsInsert Then
                EDIT_STATE = EditState.Insert
            Else
                EDIT_STATE = EditState.Update
                NEW_RECORD_ID = 0
                If RECORD_CHANGED = False Then
                    Update_Status_Label(True, "NO CHANGES in Record.")

                    DisableEditMode()
                    EDIT_STATE = EditState.None
                    Me.Cursor = Cursors.Default
                    Return True
                End If

            End If



            If TrySave_User() = False Then
                ' Cursor zurücksetzen
                Me.Cursor = Cursors.Default
                Return False
            Else
                If RECORD_CHANGED = True Then
                    RECORD_CHANGED = False
                End If


                ClassProxy.PRPROXY_RECORD_UPD_INS(CURRENT_ENTITY_ID, CURRENT_RECORD_ID)
            End If

            Dim recid As Integer
            'If EDIT_STATE = EditState.Update Then
            '    recid = RECORD_ID
            'Else
            '    recid = NEW_RECORD_ID
            'End If
            recid = CURRENT_RECORD_ID


            If recid = 0 Then
                ClassHelper.MSGBOX_Handler("ERROR", "Attention:", "No Current row selected")
                Me.Cursor = Cursors.Default
                Return False
            End If
            If EDIT_STATE = EditState.Insert Then

                Dim exec = String.Format("EXEC PRPMO_CLIENT_AFTER_RECORD_INSERT {0}", CURRENT_RECORD_ID)
                MYDB_ECM.ExecuteNonQuery(exec)
            ElseIf EDIT_STATE = EditState.Update Then
                'Weil es ein Insert war müssen noch die Daten gespeichert/erneuert werden

            End If
            CtrlCommandUI.IsInsert = False
            CtrlCommandUI.IsEdit = False
            INSERT_IN_ACTION = False
            'Jetzt den Record nochmal laden
            ' Show_Selected_Record_Data(SELECTED_RECORD_ID)
            Update_Status_Label(True, "Record saved - " & Now, EditState.Update)
            Update_Record_Label(CURRENT_RECORD_ID)

        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error Saving Record", ex.Message, ex.StackTrace)
            Return False
        End Try
        'If ADD_RECORDS_CONSTR = False Then
        '    tsButtonAdd.Enabled = False
        'Else
        '    tsButtonAdd.Enabled = True
        'End If


        If CtrlCommandUI.IsInsert Then
            bbtnitmRecSave.Enabled = False
            '
        End If


        'If CtrlCommandUI.IsInsert Then
        '    tsButtonSave.Enabled = False
        '    tsButtonCancel.Visible = False
        'End If
        DisableEditMode()

        CtrlCommandUI.IsInsert = False
        INSERT_IN_ACTION = False
        EDIT_STATE = EditState.None
        RECORD_CHANGED = False
        SAVE_ROUTINE_ACTIVE = False
        Me.Cursor = Cursors.Default
        Return True
    End Function
    Private Sub cmsResultFileDetail_Opening(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles cmsResultFileDetail.Opening
        Try
            If clsWindream.SESSION_CREATED = False Then
                ClassHelper.MSGBOX_Handler("INFO", "Attention", "Check Your windream-connection and restart ADDI afterwards.", "Could not create a windream session!")
                e.Cancel = True
            End If
            Me.Cursor = Cursors.WaitCursor

            Dim oSelectedDocs = ClassWindreamDocGrid.GetSelectedDocuments(GridViewDoc_Search)

            'Refresh_DocID()

            If ClassWindreamDocGrid.HasNoSelectedDocuments(GridViewDoc_Search) Then
                e.Cancel = True
                Exit Sub
            End If

            If oSelectedDocs.First.DocId = 0 Then
                e.Cancel = True
                Exit Sub
            End If

            If oSelectedDocs.Count > 1 Then
                ContextMenu_Multiplefiles()
            ElseIf oSelectedDocs.Count = 1 Then
                File_in_Work()
                Dim oSelectedDocument = oSelectedDocs.First
                Dim Result = ClassDOC_SEARCH.Get_File_Rights(oSelectedDocument.DocId)
                If Not IsNothing(Result) Then
                    _RowReadOnly = False
                    Select Case Result.ToString
                        Case "R"
                            ContextMenu_Read()
                        Case "RW"
                            ContextMenu_Write()
                        Case "RWA"
                            ContextMenu_Write()
                        Case ""
                            If USER_IS_ADMIN = False Then
                                ContextMenu_Read()
                            Else
                                LOGGER.Warn("FileRight is '' but User is Admin!! - Check the configuration!")
                            End If
                            _RowReadOnly = True
                    End Select
                    CURRENT_FILE_RIGHT = Result.ToString
                Else
                    ContextMenu_Read()
                    ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Getting rights - check the log")
                    e.Cancel = True
                End If
                If _RowReadOnly = False Then
                    If RIGHT_READ_ONLY_DOC = True Then
                        If USER_IS_ADMIN = False Then
                            ContextMenu_Read()
                        Else
                            LOGGER.Warn("RIGHT_READ_ONLY_DOC = True but User is Admin!! - Check the configuration!")
                        End If
                    End If
                End If

                If oSelectedDocs.First.DisplayName <> "" Then
                    tsmiFileRenameDisplayname.Visible = True
                Else
                    tsmiFileRenameDisplayname.Visible = False
                End If
            Else
                tsmiFileRenameDisplayname.Visible = False
            End If

        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Opening DocContextMenu: ", ex.Message)
            e.Cancel = True
        Finally
            Me.Cursor = Cursors.Default
        End Try
    End Sub

    Sub ContextMenu_Multiplefiles()
        tsmiFileProperties.Enabled = False

        tsmiFileOpen.Enabled = False
        tsmiFileFolderOpen.Enabled = False

        tsmiFileInWork.Enabled = False

        tsmiFileLink_Add.Enabled = True
        tsmiFileLink_ShowAll.Enabled = True
        tsmiFileLinkRemove.Enabled = True

        tsmiFileRename.Enabled = False
        tsmiFileVersion.Enabled = False
        tsmiFileRightsShow.Enabled = False

        tsmiFileDelete.Enabled = False
    End Sub

    Sub ContextMenu_Read()
        tsmiFileProperties.Enabled = True

        tsmiFileOpen.Enabled = True
        tsmiFileFolderOpen.Enabled = True

        tsmiFileInWork.Enabled = False

        tsmiFileLink_Add.Enabled = False
        tsmiFileLink_ShowAll.Enabled = True
        tsmiFileLinkRemove.Enabled = False

        tsmiFileRename.Enabled = False
        tsmiFileVersion.Enabled = True
        tsmiFileRightsShow.Enabled = True

        tsmiFileDelete.Enabled = False

    End Sub
    Sub ContextMenu_Write()
        tsmiFileProperties.Enabled = True

        tsmiFileOpen.Enabled = True
        tsmiFileFolderOpen.Enabled = True

        tsmiFileInWork.Enabled = True

        tsmiFileLink_Add.Enabled = True
        tsmiFileLink_ShowAll.Enabled = True
        tsmiFileLinkRemove.Enabled = True

        tsmiFileRename.Enabled = True
        tsmiFileVersion.Enabled = True
        tsmiFileRightsShow.Enabled = True

        tsmiFileDelete.Enabled = True
    End Sub
    Sub Open_File()
        Me.Cursor = Cursors.WaitCursor
        Dim allow_Open As Boolean = False
        'ClassWindreamDocGrid.GetDocItems(GridViewDoc_Search)

        Dim Result = ClassDOC_SEARCH.Get_File_Rights(ClassWindreamDocGrid.SELECTED_DOC_ID)


        If Not IsNothing(Result) Then
            Select Case Result.ToString
                Case "R"
                    allow_Open = True
                Case "RW"
                    allow_Open = True
                Case "RWA"
                    allow_Open = True
            End Select
        End If
        If allow_Open = True Then
            'If IsNothing(ClassWindreamDocGrid.DT_RESULTFILES) Then
            '    MsgBox("Could not read File Parameters(5)!", MsgBoxStyle.Exclamation)
            '    Exit Sub
            'End If
            If ClassWindreamDocGrid.HasNoSelectedDocuments(GridViewDoc_Search) Then
                MsgBox("Could not read File Parameters(5)!", MsgBoxStyle.Exclamation)
                Exit Sub
            End If
            'For Each row As DataRow In ClassWindreamDocGrid.DT_RESULTFILES.Rows
            '    If ClassHelper.File_open(row.Item("DOC_PATH"), row.Item("DOC_ID")) = True Then
            '        TimerFileHandle.Enabled = True
            '    End If
            'Next
            For Each oDoc As ClassWindreamDocGrid.WindreamDoc In ClassWindreamDocGrid.GetSelectedDocuments(GridViewDoc_Search)
                If ClassHelper.File_open(oDoc.DocPath, oDoc.DocId) = True Then
                    TimerFileHandle.Enabled = True
                End If
            Next
        Else
            If clsWD_GET.WDFile_exists(ClassWindreamDocGrid.SELECTED_DOC_PATH, DD_LIB_Standards.clsDatabase.DB_PROXY_INITIALIZED, ClassProxy.MyLinkedServer, True) = True Then
                ClassHelper.MSGBOX_Handler("ERROR", "Right-Management", "File is existing, but you do not have the rights to open this file! " & vbNewLine & "Please contact your admin!" & vbNewLine & "DOC-ID: " & ClassWindreamDocGrid.SELECTED_DOC_ID.ToString)
            Else
                ClassHelper.MSGBOX_Handler("ERROR", "", "File does not exist! Please contact your admin!")
            End If
        End If
        Me.Cursor = Cursors.Default
    End Sub
    Sub File_in_Work()
        IW_USER = ""
        IW_COMMENT = ""
        INWORK_FILE = False
        tsmiFileInWork.Enabled = True
        Try
            Dim expression As String
            expression = "DocID = " & ClassWindreamDocGrid.SELECTED_DOC_ID
            Dim foundRowsLevel0() As DataRow
            ' Use the Select method to find all rows matching the filter.
            foundRowsLevel0 = CURRENT_DOC_RESULTS.Select(expression)

            Try
                Dim oSQLDRList = $"Select COALESCE(IN_WORK_USER,'') IN_WORK_USER, COALESCE(IN_WORK_COMMENT,'') IN_WORK_COMMENT,IN_WORK FROM TBPMO_DOCRESULT_LIST where DocID = {ClassWindreamDocGrid.SELECTED_DOC_ID}"
                Dim oDT As DataTable = MYDB_ECM.GetDatatable(oSQLDRList)
                If Not IsNothing(oDT) Then
                    If oDT.Rows.Count = 1 Then
                        IW_USER = oDT.Rows(0).Item("IN_WORK_USER")
                        IW_COMMENT = oDT.Rows(0).Item("IN_WORK_COMMENT")
                        INWORK_FILE = CBool(oDT.Rows(0).Item("IN_WORK"))
                    End If
                End If
            Catch ex As Exception
                LOGGER.Error(ex)
                IW_USER = ""
                IW_COMMENT = ""
            End Try


            Dim displ As String
            If INWORK_FILE = True Then
                If IW_USER.ToUpper = USER_USERNAME.ToUpper Or USER_IS_ADMIN Or USER_IS_SUPERVISOR Then
                    displ = "Datei wieder freigeben"
                    If USER_LANGUAGE <> "de-DE" Then
                        displ = "Set file free"
                    End If
                Else
                    displ = "Datei in Bearbeitung (zeige Info)"
                    If USER_LANGUAGE <> "de-DE" Then
                        displ = "File is in work (show details)"
                    End If
                End If
            Else
                displ = "Datei in Bearbeitung nehmen"
                If USER_LANGUAGE <> "de-DE" Then
                    displ = "Lock file for working"
                End If
            End If
            tsmiFileInWork.Text = displ
        Catch ex As Exception
            LOGGER.Warn("Unexpected Error in File-Work Info: " & ex.Message)
            tsmiFileInWork.Enabled = False
        End Try
    End Sub

    Private Async Sub tsmiFileInWork_Click(sender As Object, e As EventArgs) Handles tsmiFileInWork.Click
        If ClassWindreamDocGrid.HasNoSelectedDocuments(GridViewDoc_Search) Then
            MsgBox("Could not read File Parameters (3)!", MsgBoxStyle.Exclamation)
            Exit Sub
        End If
        ClassFileResult.DocID = ClassWindreamDocGrid.SELECTED_DOC_ID
        If INWORK_FILE = True Then ' Datei ist in Bearbeitung
            Dim msglbl As String
            Dim msg1 As String
            If IW_USER.ToUpper = USER_USERNAME.ToUpper Or USER_IS_ADMIN Or USER_IS_SUPERVISOR Then
                If ClassFileResult.Set_InWork(0, "") = True Then
                    Await RUN_WDSEARCH_GRID(True)
                End If
            Else
                msglbl = "In Bearbeitung durch User '" & IW_USER & "' - Kommentar:"
                msg1 = IW_COMMENT
                If USER_LANGUAGE <> "de-DE" Then
                    msglbl = "File in Work through User '" & IW_USER & "' - Comment:"
                End If
                ClassHelper.MSGBOX_Handler("INFO", "Information file", msglbl, msg1)
            End If
        Else
            frmFileInWork.ShowDialog()
            ClassWindreamDocGrid.SELECTED_INWORK = ClassFileResult.InWork
            Await RUN_WDSEARCH_GRID(True)
        End If
    End Sub

    Private Sub frmNodeNavigation_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        Dim sw As New SW("Form_Shown")
        Me.BringToFront()
        ' LoadLayouts()
        sw.Done()
        FORM_SHOWN = True
    End Sub

    Private Async Sub tsmiFileRenameDisplayname_Click(sender As Object, e As EventArgs) Handles tsmiFileRenameDisplayname.Click
        Try
            If ClassWindreamDocGrid.HasNoSelectedDocuments(GridViewDoc_Search) Then
                Exit Sub
            End If

            'If ClassWindreamDocGrid.DT_RESULTFILES.Rows.Count = 1 Then
            '    If ClassWindreamDocGrid.DT_RESULTFILES.Rows(0).Item("DISPLAYNAME") <> "" Then
            '        Dim oRowHandle As Integer = GridViewDoc_Search.FocusedRowHandle
            '        Dim frm As New frmFileRename(1, ClassWindreamDocGrid.DT_RESULTFILES.Rows(0).Item("DISPLAYNAME"), "Displayname")
            '        frm.ShowDialog()
            '        RUN_WDSEARCH_GRID(True)
            '        If Not IsNothing(oRowHandle) Then
            '            GridViewDoc_Search.FocusedRowHandle = oRowHandle
            '        End If
            '    End If
            'End If
            Dim oDocuments = ClassWindreamDocGrid.GetSelectedDocuments(GridViewDoc_Search)

            If oDocuments.First.DisplayName <> "" Then
                Dim oRowHandle As Integer = GridViewDoc_Search.FocusedRowHandle
                Dim frm As New frmFileRename(1, oDocuments.First.DisplayName, "Displayname")
                frm.ShowDialog()
                Await RUN_WDSEARCH_GRID(True)
                If Not IsNothing(oRowHandle) Then
                    GridViewDoc_Search.FocusedRowHandle = oRowHandle
                End If
            End If
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Unexpected Error in getting the Displayname: ", ex.Message)
        End Try
    End Sub

    Private Async Sub tsmiFileRenameFilename_Click(sender As Object, e As EventArgs) Handles tsmiFileRenameFilename.Click
        Try
            Dim RENAME_DOC_PATH
            Try
                RENAME_DOC_PATH = GridViewDoc_Search.GetFocusedRowCellValue(GridViewDoc_Search.Columns("FULLPATH"))
            Catch ex As Exception
                LOGGER.Warn("Attention: Could not set DocVariable RENAME_DOC_PATH: " & ex.Message)
                RENAME_DOC_PATH = Nothing
            End Try
            'If IsNothing(ClassWindreamDocGrid.DT_RESULTFILES) Then
            '    MsgBox("Could not read File Parameters!", MsgBoxStyle.Exclamation)
            '    Exit Sub
            'End If
            If ClassWindreamDocGrid.HasNoSelectedDocuments(GridViewDoc_Search) Then
                MsgBox("Could not read File Parameters!", MsgBoxStyle.Exclamation)
                Exit Sub
            End If
            If RENAME_DOC_PATH <> "" Then
                Dim FileToRename As String
                FileToRename = Path.GetFileNameWithoutExtension(RENAME_DOC_PATH)
                Dim oRowHandle As Integer = GridViewDoc_Search.FocusedRowHandle
                Dim frm As New frmFileRename(1, FileToRename, "Filename")
                frm.ShowDialog()
                Await RUN_WDSEARCH_GRID(True)
                If Not IsNothing(oRowHandle) Then
                    GridViewDoc_Search.FocusedRowHandle = oRowHandle
                End If
            End If
        Catch ex As Exception
            MsgBox("Unexpected Error in getting the filename: " & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub frmNodeNavigation_Click(sender As Object, e As EventArgs) Handles MyBase.Click
        If CURRENT_ENTITY_ID <> _EntityId Then
            CURRENT_ENTITY_ID = _EntityId
            CURRENT_RECORD_ID = 0
        End If
    End Sub

    Private Sub tsmiFileOpen_Click(sender As Object, e As EventArgs) Handles tsmiFileOpen.Click
        Open_File()
    End Sub

    Private Sub tsmiFileFolderOpen_Click(sender As Object, e As EventArgs) Handles tsmiFileFolderOpen.Click
        'If IsNothing(ClassWindreamDocGrid.DT_RESULTFILES) Then
        '    MsgBox("Could not read File Parameters(5)!", MsgBoxStyle.Exclamation)
        '    Exit Sub
        'End If
        If ClassWindreamDocGrid.HasNoSelectedDocuments(GridViewDoc_Search) Then
            MsgBox("Could not read File Parameters(5)!", MsgBoxStyle.Exclamation)
            Exit Sub
        End If
        'For Each row As DataRow In ClassWindreamDocGrid.DT_RESULTFILES.Rows
        '    ClassHelper.Open_Folder(row.Item("DOC_PATH"), row.Item("DOC_ID"))
        'Next
        For Each oDoc As ClassWindreamDocGrid.WindreamDoc In ClassWindreamDocGrid.GetSelectedDocuments(GridViewDoc_Search)
            ClassHelper.Open_Folder(oDoc.DocPath, oDoc.DocId)
        Next
    End Sub

    Private Sub tsmiFileLink_Add_Click(sender As Object, e As EventArgs) Handles tsmiFileLink_Add.Click
        Try
            'ClassWindreamDocGrid.GetDocItems(GridViewDoc_Search)
            'If IsNothing(ClassWindreamDocGrid.DT_RESULTFILES) Then
            '    MsgBox("Could not read File Parameters (LinkRecord)!", MsgBoxStyle.Exclamation)
            '    Exit Sub
            'End If
            'ClassWindreamDocGrid.GetDocItems(GridViewDoc_Search)
            If ClassWindreamDocGrid.HasNoSelectedDocuments(GridViewDoc_Search) Then
                MsgBox("Could not read File Parameters (LinkRecord)!", MsgBoxStyle.Exclamation)
                Exit Sub
            End If
            Refresh_Selected_Table()

            Dim oDocuments = DocList.SelectedDocuments
            Dim oForm As New frmDocRecordLink With {.Documents = oDocuments}
            oForm.Show()

        Catch ex As Exception
            LOGGER.Error(ex)
            MsgBox("Unexpected Error in Linking Record: " & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Sub Refresh_Selected_Table()
        Dim table As New DataTable With {
            .TableName = "SelectedFiles"
        }

        ' Create two columns, ID and Name.
        Dim idColumn As DataColumn = table.Columns.Add("ID", GetType(System.Int32))
        idColumn.AutoIncrement = True
        idColumn.AutoIncrementSeed = 0
        idColumn.AutoIncrementStep = 1
        table.PrimaryKey = New DataColumn() {idColumn}
        table.Columns.Add("FILEPATH", GetType(System.String))
        table.Columns.Add("DOC_ID", GetType(System.Int32))
        table.Columns.Add("OBJECTTYPE", GetType(System.String))
        For Each oDoc As ClassWindreamDocGrid.WindreamDoc In ClassWindreamDocGrid.GetSelectedDocuments(GridViewDoc_Search)
            If oDoc.DocPath <> String.Empty Then
                'Set the ID column as the primary key column.
                Dim newRow As DataRow = table.NewRow()
                newRow("FILEPATH") = oDoc.DocPath
                newRow("DOC_ID") = oDoc.DocId
                newRow("OBJECTTYPE") = oDoc.DocType
                table.Rows.Add(newRow)
            End If
        Next
        table.AcceptChanges()
        CURRENT_DT_SELECTED_FILES = table
    End Sub

    Private Sub tsmiFileLink_ShowAll_Click(sender As Object, e As EventArgs) Handles tsmiFileLink_ShowAll.Click
        Try
            Dim oDocID = GridViewDoc_Search.GetRowCellValue(GridViewDoc_Search.FocusedRowHandle, "DocID")
            If IsNothing(oDocID) Then
                MsgBox("Could not get DocID!", MsgBoxStyle.Exclamation)
                Exit Sub
            End If
            CURRENT_DOC_ID = GridViewDoc_Search.GetRowCellValue(GridViewDoc_Search.FocusedRowHandle, "DocID")

            Dim oDocuments = DocList.SelectedDocuments
            Dim oForm As New frmDoc_Links With {.Documents = oDocuments}
            oForm.Show()
            oForm.BringToFront()
        Catch ex As Exception
            MsgBox("Unexpected Error in Showing DocLinks: " & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Async Sub tsmiFileLinkRemove_Click(sender As Object, e As EventArgs) Handles tsmiFileLinkRemove.Click
        If CURRENT_RECORD_ID = 0 Then
            ClassHelper.MSGBOX_Handler("INFO", "Attention", "Missing Selection:", "Please select a record!")
            Exit Sub
        End If
        If ClassWindreamDocGrid.HasNoSelectedDocuments(GridViewDoc_Search) Then
            Exit Sub
        End If

        Dim msg = "Wollen Sie die Verknüpfung der gewählten Datei/en wirklich entfernen?" & vbNewLine & "Datei/en bleibt/bleiben im DMS/Archiv/Explorer erhalten!"
        If USER_LANGUAGE <> "de-DE" Then
            msg = "Would You like to delete only the references?" & vbNewLine & "File(s) will stay in ECM/Archive/Explorer!"
        End If
        Dim result As MsgBoxResult
        result = MessageBox.Show(msg, CAPTION_CONFIRMATION, MessageBoxButtons.YesNo, MessageBoxIcon.Question)
        If result = MsgBoxResult.Yes Then
            Try
                For Each oDoc As ClassWindreamDocGrid.WindreamDoc In ClassWindreamDocGrid.GetSelectedDocuments(GridViewDoc_Search)
                    If ClassFileResult.Delete_ResultFile(oDoc.DocId, CURRENT_RECORD_ID, 0) = True Then
                        ClassHelper.InsertEssential_Log(oDoc.DocId, "DOC-ID", "RECORD LINK REMOVED FROM DOC-SEARCH")
                        Cursor = Cursors.WaitCursor
                        Await RUN_WDSEARCH_GRID(True)
                    End If


                Next

            Catch ex As Exception
                ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Removing links from file:", ex.Message)
            End Try
        End If
    End Sub

    Private Async Sub tsmiFileVersion_Click(sender As Object, e As EventArgs) Handles tsmiFileVersion.Click
        Refresh_Selected_Table()
        frmWM_CreateVersion.ShowDialog()
        Await RUN_WDSEARCH_GRID(True)
    End Sub

    Private Sub tsmiFileRightsShow_Click(sender As Object, e As EventArgs) Handles tsmiFileRightsShow.Click
        Dim result = ClassDOC_SEARCH.Get_File_Rights(ClassWindreamDocGrid.SELECTED_DOC_ID)
        If Not IsNothing(result) Then
            Dim msg = "Das aktuelle Recht für Sie (" & USER_USERNAME & ") ist: "
            If USER_LANGUAGE <> "de-DE" Then
                msg = "Your (" & USER_USERNAME & ") current right is: "
            End If
            msg = msg & result.ToString
            msg = msg & vbNewLine & vbNewLine & "R:" & vbTab & "Read" & vbNewLine & "W:" & vbTab & "Write" & vbNewLine & "A:" & vbTab & "Admin"
            MsgBox(msg, MsgBoxStyle.Information)
        Else
            MsgBox("Could not read the rights for selected file! Check the log for further infomation!", MsgBoxStyle.Exclamation)
        End If
    End Sub

    Private Sub tsmiFileProperties_Click(sender As Object, e As EventArgs) Handles tsmiFileProperties.Click
        Show_File_Properties()
    End Sub
    Sub Show_File_Properties()
        If ClassWindreamDocGrid.HasNoSelectedDocuments(GridViewDoc_Search) Then
            MsgBox("Could not read File Parameters(4)!", MsgBoxStyle.Exclamation)
            Exit Sub
        End If
        Cursor = Cursors.WaitCursor
        For Each oDoc As ClassWindreamDocGrid.WindreamDoc In ClassWindreamDocGrid.GetSelectedDocuments(GridViewDoc_Search)
            If oDoc.DocPath <> "" Then
                Dim oFileFullPath = ClassHelper.FORMAT_WM_PATH(oDoc.DocPath)
                Try
                    If Not WindowsEx.OpenFileProperties(oFileFullPath) Then
                        Dim ex As New System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error())
                        ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Open file propertys:", ex.Message)
                    End If
                Catch ex As Exception
                    LOGGER.Error(ex)
                End Try
            End If
        Next
        Cursor = Cursors.Default
    End Sub

    Private Sub EigenschaftenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles EigenschaftenToolStripMenuItem.Click
        Show_File_Properties()
    End Sub

    Private Async Sub bbtnitmDocResultRefresh_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbtnitmDocResultRefresh.ItemClick
        Await RUN_WDSEARCH_GRID(True)
    End Sub

    Private Sub BarButtonItem1_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem1.ItemClick
        CURRENT_SEARCH_TYPE = "ENTITY"
        RUN_ENTITY_DOC_SEARCH()
    End Sub

    Private Async Function bbtnitmReloadView_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) As Task Handles bbtnitmReloadView.ItemClick
        Await ReloadTreeView()
    End Function
    Async Function ReloadTreeView() As Task
        TreeListDevexpress.Nodes.Clear()
        Await Load_nodes()
    End Function

    Private Async Function UnterknotenNeuOrdnenToolStripMenuItem_Click(sender As Object, e As EventArgs) As Task
        MyTreeListViewState = New ClassTreeListViewState(TreeListDevexpress)
        Dim oQuestion = "Wollen Sie die gesamte Struktur unterhalb dieses Knotens neu ordnen lassen?" & vbNewLine & "Nein, wenn nur die direkten Unterknoten neu geordnet werden sollen!"
        If USER_LANGUAGE <> "de-DE" Then
            oQuestion = "Do you want to reorder the entire structure below this node?" & vbNewLine & "No, if only the direct subnodes are to be reordered!"
        End If
        Dim result As MsgBoxResult
        result = MessageBox.Show(oQuestion, CAPTION_CONFIRMATION, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)
        Dim oSubnodes As String = "0"
        If result = MsgBoxResult.Yes Then
            oSubnodes = "1"
        ElseIf result = MsgBoxResult.Cancel Then
            Exit Function
        End If
        Cursor = Cursors.WaitCursor
        Dim oSQL = $"EXEC PRCUST_REORDER_CHILD_NODES "
        Dim oNodeGUID As Integer = 0
        Dim oID = FocusedNode.Id
        Dim PID = FocusedNode.ParentNode
        Dim Column_pRecord As TreeListColumn = TreeListDevexpress.Columns("RECORD_ID")
        Dim Column_Caption As TreeListColumn = TreeListDevexpress.Columns("NODE_CAPTION")

        If oID > 0 Then
            MyTreeListViewState.SaveState()
            oNodeGUID = oID
            oSQL += $" {oNodeGUID},{oSubnodes} "
            MYDB_ECM.ExecuteNonQuery(oSQL)
            Await ReloadTreeView()
            MyTreeListViewState.LoadState()
            TreeListDevexpress.FocusedNode = FocusedNode

        End If

        Cursor = Cursors.Default

    End Function

    'Private Sub TreeListDevexpress_MouseUp(sender As Object, e As MouseEventArgs) Handles TreeListDevexpress.MouseUp
    '    Dim tree As TreeList = TryCast(sender, TreeList)
    '    Dim oLocation = e.Location
    '    'If e.Button = MouseButtons.Right AndAlso ModifierKeys = Keys.None AndAlso tree.State = TreeListState.Regular Then

    '    '    Dim info As TreeListHitInfo = tree.CalcHitInfo(e.Location)

    '    '    FocusedNode = tree.FocusedNode
    '    '    Dim SavedTopIndex As Integer = tree.TopVisibleNodeIndex
    '    '    tree.FocusedNode = info.Node
    '    '    cmsTreeView.Show(TreeListDevexpress, e.Location)
    '    'End If
    'End Sub

    Private Sub GridViewDoc_Search_RowStyle(sender As Object, e As RowStyleEventArgs) Handles GridViewDoc_Search.RowStyle
        'TODO: Refactor RowStyle maybe
        'If e.RowHandle = DevExpress.XtraGrid.GridControl.AutoFilterRowHandle Then
        '    e.Appearance.BackColor = Color.Yellow
        'Else
        '    If e.RowHandle = -1 Then
        '        Exit Sub
        '    End If
        '    Try
        '        Dim rowCellValue = GridViewDoc_Search.GetRowCellValue(e.RowHandle, "in work?")
        '        If Not IsNothing(rowCellValue) Then
        '            Dim inwork = rowCellValue
        '            If inwork = True Then
        '                e.Appearance.BackColor = Color.Orchid
        '                e.HighPriority = True
        '            End If
        '        End If
        '    Catch ex As Exception
        '        LOGGER.Warn("Unexpected Error in Checking Value In Work: " & ex.Message)
        '    End Try

        '    Try
        '        Dim DROPDOWN_VALUE
        '        If Not IsNothing(DT_DOCRESULT_DROPDOWN_ITEMS) Then
        '            'Den ColumnTitle aus ConfigTableholen
        '            If DT_DOCRESULT_DROPDOWN_ITEMS.Rows.Count > 0 Then
        '                For Each confrow As DataRow In DT_DOCRESULT_DROPDOWN_ITEMS.Rows
        '                    Dim CAPTION = confrow.Item("HEADER_CAPTION")
        '                    DROPDOWN_VALUE = GridViewDoc_Search.GetRowCellValue(e.RowHandle, CAPTION)
        '                    If Not IsNothing(DROPDOWN_VALUE) Then
        '                        Exit For
        '                    End If
        '                Next

        '                If Not IsNothing(DROPDOWN_VALUE) Then
        '                    Dim ColorRow As Color
        '                    Dim expression As String = String.Format("VALUE = '{0}'", DROPDOWN_VALUE)
        '                    Dim matchingRows() As DataRow = DT_DOCRESULT_DROPDOWN_ITEMS.Select(expression, "SEQUENCE")
        '                    Dim rowcolorname As String = ""
        '                    'Die Color für den value auswählen
        '                    For Each matchingRow As DataRow In matchingRows
        '                        rowcolorname = ""
        '                        If Not IsDBNull(matchingRow.Item("COLOR")) Then
        '                            rowcolorname = matchingRow.Item("COLOR")
        '                        End If

        '                        If rowcolorname <> "" Then
        '                            Exit For
        '                        End If
        '                    Next
        '                    If rowcolorname <> "" Then
        '                        ColorRow = Color.FromName(rowcolorname)
        '                        e.Appearance.BackColor = ColorRow
        '                        e.HighPriority = True
        '                    End If


        '                    'Dim c As Color = DirectCast(rowCellValue, Color)

        '                End If
        '            End If


        '        End If
        '    Catch ex As Exception
        '        LOGGER.Warn("Unexpected Error in RowStyle-Color Dropdown: " & ex.Message)
        '    End Try

        'End If
    End Sub

    Private Async Function BarButtonItem2_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) As Task Handles BbtnitmNodeReorder.ItemClick
        MyTreeListViewState = New ClassTreeListViewState(TreeListDevexpress)
        Dim oQuestion = "Wollen Sie die gesamte Struktur unterhalb dieses Knotens neu ordnen lassen?" & vbNewLine & "Nein, wenn nur die direkten Unterknoten neu geordnet werden sollen!"
        If USER_LANGUAGE <> "de-DE" Then
            oQuestion = "Do you want to reorder the entire structure below this node?" & vbNewLine & "No, if only the direct subnodes are to be reordered!"
        End If
        Dim result As MsgBoxResult
        result = MessageBox.Show(oQuestion, CAPTION_CONFIRMATION, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)
        Dim oSubnodes As String = "0"
        If result = MsgBoxResult.Yes Then
            oSubnodes = "1"
        ElseIf result = MsgBoxResult.Cancel Then
            Exit Function
        End If
        Cursor = Cursors.WaitCursor
        Dim oSQL = $"EXEC PRCUST_REORDER_CHILD_NODES "
        Dim oNodeGUID As Integer = 0
        Dim oID = FocusedNode.Id
        Dim PID = FocusedNode.ParentNode
        Dim Column_pRecord As TreeListColumn = TreeListDevexpress.Columns("RECORD_ID")
        Dim Column_Caption As TreeListColumn = TreeListDevexpress.Columns("NODE_CAPTION")

        If oID > 0 Then
            MyTreeListViewState.SaveState()
            oNodeGUID = oID
            oSQL += $" {oNodeGUID},{oSubnodes} "
            MYDB_ECM.ExecuteNonQuery(oSQL)
            Await ReloadTreeView()
            MyTreeListViewState.LoadState()
            TreeListDevexpress.FocusedNode = FocusedNode
            Update_Status_Label(True, "Nodes reordered")
        End If

        Cursor = Cursors.Default
    End Function

    Private Sub bbtnItm_TV_Collape_Expand_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbtnItm_TV_Collape_Expand.ItemClick
        If TV_Collapse_ExpandState = "Collapse" Then
            TreeListDevexpress.CollapseAll()
            TV_Collapse_ExpandState = "Expand"
        Else
            TreeListDevexpress.ExpandAll()
            TV_Collapse_ExpandState = "Collapse"
        End If
    End Sub

    Private Sub bbtnitmRecSave_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbtnitmRecSave.ItemClick
        Save_Record()
    End Sub

    Private Sub checkShowPreview_CheckedChanged(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles checkShowPreview.CheckedChanged
        SplitContainerDocView.Collapsed = Not checkShowPreview.Checked
    End Sub

    Private Sub GridViewDoc_Search_SelectionChanged(sender As Object, e As SelectionChangedEventArgs) Handles GridViewDoc_Search.SelectionChanged
        Dim oSelectedDocs = ClassWindreamDocGrid.GetSelectedDocuments(GridViewDoc_Search)

        If oSelectedDocs.Count = 1 Then
            Dim oDocument As ClassWindreamDocGrid.WindreamDoc = oSelectedDocs.First()
            Dim oPath = ClassHelper.FORMAT_WM_PATH(oDocument.DocPath)
            DocumentViewer.LoadFile(oPath)
        Else
            DocumentViewer.CloseDocument()
        End If
    End Sub

    Private Async Sub btnCreateNewNode_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles btnCreateNewNode.ItemClick
        Dim oForm As New frmNewNode() With {
            .NodeConfigTypes = AvailableConfigNodes
        }

        If oForm.ShowDialog() <> DialogResult.OK Then
            Exit Sub
        End If

        Dim oRow = NODE_CONFIGURABLE_NODES_DT.Select($"GUID = {oForm.Id}").First()
        Dim oCreateRecord = oRow.Item("CREATE_RECORD")

        Dim oParentNodeGuid As Integer = FocusedNode.Item("GUID")
        Dim oIsExpanded As Boolean = FocusedNode.Expanded
        Dim oNodeCreator = New ClassNodeCreator(LOGCONFIG, ImageCollection1)
        oNodeCreator.AddNode(_EntityId, oForm.Title, oParentNodeGuid, oForm.Id, oCreateRecord)

        Await ReloadTreeView()

        Dim oNode = TreeListDevexpress.FindNodeByFieldValue("GUID", oParentNodeGuid)
        Dim oNodeIndex = TreeListDevexpress.MakeNodeVisible(oNode)
        TreeListDevexpress.SetFocusedNode(oNode)
        If oIsExpanded Then
            oNode.Expand()
        End If
    End Sub
End Class