Imports DevExpress.Utils
Imports DevExpress.XtraBars.Navigation
Imports DevExpress.XtraEditors
Imports DevExpress.XtraEditors.Controls
Imports DevExpress.XtraEditors.Repository
Imports DevExpress.XtraGrid.Columns
Imports DevExpress.XtraGrid.Views.Base
Imports DevExpress.XtraGrid.Views.Tile
Imports DevExpress.XtraGrid.Views.Grid
Imports DevExpress.XtraGrid.Views.Grid.ViewInfo
Imports DevExpress.XtraGrid
Imports DevExpress.XtraScheduler
Imports System.Text
Imports System.IO

Imports WINDREAMLib
Imports System.Runtime.InteropServices
Imports DD_Rights
Imports DD_LIB_Standards

Public Class frmConstructor_Main


   

    <DllImport("Shell32", CharSet:=CharSet.Auto, SetLastError:=True)> _
    Public Shared Function ShellExecuteEx(ByRef lpExecInfo As SHELLEXECUTEINFO) As Boolean
    End Function
    Public Structure SHELLEXECUTEINFO
        Public cbSize As Integer
        Public fMask As Integer
        Public hwnd As IntPtr
        <MarshalAs(UnmanagedType.LPTStr)> Public lpVerb As String
        <MarshalAs(UnmanagedType.LPTStr)> Public lpFile As String
        <MarshalAs(UnmanagedType.LPTStr)> Public lpParameters As String
        <MarshalAs(UnmanagedType.LPTStr)> Public lpDirectory As String
        Dim nShow As Integer
        Dim hInstApp As IntPtr
        Dim lpIDList As IntPtr
        <MarshalAs(UnmanagedType.LPTStr)> Public lpClass As String
        Public hkeyClass As IntPtr
        Public dwHotKey As Integer
        Public hIcon As IntPtr
        Public hProcess As IntPtr
    End Structure
#Region "Laufzeitvariablen & Konstanten"
    Private ERROR_FORM_LOAD As Boolean = False
    Private Const SEE_MASK_INVOKEIDLIST = &HC
    Private Const SEE_MASK_NOCLOSEPROCESS = &H40
    Private Const SEE_MASK_FLAG_NO_UI = &H400
    Public Const SW_SHOW As Short = 5
    Private PARENT_SKIPPED As Boolean = False

    Public CtrlBuilder As ClassControlBuilder
    Public CtrlCommandUI As ClassControlCommandsUI

    Private CONSTRUCTORID As Integer
    Private CONSTRUCTOR_DETAIL_ID As Integer
    Private DT_CONSTRUCT_VIEW As DataTable
    Private DT_VWPMO_CONSTRUCTOR_FORMS As DataTable
    Private DT_ENTITY_DATA As DataTable
    Private DT_TREEVIEW_NODES As DataTable

    Private DT_TREEVIEW_CONFIGURATION As DataTable
    Private DT_CONTROLS_ENTITY As DataTable

    Private DT_ADDING_USERS As DataTable

    Private DT_CONTROL_SCREEN As DataTable
    Private TREEVIEW_IMAGELIST As ImageList
    Private NODE_NAVIGATION As Boolean = False
    Private NODE_NAVIGATION_LOADED As Boolean = False

    Private LOCK_CONTROLS_BG_LOAD As Boolean = False

    Private EBENE2_PARENT_ID As Integer
    Private EBENE3_PARENT_ID As Integer
    Private ACT_EBENE As Integer
    Private ACT_EBENE_STRING As String
    Private SELECTED_RECORD_ID As Integer
    Private PARENT_RECORDID As Integer
    Private POS_ENTITY As Integer = 0
    Private POS_SQL As String = ""
    Private POS_RECORD_ID

    Private TreeView_perControl As Boolean = False

    Dim IsTopFirstRow As Boolean = True
    Private GRIDRightMouse_Clicked = False
    Private GRIDdownHitInfo As GridHitInfo

    Private VIEW_ID
    Private VIEW_ID_RUNTIME As Integer = -1

    Public RECORD_ENABLED As Boolean = False
    Public POS_ENABLED As Boolean = False
    Private windream_inited = False

    Private ENTITY_RECORD_COUNT As Integer = 0
    Private EBENE1_ENTITY
    Private EBENE2_ENTITY
    Private EBENE3_ENTITY
    Private EBENE1_COLUMNNAME
    Private EBENE2_COLUMNNAME
    Private EBENE3_COLUMNNAME
    Private EBENE1_RECID
    Private EBENE2_RECID
    Private EBENE3_RECID
    Private EBENE1_GRID_RESULT
    Private EBENE2_GRID_RESULT
    Private EBENE3_GRID_RESULT
    Private act_FormViewID
    Private DT_SELECTION As DataTable
    Private EDIT_STATE As EditState = EditState.None
    Private GRID_TYPE As GridType = GridType.Tiles
    Private GRID_TYPE_ID As Integer = 1
    Private FORM_LOADED As Boolean = False
    Private FORM_SHOWN As Boolean = False
    Private SAVE_ROUTINE_ACTIVE As Boolean = False
    Private SP1 As String
    Private SP2 As String
    Private SP3 As String
    Private SP4 As String
    Private SP5 As String

    Private windream_Docshow As Boolean = False
    Private WD_Suche As String
    Private DocView
    Private DocViewString As String
    Private OpenedFileString As String

    Private _FormClosing As Boolean = False

    Private ENTITY_LOADED As Boolean = False

    Private LinkParentID As Integer

    Private CONTROL_DOCTYPE_MATCH As Integer = 0

    Private FOLLOW_UPisActive As Boolean = False
    Private DT_FU_Record As DataTable
    Private DT_FU_ENTITY As DataTable
    ' Private gridGUID = 2

    Private DT_WINDREAM_RESULTLIST_DEF As DataTable
    Private DT_WINDREAM_RESULTLIST As DataTable
    Private DT_DOCRESULT_DROPDOWN_ITEMS As DataTable
    Private DT_RESULTLIST_OPTIONS As DataTable
    Private DT_RESULTLIST_VARIABLE_VALUE As DataTable
    Private DT_WORKFLOWS_MANUAL As DataTable
    Private _MANUAL_WORKFLOW As Boolean = False

    Private USER_RESULTLIST_CONFIG_GUID As Integer = 0
    Private DT_TBPMO_FORM_VIEW As DataTable


    Private FOLL_UP_RECORD_DEFINED As Boolean = False
    Private FOLL_UP_DATE_CTRL_ID As Integer
    Private FOLL_UP_DONE_CTRL_ID As Integer
    Private FOLL_UP_ID As Integer

    Private LOAD_DIRECT As Boolean = False
    Private IS_SINGLE_RECORD As Boolean = False
    Private LOAD_ENTITY_SEARCH_AT_STARTUP As Boolean = False
    Private RECORD_ID As Integer
    Private PARENT_ENTITYID As Integer
    Private DOC_SEARCH_TAB1 As Boolean = False
    Private ACTIVATE_DOC_SEARCH_ON_EDIT As Boolean = False
    Private FORM_TYPE As Integer
    Private ENTITY_ID As Integer
    Private REDUNDANT_FORM As Integer
    Private COUNT_RO_CONTROLS As Integer

    Private FORMVIEW_ID As Integer
    Private _ENTITYSQL As String
    Private _VIEWNAME As String
    Private _ENTITYSTRING As String

    'Private ClassWindreamDocGrid.RESULT_DOC_PATH
    'Private ClassWindreamDocGrid.RESULT_OBJECTTYPE
    'Private ClassWindreamDocGrid.RESULT_INWORK
    'Private ClassWindreamDocGrid.RESULT_DOC_ID
    'Private ClassWindreamDocGrid.RESULT_DISPLAYNAME

    Private IW_USER As String
    Private IW_COMMENT As String
    Private BACKGROUND_HELPER As ClassBackgroundHelper
    Private ROW_READ_ONLY As Boolean = False

    Public Enum EditState
        None
        Insert
        Update
        Delete
    End Enum

    Public Enum GridType
        Grid
        Carousel
        Tiles
    End Enum
#End Region

    Private Sub frmForm_Constructor_Main_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        'If RECORD_CHANGED = True Then
        '    Dim ResultMessage As String
        '    Try
        '        ResultMessage = Update_Record_OnChange()
        '    Catch ex As Exception
        '        MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Error in saving Record")
        '        Me.Cursor = Cursors.Default
        '        ' Verhindert den Zeilenwechsel
        '        e.Cancel = True
        '        Exit Sub
        '    End Try
        'End If

        If TrySave_Automatic() = False Then

            e.Cancel = True
        End If

        _FormClosing = True
        ' Check_Record_Changed()
        CloseWDDocview()
        Save_Grid_Layout()
        If DOC_SEARCH_TAB1 = True Then
            Save_DocGrid_Layout()
        End If
        Save_Splitter_Layout()
        ClassWindowLocation.SaveFormLocationSize(Me, CONSTRUCTORID, CURRENT_SCREEN_ID, "CONSTRUCTOR_MAIN")

        ' 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 frmForm_Constructor_Main_Load(sender As Object, e As EventArgs) Handles Me.Load
        Dim sw As New Stopwatch
        ' Try
        sw.Start()
        CURRENT_DT_DOC_ENTITY_SEARCH = Nothing
        tsslblRecord.Text = ""
        tsslblStatus.Text = ""
        _FormClosing = False
        CONSTRUCTORID = CURRENT_CONSTRUCTOR_ID
        Me.Cursor = Cursors.WaitCursor

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

        ' Hintergrund Bild initialisieren
        BACKGROUND_HELPER = New ClassBackgroundHelper(GridViewDoc_Search, My.Resources.windream_Logo_transparent_klein)


        ' Bestimme Dinge ausblenden wenn kein admin
        If USER_IS_ADMIN = True Then
            FormDesignerToolStripMenuItem.Visible = True
        Else
            FormDesignerToolStripMenuItem.Visible = False
        End If

        'Try
        Dim SQL
        Dim DT_PROXY_ENTITY As DataTable
        If LICENSE_SITE_PROXY = True And DD_LIB_Standards.clsDatabase.DB_PROXY_INITIALIZED Then
            SQL = "SELECT * FROM TBPROXY_SYNC_ENTITY"
            DT_PROXY_ENTITY = ClassDatabase.Return_Datatable(SQL, True)
        End If

        ClassWindowLocation.LoadFormLocationSize(Me, CONSTRUCTORID, CURRENT_SCREEN_ID, "CONSTRUCTOR_MAIN")
        ' VWPMO_WF_USER_ACTIVETableAdapter.Connection.ConnectionString = MyConnectionString
        'Me.VWPMO_WF_ACTIVETableAdapter.Connection.ConnectionString = MyConnectionString
        'VWPMO_WF_ACTIVETableAdapter.Fill(Me.DD_DMSDataSet.VWPMO_WF_ACTIVE, USER_LANGUAGE, USER_USERNAME)
        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, CONSTRUCTORID)

        DT_VWPMO_CONSTRUCTOR_FORMS = ClassDatabase.Return_Datatable(SQL, True)

        If LICENSE_SITE_PROXY = True And DD_LIB_Standards.clsDatabase.DB_PROXY_INITIALIZED Then
            If DT_VWPMO_CONSTRUCTOR_FORMS.Rows.Count = 0 Then
                ClassHelper.MSGBOX_Handler("ERROR", "Missing Proxy-Configuration", String.Format("Attention: You are using Proxy-Server with synchronized data:" & vbNewLine & _
                                                                                                       "Actually there is no data for this view synchronized or configured! Please inform Digital Data!" & vbNewLine & _
                                                                                                       "View will now be terminated!"))
                ERROR_FORM_LOAD = True
                Exit Sub
            Else
                Dim Entity_Exists As Boolean = False
                Dim Entity_Name As String
                For Each Constr_row As DataRow In DT_VWPMO_CONSTRUCTOR_FORMS.Rows
                    Entity_Name = Constr_row.Item("FORM_TITLE")
                    Dim Constr_FORM = Constr_row.Item("FORM_ID")
                    Dim expression As String = String.Format("ENTITY_ID = {0}", Constr_FORM)
                    Dim matchingRows() As DataRow = DT_PROXY_ENTITY.Select(expression)
                    'Prüfen ob Form in Config Proxy vorhanden
                    For Each matchingRow As DataRow In matchingRows
                        Entity_Exists = True
                    Next
                    If Entity_Exists = False Then
                        ClassHelper.MSGBOX_Handler("ERROR", "Missing Proxy-Configuration", String.Format("Attention: You are using Proxy-Server with synchronized data:" & _
                                                                                                          "The entity '{0}' used in this view is not configured for Your proxy-server! Please inform Digital Data!" & _
                                                                                                          "View will now be terminated!", Entity_Name))
                        ERROR_FORM_LOAD = True
                        Exit Sub
                    End If
                Next
            End If
        End If

        CURRENT_DT_TBPMO_ENTITY_RIGHT_CONTROLS = ClassDatabase.Return_Datatable(String.Format("SELECT * FROM TBPMO_ENTITY_RIGHT_CONTROLS where ENTITY_ID IN (SELECT FORM_ID FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = {0})", CONSTRUCTORID), False)

        SQL = String.Format("SELECT * FROM TBPMO_ENTITY_USERRIGHT_ADDING where ENTITY_ID IN (SELECT FORM_ID FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = {0})", CONSTRUCTORID)
        DT_ADDING_USERS = ClassDatabase.Return_Datatable(SQL, False)
        SQL = 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})", CONSTRUCTORID)
        CURRENT_DT_NODE_CONFIGURABLE_NODES = ClassDatabase.Return_Datatable(SQL, False)

        SQL = String.Format("select * from VWPMO_STRUCTURE_NODES where ENTITY_ID IN (SELECT FORM_ID FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = {0})", CONSTRUCTORID)
        Dim DT As DataTable = ClassDatabase.Return_Datatable(SQL, True)
        If DT.Rows.Count > 1 Then
            TreeView_perControl = True
            DT_TREEVIEW_NODES = DT
            SQL = String.Format("select * from TBPMO_STRUCTURE_NODES_CONFIGURATION where ENTITY_ID IN (SELECT FORM_ID FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = {0})", CONSTRUCTORID)
            DT_TREEVIEW_CONFIGURATION = ClassDatabase.Return_Datatable(SQL)

            Try
                TREEVIEW_IMAGELIST = New ImageList
                For Each row As DataRow In DT_TREEVIEW_CONFIGURATION.Rows
                    Try
                        Dim bimage = row.Item("NODE_IMAGE")
                        If Not IsDBNull(bimage) Then
                            Dim Node_image = ByteArrayToBitmap(bimage)
                            TREEVIEW_IMAGELIST.Images.Add(row.Item("GUID").ToString & "#" & row.Item("ENTITY_ID"), Node_image)
                        End If
                    Catch ex As Exception

                    End Try

                Next
                TreeViewMain.ImageList = TREEVIEW_IMAGELIST
            Catch ex As Exception
                ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", ex.Message, "Error in Adding NodeConfigurations to TreeView: ")
            End Try


            Me.SplitContainerTop.Panel1.Controls.Remove(Me.TreeViewMain)
            Me.SplitContainerFORM.Panel1.Controls.Add(Me.TreeViewMain)
            SplitContainerFORM.Collapsed = False
            SplitContainerFORM.PanelVisibility = SplitPanelVisibility.Both
            SplitContainerTop.Collapsed = True
            SplitContainerTop.PanelVisibility = SplitPanelVisibility.Panel2
            SplitContainerMain.Collapsed = True
            NODE_NAVIGATION = True
            tsmiNodedownSearch.Visible = True
            tsmi_NewNode.Visible = True
        Else
            tsmi_NewNode.Visible = False
            If DT_VWPMO_CONSTRUCTOR_FORMS.Rows.Count = 1 Then
                SplitContainerTop.PanelVisibility = SplitPanelVisibility.Both
                SplitContainerTop.CollapsePanel = SplitCollapsePanel.Panel1
                SplitContainerTop.Collapsed = True
            End If
        End If
        DT_CONSTRUCT_VIEW = ClassDatabase.Return_Datatable("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 = ClassDatabase.Return_Datatable(SEL1, True)
        DT_CONTROL_SCREEN = ClassDatabase.Return_Datatable("SELECT FORM_ID, CONTROL_ID, CONTROL_COL_NAME, CONTROL_SHOW_COLUMN FROM VWPMO_CONTROL_SCREEN WHERE CONTROL_SHOW_COLUMN = 0", True)
        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 = ClassDatabase.Return_Datatable(sql_ResultList)
        Load_Tree_View(CONSTRUCTORID)

        FORM_LOADED = True
        Dim elapsed As Double
        elapsed = sw.Elapsed.TotalSeconds
        sw.Stop()
        sw.Reset()
        If LogErrorsOnly = False Then ClassLogger.Add(" >> Form Load took " & Format(elapsed, "0.000000000") & " seconds", False)
        'Catch ex As System.Exception
        '    ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", ex.Message, "Error in Loading Form part 2")
        'End Try
        Me.Cursor = Cursors.Default
    End Sub

#Region "Layout"
    Sub Save_POSGrid_Layout()
        Try
            Dim EntityRegex As New RegularExpressions.Regex("\s+\(\d+\)")
            Dim EntityName As String = EntityRegex.Replace(ACT_EBENE_STRING & "_POS", "")
            Dim Filename As String = String.Format("{0}-{1}-{2}-UserLayout.xml", grvwGridPos.Name, EntityName, CONSTRUCTORID)
            Dim XMLPath = System.IO.Path.Combine(Application.UserAppDataPath(), Filename)
            grvwGridPos.SaveLayoutToXml(XMLPath)
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", ex.Message, ex.StackTrace)
        End Try
    End Sub
    Sub Load_POSGrid_Layout()
        Try
            Dim EntityRegex As New RegularExpressions.Regex("\s+\(\d+\)")
            Dim EntityName As String = EntityRegex.Replace(ACT_EBENE_STRING & "_POS", "")
            Dim Filename As String = String.Format("{0}-{1}-{2}-UserLayout.xml", grvwGridPos.Name, EntityName, CONSTRUCTORID)
            Dim XMLPath = System.IO.Path.Combine(Application.UserAppDataPath(), Filename)
            If File.Exists(XMLPath) Then
                grvwGridPos.RestoreLayoutFromXml(XMLPath)
                grvwGridPos.GuessAutoFilterRowValuesFromFilter()
                'grvwGrid.ClearGrouping()
                ' grvwGridPos.ClearSelection()
                ' grvwGridPos.OptionsView.ShowPreview = False

            End If
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", ex.Message, ex.StackTrace)
        End Try
    End Sub
    Sub Save_Grid_Layout()
        Try
            If ACT_EBENE_STRING Is Nothing Then
                Exit Sub
            End If

            Dim XMLPath = Get_Grid_Layout_Filename()
            grvwGrid.SaveLayoutToXml(XMLPath)
            ' Update_Status_Label(True, "Grid Layout Loaded")
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", ex.Message, ex.StackTrace)
        End Try
    End Sub
    Sub Save_DocGrid_Layout()
        Try
            If ACT_EBENE_STRING Is Nothing Then
                Exit Sub
            End If

            Dim XMLPath = Get_DocGrid_Layout_Filename()
            GridViewDoc_Search.SaveLayoutToXml(XMLPath)
            ' Update_Status_Label(True, "Grid Layout Loaded")
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", ex.Message, ex.StackTrace)
        End Try
    End Sub
    Sub Load_DocGrid_Layout()
        Try
            If ACT_EBENE_STRING Is Nothing Then
                Exit Sub
            End If
            Dim XMLPath = Get_DocGrid_Layout_Filename()
            If File.Exists(XMLPath) Then
                GridViewDoc_Search.RestoreLayoutFromXml(XMLPath)
                GridViewDoc_Search.GuessAutoFilterRowValuesFromFilter()
            End If

        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", ex.Message, ex.StackTrace)
        End Try
    End Sub
    Sub Load_Grid_Layout()
        Try
            Dim XMLPath = Get_Grid_Layout_Filename()
            If File.Exists(XMLPath) And GRID_TYPE = GridType.Grid Then
                grvwGrid.RestoreLayoutFromXml(XMLPath)
                grvwGrid.GuessAutoFilterRowValuesFromFilter()
            End If
        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))
                settings.Add(New ClassSetting("SplitViewMainSplitterPosition", SplitContainerMain.SplitterPosition))
                settings.Add(New ClassSetting("SplitViewDetailsSplitterPosition", SplitContainerDetails.SplitterPosition))
                layout.Save(settings)
            End If

            For Each setting As ClassSetting In settings
                Select Case setting._name
                    Case "SplitViewTopSplitterPosition"
                        SplitContainerTop.SplitterPosition = Integer.Parse(setting._value)
                    Case "SplitViewMainSplitterPosition"
                        If NODE_NAVIGATION = False Then
                            SplitContainerMain.SplitterPosition = Integer.Parse(setting._value)
                        Else
                            SplitContainerFORM.SplitterPosition = Integer.Parse(setting._value)
                        End If
                    Case "SplitViewDetailsSplitterPosition"
                        If DOC_SEARCH_TAB1 = True Then
                            SplitContainerDetails.SplitterPosition = Integer.Parse(setting._value)
                        End If
                End Select
            Next
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", ex.Message, ex.StackTrace)
        End Try
    End Sub
    Sub Save_Splitter_Layout()
        Try
            Dim XMLPath = Get_Splitter_Layout_Filename()
            Dim layout As New ClassLayout(XMLPath)
            Dim settings As New System.Collections.Generic.List(Of ClassSetting)
            If NODE_NAVIGATION = False Then
                settings.Add(New ClassSetting("SplitViewTopSplitterPosition", SplitContainerTop.SplitterPosition))
                settings.Add(New ClassSetting("SplitViewMainSplitterPosition", SplitContainerMain.SplitterPosition))

            Else
                settings.Add(New ClassSetting("SplitViewTopSplitterPosition", SplitContainerTop.SplitterPosition))
                settings.Add(New ClassSetting("SplitViewMainSplitterPosition", SplitContainerFORM.SplitterPosition))

            End If
            If DOC_SEARCH_TAB1 = True Then
                settings.Add(New ClassSetting("SplitViewDetailsSplitterPosition", SplitContainerDetails.SplitterPosition))
            End If
            layout.Save(settings)
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", ex.Message, ex.StackTrace)
        End Try
    End Sub

    Function GetSafeFilename(filename As String)
        Return String.Join("_", filename.Split(Path.GetInvalidFileNameChars()))
    End Function

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

    Private Function Get_POSGrid_Layout_Filename()
        Dim EntityRegex As New RegularExpressions.Regex("\s+\(\d+\)")
        Dim EntityName As String = EntityRegex.Replace(ACT_EBENE_STRING, "")
        Dim Filename As String = String.Format("{0}-{1}-{2}-UserLayout.xml", grvwGrid.Name, GetSafeFilename(EntityName), CONSTRUCTORID)
        Return System.IO.Path.Combine(Application.UserAppDataPath(), Filename)
    End Function
    Private Function Get_Grid_Layout_Filename()
        Dim EntityRegex As New RegularExpressions.Regex("\s+\(\d+\)")
        If NODE_NAVIGATION = True Then
            ACT_EBENE_STRING = "NODE_NAVIGATION"
        End If
        Dim EntityName As String = EntityRegex.Replace(ACT_EBENE_STRING, "")
        Dim Filename As String = String.Format("{0}-{1}-{2}-UserLayout.xml", grvwGrid.Name, GetSafeFilename(EntityName), CONSTRUCTORID)
        Return System.IO.Path.Combine(Application.UserAppDataPath(), Filename)
    End Function
    Private Function Get_DocGrid_Layout_Filename()
        Dim EntityRegex As New RegularExpressions.Regex("\s+\(\d+\)")
        Dim EntityName As String = EntityRegex.Replace(ACT_EBENE_STRING, "")
        Dim Filename As String = String.Format("GridViewDoc_Search-{0}-{1}-UserLayout.xml", GetSafeFilename(EntityName), CONSTRUCTORID)
        Return System.IO.Path.Combine(Application.UserAppDataPath(), Filename)
    End Function
#End Region

#Region "NavPane"
    Sub Refresh_Navpane()
        'Die aktuelle Ebene überprüfen und das NAvpane aktualisieren
        Select Case ACT_EBENE
            Case 1
                If Not EBENE1_COLUMNNAME Is Nothing Then
                    EBENE1_GRID_RESULT = Get_GridResult(EBENE1_COLUMNNAME)
                    Dim cat As TileNavCategory = LoadLevel1Nav()
                    NavPane.Categories.Clear()
                    NavPane.Categories.Add(cat)
                End If
            Case 2
                If Not EBENE2_COLUMNNAME Is Nothing Then
                    EBENE2_GRID_RESULT = Get_GridResult(EBENE2_COLUMNNAME)
                    Dim cat As TileNavCategory = LoadLevel1Nav()
                    NavPane.Categories.Clear()
                    NavPane.Categories.Add(cat)

                    Dim item As TileNavItem = LoadLevel2Nav()
                    cat.Items.Add(item)
                End If
            Case 3
                EBENE3_RECID = SELECTED_RECORD_ID
                If Not EBENE3_COLUMNNAME Is Nothing Then
                    EBENE3_GRID_RESULT = Get_GridResult(EBENE3_COLUMNNAME)
                    Dim cat As TileNavCategory = LoadLevel1Nav()
                    NavPane.Categories.Clear()
                    NavPane.Categories.Add(cat)

                    Dim item As TileNavItem = LoadLevel2Nav()
                    cat.Items.Add(item)

                    Dim subitem As TileNavSubItem = LoadLevel3Nav()
                    item.SubItems.Add(subitem)

                End If
        End Select
    End Sub
    Private Function FindNode(tncoll As TreeNodeCollection, strText As [String]) As TreeNode
        Dim tnFound As TreeNode
        For Each tnCurr As TreeNode In tncoll
            If tnCurr.Text.StartsWith(strText) Then
                Return tnCurr
            End If
            tnFound = FindNode(tnCurr.Nodes, strText)
            If tnFound IsNot Nothing Then
                Return tnFound
            End If
        Next
        Return Nothing
    End Function

    Private Sub NavPane_MouseUp(sender As Object, e As MouseEventArgs) Handles NavPane.MouseUp
        Dim pane As TileNavPane = TryCast(sender, TileNavPane)
        Dim hitInfo As TileNavPaneHitInfo = pane.ViewInfo.CalcHitInfo(e.Location)
        If hitInfo.InButton Then
            Dim element = hitInfo.ButtonInfo.Element
            NavPane.HideDropDownWindow()

            Save_Grid_Layout()

            If TypeOf element Is NavButton Then
                Dim btn As NavButton = TryCast(element, NavButton)

                If btn.IsMain Then
                    ResetNav()
                ElseIf btn.Name = "NavButtonRefresh" Then
                    Refresh_Entity_Data()
                End If

            Else
                Dim Entity As String = element.Tag
                Dim Node = FindNode(TreeViewMain.Nodes, Entity)

                If Node IsNot Nothing Then
                    TreeViewMain.SelectedNode = Node
                    Load_Datafor_Entity()
                End If
            End If

        End If
    End Sub
    Sub Refresh_Entity_Data()
        If ClassProxy.IS_PROXY_BUSY = True Then
            MsgBox("Proxy-Server is actually synchronizing! Please wait until synchronisation is finished!" & vbNewLine & "This might take up to 3 minutes!", MsgBoxStyle.Information)
            Exit Sub
        End If
        If TrySave_Automatic() = True Then
            ' Setzt die RECORD_ID auf Null
            ' damit beim Refresh keine alten Werte
            ' in die Datenbank geschrieben werden
            SELECTED_RECORD_ID = 0
            RECORD_ID = 0
            CURRENT_RECORD_ID = 0

            If CtrlCommandUI.IsInsert Then
                ActivateAllTabs()
            End If
            Load_Datafor_Entity()
        End If
    End Sub
    Private Function LoadLevel1Nav()
        Dim cat As New TileNavCategory()
        cat.Caption = EBENE1_GRID_RESULT
        cat.Name = EBENE1_GRID_RESULT
        cat.TileText = EBENE1_GRID_RESULT
        cat.Tag = EBENE1_ENTITY

        NavPane.SelectedElement = cat

        Return cat
    End Function

    Private Function LoadLevel2Nav()
        Dim item As New TileNavItem()
        item.Caption = EBENE2_GRID_RESULT
        item.Name = EBENE2_GRID_RESULT
        item.TileText = EBENE2_GRID_RESULT
        item.Tag = EBENE2_ENTITY

        NavPane.SelectedElement = item

        Return item
    End Function

    Private Function LoadLevel3Nav()
        Dim subitem As New TileNavSubItem()
        subitem.Caption = EBENE3_GRID_RESULT
        subitem.Name = EBENE3_GRID_RESULT
        subitem.TileText = EBENE3_GRID_RESULT
        subitem.Tag = EBENE3_ENTITY

        NavPane.SelectedElement = subitem

        Return subitem
    End Function

    Private Sub ResetNav()
        'Grid zurücksetzen
        Clear_Grid_View()
        ACT_EBENE = 0
        CURRENT_ACT_LEVEL = 0
        ACT_EBENE_STRING = ""
        EBENE1_ENTITY = ""
        EBENE1_RECID = 0
        EBENE2_ENTITY = ""
        EBENE2_RECID = 0
        EBENE3_ENTITY = ""
        EBENE3_RECID = 0
        'Navigation zurücksetzen
        NavPane.Categories.Clear()
        'TreeView zurücksetzen
        'Load_Tree_View(CONSTRUCTORID)
        TreeViewMain.SelectedNode = Nothing
        SetSelectedNodeStyle(TreeViewMain.Nodes)

        Load_Tree_View(CONSTRUCTORID)
    End Sub
#End Region

#Region "GridControl"


    Public Sub Init_Grid_Control()
        GRID_TYPE = GridType.Tiles
        GRID_TYPE_ID = 1
        GridControlMain.MainView = grvwTiles
    End Sub
    Public Function Get_Pos_SQL(FormId As Integer)
        POS_SQL = "SELECT T.* FROM VWTEMP_PMO_FORM" & FormId.ToString & " T, TBPMO_RECORD_CONNECT t1 where T.[Record-ID] = T1.RECORD2_ID AND T1.RECORD1_ID = @PARENT_ID"
    End Function
    Public Sub Clear_Grid_View()
        GridControlMain.DataSource = Nothing

        If GRID_TYPE = GridType.Grid Then
            If grvwGrid.Columns.Count > 0 Then
                grvwGrid.Columns.Clear()
            End If

        ElseIf GRID_TYPE = GridType.Tiles Then
            grvwTiles.Columns.Clear()
        Else
            grvwCarousel.Columns.Clear()
        End If
    End Sub
    Public Sub Clear_GridPos_View()
        BindingNavigatorPOS.BindingSource = Nothing
        GridControlPos.DataSource = Nothing
        grvwGridPos.Columns.Clear()
        POS_RECORD_ID = 0
    End Sub
    Public Function Get_Grid_Row_Count() As Integer
        If GRID_TYPE = GridType.Grid Then
            Return grvwGrid.RowCount
        ElseIf GRID_TYPE = GridType.Tiles Then
            Return grvwTiles.RowCount
        Else
            Return grvwCarousel.RowCount
        End If
    End Function

    'Public Function Get_Grid_Row_Handle(value As String)
    '    Try
    '        Dim rowHandle As Integer = DT_SELECTION.Rows.IndexOf(DT_SELECTION.Rows.Find(value))
    '        If rowHandle > 0 Then
    '            If GRID_TYPE = GridType.Grid Then
    '                grvwGrid.FocusedRowHandle = rowHandle
    '            ElseIf GRID_TYPE = GridType.Tiles Then
    '                grvwTiles.FocusedRowHandle = rowHandle
    '            Else
    '                grvwCarousel.FocusedRowHandle = rowHandle
    '            End If
    '        End If
    '    Catch ex As Exception
    '        ClassLogger.Add("Error in Search_RowHandle: " & ex.Message, False)
    '    End Try
    'End Function
    Public Function Get_Grid_Column_Count() As Integer
        If GRID_TYPE = GridType.Grid Then
            Return grvwGrid.Columns.Count
        ElseIf GRID_TYPE = GridType.Tiles Then
            Return grvwTiles.Columns.Count
        Else
            Return grvwCarousel.Columns.Count
        End If
    End Function

    Public Function Get_Focused_Row_Cell_Value(columnName As String)
        If GRID_TYPE = GridType.Grid Then
            Return grvwGrid.GetFocusedRowCellValue(grvwGrid.Columns(columnName))
        ElseIf GRID_TYPE = GridType.Tiles Then
            Return grvwTiles.GetFocusedRowCellValue(grvwTiles.Columns(columnName))
        Else
            Return grvwCarousel.GetFocusedRowCellValue(grvwCarousel.Columns(columnName))
        End If
    End Function
    Public Function Get_Focused_Row_Cell_Value_pos(columnName As String)
        Return grvwGridPos.GetFocusedRowCellValue(grvwGrid.Columns(columnName))
    End Function

    Private Sub grvwGrid_BeforeLeaveRow(sender As Object, e As RowAllowEventArgs) Handles grvwGrid.BeforeLeaveRow
        'If RECORD_CHANGED = True Then
        '    Dim ResultMessage As String
        '    Try
        '        ResultMessage = Update_Record_OnChange()
        '    Catch ex As Exception
        '        MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Error in saving Record")
        '        Me.Cursor = Cursors.Default
        '        ' Verhindert den Zeilenwechsel
        '        e.Allow = False
        '    End Try
        'End If
        If TrySave_Automatic() = False Then
            e.Allow = False
        Else
            If CtrlCommandUI.IsInsert Then
                ActivateAllTabs()
                CtrlCommandUI.IsInsert = False
            End If
        End If
    End Sub

    Private Sub grvwGrid_FocusedColumnChanged(sender As Object, e As FocusedColumnChangedEventArgs) Handles grvwGrid.FocusedColumnChanged
        Cursor = Cursors.WaitCursor
        Column_Row_Handler()
        Me.Cursor = Cursors.Default
    End Sub
    Private Sub GridView_FocusedRowChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs) Handles grvwGrid.FocusedRowChanged, grvwTiles.FocusedRowChanged, grvwCarousel.FocusedRowChanged
        Dim sw As New Stopwatch
        sw.Start()
        Dim elapsed As Double
        Me.Cursor = Cursors.WaitCursor
        Column_Row_Handler()
        Me.Cursor = Cursors.Default
        elapsed = sw.Elapsed.TotalSeconds
        sw.Stop()
        sw.Reset()
        If LogErrorsOnly = False Then ClassLogger.Add(" >>>> GridView_FocusedRowChanged took " & Format(elapsed, "0.000000000") & " seconds", False)
    End Sub
    Private Sub gridView1_CustomDrawRowIndicator(sender As Object, e As DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs)
        If IsTopFirstRow Then
            e.Info.ImageIndex = -1
        End If
    End Sub
    Sub Column_Row_Handler(Optional RECID As Integer = 0, Optional _navload As Boolean = False, Optional _refresh As Boolean = False)
        Try
            Dim sw As New Stopwatch
            sw.Start()
            Dim elapsed As Double
            If RECID = 0 Then
                If _FormClosing = True Then 'Or SaveRoutine_Active = True
                    Exit Sub
                End If
                'Aussteigen, wenng erade die Entität gewechselt wird
                If ENTITY_LOADED = False Then
                    Exit Sub
                End If
                If GRIDRightMouse_Clicked Then
                    Exit Sub
                End If
                '     If NODE_NAVIGATION = False Then
                Dim Grid_RecordID = Get_Focused_Row_Cell_Value("Record-ID")
                If IsNothing(Grid_RecordID) Then
                    Console.WriteLine("No Record ID selectable")
                Else
                    If Grid_RecordID = 0 Then
                        Console.WriteLine("Grid_RecordID = 0")
                    Else
                        RECID = Grid_RecordID
                    End If
                End If
                'End If

            End If
            CURRENT_RECORD_ID = RECORD_ID
            CURRENT_SEARCH_TYPE = "RECORD"
            If RECID = RECORD_ID And ENTITY_RECORD_COUNT > 1 And _refresh = False Then
                Exit Sub
            End If
            If LogErrorsOnly = False Then ClassLogger.Add(" >> RowHandler: RID: " & RECID.ToString & " - " & Now, False)
            'Hier jetzt erst das Anzeigen für einen selektierten Datensatz
            If GRID_TYPE = GridType.Grid Then
                If IsTopFirstRow Then
                    IsTopFirstRow = False
                    'grvwGrid.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus
                    'grvwGrid.OptionsBehavior.Editable = Not IsTopFirstRow
                    'grvwGrid.OptionsSelection.EnableAppearanceFocusedCell = Not IsTopFirstRow
                    'grvwGrid.OptionsSelection.EnableAppearanceFocusedRow = Not IsTopFirstRow
                    'grvwGrid.OptionsSelection.EnableAppearanceHideSelection = Not IsTopFirstRow
                End If
            ElseIf GRID_TYPE = GridType.Carousel Then
                If IsTopFirstRow Then
                    IsTopFirstRow = False
                    grvwCarousel.OptionsBehavior.Editable = Not IsTopFirstRow
                End If
            ElseIf GRID_TYPE = GridType.Tiles Then
                If IsTopFirstRow Then
                    IsTopFirstRow = False
                    grvwTiles.OptionsBehavior.Editable = Not IsTopFirstRow
                End If
            End If

            'Wird jetzt bei BeforeRowChange überprüft
            'Check_Record_Changed()

            DisableEditMode()

            elapsed = sw.Elapsed.TotalSeconds
            sw.Stop()
            sw.Reset()
            If LogErrorsOnly = False Then ClassLogger.Add(" >> Precheck Row took " & Format(elapsed, "0.000000000") & " seconds", False)
            sw.Start()
            ' muss vor show selected record data kommen,
            ' sodass die datasource für die angehakten werte existiert (checked list box)
            CtrlBuilder.WatchRecordChanges = False
            ClassControlValues.LoadControlValuesListWithPlaceholders(ENTITY_ID, RECID, PARENT_RECORDID, CtrlBuilder.AllControls, ENTITY_ID)
            CtrlBuilder.WatchRecordChanges = True
            Show_Selected_Record_Data(RECID, False)
            Dim sw1 As New Stopwatch
            sw1.Start()
            ClassRightManagement.Check_Set_Rights(RECORD_ID, ENTITY_ID)
            CONTROL_HANDLING()
            elapsed = sw1.Elapsed.TotalSeconds
            sw1.Stop()

            If LogErrorsOnly = False Then ClassLogger.Add(" >> Check Rights took " & Format(elapsed, "0.000000000") & " seconds", False)
            If TCDetails.SelectedTabPage Is Nothing Then
                Exit Sub
            End If
            If TabPos.PageVisible = True And TCDetails.SelectedTabPage.Name = "TabPos" Then
                Clear_GridPos_View()
                Dim POS_GRID_RECORD = Get_Focused_Row_Cell_Value_pos("Record-ID")
                Load_Pos_Data()
                Load_POSGrid_Layout()
            End If

            If 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
                        tsButtonEdit.Enabled = False
                    Else
                        ' tsButtonEdit.Enabled = True
                    End If

                End If
                If NODE_NAVIGATION = False Then
                    Get_RecordCounts_Nodes()
                Else
                    tsButtonAdd.Enabled = False
                End If

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

            elapsed = sw.Elapsed.TotalSeconds
            sw.Stop()
            Console.WriteLine("Column_Row_Handler took {0}ms to load", sw.ElapsedMilliseconds)
            sw.Reset()
            If LogErrorsOnly = False Then ClassLogger.Add(" >>>> Column/Row Change took " & Format(elapsed, "0.000000000") & " seconds", False)
            If NODE_NAVIGATION = True And _navload = False Then
                SearchNode(TreeViewMain.Nodes, RECORD_ID)
            End If
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error:", ex.Message & vbNewLine & ex.StackTrace)
        End Try
       
    End Sub
    Sub CONTROL_HANDLING()
        tsButtonSave.Enabled = True
        tsButtonAdd.Enabled = True
        tsButtonEdit.Enabled = True
        tsButtonDelete.Enabled = True
        docCM_PropertiesFile.Enabled = True
        tslblLocked.Visible = False
        tslblFileslocked.Visible = False
        TabFollowUp.PageEnabled = True
        TabPos.PageEnabled = True
        TabWindream.PageEnabled = True
        tsbtnDoc_Refresh.Enabled = True
        tsmientitySearch.Enabled = True

        If SQL_RECORD_AND_FILE_READ_ONLY <> "" Or SQL_DOC_READ_ONLY <> "" Then
            If RIGHT_RECORD_AND_FILE_READ_ONLY = True Then
                tsButtonSave.Enabled = False
                tsButtonDelete.Enabled = False
                tsButtonEdit.Enabled = False
                tslblLocked.Visible = True
                TabFollowUp.PageEnabled = False
                TabPos.PageEnabled = False
                ' tsButtonShowTaskOverview.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
                    tsButtonEdit.Enabled = False
                    If RIGHT_ADD_R = False Then
                        tsButtonSave.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
    End Sub
#End Region

#Region "TreeView"

    Public Sub SetSelectedNodeStyle(tncoll As TreeNodeCollection)
        If NODE_NAVIGATION = False Then
            For Each node As TreeNode In tncoll

                If node.IsSelected Then
                    node.NodeFont = New Font(TreeViewMain.Font.FontFamily, TreeViewMain.Font.Size, FontStyle.Bold)
                    node.Text = node.Text
                Else
                    node.NodeFont = New Font(TreeViewMain.Font.FontFamily, TreeViewMain.Font.Size, FontStyle.Regular)
                End If

                If node.Nodes.Count > 0 Then
                    SetSelectedNodeStyle(node.Nodes)
                End If

            Next
        End If

        TreeViewMain.Refresh()
    End Sub
    Private Sub NodeRecursive(ByVal n As TreeNode, searchRecord As Integer)
        Dim aNode As TreeNode
        For Each aNode In n.Nodes
            If Not IsNothing(aNode.Tag) Then
                If aNode.Tag.ToString.Contains("RECORD-ID") Then
                    Dim Record = ClassNodeNavigation.Return_RECORD_forTag(aNode.Tag)
                    If IsNumeric(Record) And Record <> 0 And searchRecord = Record Then
                        TreeViewMain.SelectedNode = aNode
                        Exit Sub
                    End If

                End If
            End If
            NodeRecursive(aNode, searchRecord)
        Next
    End Sub
    Public Sub SearchNode(tncoll As TreeNodeCollection, searchRecord As Integer)
        Try
            Dim n As TreeNode
            For Each n In TreeViewMain.Nodes
                NodeRecursive(n, searchRecord)
            Next
        Catch ex As Exception
            ClassLogger.Add("Error in SearchNode: " & ex.Message, True)
        End Try
    End Sub
    Private Sub TreeViewMain_AfterSelect(sender As Object, e As TreeViewEventArgs) Handles TreeViewMain.AfterSelect
        DisableEditMode()
        If NODE_NAVIGATION = False Then
            SetSelectedNodeStyle(TreeViewMain.Nodes)
        Else
            ACT_EBENE_STRING = "NODE_NAVIGATION"
            Dim SelectedNode As TreeNode = TryCast(TreeViewMain.SelectedNode, TreeNode)
            If SelectedNode IsNot Nothing Then
                SelectedNode.NodeFont = New Font(TreeViewMain.Font.FontFamily, TreeViewMain.Font.Size, FontStyle.Bold)
                SelectedNode.Text = SelectedNode.Text
            End If
        End If
        Dim fl = FORM_LOADED
        Dim firstORFOLLWOWIN
        If FORM_SHOWN = False Then
            firstORFOLLWOWIN = True
        Else
            firstORFOLLWOWIN = False
        End If
        Load_Datafor_Entity()
        If DOC_SEARCH_TAB1 = True Then
            tsbtnPanel1Collapse.Visible = True
        Else
            tsbtnPanel1Collapse.Visible = False
        End If
        If NODE_NAVIGATION = True Then
            Dim SelectedNode As TreeNode = TryCast(TreeViewMain.SelectedNode, TreeNode)
            If SelectedNode IsNot Nothing Then
                Update_Status_Label(True, SelectedNode.Tag)
                ClassNodeNavigation.Check_NODE_CONFIG_ID(ENTITY_ID)

                If SelectedNode.Tag.ToString.Contains("RECORD-ID") Then
                    Dim Record = ClassNodeNavigation.Return_RECORD_forTag(SelectedNode.Tag)
                    If Record <> 0 Then
                        ToolStripEdit.Enabled = True
                        Column_Row_Handler(Record, True)
                        LocateRecordById(RECORD_ID)
                    End If
                    If pnlDetails.Enabled = False Then pnlDetails.Enabled = True
                Else
                    If pnlDetails.Enabled = True Then pnlDetails.Enabled = False
                    ToolStripEdit.Enabled = False
                End If
                If RIGHT_READ_ONLY_DOC = False Then
                    If ACTIVATE_DOC_SEARCH_ON_EDIT = False Then
                        Doc_ReadOnlyHandler(False)
                    Else
                        Doc_ReadOnlyHandler(True)
                    End If
                End If
            End If
        End If

    End Sub
    Sub Doc_ReadOnlyHandler(state As Boolean)
        If state = False Then
            GridControlDocSearch.ContextMenuStrip = cmsResultFilesBasic
            tslblDocViewLocked.Visible = True
        ElseIf state = True Then
            GridControlDocSearch.ContextMenuStrip = ContextMenuStripResultFiles
            tslblDocViewLocked.Visible = False
        End If
    End Sub
    Private Sub TreeViewMain_BeforeSelect(sender As Object, e As TreeViewCancelEventArgs) Handles TreeViewMain.BeforeSelect
        If NODE_NAVIGATION = False Then
            If grvwGrid.Columns.Count > 0 Then
                Save_Grid_Layout()
            End If
            If DOC_SEARCH_TAB1 = True Then
                Save_DocGrid_Layout()
            End If
        Else
            If Not IsNothing(TreeViewMain.SelectedNode) Then
                TreeViewMain.SelectedNode.NodeFont = New Font(TreeViewMain.Font.FontFamily, TreeViewMain.Font.Size, FontStyle.Regular)
            End If
        End If
    End Sub
    Sub Load_TreeView_Node_Navigation()
        Dim newTreeview As TreeView
        'If DT_TREEVIEW_NODES.Rows.Count > 500 Then
        '    newTreeview = ClassNodeNavigation.CreateTreeViewNodes(DT_TREEVIEW_NODES, TREEVIEW_IMAGELIST)
        'Else
        newTreeview = ClassNodeNavigation.CreateTreeViewNodesNew1(DT_TREEVIEW_NODES, TREEVIEW_IMAGELIST)
        'End If

        If Not IsNothing(newTreeview) Then
            For Each node As TreeNode In newTreeview.Nodes
                TreeViewMain.Nodes.Add(node.Clone)
            Next
        End If
    End Sub
    Sub Load_Tree_View(ConstructorId As Integer)
        Try
            Dim sw As New SW("Load_Tree_View")

            TreeViewMain.Nodes.Clear()
            If NODE_NAVIGATION = True Then
                Try
                    Load_TreeView_Node_Navigation()
                Catch ex As Exception
                    ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", ex.Message, ex.StackTrace)
                End Try
            Else
                ' LINQ für Zugriff auf DT_VWPMO_CONSTRUCTOR_FORMS
                Dim query1 = From form In DT_VWPMO_CONSTRUCTOR_FORMS.AsEnumerable()
                            Select form
                            Order By form.Item("SEQUENCE")
                            Where form.Item("PARENT_ID") = 0

                Dim Rows1 = query1.ToList()

                For Each LEVEL1ROW In Rows1
                    Dim LEVEL0_NODE As TreeNode

                    Dim LEVEL2_NODE As TreeNode

                    '################## LEVEL 1 wird geladen ###########################
                    Dim LEVEL1_TITLE = LEVEL1ROW.Item("CAPTION").ToString
                    Dim NODE1_ENTITY_ID = LEVEL1ROW.Item("FORM_ID").ToString
                    Dim ENTITY_ID = LEVEL1ROW.Item("FORM_ID")

                    ' Rootnode erstellen und taggen
                    LEVEL0_NODE = New TreeNode(LEVEL1_TITLE)
                    LEVEL0_NODE.Tag = NODE1_ENTITY_ID
                    ' TreeView Rootnode einfügen
                    TreeViewMain.Nodes.Add(LEVEL0_NODE)

                    '################## LEVEL 2 wird geladen #########
                    Dim LEVEL1_NODE As TreeNode

                    Dim query2 = From form In DT_VWPMO_CONSTRUCTOR_FORMS.AsEnumerable()
                                Select form
                                Order By form.Item("SEQUENCE")
                                Where form.Item("PARENT_ID") = NODE1_ENTITY_ID

                    Dim Rows2 = query2.ToList()
                    For Each Row2 In Rows2

                        Dim LEVEL2_TITLE As String = Row2.Item("CAPTION").ToString
                        Dim LEVEL2_ID As Integer = Row2.Item("FORM_ID")
                        Dim LEVEL2_PARENT_ID As Integer = Row2.Item("PARENT_ID")

                        ' Node erstellen..
                        LEVEL1_NODE = New TreeNode(LEVEL2_TITLE)
                        LEVEL1_NODE.Tag = LEVEL2_ID
                        ' ..und einfügen
                        LEVEL0_NODE.Nodes.Add(LEVEL1_NODE)
                        '##### LEVEL 3 wird geladen #########
                        Dim query3 = From form In DT_VWPMO_CONSTRUCTOR_FORMS.AsEnumerable()
                                Select form
                                Order By form.Item("SEQUENCE")
                                Where form.Item("PARENT_ID") = LEVEL2_ID

                        Dim Rows3 = query3.ToList()

                        For Each Row3 In Rows3

                            Dim LEVEL3_TITLE As String = Row3.Item("CAPTION")
                            Dim LEVEL3_ID As Integer = Row3.Item("FORM_ID")

                            ' Node erstellen..
                            LEVEL2_NODE = New TreeNode(LEVEL3_TITLE)
                            LEVEL2_NODE.Tag = LEVEL3_ID
                            ' ..und einfügen
                            LEVEL1_NODE.Nodes.Add(LEVEL2_NODE)

                        Next
                    Next
                Next
            End If
            If NODE_NAVIGATION = False Then
                TreeViewMain.ExpandAll()
            End If
            TreeViewMain.Nodes(0).EnsureVisible()

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

    End Sub

    Sub Create_variable_node()

    End Sub

    Sub Load_Datafor_Entity()
        If ClassProxy.IS_PROXY_BUSY = True Then
            MsgBox("Proxy-Server is actually synchronizing! Please wait until synchronisation is finished!" & vbNewLine & "This might take up to 3 minutes!", MsgBoxStyle.Information)
            Exit Sub
        End If
        Try
            If NODE_NAVIGATION = True Then
                If NODE_NAVIGATION_LOADED = True Then
                    Exit Sub
                Else
                    NODE_NAVIGATION_LOADED = True
                End If
            End If

            Dim sw As New Stopwatch
            sw.Start()
            Dim SelectedNode As TreeNode = TryCast(TreeViewMain.SelectedNode, TreeNode)

            If SelectedNode IsNot Nothing Then
                ENTITY_LOADED = False
                ENTITY_ID = ClassNodeNavigation.Return_ENTITY_FOR_TAG(SelectedNode.Tag)
                CURRENT_ENTITY_ID = ENTITY_ID
                Dim result = (From form In DT_VWPMO_CONSTRUCTOR_FORMS.AsEnumerable()
                                 Select form
                                 Where form.Item("FORM_ID") = ENTITY_ID).Single()
                CONSTRUCTOR_DETAIL_ID = result.Item("GUID")
                Dim FORM_DATE_FORMAT = result.Item("DATE_FORMAT")
                If FORM_DATE_FORMAT <> USER_DATE_FORMAT Then
                    CURRENT_DATE_FORMAT = FORM_DATE_FORMAT
                Else
                    CURRENT_DATE_FORMAT = USER_DATE_FORMAT
                End If
                LOCK_CONTROLS_BG_LOAD = result.Item("LOCK_CONTROLS_BG_LOAD")
                If NODE_NAVIGATION = True Then
                    If SelectedNode.Tag.ToString.Contains("RECORD_ID") Then
                        Console.WriteLine("Record beinhaltet")
                    End If
                    Console.WriteLine("CONTROL Navigacion")
                Else
                    Dim parentNode As TreeNode = TryCast(SelectedNode.Parent, TreeNode)

                    ACT_EBENE = 2
                    CURRENT_ACT_LEVEL = 2
                    If parentNode IsNot Nothing Then
                        Dim grandParentNode As TreeNode = TryCast(parentNode.Parent, TreeNode)
                        If grandParentNode IsNot Nothing Then
                            ACT_EBENE = 3
                            CURRENT_ACT_LEVEL = 3
                        End If
                    Else
                        ACT_EBENE = 1
                        CURRENT_ACT_LEVEL = 1
                    End If

                End If

                ' LINQ für Zugriff auf DT_VWPMO_CONSTRUCTOR_FORMS
                Dim query2 = From form In DT_WORKFLOWS_MANUAL.AsEnumerable()
                            Select form Where form.Item("ENTITY_ID") = ENTITY_ID
                Dim Rows = query2.ToList()
                _MANUAL_WORKFLOW = False
                For Each _row In Rows
                    _MANUAL_WORKFLOW = _row.Item("MANUALLY")
                Next
                FAU_AD_DOMAIN = ""
                FAU_AD_SERVER = ""
                FAU_AD_USER = ""
                FAU_AD_USER_PW = ""

                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") = ENTITY_ID
                    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
                            ClassLogger.Add("- the Password for FileAddingUser '" & FAU_AD_USER & "' could not be decrypted", False)
                            PWplainText = ""
                        End Try
                        FAU_AD_USER_PW = PWplainText
                    Next
                End If


                Dim elapsed As Double
                elapsed = sw.Elapsed.TotalSeconds
                If LogErrorsOnly = False Then ClassLogger.Add(" >> Load_Datafor_Entity1 took " & Format(elapsed, "0.000000000") & " seconds", False)
                If NODE_NAVIGATION = True Then
                    If SelectedNode.Tag.ToString.Contains("RECORD_ID") Then
                        Console.WriteLine("Record beinhaltet")
                    End If
                    Console.WriteLine("CONTROL Navigacion")
                Else
                    Get_RecordCounts_Nodes()
                End If
                Load_Entity_Data(ACT_EBENE)

                sw.Stop()
                sw.Reset()
                elapsed = elapsed - sw.Elapsed.TotalSeconds
                If LogErrorsOnly = False Then ClassLogger.Add(" >> Load_Datafor_Entity2 took " & Format(elapsed, "0.000000000") & " seconds", False)
            End If
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", ex.Message, "Load_Datafor_Entity: " & ex.StackTrace)
        End Try

    End Sub

    Sub Get_RecordCounts_Nodes()
        Try
            If NODE_NAVIGATION = True Then
                Exit Sub
            End If
            Dim selnode As TreeNode = TreeViewMain.SelectedNode
            Dim a As Integer = 0
            For Each childNodeLevel1 As TreeNode In selnode.Nodes
                Dim PARENT_ID1 As Integer
                Dim TYPE_ID1 As Integer
                If a = 0 Then
                    Dim sql As String = "SELECT PARENT_ID, FORM_TYPE_ID FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND FORM_ID = " & ClassNodeNavigation.Return_ENTITY_FOR_TAG(childNodeLevel1.Tag) & " AND SCREEN_ID = " & CURRENT_SCREEN_ID
                    Dim DT As DataTable = ClassDatabase.Return_Datatable(sql, True)
                    PARENT_ID1 = DT.Rows(0).Item(0)
                    TYPE_ID1 = DT.Rows(0).Item(1)
                End If
                If TYPE_ID1 <> 5 Then
                    If childNodeLevel1.Text = "Allgemein" Then
                        Console.WriteLine("Allgemein-Reiter")
                    End If
                    Dim result As Integer = ReturnAmountofRecords(ClassNodeNavigation.Return_ENTITY_FOR_TAG(childNodeLevel1.Tag))
                    If result <> 99999999 Then
                        Dim origtext As String = childNodeLevel1.Text
                        If origtext.Contains(" (") Then
                            Dim existingstring = origtext.Substring(0, origtext.IndexOf("(") - 1)
                            childNodeLevel1.Text = existingstring & " (" & result.ToString & ")"
                        Else
                            childNodeLevel1.Text = childNodeLevel1.Text & " (" & result.ToString & ")"
                        End If
                    End If

                    For Each childNodeLevel2 As TreeNode In childNodeLevel1.Nodes
                        Dim origtext As String = childNodeLevel2.Text
                        If origtext.Contains(" (") Then
                            Dim existingstring = origtext.Substring(0, origtext.IndexOf("(") - 1)
                            childNodeLevel2.Text = existingstring
                        End If
                        For Each childNodeLevel3 As TreeNode In childNodeLevel2.Nodes
                            Dim origtext1 As String = childNodeLevel3.Text
                            If origtext1.Contains(" (") Then
                                Dim existingstring = origtext1.Substring(0, origtext1.IndexOf("(") - 1)
                                childNodeLevel1.Text = existingstring
                            End If
                        Next
                    Next
                    a += 1
                End If

            Next
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", ex.Message, "Load_Datafor_Entity: " & ex.StackTrace)
        End Try
    End Sub
    Function ReturnAmountofRecords(EntityID As Integer)
        ' Statt eine Table zurückzugeben, können wir die anzahl der Zeilen auch in der Datenbank berechnen,
        ' dadurch wird die Abfrage um einiges schneller
        Dim SQL As String = "SELECT COUNT(*) FROM ( SELECT T.* FROM VWTEMP_PMO_FORM" & EntityID & " AS T,TBPMO_RECORD_CONNECT T1 WHERE T.[Record-ID] = T1.RECORD2_ID AND T1.RECORD1_ID = @RecordID ) x"

        'Abhängig von der Entität dieAnzahl der Datensätze laden
        Select Case ACT_EBENE
            Case 1
                If EBENE1_RECID = 0 Then
                    Return 99999999
                End If

                '_sql = _sql.Replace("@RecordID", EBENE1_RECID)
                SQL = SQL.Replace("@RecordID", EBENE1_RECID)
            Case 2
                If EBENE2_RECID = 0 Then
                    Return 99999999
                End If
                If EBENE1_RECID = 0 Then

                End If
                '_sql = _sql.Replace("@RecordID", EBENE2_RECID)
                SQL = SQL.Replace("@RecordID", EBENE2_RECID)
            Case 3
                If EBENE3_RECID = 0 Then
                    Return 99999999
                End If
                '_sql = _sql.Replace("@RecordID", EBENE2_RECID)
                SQL = SQL.Replace("@RecordID", EBENE2_RECID)

        End Select

        'Dim DT2 As DataTable = ClassDatabase.Return_Datatable(_sql, "ReturnAmountofRecords 1")
        Dim count As Integer = ClassDatabase.Execute_Scalar(SQL, True)

        Return count
    End Function

#End Region

#Region "Status Bar"

    Public Sub Update_Status_Label(visible As Boolean, Optional text As String = "", Optional state As EditState = EditState.None)
        tsslblStatus.Text = text
        tsslblStatus.Visible = visible

        Select Case state
            Case EditState.Insert
                tsslblStatus.BackColor = Color.Yellow
            Case EditState.Update
                tsslblStatus.BackColor = Color.LightBlue
            Case Else
                tsslblStatus.BackColor = Color.LightGray
        End Select
    End Sub

    Public Sub Update_Record_Label(RecordId As Integer)
        Try
            Dim SQL 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 resultDT As DataTable
            If CtrlCommandUI.IsInsert = True Then
                resultDT = ClassDatabase.Return_Datatable(SQL)
            Else
                resultDT = ClassDatabase.Return_Datatable(SQL, True)
            End If


            If Not IsNothing(resultDT) Then
                If resultDT.Rows.Count = 0 Then
                    Exit Sub
                End If
                tsslblRecord.Visible = False
                Dim CreateChangeString = String.Format("Added by '{0}', when: {1}", resultDT.Rows(0).Item(0), resultDT.Rows(0).Item(1))
                If CtrlCommandUI.IsInsert = False Then
                    CreateChangeString = CreateChangeString + String.Format(" - Changed by '{0}', when: {1}", resultDT.Rows(0).Item(2), resultDT.Rows(0).Item(3))
                End If

                If FORM_TYPE = 5 Then
                    tsslblRecord.Text = String.Format("Group-Record ({0}) - {1}", RecordId, CreateChangeString.ToString)
                Else
                    If IS_SINGLE_RECORD = True Then
                        tsslblRecord.Text = String.Format("Single-Record ({0}) - {1}", RecordId, CreateChangeString.ToString)
                    Else
                        tsslblRecord.Text = String.Format("Record ({0}) - {1}", RecordId, CreateChangeString.ToString)
                    End If

                End If
                tsslblRecord.Visible = True
            End If
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", ex.Message, ex.StackTrace)
        End Try

    End Sub

#End Region

#Region "Controls"
    Sub Load_Controls(frmview_id As Integer)
        Dim sw As New Stopwatch
        sw.Start()
        Dim elapsed As Double
        FORMVIEW_ID = frmview_id
        ENTITY_ID = DT_TBPMO_FORM_VIEW.Rows(0).Item("FORM_ID")
        CtrlBuilder = New ClassControlBuilder(pnlDetails)
        CtrlCommandUI = New ClassControlCommandsUI(CtrlBuilder,
                                                   ContextMenuDetails,
                                                   AddressOf NewEditAppointment)

        CtrlCommandUI.LoadControls(ENTITY_ID)
        Lock_RecordControls(True)

        AddHandler CtrlBuilder.OnRecordChanged, AddressOf OnRecordChanged
        AddHandler CtrlBuilder.OnMouseHover, AddressOf HandleToolTip
        elapsed = sw.Elapsed.TotalSeconds
        If LogErrorsOnly = False Then ClassLogger.Add(" >> Load_Controls took " & Format(elapsed, "0.000000000") & " seconds", False)
        sw.Stop()
        sw.Reset()
    End Sub

    Private Sub HandleToolTip(sender As Object, e As EventArgs)
        Dim control As Control = DirectCast(sender, 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

    Private Sub OnRecordChanged(sender As Object, e As System.EventArgs)
        If ENTITY_LOADED Then
            RECORD_CHANGED = True
        End If

    End Sub
#End Region

#Region "DetailView - Toolstrip"

    Private Sub tsButtonAdd_Click(sender As Object, e As EventArgs) Handles tsButtonAdd.Click
        If USER_PERSONIFIED_TEST = True Then
            ClassHelper.MSGBOX_Handler("INFO", "Attention", "You are using ADDi in personified mode! Adding records is not allowed!")
            Exit Sub
        End If
        If ClassProxy.IS_PROXY_BUSY = True Then
            MsgBox("Proxy-Server is actually synchronizing! Please wait until synchronisation is finished!" & vbNewLine & "This might take up to 3 minutes!", MsgBoxStyle.Information)
            Exit Sub
        End If
        ' Vor dem Hinzufügen muss der EditMode auf jeden Fall ausgeschaltet werden!!
        DisableEditMode()
        tsButtonEdit.Enabled = False

        ' IsInsert muss true sein, damit wir wissen ob wir bei
        ' Abbruch den Record Wieder löschen können
        CtrlCommandUI.IsInsert = True

        ' Alle Tabs außer Detailansicht deaktivierne
        '  DeactivateTabs()

        'Wenn es eine Parent_ID gibt aber kein PArent_Datensatz ausgewählt wurde muss dies nachgeholt werden
        If PARENT_ENTITYID > 0 Then
            If PARENT_SKIPPED = True And PARENT_RECORDID = 0 Then
                Dim msg = "Achtung es wurde noch kein Parent-Datensatz ausgewählt! Bitte wählen Sie einen Datensatz aus!"
                If USER_LANGUAGE <> "de-DE" Then
                    msg = "Attention: No parent-record was selected! Please choose a parent record!"
                End If
                MsgBox(msg, MsgBoxStyle.Exclamation)
                Try
                    Dim sql
                    sql = "select * from VWTEMP_PMO_FORM" & PARENT_ENTITYID.ToString
                    CURRENT_PARENT_DT = ClassDatabase.Return_Datatable(sql, True)
                    frmChooseParentRecord.ShowDialog()
                    If CURRENT_PARENT_RECORD_ID = 0 Then
                        MsgBox("No Parent-Record selected. Adding will be terminated.", MsgBoxStyle.Exclamation)
                        Exit Sub
                    End If
                    PARENT_RECORDID = CURRENT_PARENT_RECORD_ID
                    Select Case ACT_EBENE '#### Hier muss nun der Parent-Record gesetzt werden ####
                        Case 1
                            EBENE1_RECID = CURRENT_PARENT_RECORD_ID
                        Case 2
                            EBENE1_RECID = CURRENT_PARENT_RECORD_ID
                        Case 3
                            EBENE2_RECID = CURRENT_PARENT_RECORD_ID
                    End Select
                Catch ex As Exception
                    ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", ex.Message, ex.StackTrace)
                End Try
            End If
        End If
        Me.Cursor = Cursors.WaitCursor
        Try
            If TCDetails.SelectedTabPage.Text.StartsWith("Pos") = False Then
                SELECTED_RECORD_ID = 0
                Lock_RecordControls(False)
                tsButtonCancel.Visible = True

                CURRENT_PARENT_ENTITY_ID = PARENT_ENTITYID
                ' Den Record anlegen, damit wir eine RECORD_ID bekommen
                ClassRecordCommands.CreateRecord(ENTITY_ID)
                ' Die RECORD_ID auslesen und setzen
                NEW_RECORD_ID = ClassRecordCommands.GetLastRecord()
                CURRENT_RECORD_ID = NEW_RECORD_ID
                RECORD_ID = NEW_RECORD_ID
                SELECTED_RECORD_ID = NEW_RECORD_ID
                ClassProxy.PRPROXY_RECORD_UPD_INS(ENTITY_ID, SELECTED_RECORD_ID)
                If PARENT_ENTITYID > 0 And PARENT_RECORDID > 0 Then
                    If ClassRecordCommands.ConnectRecord(PARENT_RECORDID, CURRENT_RECORD_ID, "INSERT RECORD") = False Then
                        ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "In Connecting Record - Check the log!")
                    Else
                        ClassProxy.PRPROXY_RECORD_CONNECT(PARENT_RECORDID, CURRENT_RECORD_ID)
                    End If
                End If

                ClassControlValues.LoadDefaultValues(ENTITY_ID, SELECTED_RECORD_ID, pnlDetails.Controls, CURRENT_PARENT_ENTITY_ID, ENTITY_ID)
                ClassControlValues.Enable_Depending_Controls(ENTITY_ID, RECORD_ID, PARENT_RECORDID, CtrlBuilder.AllControls, ENTITY_ID)
                ' Das StatusLabel aktualisieren
                Update_Record_Label(NEW_RECORD_ID)
                Doc_ReadOnlyHandler(True)
                RUN_WDSEARCH_GRID()
                ' Im gegensatz zu EnableEditMode muss hier nur der save button enabled werden
                tsButtonSave.Enabled = True
                ' Muss aktiviert werden, sonst funktionieren die Combobox Abhängigkeits Events nicht
                CURRENT_RECORD_ENABLED = True
                ' EDIT_STATE muss hier (immer?) Update sein, sonst wird beim Speichern noch ein Datensatz angelegt
                EDIT_STATE = EditState.Update
                RECORD_CHANGED = True
                'tsslblRecord.Text = "Adding record ......"
                RIGHT_RECORD_AND_FILE_READ_ONLY = False
                tslblLocked.Visible = False
                tslblFileslocked.Visible = False
                tsButtonAdd.Enabled = False
            End If
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", ex.Message, ex.StackTrace)
        Finally
            Me.Cursor = Cursors.Default
        End Try
    End Sub

    Private Sub tsButtonSave_Click(sender As Object, e As EventArgs) Handles tsButtonSave.Click
        Me.Cursor = Cursors.WaitCursor
        Save_Record()
    End Sub

    Sub Focus_Control(name As String)
        Dim controls As Control.ControlCollection = pnlDetails.Controls

        For Each c As 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
    Function Save_Record()
        Try
            Me.Cursor = Cursors.WaitCursor
            SAVE_ROUTINE_ACTIVE = True
            Save_Grid_Layout()
            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.")
                    ActivateAllTabs()
                    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 CtrlCommandUI.IsInsert Then
                    ActivateAllTabs()
                    DisableEditMode()
                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

            SELECTED_RECORD_ID = recid
            RECORD_ID = recid
            CURRENT_RECORD_ID = RECORD_ID
            If RECORD_ID = 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
                Select Case ACT_EBENE
                    Case 1
                        EBENE1_RECID = recid
                        For Each row As DataRow In DT_SELECTION.Rows
                            If row.Item("Record-ID") = SELECTED_RECORD_ID Then
                                EBENE1_GRID_RESULT = row.Item(EBENE1_COLUMNNAME)
                            End If
                        Next
                    Case 2
                        EBENE2_RECID = recid
                        For Each row As DataRow In DT_SELECTION.Rows
                            If row.Item("Record-ID") = SELECTED_RECORD_ID Then
                                EBENE2_GRID_RESULT = row.Item(EBENE2_COLUMNNAME)
                            End If
                        Next
                        If EBENE1_RECID = 0 Then
                            'Bis jetzt konnte noch keine Parent-ID angelegt werden!
                            ClassHelper.MSGBOX_Handler("INFO", "Attention", "No parent-link created!")
                            'Show_Verknuepfungen()
                        End If
                End Select
                'Dim exec = String.Format("EXEC PRPMO_CLIENT_AFTER_RECORD_INSERT {0}", CURRENT_RECORD_ID)
                'ClassDatabase.Execute_non_Query_withConn(exec, 1)
            ElseIf EDIT_STATE = EditState.Update Then
                'Weil es ein Insert war müssen noch die Daten gespeichert/erneuert werden
                Select Case ACT_EBENE
                    Case 1
                        EBENE1_RECID = recid
                        For Each row As DataRow In DT_SELECTION.Rows
                            If row.Item("Record-ID") = SELECTED_RECORD_ID Then
                                If EBENE1_COLUMNNAME = "" Then
                                    EBENE1_GRID_RESULT = "No Column configured"
                                Else
                                    EBENE1_GRID_RESULT = Get_GridResult(EBENE1_COLUMNNAME)
                                    ' EBENE1_GRID_RESULT = row.Item(EBENE1_COLUMNNAME)
                                End If
                            End If
                        Next
                    Case 2
                        EBENE2_RECID = recid
                        For Each row As DataRow In DT_SELECTION.Rows
                            If row.Item("Record-ID") = SELECTED_RECORD_ID Then
                                If EBENE2_COLUMNNAME = "" Then
                                    EBENE2_GRID_RESULT = "No Column configured"
                                Else
                                    EBENE2_GRID_RESULT = row.Item(EBENE2_COLUMNNAME)
                                End If

                            End If
                        Next
                End Select
            End If
            CtrlCommandUI.IsInsert = False
            CtrlCommandUI.IsEdit = 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(SELECTED_RECORD_ID)

            If IS_SINGLE_RECORD = False Then
                If FORM_TYPE <> 5 Then
                    Load_Entity_Data_Only()
                    LocateRecordById(RECORD_ID)
                    If EDIT_STATE = EditState.Insert Then
                        'Die Daten neu laden

                        'Get_Grid_Row_Handle(NEW_RECORD_ID)
                    Else
                        'Die Daten neu laden

                        'Get_Grid_Row_Handle(RECORD_ID)
                        'Die Daten auf dem Panel laden
                        'ClassControlValues.LoadControlValues(RECORD_ID, ENTITY_ID, CtrlBuilder.AllControls)
                        ' Laden der Daten bedeutet nicht dass Daten vom Benutzer geändert wurden!
                        RECORD_CHANGED = False
                    End If

                End If
            End If

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

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

        CtrlCommandUI.IsInsert = False
        EDIT_STATE = EditState.None
        RECORD_CHANGED = False
        SAVE_ROUTINE_ACTIVE = False
        Me.Cursor = Cursors.Default
        Return True
    End Function
    Sub Delete_Record()
        RECORD_ID = SELECTED_RECORD_ID
        If USER_PERSONIFIED_TEST = True Then
            ClassHelper.MSGBOX_Handler("INFO", "Attention", "You are using ADDI in personified mode! Deleting records is not allowed!")
            Exit Sub
        End If
        If ClassProxy.IS_PROXY_BUSY = True Then
            MsgBox("Proxy-Server is actually synchronizing! Please wait until synchronisation is finished!" & vbNewLine & "This might take up to 3 minutes!", MsgBoxStyle.Information)
            Exit Sub
        End If
        Dim msg As String
        If RIGHT_RECORD_AND_FILE_READ_ONLY = False Then
            msg = "Sind Sie sicher, dass Sie diesen Record/Datensatz '" & SELECTED_RECORD_ID.ToString & "' löschen wollen?"
            If USER_LANGUAGE <> "de-DE" Then
                msg = "Are You sure You want to delete the selected record'" & SELECTED_RECORD_ID.ToString & "'?"
            End If
            Dim result As MsgBoxResult
            result = MessageBox.Show(msg, "Confirmation:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
            If result = MsgBoxResult.Yes Then
                RECORD_ID = SELECTED_RECORD_ID
                ClassRightManagement.Check_Set_Rights(RECORD_ID, ENTITY_ID)
                CONTROL_HANDLING()
                Dim DT_DOC_RESULT As DataTable = ClassDOC_SEARCH.Get_DOCRESULTS(DT_RESULTLIST_OPTIONS, DT_RESULTLIST_VARIABLE_VALUE, DT_WINDREAM_RESULTLIST, ENTITY_ID, "RECORD")
                If IsNothing(DT_DOC_RESULT) Then
                    ClassLogger.Add(">> DT_DOC_RESULT is nothing!", True)
                End If
                If ClassHelper.DeleteRecord(SELECTED_RECORD_ID) = True Then
                    RECORD_CHANGED = False
                    EDIT_STATE = EditState.None
                    CURRENT_RECORD_ENABLED = False
                    ' Update_Record_Label(SELECTED_RECORD_ID)
                    ClassHelper.InsertEssential_Log(SELECTED_RECORD_ID, "RECORD-ID", "RECORD WAS DELETED MANUALLY by USER: " & USER_USERNAME)
                    msg = "Der Datensatz '" & SELECTED_RECORD_ID & "' und alle Abhängigkeiten wurden erfolgreich gelöscht - " & Now
                    If USER_LANGUAGE <> "de-DE" Then
                        msg = "The record and all dependencies for '" & SELECTED_RECORD_ID & "' were deleted - " & Now
                    End If
                    Update_Status_Label(True, msg, EditState.Update)

                    WD_DELETE_DOCS(DT_DOC_RESULT)
                    SELECTED_RECORD_ID = 0
                    RECORD_ID = 0
                    CURRENT_RECORD_ID = 0
                    RECORD_CHANGED = False
                    'Den derzeitigen Record Neuladen
                    DisableEditMode()
                    Load_Entity_Data(ACT_EBENE)
                    RECORD_CHANGED = False
                End If
            End If
        Else
            msg = "Sie dürfen diesen Datensatz nicht löschen! (Rechtekonzept)!"
            If USER_LANGUAGE <> "de-DE" Then
                msg = "Due to right-privileges You are not allowed to delete this record!"
            End If
            MessageBox.Show(msg, "Warning:", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If

    End Sub
    Private Sub tsButtonDelete_Click(sender As Object, e As EventArgs) Handles tsButtonDelete.Click
        Delete_Record()
    End Sub

    Private Sub tsButtonEditMode_Click(sender As Object, e As EventArgs) Handles tsButtonEdit.Click
        ToggleEditMode()
    End Sub

    Sub ToggleEditMode()

        If RECORD_ENABLED = False Then
            EnableEditMode()
        Else
            'If RECORD_CHANGED = True Then
            '    Dim ResultMessage As String
            '    Try
            '        ResultMessage = Update_Record_OnChange()
            '    Catch ex As Exception
            '        MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Error in saving Record")
            '        Me.Cursor = Cursors.Default
            '        Exit Sub
            '    End Try
            'End If
            If TrySave_Automatic() = True Then
                DisableEditMode()
            End If
        End If
    End Sub

    Sub EnableEditMode()
        Dim rec = RECORD_ID
        Dim EditingUser = ClassRecordState.IsRecordLocked(SELECTED_RECORD_ID)
        ' Überprüfen, ob der Record gerade bearbeitet wird
        If Not IsNothing(EditingUser) And EditingUser <> USER_USERNAME Then

            tslblLocked.Visible = True
            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

        Else
            'Wenn Record bearbeitet werden kann, IN_WORK auf 1 setzen, um Bearbeitung durch andere zu verhindern!
            ClassRecordState.LockRecord(SELECTED_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)
        ClassDatabase.Execute_non_Query(del)
        Lock_RecordControls(False)
        Me.tsButtonAdd.Enabled = False
        Me.tsButtonSave.Enabled = True
        tsbtnRedo.Visible = True
        Dim stg As String
        If USER_LANGUAGE = "de-DE" Then
            stg = "Bearbeiten beenden"
        Else
            stg = "End Working"
        End If
        Me.tsButtonEdit.Text = stg
        If RIGHT_RECORD_AND_FILE_READ_ONLY = False Then
            tsButtonDelete.Enabled = True
        End If

        CURRENT_RECORD_ID = 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(ENTITY_ID, RECORD_ID, PARENT_RECORDID, CtrlBuilder.AllControls, ENTITY_ID)
        CtrlBuilder.WatchRecordChanges = True

        RECORD_ENABLED = True
        CURRENT_RECORD_ENABLED = True
        If RIGHT_READ_ONLY_DOC = False Then
            Doc_ReadOnlyHandler(True)
        End If
        pnlDetails.Focus()
        'If RECORD_ENABLED = False Then
        '    ClassControlValues.LoadControlValuesList(SELECTED_RECORD_ID, ENTITY_ID, CtrlBuilder.AllControls)
        'End If
    End Sub

    Sub DisableEditMode()
        Dim REC = RECORD_ID
        ClassRecordState.UnlockRecord(SELECTED_RECORD_ID)
        tsbtnRedo.Visible = False
        Lock_RecordControls(True)
        RECORD_ENABLED = False
        POS_ENABLED = False
        CURRENT_RECORD_ENABLED = False

        Me.tsButtonDelete.Enabled = False
        Me.tsButtonAdd.Enabled = True
        Me.tsButtonSave.Enabled = False
        Dim stg As String
        If USER_LANGUAGE = "de-DE" Then
            stg = "Bearbeiten"
        Else
            stg = "Edit record"
        End If
        Me.tsButtonEdit.Text = stg
        Me.tsButtonEdit.Text = stg

        If Not IsNothing(CtrlCommandUI) Then
            ActivateAllTabs()
        End If
        If RECORD_ENABLED = True Then
            ClassControlValues.UnloadControlValuesList(SELECTED_RECORD_ID, RECORD_ID, 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
            If ACTIVATE_DOC_SEARCH_ON_EDIT = False Then
                Doc_ReadOnlyHandler(False)
            Else
                Doc_ReadOnlyHandler(True)
            End If

        End If

    End Sub

#End Region

#Region "Appointments"
    Sub NewEditAppointment(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
        Try
            Dim ctrl As Control = sender
            ClassFunctionCommandsUI.NewEditAppointment(ctrl.Name, ENTITY_ID, RECORD_ID, pnlDetails.Controls)
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", ex.Message, ex.StackTrace)
        End Try
    End Sub

    Sub EditAppointment(ByVal sender As 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_RECORD_ID
    End Function
#End Region
   

    Sub Load_Entity_Data(ClickedLevel As Integer)
        Try
            Dim sw As New SW("Load_Entity_Data")
            PARENT_SKIPPED = False
            Me.Cursor = Cursors.WaitCursor
            RECORD_CHANGED = False
            RECORD_ID = 0
            'Setzen von Rechten

            'VerknüpfungenToolStripMenuItem.Enabled = False
            Dim sql = "SELECT CONTROL_ID, CONTROL_READ_ONLY FROM VWPMO_CONTROL_SCREEN WHERE CTRLTYPE_ID NOT IN (1) AND CONTROL_ENTITY_ID = " & ENTITY_ID
            DT_CONTROLS_ENTITY = ClassDatabase.Return_Datatable(sql, True)

            COUNT_RO_CONTROLS = 0
            Dim expression As String
            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
                tsButtonEdit.Enabled = False
            Else
                tsButtonEdit.Enabled = True
            End If

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

            LOAD_DIRECT = result.Item("LOAD_DIRECT")
            CURRENT_CONSTRUCTOR_DETAIL_ID = result.Item("GUID")
            CONTROL_DOCTYPE_MATCH = result.Item("CONTROL_DOCTYPE_MATCH")
            SQL_RECORD_AND_FILE_READ_ONLY = result.Item("SQL_RIGHT_READ_AND_VIEW_ONLY")
            SQL_DOC_READ_ONLY = result.Item("SQL_RIGHT_WINDREAM_VIEW")
            DOC_SEARCH_TAB1 = result.Item("DOC_SEARCH_TAB1")
            If DOC_SEARCH_TAB1 = True Then
                tslblDocIDMain.Visible = False
                tslblDocIDTab1.Visible = True
            Else
                tslblDocIDMain.Visible = True
                tslblDocIDTab1.Visible = False
            End If

            Dim GEODATA As Boolean = False
            sql = String.Format("SELECT COUNT(*) FROM TBPMO_RECORD_GEODATA WHERE RECORD_ID IN (SELECT GUID FROM TBPMO_RECORD WHERE PARENT_RECORD = 0 AND FORM_ID = {0})", ENTITY_ID)
            Dim count = ClassDatabase.Execute_Scalar(sql, True)
            If count > 0 Then
                GEODATA = True
            Else
                GEODATA = False
            End If
            If GEODATA = True Then
                tsbtnGeodata.Visible = True
            Else
                tsbtnGeodata.Visible = False
            End If
            ACTIVATE_DOC_SEARCH_ON_EDIT = result.Item("ACTIVATE_DOC_SEARCH_ON_EDIT")
            sql = String.Format("select * from TBPMO_DOCSEARCH_RESULTLIST_CONFIG WHERE VISIBLE = 1 AND ENTITY_ID = {0} AND LANGUAGE = '{1}'", ENTITY_ID, USER_LANGUAGE) 'TBPMO_WINDREAM_RESULTLIST_CONFIG"
            DT_WINDREAM_RESULTLIST = ClassDatabase.Return_Datatable(sql, True)
            sql = String.Format("select T.*, T1.HEADER_CAPTION from TBPMO_DOCRESULT_DROPDOWN_ITEMS T, TBPMO_DOCSEARCH_RESULTLIST_CONFIG T1 WHERE T.CONFIG_ID = T1.GUID AND T.CONFIG_ID IN (SELECT GUID FROM TBPMO_DOCSEARCH_RESULTLIST_CONFIG WHERE ENTITY_ID = {0} AND TYPE_ID = 4 AND LANGUAGE = '{1}')", ENTITY_ID, USER_LANGUAGE)
            DT_DOCRESULT_DROPDOWN_ITEMS = ClassDatabase.Return_Datatable(sql, True)

            sql = String.Format("select * from TBPMO_DOCSEARCH_VARIABLE_CONTROLS WHERE ENTITY_ID = {0}", ENTITY_ID) 'TBPMO_WINDREAM_RESULTLIST_CONFIG"
            DT_RESULTLIST_OPTIONS = ClassDatabase.Return_Datatable(sql, True)
            sql = String.Format("select * from TBPMO_DOCSEARCH_RESULTLIST_CONFIG WHERE VISIBLE = 1 AND ENTITY_ID = {0} AND LANGUAGE = '{1}' AND COLUMN_VIEW LIKE 'VALUE%'", ENTITY_ID, USER_LANGUAGE)
            DT_RESULTLIST_VARIABLE_VALUE = ClassDatabase.Return_Datatable(sql, True)
            Dim ENTITY_ROW = (From form In DT_ENTITY_DATA.AsEnumerable()
                      Select form
                      Where form.Item("GUID") = ENTITY_ID).Single()

            FORM_TYPE = ENTITY_ROW.Item("FORM_TYPE_ID")
            IS_SINGLE_RECORD = ENTITY_ROW.Item("SINGLE_RECORD")
            POS_ENTITY = ENTITY_ROW.Item("POS_ENTITY")
            REDUNDANT_FORM = ENTITY_ROW.Item("REDUNDANT_ENTITY")
            LOAD_ENTITY_SEARCH_AT_STARTUP = ENTITY_ROW.Item("LOAD_ENT_SEARCH_AT_SU")
            If REDUNDANT_FORM <> 0 Then
                CURRENT_ENTITY_REDUNDANT_ID = REDUNDANT_FORM
            Else
                CURRENT_ENTITY_REDUNDANT_ID = 0
            End If
            sql = String.Format("select * from TBPMO_RIGHT_USER WHERE USER_ID = {0} AND ENTITY_ID = {1}", USER_GUID, ENTITY_ID)
            DT_RIGHTS_USER = ClassDatabase.Return_Datatable(sql, True)
            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})", ENTITY_ID, USER_GUID)
            DT_RIGHTS_GROUP = ClassDatabase.Return_Datatable(sql, True)

            If VIEW_ID_RUNTIME <> -1 Then
                GRID_TYPE_ID = VIEW_ID_RUNTIME
            Else
                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, ENTITY_ID, USER_GUID)
                Dim VIEW_ID = ClassDatabase.Execute_Scalar(sql, True)
                If IsNothing(VIEW_ID) Then
                    ClassDatabase.Execute_non_Query("INSERT INTO TBPMO_USER_CONSTR_VIEW_TYPE ([USER_ID],CONSTRUCTOR_DETAIL_ID,[ENTITY_ID]) VALUES (" & USER_GUID & "," & CURRENT_CONSTRUCTOR_DETAIL_ID & "," & ENTITY_ID & ")")
                    VIEW_ID = 1
                End If
                GRID_TYPE_ID = VIEW_ID
            End If

            ' Den GridType setzen: 1=TileView,2=Carousel,3=GridView
            Select Case GRID_TYPE_ID
                Case 1
                    GRID_TYPE = GridType.Tiles
                    GridControlMain.MainView = grvwTiles
                Case 2
                    GRID_TYPE = GridType.Carousel
                    GridControlMain.MainView = grvwCarousel
                Case 3
                    GRID_TYPE = GridType.Grid
                    GridControlMain.MainView = grvwGrid
            End Select
            SELECTED_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") = ENTITY_ID).Single()
            PARENT_ENTITYID = result1.Item("PARENT_ID")
            CURRENT_PARENT_ENTITY_ID = PARENT_ENTITYID

            'Abhängig von der Entität die Selektierungs-Daten laden
            'Get_Grid_Sql(CONSTRUCTORID, ENTITY_ID, CURRENT_CONSTRUCTOR_DETAIL_ID)

            ' 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") = ENTITY_ID

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

            Dim GridSQL As String = Get_Grid_Sql(CONSTRUCTORID, ENTITY_ID, CURRENT_CONSTRUCTOR_DETAIL_ID, GRID_TYPE, USER_GUID, QuickViewSQL, IS_SINGLE_RECORD, FORM_TYPE, VIEW_ID, GridControlMain, grvwGrid)
            _ENTITYSQL = GridSQL
            CURRENT_ENTITYSQL = GridSQL

            'Anzahl der Datensätze
            ENTITY_RECORD_COUNT = ClassDatabase.Execute_Scalar("SELECT COUNT(*) FROM TBPMO_RECORD where PARENT_RECORD = 0 AND FORM_ID = " & ENTITY_ID, True)

            If CBool(LOAD_ENTITY_SEARCH_AT_STARTUP) = True Then
                ClassDOC_SEARCH.Get_DOC_RESULTTABLE(DT_RESULTLIST_OPTIONS, DT_RESULTLIST_VARIABLE_VALUE, DT_WINDREAM_RESULTLIST, ENTITY_ID, RECORD_ID, True, True)
            End If
            Select Case ClickedLevel
                Case 1
                    EBENE1_ENTITY = ""
                    EBENE1_RECID = 0
                    EBENE2_ENTITY = ""
                    EBENE2_RECID = 0
                    EBENE3_ENTITY = ""
                    EBENE3_RECID = 0

                    PARENT_RECORDID = 0
                    EBENE1_ENTITY = TreeViewMain.SelectedNode.Text
                    ACT_EBENE_STRING = EBENE1_ENTITY
                    If LogErrorsOnly = False Then ClassLogger.Add(" >> Level 1 selected in TreeView", False)


                    'tslblEntity2.Visible = False
                    'tslblEntity3.Visible = False


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

                    EBENE1_COLUMNNAME = result2.Item("COLUMN_NAME1")
                    EBENE2_COLUMNNAME = ""
                    EBENE3_COLUMNNAME = ""
                    EBENE2_GRID_RESULT = Nothing
                    EBENE3_GRID_RESULT = Nothing
                Case 2
                    EBENE2_ENTITY = TreeViewMain.SelectedNode.Text
                    ACT_EBENE_STRING = EBENE2_ENTITY
                    If LogErrorsOnly = False Then ClassLogger.Add(" >> Level 2 selected in TreeView", False)
                    EBENE3_ENTITY = ""
                    'Wenn bereits ein Record für Ebene 1 gewählt wurde dann einschränken
                    If EBENE1_RECID > 0 Then
                        PARENT_RECORDID = EBENE1_RECID
                        If GRID_TYPE = GridType.Grid Then
                            _ENTITYSQL = "SELECT T.* FROM VWTEMP_PMO_FORM" & ENTITY_ID.ToString & " T, TBPMO_RECORD_CONNECT t1 where T.[Record-ID] = T1.RECORD2_ID AND T1.RECORD1_ID = " & PARENT_RECORDID
                        Else
                            _ENTITYSQL = _ENTITYSQL.Replace("@RecordID", EBENE2_RECID)
                            _ENTITYSQL = _ENTITYSQL.ToString.Replace("TBPMO_FORM T1", "TBPMO_FORM T1 ,TBPMO_RECORD_CONNECT T2")
                            _ENTITYSQL = _ENTITYSQL & " AND T.GUID = T2.RECORD2_ID  AND T2.RECORD1_ID = @T2.RECORD1_ID"
                            _ENTITYSQL = _ENTITYSQL.ToString.Replace("@T2.RECORD1_ID", PARENT_RECORDID)
                        End If
                    Else
                        SELECTED_RECORD_ID = 0
                        PARENT_RECORDID = 0
                        NavPane.Categories.Clear()
                        tsslblRecord.Text = ""
                        Update_Status_Label(True, "Entity 1 skipped - All Records loaded", EditState.Update)
                        PARENT_SKIPPED = True
                    End If

                    Dim result3 = (From form In DT_VWPMO_CONSTRUCTOR_FORMS.AsEnumerable()
                                Select form
                                Where form.Item("FORM_ID") = ENTITY_ID).Single()
                    EBENE2_COLUMNNAME = result3.Item("COLUMN_NAME1")

                    EBENE3_COLUMNNAME = ""
                    EBENE2_GRID_RESULT = Nothing
                    EBENE3_GRID_RESULT = Nothing

                Case 3
                    EBENE3_ENTITY = TreeViewMain.SelectedNode.Text
                    ACT_EBENE_STRING = EBENE3_ENTITY
                    If LogErrorsOnly = False Then ClassLogger.Add(" >> Level 3 selected in TreeView", False)

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

                    EBENE3_COLUMNNAME = result4.Item("COLUMN_NAME1")
                    'Wenn bereits ein Record für Ebene 1 gewählt wurde dann eisnchränken
                    If EBENE2_RECID > 0 Then
                        'Parent-ID setzen
                        PARENT_RECORDID = EBENE2_RECID
                        Try
                            If GRID_TYPE = GridType.Grid Then
                                _ENTITYSQL = "SELECT T.* FROM VWTEMP_PMO_FORM" & ENTITY_ID.ToString & " T, TBPMO_RECORD_CONNECT t1 where T.[Record-ID] = T1.RECORD2_ID AND T1.RECORD1_ID = " & PARENT_RECORDID
                            Else
                                _ENTITYSQL = _ENTITYSQL.Replace("@RecordID", EBENE2_RECID)
                                _ENTITYSQL = _ENTITYSQL.ToString.Replace("TBPMO_FORM T1", "TBPMO_FORM T1 ,TBPMO_RECORD_CONNECT T2")
                                _ENTITYSQL = _ENTITYSQL & " AND T.GUID = T2.RECORD2_ID  AND T2.RECORD1_ID = @T2.RECORD1_ID"
                                _ENTITYSQL = _ENTITYSQL.ToString.Replace("@T2.RECORD1_ID", PARENT_RECORDID)
                            End If
                        Catch ex As Exception
                            ClassLogger.Add("Error in Replacing patterns in entity_sql: " & ex.Message)
                        End Try
                    Else

                        SELECTED_RECORD_ID = 0
                        PARENT_RECORDID = 0
                        NavPane.Categories.Clear()
                        Update_Status_Label(True, "Entity 2 skipped - All Records loaded", EditState.Update)
                        tsslblRecord.Text = ""
                        PARENT_SKIPPED = True
                    End If
                    'Select Case FORM_TYPE
                    '    Case 5
                    '        If GET_GROUP_OR_SINGLE_RECORD(PARENT_RECORDID) = True Then
                    '            EBENE3_RECID = RECORD_ID
                    '        End If
                    'End Select
                    EBENE3_GRID_RESULT = Nothing
            End Select


            _ENTITYSTRING = ACT_EBENE_STRING
            CURRENT_PARENT_RECORD_ID = PARENT_RECORDID
            DT_TBPMO_FORM_VIEW = ClassDatabase.Return_Datatable("SELECT * FROM TBPMO_FORM_VIEW WHERE FORM_ID = " & ENTITY_ID & " AND SCREEN_ID = " & CURRENT_SCREEN_ID, True)

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

            If EDIT_STATE = EditState.None Then
                'Die Controls der Entität laden
                Load_Controls(act_FormViewID)
                tsButtonAdd.Enabled = True
                'set_pnlsize()
            End If
            'Überprüfen ob windream Dos angezeigt werden sollen?
            Check_windream_Show(act_FormViewID)



            If windream_Docshow = True Then
                If TCDetails.SelectedTabPage.Name = "TabWindream" Or (TCDetails.SelectedTabPage.Name = "TabDetails" And DOC_SEARCH_TAB1 = True) Then
                    Me.GridControlDocSearch.DataSource = Nothing

                    If WD_ShowEnitityDocs = True Then
                        Clear_Windream_ResultList()
                        GridControlDocSearch.Visible = True
                    End If
                End If
            End If

            If FORM_TYPE = 5 Or IS_SINGLE_RECORD = True Then
                If GET_GROUP_OR_SINGLE_RECORD(PARENT_RECORDID, True) = True Then
                    ' Laden der Daten bedeutet nicht dass Daten vom Benutzer geändert wurden!

                    If IS_SINGLE_RECORD Then
                        Show_Selected_Record_Data(RECORD_ID, True)
                    Else
                        Refresh_Navpane()
                        Update_Record_Label(SELECTED_RECORD_ID)
                    End If
                    Get_RecordCounts_Nodes()
                End If

                ' Hide_Grid_Columns()
                If FORM_TYPE = 5 Then
                    TabDetails.PageVisible = False
                Else
                    TabDetails.PageVisible = True
                End If

            Else
                TabDetails.PageVisible = True
                GridControlMain.Visible = True

                progressLoadEntity.Visible = True
                labelLoadEntity.Visible = True
                Load_Splitter_Layout()
                If LOCK_CONTROLS_BG_LOAD = True Then
                    SplitContainerMain.Panel2.Enabled = False
                End If
                Dim DTEntity As DataTable
                Try
                    Dim async As New ClassAsyncSQL(_ENTITYSQL)
                    async.bw.RunWorkerAsync()
                    While async.bw.IsBusy
                        Application.DoEvents()
                    End While
                    DTEntity = async.dt
                Catch ex As Exception
                    ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", ex.Message, ex.StackTrace)
                End Try


                If LOCK_CONTROLS_BG_LOAD = True Then
                    SplitContainerMain.Panel2.Enabled = True
                End If

                progressLoadEntity.Visible = False
                labelLoadEntity.Visible = False

                If IsNothing(DTEntity) Then
                    ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in getting Entity-Data - Check logfile")
                Else
                    DTEntity.TableName = "VWTEMP_PMO_FORM" & ENTITY_ID
                    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 = " & ENTITY_ID
                    Dim DT_AUTOVALUES As DataTable = ClassDatabase.Return_Datatable(SQL_AutoValues, True)
                    CURRENT_SQL_AUTO_VALUES_DT = DT_AUTOVALUES

                    If USER_WAN = True Then

                    End If


                    Dim primaryKey(1) As DataColumn
                    primaryKey(0) = DTEntity.Columns("Record-ID")
                    DTEntity.PrimaryKey = primaryKey
                    DT_SELECTION = DTEntity
                    LoadGrid_Selection()

                    If GRID_TYPE = GridType.Grid Then
                        grvwGrid.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.None
                        grvwGrid.OptionsBehavior.Editable = False
                        grvwGrid.OptionsSelection.EnableAppearanceFocusedCell = False
                        grvwGrid.OptionsSelection.EnableAppearanceFocusedRow = False
                        grvwGrid.OptionsSelection.EnableAppearanceHideSelection = False
                    ElseIf GRID_TYPE = GridType.Carousel Then
                        grvwCarousel.OptionsBehavior.Editable = False
                    ElseIf GRID_TYPE = GridType.Tiles Then
                        grvwTiles.FocusedRowHandle = -1
                        grvwTiles.OptionsBehavior.Editable = False
                        grvwTiles.FocusedRowHandle = -1
                        grvwTiles.OptionsTiles.HighlightFocusedTileOnGridLoad = False
                    End If
                    Load_Grid_Layout()
                    HideColumns()

                    'Überprüfen ob es für diese Entität Wiedervorlagen gibt?
                    Check_FOLLOWUP_IsConfigured(ENTITY_ID)

                    SET_ROWCOUNT_STRING()
                End If
                If POS_ENTITY > 0 Then
                    If USER_LANGUAGE <> "de-DE" Then
                        TabDetails.Text = "Head-Data"
                    Else
                        TabDetails.Text = "Kopfdaten"
                    End If

                    TabPos.PageVisible = True
                Else
                    If USER_LANGUAGE <> "de-DE" Then
                        TabDetails.Text = "Details"
                    Else
                        TabDetails.Text = "Detailansicht"
                    End If

                    TabPos.PageVisible = False
                End If
                Load_Templates()

                ' Hinfällig, da hier die Record-ID nicht gebraucht wird
                CtrlBuilder.WatchRecordChanges = False
                ClassControlValues.LoadControlValuesList(ENTITY_ID, CtrlBuilder.MasterPanel.Controls)
                CtrlBuilder.WatchRecordChanges = True

                'Zurücksetzen
                ENTITY_LOADED = True
                Dim RecLoaded As Boolean = False
                If LOAD_DIRECT = True Then
                    Load_Record_Direct()
                    RecLoaded = True
                End If
                If ENTITY_RECORD_COUNT = 1 Then
                    If RecLoaded = False Then
                        Load_Record_Direct()
                    End If
                End If
                If DOC_SEARCH_TAB1 = True Then
                    SplitContainerDetails.Collapsed = False
                    SplitContainerDetails.PanelVisibility = SplitPanelVisibility.Both
                    'ToolStripDokumente.Dock = DockStyle.None
                    pnlDocToolStrip.Controls.Add(ToolStripDokumente)
                    pnlDocFill.Controls.Add(GridControlDocSearch)
                    TabWindream.PageVisible = False


                    Load_DocGrid_Layout()
                Else
                    SplitContainerDetails.PanelVisibility = SplitPanelVisibility.Panel1
                    SplitContainerDetails.Collapsed = True
                    'ToolStripDokumente.Dock = DockStyle.None
                    TabWindream.Controls.Add(ToolStripDokumente)
                    'ToolStripDokumente.Dock = DockStyle.Top
                    TabWindream.Controls.Add(GridControlDocSearch)
                    TabWindream.PageVisible = True
                End If
                If RIGHT_READ_ONLY_DOC = False Then
                    If ACTIVATE_DOC_SEARCH_ON_EDIT = False Then
                        Doc_ReadOnlyHandler(False)
                    Else
                        Doc_ReadOnlyHandler(True)
                    End If

                End If
            End If

            sw.Done()

            If ENTITY_RELOAD_AFT_CONTROL_LOAD = True Then
                Reload_Entity_while_Control_Load()
            End If
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", ex.Message, ex.StackTrace)
        Finally
            Me.Cursor = Cursors.Default
            ENTITY_LOADED = True
        End Try


    End Sub
    Sub Load_Record_Direct()
        Try
            grvwGrid.FocusedRowHandle = 0
            Dim Grid_RecordID = Get_Focused_Row_Cell_Value("Record-ID")
            If Not IsNothing(Grid_RecordID) Then
                Select Case ACT_EBENE
                    Case 1
                        Column_Row_Handler()
                        'PARENT_RECORDID = Grid_RecordID
                        'CURRENT_RECORD_ID = PARENT_RECORDID
                        'SELECTED_RECORD_ID = Grid_RecordID
                        'RECORD_ID = Grid_RecordID
                        'ENTITY_RELOAD_AFT_CONTROL_LOAD = False
                        ''Daten zu Record in jedem Fall laden
                        ''ClassControlValues.LoadControlValues(SELECTED_RECORD_ID, ENTITY_ID, CtrlBuilder.AllControls)
                        'CtrlBuilder.WatchRecordChanges = False
                        'ClassControlValues.LoadControlValuesListWithPlaceholders(ENTITY_ID, Grid_RecordID, PARENT_RECORDID, CtrlBuilder.AllControls, ENTITY_ID)
                        'ClassControlValues.LoadControlValues(SELECTED_RECORD_ID, PARENT_RECORDID, ENTITY_ID, CtrlBuilder.AllControls, ENTITY_ID)
                        'CtrlBuilder.WatchRecordChanges = True
                        '' Laden der Daten bedeutet nicht dass Daten vom Benutzer geändert wurden!
                        'RECORD_CHANGED = False
                        'Update_Record_Label(Grid_RecordID)
                        'Check_Rights()
                End Select
            End If
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", ex.Message, ex.StackTrace)
        End Try
    End Sub
    Sub Load_Entity_Data_Only()
        Try
            ENTITY_LOADED = False
            Dim DTEntity As DataTable = ClassDatabase.Return_Datatable(_ENTITYSQL, True)
            Dim primaryKey(1) As DataColumn
            primaryKey(0) = DTEntity.Columns("Record-ID")
            DTEntity.PrimaryKey = primaryKey
            DT_SELECTION = DTEntity
            LoadGrid_Selection()
            Load_Grid_Layout()
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", ex.Message, ex.StackTrace)
        End Try
        ENTITY_LOADED = True
    End Sub

    Sub CreateTile()
        Try
            Dim ImageIndex As Integer = -1
            Dim i As Integer = 0
            Dim j As Integer = 0
            Dim DT As DataTable = DirectCast(DT_SELECTION, DataTable)
            If DT Is Nothing Then
                MsgBox("Daten können nicht geladen werden - Datatable SELECTION is empty", MsgBoxStyle.Critical)
                Exit Sub
            End If
            Dim PrimaryFont As New Font("Segoe UI", 12, FontStyle.Bold)
            Dim SecondaryFont As New Font("Segoe UI", 10)
            Dim WhiteBackground As Color = System.Drawing.Color.FromArgb(230, Color.White)

            ' Datatable laden
            GridControlMain.DataSource = DT

            grvwTiles.TileTemplate.Clear()

            For Each Column As DataColumn In DT.Columns
                Dim index As Integer = DT.Columns.IndexOf(Column)
                Dim RECORDID_Column As TileViewItemElement
                Dim ImageColumn As TileViewItemElement
                Dim HeadlineColumn As TileViewItemElement
                Dim TextColumn As TileViewItemElement
                Dim TextHeaderColumn As TileViewItemElement

                Select Case index
                    'Case 0
                    '    ' RecordId
                    '    RECORDID_Column = New TileViewItemElement()
                    '    With RECORDID_Column
                    '        .Column = grvwTiles.Columns(0)
                    '        .Column.OptionsFilter.AllowFilter = True
                    '        .TextAlignment = TileItemContentAlignment.TopLeft
                    '    End With
                    '    grvwTiles.TileTemplate.Add(RECORDID_Column)
                    Case 1
                        ' Index 1 ist das Bild
                        If Column.DataType.ToString.Contains("Byte") Then
                            ImageColumn = New TileViewItemElement()
                            With ImageColumn
                                .Image = My.Resources.keinbild
                                .Column = grvwTiles.Columns(1)
                                '.ImageSize = New Size(186, 90)
                                .ImageSize = New Size(186, 118)
                                .ImageScaleMode = TileItemImageScaleMode.ZoomInside
                                .ImageAlignment = TileItemContentAlignment.Manual
                                .ImageLocation = New Point(-10, -10)
                            End With
                            grvwTiles.TileTemplate.Add(ImageColumn)
                        End If
                    Case 2
                        ' Index 2 ist die Headline
                        HeadlineColumn = New TileViewItemElement()
                        With HeadlineColumn
                            .Column = grvwTiles.Columns(2)
                            .TextAlignment = TileItemContentAlignment.TopRight
                            .Appearance.Normal.Font = PrimaryFont
                            .Appearance.Normal.ForeColor = Color.DodgerBlue
                            .Column.OptionsFilter.AllowFilter = True
                        End With
                        grvwTiles.TileTemplate.Add(HeadlineColumn)
                    Case 3 To 4
                        ' Indexe 3 und 4 sind normale Textzeilen
                        TextColumn = New TileViewItemElement()
                        TextHeaderColumn = New TileViewItemElement()
                        Dim OffsetIndex = index - 3

                        With TextHeaderColumn
                            .Text = Column.ColumnName
                            .TextAlignment = TileItemContentAlignment.Manual
                            .TextLocation = New Point(120, 20 + (OffsetIndex * 40))
                            .Appearance.Normal.Font = SecondaryFont
                            .Appearance.Normal.ForeColor = Color.DarkGray
                            .Appearance.Normal.BackColor = WhiteBackground
                        End With

                        With TextColumn
                            .Column = grvwTiles.Columns(index)
                            .TextAlignment = TileItemContentAlignment.Manual
                            .TextLocation = New Point(120, 20 + 18 + (OffsetIndex * 40))
                            .Appearance.Normal.Font = SecondaryFont
                            .Appearance.Normal.ForeColor = Color.Black
                            .Appearance.Normal.BackColor = WhiteBackground
                        End With

                        grvwTiles.TileTemplate.Add(TextHeaderColumn)
                        grvwTiles.TileTemplate.Add(TextColumn)
                End Select
            Next
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", ex.Message, ex.StackTrace)
        End Try


    End Sub
    Sub Lock_RecordControls(state As Boolean)
        Lock_Record_Controls_Recursive(state, pnlDetails.Controls)
    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 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(Windows.Forms.GroupBox)
                    Lock_Record_Controls_Recursive(state, DirectCast(Control, GroupBox).Controls)
                Case GetType(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 Sub Check_Record_Changed()
        If EDIT_STATE <> EditState.None Then
            Update_Status_Label(False, "")
            EDIT_STATE = EditState.None
        End If

        If RECORD_CHANGED = True Then
            Dim msg = "Sie haben ungespeicherte Änderungen. Wollen Sie diese speichern?"
            Dim msg1 = "Ungespeicherte Änderungen"
            If USER_LANGUAGE <> "de-DE" Then
                msg = "There are unsaved changes. Would You like to save?"
                msg1 = "Unsaved changes"
            End If
            Dim result As DialogResult = MessageBox.Show(msg, msg1, MessageBoxButtons.YesNo, MessageBoxIcon.Question)
            If result = Windows.Forms.DialogResult.Yes Then
                If CtrlCommandUI.IsInsert = True Then
                    EDIT_STATE = EditState.None
                    Lock_RecordControls(True)
                    'Me.pnlDetails.Enabled = False
                    'CtrlCommandUI.IsInsert = False
                End If
                Try
                    Dim ResultMessage = Update_Record_OnChange()
                    Update_Status_Label(True, ResultMessage)
                Catch ex As Exception
                    ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Save Record Changes: " & ex.Message, ex.StackTrace)
                End Try
            Else
                If CtrlCommandUI.IsInsert = True Then  ' Wenn nicht gespeichert werden soll, den Record wieder löschen
                    ClassHelper.DeleteRecord(SELECTED_RECORD_ID)
                End If
                tsButtonAdd.Enabled = True
            End If
            CtrlCommandUI.IsEdit = False
            CtrlCommandUI.IsInsert = False
            RECORD_CHANGED = False
        End If
    End Sub
    Private Function GET_GROUP_OR_SINGLE_RECORD(PARENT_RECORD_ID As Integer, Entityload As Boolean)
        'Dim sqlRecord As String = String.Format("SELECT T.RECORD2_ID FROM TBPMO_RECORD_CONNECT T, TBPMO_RECORD T1 WHERE T.RECORD2_ID = T1.GUID AND T.RECORD1_ID = {0} AND T1.ENTITY_ID = (SELECT PARENT_ID FROM TBPMO_FORM WHERE GUID = {1})", LINKED_RECORD, ENTITY_ID)
        Dim sql As String = String.Format("SELECT T.RECORD2_ID FROM TBPMO_RECORD_CONNECT T, TBPMO_RECORD T1 WHERE T.RECORD2_ID = T1.GUID AND T.RECORD1_ID = {0} and T1.FORM_ID = {1}", PARENT_RECORD_ID, ENTITY_ID)
        Dim GRP_SINGLE_REC = ClassDatabase.Execute_Scalar(sql, True)
        If IsNothing(GRP_SINGLE_REC) Then
            If ClassRecordCommands.CreateRecord(ENTITY_ID) = True Then
                GRP_SINGLE_REC = ClassRecordCommands.GetLastRecord
                If Not IsNothing(GRP_SINGLE_REC) Then
                    'Die neue Record-ID setzen
                    RECORD_ID = GRP_SINGLE_REC
                    SELECTED_RECORD_ID = RECORD_ID
                    ClassProxy.PRPROXY_RECORD_UPD_INS(CURRENT_ENTITY_ID, SELECTED_RECORD_ID)
                    If ClassRecordCommands.ConnectRecord(PARENT_RECORD_ID, RECORD_ID, "PARENT_LINK (Group/Single-Record) for Entity " & ENTITY_ID.ToString) = False Then
                        MsgBox("Unexpected Error in Connecting Record. Check log", MsgBoxStyle.Critical)
                        Return False
                    Else
                        ClassProxy.PRPROXY_RECORD_CONNECT(PARENT_RECORDID, RECORD_ID)
                    End If
                Else
                    Return False
                End If
            Else
                Return False
            End If
        Else
            Try
                RECORD_ID = CInt(GRP_SINGLE_REC)
                SELECTED_RECORD_ID = RECORD_ID
            Catch ex As Exception
                ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in getting CURRENT_RECORDID FOR PARENT_ID: " & ex.Message, ex.StackTrace)
                Return False
            End Try
        End If

        Select Case ACT_EBENE '#### Hier muss nun der Parent-Record gesetzt werden ####
            Case 1
                EBENE1_RECID = RECORD_ID
            Case 2
                EBENE2_RECID = RECORD_ID
            Case 3
                EBENE3_RECID = RECORD_ID
        End Select
        Return True
    End Function

    Private Function GET_LINKED_RECORD(RECORDID As Integer, ENTITY_ID As Integer)
        Try
            Dim ENTITY_ROW = (From form In DT_ENTITY_DATA.AsEnumerable()
                     Select form
                     Where form.Item("GUID") = ENTITY_ID).Single()

            'Je nach der Ebene muss evtl die übergeordnete Entität ausgelesen werden
            Select Case ACT_EBENE
                Case 2
                    Dim sql As String = String.Format("SELECT T.RECORD2_ID FROM TBPMO_RECORD_CONNECT T, TBPMO_RECORD T1 WHERE T.RECORD2_ID = T1.GUID AND T.RECORD1_ID = {0} and T1.FORM_ID = {1}", RECORDID, ENTITY_ID)
                    Dim PARENT_RECORD1 = ClassDatabase.Execute_Scalar(sql, True)
                    If IsNothing(PARENT_RECORD1) Then
                        Dim New_Record = ClassRecordCommands.GetLastRecord
                        If Not IsNothing(New_Record) Then
                            If LogErrorsOnly = False Then ClassLogger.Add(" >> Parent-Record Ebene 1 wird neu angelegt...", False)
                            'Die neue Record-ID setzen
                            ClassRecordCommands.ConnectRecord(New_Record, RECORDID, "PARENT-LINK FOR ENTITY " & ENTITY_ID & "")
                            Return New_Record
                        Else
                            Return 0
                        End If
                    Else
                        Return PARENT_RECORD1
                    End If
                Case 3
                    Dim Parent_EntityID = ENTITY_ROW.Item("PARENT_ID") 'ClassDatabase.Execute_Scalar(sqlp, True)
                    Dim sql As String = String.Format("SELECT T.RECORD2_ID FROM TBPMO_RECORD_CONNECT T, TBPMO_RECORD T1 WHERE T.RECORD2_ID = T1.GUID AND T.RECORD1_ID = (SELECT T.RECORD2_ID FROM TBPMO_RECORD_CONNECT T, TBPMO_RECORD T1 WHERE " & _
                    "T.RECORD2_ID = T1.GUID AND T.RECORD1_ID = {0} and T1.FORM_ID = {1}) and T1.FORM_ID = {2}", RECORDID, Parent_EntityID, ENTITY_ID)
                    Dim PARENT_RECORD2 = ClassDatabase.Execute_Scalar(sql, True)
                    If IsNothing(PARENT_RECORD2) Then
                        Dim New_Record = ClassRecordCommands.GetLastRecord
                        If Not IsNothing(New_Record) Then
                            If LogErrorsOnly = False Then ClassLogger.Add(" >> Parent-Record Ebene 1 wird neu angelegt...", False)
                            'Die neue Record-ID setzen
                            ClassRecordCommands.ConnectRecord(New_Record, RECORDID, "PARENT-LINK FOR ENTITY " & ENTITY_ID & "")
                            Return New_Record
                        Else
                            Return 0
                        End If
                    Else
                        Return PARENT_RECORD2
                    End If
            End Select
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", ex.Message, ex.StackTrace)
            Return 0
        End Try
    End Function
    Private Function LoadGrid_Selection()
        Try
            If GRID_TYPE = GridType.Tiles Then
                CreateTile()
            Else
                'Grid leeren
                Clear_Grid_View()

                Dim gridFormatter As New ClassGridFormatter.ConstructorView(DT_SELECTION, ENTITY_ID)
                Dim DT_RESULT As DataTable = gridFormatter.FormatDatatable()
                GridControlMain.DataSource = DT_RESULT
                gridFormatter.FormatGridView(grvwGrid)

                Try
                    grvwGrid.Columns("AddedWhen").DisplayFormat.FormatType = FormatType.DateTime
                    grvwGrid.Columns("AddedWhen").DisplayFormat.FormatString = CURRENT_DATE_FORMAT & " HH:MM:ss"
                    grvwGrid.Columns("ChangedWhen").DisplayFormat.FormatType = FormatType.DateTime
                    grvwGrid.Columns("ChangedWhen").DisplayFormat.FormatString = CURRENT_DATE_FORMAT & " HH:MM:ss"
                Catch ex As Exception

                End Try
                'Try
                '    Dim chkRep As New DevExpress.XtraEditors.Repository.RepositoryItemCheckEdit
                '    grvwGrid.GridControl.RepositoryItems.Add(chkRep)
                '    grvwGrid.Columns("files?").ColumnEdit = chkRep
                'Catch ex As Exception
                '    ClassLogger.Add(">> Attention: Column files? not existing in GridView?", False)
                'End Try
                'grvwGrid.Columns("Record-ID").OptionsColumn.AllowShowHide = False
            End If

            HideColumns()
            If NODE_NAVIGATION = False Then
                Dim selnode As TreeNode = TreeViewMain.SelectedNode
                Dim origtext As String = selnode.Text
                If origtext.Contains(" (") Then
                    Dim existingstring = origtext.Substring(0, origtext.IndexOf("(") - 1)
                    selnode.Text = String.Format("{0} ({1})", existingstring, Get_Grid_Row_Count())
                Else
                    selnode.Text = String.Format("{0} ({1})", selnode.Text, Get_Grid_Row_Count())
                End If
                Dim msg = "Anzahl Datensätze: "
                If USER_LANGUAGE <> "de-DE" Then
                    msg = "number of records: "
                End If
                tslbldisplayRecords.Text = msg & Get_Grid_Row_Count()
            End If
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", ex.Message, ex.StackTrace)
            Return False
        End Try

        Return True
    End Function
    Sub HideColumns()
        Try
            ' Presuming the DataTable has a column named FORM_ID
            Dim expression As String
            expression = "FORM_ID = " & ENTITY_ID
            Dim foundRowsLevel0() As DataRow
            ' Use the Select method to find all rows matching the filter.
            foundRowsLevel0 = DT_CONTROL_SCREEN.Select(expression)
            Dim i As Integer

            ' Dim DT As DataTable = ClassDatabase.Return_Datatable(SQL)
            If GRID_TYPE = GridType.Grid Then
                Dim cols As DevExpress.XtraGrid.Columns.GridColumnCollection = grvwGrid.Columns

                'If DT.Rows.Count <> 0 Then
                '    ' Alle Spalten, die ausgeblendet werden sollten durchgehen und Visible = False
                '    For Each row As DataRow In DT.Rows
                '        Dim colname As String = row.Item("CONTROL_COL_NAME")
                '        Dim col As DevExpress.XtraGrid.Columns.GridColumn = grvwGrid.Columns.Item(colname)
                '        If Not IsNothing(col) Then
                '            col.Visible = False
                '        End If
                '    Next
                'End If
                ' For each row create a Node
                For i = 0 To foundRowsLevel0.GetUpperBound(0)
                    Dim colname As String = foundRowsLevel0(i)("CONTROL_COL_NAME")
                    Dim col As DevExpress.XtraGrid.Columns.GridColumn = grvwGrid.Columns.Item(colname)
                    If Not IsNothing(col) Then
                        col.Visible = False
                    End If
                Next
                ' FormID und RecordID immer ausblenden
                grvwGrid.Columns.Item("Record-ID").Visible = False
                grvwGrid.Columns.Item("Form-ID").Visible = False
                grvwGrid.Columns.Item("ROW_COLOR").Visible = False
            End If
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in HideColumns: ", ex.Message)
        End Try
    End Sub
    Sub HideColumns_Pos(EntityID As Integer)
        Try
            Dim SQL As String = "SELECT CONTROL_ID, CONTROL_COL_NAME, CONTROL_SHOW_COLUMN FROM VWPMO_CONTROL_SCREEN WHERE CONTROL_SHOW_COLUMN = 0 AND FORM_ID = " & EntityID
            Dim DT As DataTable = ClassDatabase.Return_Datatable(SQL, True)
            Dim cols As DevExpress.XtraGrid.Columns.GridColumnCollection = grvwGridPos.Columns

            If DT.Rows.Count <> 0 Then
                ' Alle Spalten, die ausgeblendet werden sollten durchgehen und Visible = False
                For Each row As DataRow In DT.Rows
                    Dim colname As String = row.Item("CONTROL_COL_NAME")
                    Dim col As DevExpress.XtraGrid.Columns.GridColumn = grvwGridPos.Columns.Item(colname)

                    If Not IsNothing(col) Then
                        col.Visible = False
                    End If
                Next
            End If

            ' FormID und RecordID immer ausblenden
            grvwGridPos.Columns.Item("Record-ID").Visible = False
            grvwGridPos.Columns.Item("Form-ID").Visible = False
            grvwGridPos.Columns.Item("ROW_COLOR").Visible = False
            Try
                grvwGridPos.Columns.Item("files?").Visible = False
                grvwGridPos.Columns.Item("file count").Visible = False
            Catch ex As Exception

            End Try
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in HideColumns_Pos: ", ex.Message)
        End Try
    End Sub
    Private Sub Show_Selected_Record_Data(Rec_ID As Integer, EntityLoad As Boolean)
        Try
            Dim ENTITY_ROW = (From form In DT_ENTITY_DATA.AsEnumerable()
                   Select form
                   Where form.Item("GUID") = ENTITY_ID).Single()

            Update_Status_Label(False, "")
            If LogErrorsOnly = False Then ClassLogger.Add(" >> GRID_RECORD ID: " & Rec_ID.ToString, False)
            'Me.pnlDetails.Visible = True
            If FORM_TYPE = 5 And EntityLoad = False Or IS_SINGLE_RECORD = True And EntityLoad = False Then '#### Es sind untergeordnete Entitäten geöffnet####
                Dim linkedRecord
                ' Dim pID As Integer
                Select Case ACT_EBENE '#### Hier muss nun der Parent-Record gewählt werden ####
                    Case 3
                        linkedRecord = GET_LINKED_RECORD(Rec_ID, ENTITY_ID)
                        If linkedRecord > 0 Then
                            Dim Parent_EntityID = ENTITY_ROW.Item("PARENT_ID")
                            Dim sql As String = String.Format("SELECT T.RECORD2_ID FROM TBPMO_RECORD_CONNECT T, TBPMO_RECORD T1 WHERE T.RECORD2_ID = T1.GUID AND T.RECORD1_ID = {0} and T1.FORM_ID = {1}", RECORD_ID, Parent_EntityID)
                            Dim PARENT_RECORD1 = ClassDatabase.Execute_Scalar(sql, True)

                            EBENE2_RECID = PARENT_RECORD1
                            PARENT_RECORDID = PARENT_RECORD1
                            CURRENT_PARENT_RECORD_ID = PARENT_RECORDID

                        End If
                    Case 2
                        linkedRecord = GET_LINKED_RECORD(Rec_ID, ENTITY_ID)
                        If linkedRecord > 0 Then
                            EBENE1_RECID = Rec_ID
                            PARENT_RECORDID = EBENE1_RECID
                            CURRENT_PARENT_RECORD_ID = PARENT_RECORDID
                        End If
                    Case 1
                        PARENT_RECORDID = Rec_ID
                        EBENE1_RECID = PARENT_RECORDID
                        CURRENT_PARENT_RECORD_ID = PARENT_RECORDID
                End Select
                RECORD_ID = CInt(linkedRecord)
                SELECTED_RECORD_ID = RECORD_ID
                '#### Den Group or Single_Record holen/anlegen
                ' GET_GROUP_OR_SINGLE_RECORD(pID, False)
            Else '#### Datensatz wird normal geladen ####
                SELECTED_RECORD_ID = Rec_ID
                RECORD_ID = SELECTED_RECORD_ID
                'Die aktuelle Ebene überprüfen und den Datensatz übergeben, ebenso den PARENT-Record setzen
                Select Case ACT_EBENE
                    Case 1
                        PARENT_RECORDID = RECORD_ID
                        EBENE1_RECID = PARENT_RECORDID
                        CURRENT_PARENT_RECORD_ID = PARENT_RECORDID
                        If Not EBENE1_COLUMNNAME Is Nothing Then
                            EBENE1_GRID_RESULT = Get_GridResult(EBENE1_COLUMNNAME)
                        End If
                    Case 2
                        EBENE2_RECID = SELECTED_RECORD_ID
                        If Not EBENE2_COLUMNNAME Is Nothing Then
                            EBENE2_GRID_RESULT = Get_GridResult(EBENE2_COLUMNNAME)
                        End If
                        If EBENE1_RECID > 0 Then
                            PARENT_RECORDID = EBENE1_RECID
                            CURRENT_PARENT_RECORD_ID = PARENT_RECORDID
                        Else
                            CURRENT_PARENT_RECORD_ID = PARENT_RECORDID
                        End If
                    Case 3
                        EBENE3_RECID = SELECTED_RECORD_ID
                        If Not EBENE3_COLUMNNAME Is Nothing Then
                            EBENE3_GRID_RESULT = Get_GridResult(EBENE3_COLUMNNAME)
                        End If
                        If EBENE2_RECID > 0 Then
                            PARENT_RECORDID = EBENE2_RECID
                            CURRENT_PARENT_RECORD_ID = PARENT_RECORDID
                        End If
                End Select
            End If
            RIGHT_CONTROL_CHANGED = False
            Select Case TCDetails.SelectedTabPage.Name
                Case "TabDetails"
                    ENTITY_RELOAD_AFT_CONTROL_LOAD = False
                    CtrlBuilder.WatchRecordChanges = False
                    ClassControlValues.LoadControlValues(SELECTED_RECORD_ID, PARENT_RECORDID, ENTITY_ID, CtrlBuilder.AllControls, ENTITY_ID)
                    CtrlBuilder.WatchRecordChanges = True

                    If windream_Docshow = True Then
                        Dim stg As String = "Dateien"
                        If USER_LANGUAGE <> "de-DE" Then
                            stg = "files"
                        End If
                        TabWindream.Text = stg
                    End If
                    Dim sel = String.Format("SELECT * FROM TBPMO_RECORD WHERE RECORD_ENTITY_ID = (SELECT RECORD_ENTITY_ID FROM TBPMO_RECORD WHERE GUID = {0}) AND FORM_ID = {1} AND GUID <> {2}", SELECTED_RECORD_ID, ENTITY_ID, SELECTED_RECORD_ID)
                    Dim DT_VARIANT As DataTable = ClassDatabase.Return_Datatable(sel, True)
                    If DT_VARIANT.Rows.Count > 0 Then
                        TabPageVariant.PageVisible = True
                        Dim msg = "Vorgängervarianten"
                        If USER_LANGUAGE <> "de-DE" Then
                            msg = "Pre variants"
                        End If

                        TabPageVariant.Text = String.Format(msg & " ({0})", DT_VARIANT.Rows.Count)
                    Else
                        TabPageVariant.PageVisible = False
                    End If
                    If DOC_SEARCH_TAB1 = True Then
                        DocSearch_Decision()
                    End If

                Case "TabWindream"
                    DocSearch_Decision()
                Case "TabFollowUp"
                    tsButtonEdit.Enabled = False
                    Refresh_FollowUps()
                    dtpFollowUp.Enabled = False
                    lblWiedervorlage_Control.Text = "<< Waiting for Selection:"
                    'ListBoxUser2Profile.Items.Clear()
                    grpbxFU_Profile.Enabled = False
            End Select
            Dim sw As New Stopwatch
            sw.Start()
            ' Laden der Daten bedeutet nicht dass Daten vom Benutzer geändert wurden!
            RECORD_CHANGED = False
            Refresh_Navpane()
            Update_Record_Label(SELECTED_RECORD_ID)
            Show_act_WFTask()

            RECORD_ID = SELECTED_RECORD_ID
            Dim elapsed As Double
            elapsed = sw.Elapsed.TotalSeconds - elapsed
            sw.Stop()
            sw.Reset()
            If LogErrorsOnly = False Then ClassLogger.Add(" >> Show Selected RecordData 2 took " & Format(elapsed, "0.000000000") & " seconds", False)
            If ENTITY_RELOAD_AFT_CONTROL_LOAD = True Then
                Reload_Entity_while_Control_Load()
            End If
            'tsstatus_Detail_show(False, "")
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in SelectedRecord_ShowData: ", ex.Message)
        End Try

    End Sub
    Sub DocSearch_Decision()
        If RECORD_ID = 0 Then
            'RUN_WD_SEARCH(WD_Suche, "ENTITY")
            RUN_WDSEARCH_GRID()
        Else
            RUN_WDSEARCH_GRID()
            ' RUN_WD_SEARCH(WD_Suche, "RECORD")
        End If
    End Sub
    Sub Reload_Entity_while_Control_Load()
        Dim result As MsgBoxResult
        Dim stg As String
        If USER_LANGUAGE = "de-DE" Then
            stg = "Es gab ein unerwartetes Problem beim Laden der Control-Values! Wollen Sie versuchen die Daten erneut zu laden?" & vbNewLine & "'Nein' beendet die Sicht für einen manuellen Neustart!"
        Else
            stg = "ADDI encountered an unexpected error while loading the control values for the record! Do You want to try to relaod the entity data?" & vbNewLine & "No is terminating the entity-form to restart it manually!"
        End If
        result = MessageBox.Show(stg, "Confirmation needed:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
        If result = MsgBoxResult.Yes Then
            Load_Datafor_Entity()
        Else
            Me.Close()
        End If

    End Sub
    Sub Create_Grid_Editor(formId As Integer)
        Try
            Dim SQL As String = "SELECT CONTROL_COL_NAME,CONTROL_SQLCOMMAND_1,CONTROL_STATIC_LIST FROM VWPMO_CONTROL_SCREEN WHERE CTRLTYPE_ID = 3 AND FORM_ID = " & formId
            Dim ComboColumns As DataTable = ClassDatabase.Return_Datatable(SQL, True)

            ' Alle Checkboxen für aktuelle Ansicht heraussuchen
            Dim sqlcheck As String = "SELECT COL_NAME FROM TBPMO_CONTROL WHERE CONTROL_TYPE_ID in (10,11) AND FORM_ID = " & formId
            Dim dtcheck As DataTable = ClassDatabase.Return_Datatable(sqlcheck, True)
            Dim listcheck As New List(Of String)

            'Liste von allen Spaltentiteln mit Checkbox erstellen
            If dtcheck.Rows.Count > 0 Then
                For Each row As DataRow In dtcheck.Rows
                    listcheck.Add(row.Item(0))
                Next
            End If
            ' Den Editor Initialisieren und Optionen setzen
            Dim CheckBoxEditorForDisplay = New RepositoryItemCheckEdit()
            CheckBoxEditorForDisplay.ValueChecked = 1
            CheckBoxEditorForDisplay.ValueUnchecked = 0
            ' Alle Checkbox Spalten durchgehen und CheckBoxEditor zuweisen
            For Each col As String In listcheck
                grvwGridPos.GridControl.RepositoryItems.Add(CheckBoxEditorForDisplay)

                If Not IsNothing(grvwGridPos.Columns(col)) Then
                    grvwGridPos.Columns(col).ColumnEdit = CheckBoxEditorForDisplay
                End If
            Next


            For Each col As DataRow In ComboColumns.Rows
                Dim colName As String = col.Item(0)

                Dim hasSqlCommand = col.Item(1).ToString() <> ""
                Dim hasStaticList = col.Item(2).ToString() <> ""

                If hasStaticList = True Then
                    Dim comboEdit1 As New RepositoryItemComboBox()
                    Dim comboItems1 As ComboBoxItemCollection = comboEdit1.Items
                    Dim staticListItems = col.Item(2).ToString.Split(";")
                    comboItems1.BeginUpdate()
                    Try
                        For Each item In staticListItems
                            comboItems1.Add(item)
                        Next
                    Finally
                        comboItems1.EndUpdate()
                    End Try
                    GridControlPos.RepositoryItems.Add(comboEdit1)
                    If Not IsNothing(grvwGridPos.Columns(colName)) Then
                        grvwGridPos.Columns(colName).ColumnEdit = comboEdit1
                    End If
                ElseIf hasSqlCommand = True Then
                    SQL = col.Item(1).ToString()
                    Dim dt As DataTable = ClassDatabase.Return_Datatable(SQL)
                    Dim comboEdit2 As New RepositoryItemComboBox()
                    Dim comboItems2 As ComboBoxItemCollection = comboEdit2.Items
                    For Each row As DataRow In dt.Rows
                        Dim value = row.Item(0)
                        comboItems2.BeginUpdate()
                        Try
                            comboItems2.Add(value)
                        Finally
                            comboItems2.EndUpdate()
                        End Try
                    Next
                    GridControlPos.RepositoryItems.Add(comboEdit2)
                    If Not IsNothing(grvwGridPos.Columns(colName)) Then
                        grvwGridPos.Columns(colName).ColumnEdit = comboEdit2
                    End If
                End If
            Next
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Create_Grid_Editor: ", ex.Message)
        End Try

    End Sub

    Sub Load_Pos_Data()
        Try
            If POS_ENTITY > 0 Then
                Get_Pos_SQL(POS_ENTITY)
                POS_SQL = POS_SQL.Replace("@PARENT_ID", PARENT_RECORDID)
                Dim DT_POS As DataTable = ClassDatabase.Return_Datatable(POS_SQL, True)

                Clear_GridPos_View()
                If Not IsNothing(DT_POS) Then
                    GridControlPos.DataSource = DT_POS
                    Dim bs As New BindingSource
                    bs.DataSource = DT_POS
                    BindingNavigatorPOS.BindingSource = bs
                    ' --- Editoren laden für Combobox ---
                    Create_Grid_Editor(POS_ENTITY)
                    HideColumns_Pos(PARENT_RECORDID)
                End If
            End If
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Load_Pos_Data: ", ex.Message)
        End Try

    End Sub
    Function Get_GridResult(Columnname As String)
        Dim result = Get_Focused_Row_Cell_Value(Columnname)
        Dim str = String.Empty

        If DT_VWPMO_CONSTRUCTOR_FORMS.Rows.Count >= 3 Then
            str &= System.Text.RegularExpressions.Regex.Replace(ACT_EBENE_STRING, "\s\(\d+\)", "")
            str &= " - "
        End If

        If IsDBNull(result) OrElse result = "" Then
            str &= "No Column configured"
        Else
            str &= result
        End If

        Return str
    End Function

    Function GetSelected_RecordID()
        Try
            If Get_Grid_Column_Count() = 0 Then
                Lock_RecordControls(True)
                '   Me.pnlDetails.Enabled = False
                'Me.tsbtnshowWorkflowtasks.Enabled = False
                'tsstatus_Detail_show(True, "Keine Columns in Grid")
                Return Nothing
            End If
            'Überhaupt Rows in Grid?
            If Get_Grid_Row_Count() > 0 Then
                Dim Grid_RecordID = Get_Focused_Row_Cell_Value("Record-ID")
                If Grid_RecordID Is Nothing = False Then
                    Return Grid_RecordID
                Else
                    'tsstatus_Detail_show(True, "Grid_RecordID konnte nicht gewählt werden!")
                    'ClassLogger.Add(">> Grid_RecordID konnte nicht gewählt werden - SelectedRecord_ShowData", True)
                    Return Nothing
                End If
            Else
                Return Nothing
            End If
        Catch ex As Exception

        End Try
    End Function
    Private Sub Refresh_FollowUp_TabHeader()
        Try
            DT_FU_Record = ClassDatabase.Return_Datatable("select * from VWPMO_FOLLOW_UP_EMAIL_ENTITY_RECORD where Record_ID = " & RECORD_ID)
            Dim msg As String = "Wiedervorlage (Nicht Abrufbar)"
            If USER_LANGUAGE <> "de-DE" Then
                msg = "Follow Up - (Not accessable)"
            End If
            If IsNothing(DT_FU_Record) Then
                TabFollowUp.Text = msg
                Exit Sub
            End If
            If DT_FU_Record.Rows.Count = 0 Then
                msg = "Wiedervorlage (Nicht aktiviert)"
                If USER_LANGUAGE <> "de-DE" Then
                    msg = "Follow Up - (Not activated)"
                End If
                TabFollowUp.Text = msg
            Else
                msg = "Wiedervorlage (Aktive Profile)"
                If USER_LANGUAGE <> "de-DE" Then
                    msg = "Follow Up - (active profiles)"
                End If
                TabFollowUp.Text = msg
            End If
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Refresh_FollowUp_TabHeader: ", ex.Message)
        End Try

    End Sub

    Private Function Update_Record_OnChange() As String
        ' Überprüfen, ob alle "Required Felder ausgefüllt wurden"

        Dim missingControlValues As List(Of String) = ClassControlValues.CheckRequiredControlValues(CtrlBuilder.MasterPanel.Controls)
        If missingControlValues.Count > 0 Then

            Dim nameString As String = String.Join(vbNewLine, missingControlValues)
            Dim msg = String.Format("Die folgenden Steuerelemente müssen ausgefüllt sein: {0}{1}", vbNewLine, nameString)

            If USER_LANGUAGE <> "de-DE" Then
                msg = String.Format("the following controls must be filled with values: {0}{1}", vbNewLine, nameString)
            End If
            Dim errorMessage As String = msg

            ' Das erste fehlende Control in den Fokus nehmen
            Dim firstControlName = missingControlValues.First()
            Focus_Control(firstControlName)

            Throw New Exception(errorMessage)
        End If

        ' Record Speichern
        Dim ResultMessage = CtrlCommandUI.SaveRecord(SELECTED_RECORD_ID, ENTITY_ID, PARENT_RECORDID)
        'Jetzt die für die Entität notwendigen Prroceduren ausführen
        Customer_Run_Procedures()

        RECORD_CHANGED = False

        Return ResultMessage
    End Function

    Private Sub Customer_Run_Procedures()
        Try
            Dim DT As DataTable = ClassDatabase.Return_Datatable("SELECT * FROM TBPMO_RUN_PROCEDURES WHERE FORM_ID = " & ENTITY_ID)
            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", ENTITY_ID)
                    prsql = prsql.ToUpper.Replace("@ENTITY_ID", ENTITY_ID)
                    prsql = prsql.ToUpper.Replace("@RECORD_ID", RECORD_ID)
                    ClassDatabase.Execute_non_Query(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

#Region "WindreamSuche"
    Private Sub Check_windream_Show(FORM_VIEW_ID As Integer)
        Try
            'Dim sql = "SELECT * FROM TBPMO_FORM_VIEW WHERE WINDREAM_SEARCH <> '' AND GUID = " & FORM_VIEW_ID
            'Dim DTWD As DataTable = ClassDatabase.Return_Datatable(sql)
            Dim wdsearch = DT_TBPMO_FORM_VIEW.Rows(0).Item("DOCUMENT_VIEW")
            If CBool(wdsearch) = False Then
                windream_Docshow = False
                TabWindream.PageVisible = False
                tsbtnDoc_Refresh.Enabled = False
                tsmiFilesearch.Enabled = False
                Exit Sub
            Else
                TabWindream.PageVisible = True
                tsbtnDoc_Refresh.Enabled = True
                tsmiFilesearch.Enabled = True
                windream_Docshow = True
                If windream_inited = False Then
                    Dim sw As New Stopwatch
                    sw.Start()
                    Dim elapsed As Double
                    Try
                        If clsWindream.Create_Session = True Then
                            windream_inited = True
                        End If
                    Catch ex As Exception
                        windream_inited = False
                    End Try
                   
                    elapsed = sw.Elapsed.TotalSeconds
                    sw.Stop()
                    sw.Reset()
                    If LogErrorsOnly = False Then ClassLogger.Add(" >> Windream init took " & Format(elapsed, "0.000000000") & " seconds", False)
                End If
            End If
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Check windream show: ", ex.Message)
            windream_Docshow = False
        End Try

    End Sub

    Private Sub WD_DELETE_DOCS(DT_RESULT As DataTable)
        Dim sw As New Stopwatch
        sw.Start()
        Dim elapsed As Double
        ' Dim Basesearch As String
        Try
            If Not IsNothing(DT_RESULT) Then


                If DT_RESULT.Rows.Count > 0 Then 'Es gibt Suchergebnisse
                    Dim msg As String
                    msg = "Wollen Sie die zugehörigen Dateien (" & DT_RESULT.Rows.Count.ToString & ") ebenfalls löschen?"
                    If USER_LANGUAGE <> "de-DE" Then
                        msg = "Do You want to delete the related files (" & DT_RESULT.Rows.Count.ToString & ")?"
                    End If
                    Dim result1 As MsgBoxResult
                    result1 = MessageBox.Show(msg, "Confirmation:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                    If result1 = MsgBoxResult.Yes Then
                        For Each row As DataRow In DT_RESULT.Rows
                            Dim DOC_ID = row.Item("DocID")
                            Dim path
                            Try
                                path = row.Item("FULL_FILENAME")
                            Catch ex As Exception
                                path = row.Item(1)
                            End Try
                            If Not IsNothing(path) Then
                                Dim Count As Integer = ClassDatabase.Execute_Scalar("SELECT COUNT(GUID) FROM TBPMO_DOC_RECORD_LINK WHERE DOC_ID = " & DOC_ID, True)
                                If Count > 1 Then
                                    msg = "Diese Datei ist noch mit anderen Datensätzen verknüpft! Lediglich die Verknüpfung zum aktuellen Datensatz wird gelöscht!"
                                    If USER_LANGUAGE <> "de-DE" Then
                                        msg = "This file is also linked to other records! Only the link for this Record will be deleted!"
                                    End If
                                    MsgBox(msg, MsgBoxStyle.Information)
                                    ClassFileResult.Delete_ResultFile(DOC_ID, RECORD_ID, 0)
                            Else
                                If ClassFileResult.Delete_ResultFile(DOC_ID, RECORD_ID, 1) = False Then
                                    msg = String.Format("Die Datei {0} konnte nicht gelöscht werden! Prüfen Sie die logfile!", path)
                                    If USER_LANGUAGE <> "de-DE" Then
                                        msg = String.Format("The file {0} could not be deleted! Check the logfile!", path)
                                    End If
                                    MsgBox(msg, MsgBoxStyle.Critical, "Attention:")
                                Else
                                    If clsWD_SET.Delete_WDFile(path) Then
                                        ClassHelper.InsertEssential_Log(DOC_ID, "DOC-ID", "FILE DELETED BY USER")
                                    End If
                                End If
                            End If

                            End If
                        Next
                    End If
                End If
            Else
                ClassLogger.Add(">> No files 2 delete - after deleting record!", False)
            End If
            Cursor = Cursors.Default
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in WD-Delete Docs: ", ex.Message)
        End Try
        elapsed = sw.Elapsed.TotalSeconds
        sw.Stop()
        sw.Reset()
        If LogErrorsOnly = False Then ClassLogger.Add(" >> Run WD Delete Docs took " & Format(elapsed, "0.000000000") & " seconds", False)
        Cursor = Cursors.Default
    End Sub
    Private Sub RUN_WDSEARCH_GRID()
        Me.Cursor = Cursors.WaitCursor
        Try
            Dim sw As New Stopwatch
            sw.Start()
            Dim elapsed As Double
            If CURRENT_SEARCH_TYPE = "NODE_DOWN" Then
                Dim node As TreeNode = TreeViewMain.SelectedNode
                Dim NODE_GUID = ClassNodeNavigation.Return_NODEID_forTag(node.Tag)
                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, NODE_GUID)
                Me.Cursor = Cursors.WaitCursor
                Dim DT As DataTable = ClassDatabase.Return_Datatable(sql)
                If Not IsNothing(DT) Then
                    Dim result = DT.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
                Me.Cursor = Cursors.Default
            End If
            Dim DT_RESULT As DataTable
            DT_RESULT = ClassDOC_SEARCH.Get_DOC_RESULTTABLE(DT_RESULTLIST_OPTIONS, DT_RESULTLIST_VARIABLE_VALUE, DT_WINDREAM_RESULTLIST, ENTITY_ID, RECORD_ID, CBool(LOAD_ENTITY_SEARCH_AT_STARTUP))

            If IsNothing(DT_RESULT) Then
                Dim msg = "wrong DocSearch-Configuration oer unexpected Error in Get_DOC_RESULTTABLE - Check logfile and contact Digital Data"
                tslblWindreamView.Text = msg
                Me.Cursor = Cursors.Default
                Exit Sub
            End If
            If DT_RESULT.Rows.Count > 0 Then 'Es gibt Suchergebnisse
                Dim selnode As TreeNode = TreeViewMain.SelectedNode
                Dim NODE_TEXT As String = selnode.Text

                Dim msg = "Dateien für Record: " & RECORD_ID
                If CURRENT_SEARCH_TYPE = "ENTITY" Then
                    selnode = TreeViewMain.SelectedNode
                    Dim Entitystring
                    If selnode.Text.Contains(" (") Then
                        Entitystring = selnode.Text.Substring(0, selnode.Text.IndexOf("(") - 1)
                    Else
                        Entitystring = selnode.Text
                    End If
                    msg = "Dateien für Entität: " & Entitystring
                    If USER_LANGUAGE <> "de-DE" Then
                        msg = "files for entity: " & Entitystring
                    End If
                    msg &= " (" & DT_RESULT.Rows.Count.ToString & ")"
                ElseIf CURRENT_SEARCH_TYPE = "RECORD" Then
                    If NODE_NAVIGATION 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}' ", NODE_TEXT)
                        If USER_LANGUAGE <> "de-DE" Then
                            msg = String.Format("Files for Object  '{0}'", NODE_TEXT)
                        End If
                        msg &= " (" & DT_RESULT.Rows.Count.ToString & ")"
                    Else
                        msg = String.Format("Dateien für Record '{0}' ", RECORD_ID)
                        If USER_LANGUAGE <> "de-DE" Then
                            msg = String.Format("Files for record '{0}'", RECORD_ID)
                        End If
                        msg &= " (" & DT_RESULT.Rows.Count.ToString & ")"
                    End If
                ElseIf CURRENT_SEARCH_TYPE = "NODE_DOWN" Then
                    selnode = TreeViewMain.SelectedNode
                    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

                tslblWindreamView.Text = msg

                If DT_RESULT.Rows.Count > 0 Then
                    If CURRENT_SEARCH_TYPE = "FULLTEXT" Then
                        If SplitContainerDetails.Collapsed = False And tsbtnPanel1Collapse.Visible = True Then
                            Collapse_Details()
                        End If
                        grvwGrid.ShowFindPanel()
                        grvwGrid.FindFilterText = CURRENT_FULLTEXT_PATTERN
                    End If

                    ClassWindreamDocGrid.FillColumns(
                       GridViewDoc_Search,
                       DT_RESULT,
                       DT_WINDREAM_RESULTLIST,
                       DT_DOCRESULT_DROPDOWN_ITEMS,
                       AddressOf OnCBSelectedValueChanged,
                       AddressOf OnDateSelectedValueChanged,
                       AddressOf OnTextSelectedValueChanged,
                       AddressOf OnCheckboxValueChanged,
                       CURRENT_SEARCH_TYPE, RECORD_ID)
                End If
            Else
                Dim selnode As TreeNode = TreeViewMain.SelectedNode
                Dim NODE_TEXT As String = selnode.Text
                Dim msg = "Keine Dateien für '"
                If CURRENT_SEARCH_TYPE = "ENTITY" Then
                    selnode = TreeViewMain.SelectedNode
                    Dim Entitystring
                    If selnode.Text.Contains(" (") Then
                        Entitystring = selnode.Text.Substring(0, selnode.Text.IndexOf("(") - 1)
                    Else
                        Entitystring = selnode.Text
                    End If
                    msg = "Keine Dateien für Entität: " & Entitystring & " gefunden"
                    If USER_LANGUAGE <> "de-DE" Then
                        msg = "No files found for entity: " & Entitystring
                    End If
                ElseIf CURRENT_SEARCH_TYPE = "RECORD" Then
                    If NODE_NAVIGATION Then
                        If NODE_TEXT.Contains(" (") Then
                            NODE_TEXT = NODE_TEXT.Substring(0, NODE_TEXT.IndexOf("(") - 1)
                        End If
                        msg &= NODE_TEXT & "' gefunden"
                        If USER_LANGUAGE <> "de-DE" Then
                            msg = "No files found for object '" & NODE_TEXT & "'"
                        End If
                    Else
                        msg &= "Record '" & RECORD_ID & "' gefunden"
                    End If
                    If USER_LANGUAGE <> "de-DE" Then
                        msg = "No files found for record " & 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

                tslblWindreamView.Text = msg
                GridControlDocSearch.DataSource = Nothing
                'Clear_Windream_ResultList()
            End If
            elapsed = sw.Elapsed.TotalSeconds
            sw.Stop()
            sw.Reset()
            If LogErrorsOnly = False Then ClassLogger.Add(" >> Run RUN_WDSEARCH_GRID took " & Format(elapsed, "0.000000000") & " seconds", False)
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Run WD-Search Database: ", ex.Message)
        End Try
        Cursor = Cursors.Default
    End Sub
    Private Sub OnCBSelectedValueChanged(sender As Object, e As EventArgs)
        Try
            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 docId As Integer = ClassWindreamDocGrid.SELECTED_DOC_ID
            Dim user As String = USER_USERNAME

            Dim Sql As String = String.Format("EXEC PRPMO_DOC_VALUE {0}, {1}, '{2}', '{3}'", docId, configId, value, user)
            ClassDatabase.Execute_non_Query(Sql)
        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 = Date.TryParse(DatePicker.OldEditValue, oldValue)

            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
                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 {0}, {1}, '{2}', '{3}'", docId, configid, dateString, user)
                If ClassDatabase.Execute_non_Query(Sql) = False Then
                    ClassHelper.MSGBOX_Handler("ERROR", "UnexpectedError:", "Error updating doc-metadata (date): " & vbNewLine & "Check the log for further information!")
                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
            Dim user As String = USER_USERNAME

            Dim Sql As String = String.Format("EXEC PRPMO_DOC_VALUE {0}, {1}, '{2}', '{3}'", docId, configid, value, user)
            If ClassDatabase.Execute_non_Query(Sql) = False Then
                ClassHelper.MSGBOX_Handler("ERROR", "UnexpectedError:", "Error updating doc-metadata (textbox): " & vbNewLine & "Check the log for further information!")
            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
            Dim user As String = USER_USERNAME

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

    Public Class WDDoc_Combobox_Item
        Implements IConvertible

        Public ConfigID As Integer
        Public Value As String

        Public Overrides Function ToString() As String
            Return Me.Value
        End Function

        Public Function GetTypeCode() As TypeCode Implements IConvertible.GetTypeCode
            Throw New NotImplementedException
        End Function

        Public Function ToBoolean(provider As IFormatProvider) As Boolean Implements IConvertible.ToBoolean
            Throw New NotImplementedException
        End Function

        Public Function ToByte(provider As IFormatProvider) As Byte Implements IConvertible.ToByte
            Throw New NotImplementedException
        End Function

        Public Function ToChar(provider As IFormatProvider) As Char Implements IConvertible.ToChar
            Throw New NotImplementedException
        End Function

        Public Function ToDateTime(provider As IFormatProvider) As Date Implements IConvertible.ToDateTime
            Throw New NotImplementedException
        End Function

        Public Function ToDecimal(provider As IFormatProvider) As Decimal Implements IConvertible.ToDecimal
            Throw New NotImplementedException
        End Function

        Public Function ToDouble(provider As IFormatProvider) As Double Implements IConvertible.ToDouble
            Throw New NotImplementedException
        End Function

        Public Function ToInt16(provider As IFormatProvider) As Short Implements IConvertible.ToInt16
            Throw New NotImplementedException
        End Function

        Public Function ToInt32(provider As IFormatProvider) As Integer Implements IConvertible.ToInt32
            Throw New NotImplementedException
        End Function

        Public Function ToInt64(provider As IFormatProvider) As Long Implements IConvertible.ToInt64
            Throw New NotImplementedException
        End Function

        Public Function ToSByte(provider As IFormatProvider) As SByte Implements IConvertible.ToSByte
            Throw New NotImplementedException
        End Function

        Public Function ToSingle(provider As IFormatProvider) As Single Implements IConvertible.ToSingle
            Throw New NotImplementedException
        End Function

        Public Function ToString1(provider As IFormatProvider) As String Implements IConvertible.ToString
            Return Me.Value
        End Function

        Public Function ToType(conversionType As Type, provider As IFormatProvider) As Object Implements IConvertible.ToType
            Throw New NotImplementedException
        End Function

        Public Function ToUInt16(provider As IFormatProvider) As UShort Implements IConvertible.ToUInt16
            Throw New NotImplementedException
        End Function

        Public Function ToUInt32(provider As IFormatProvider) As UInteger Implements IConvertible.ToUInt32
            Throw New NotImplementedException
        End Function

        Public Function ToUInt64(provider As IFormatProvider) As ULong Implements IConvertible.ToUInt64
            Throw New NotImplementedException
        End Function
    End Class

    Private Sub GridViewDropDown_ValueChanged(sender As Object, e As DragEventArgs) Handles TCDetails.DragDrop
        Drag_Drop(e)
    End Sub
    Private Function Return_SearchPattern(ByVal content As String)
        Select Case content.ToUpper
            Case "@Record-ID".ToUpper
                Return RECORD_ID
            Case "@EntityID".ToUpper
                Return ENTITY_ID
            Case "@ParentID".ToUpper
                Return PARENT_RECORDID
            Case Else
                MsgBox("Undefined pattern '" & content & "' in windream-Search Config. Please inform Your system-administrator.", MsgBoxStyle.Exclamation)
                ClassLogger.Add(" >> Undefined Search-pattern in windream-search config: " & content, True)
        End Select
    End Function
    'Private Sub AxObjectListControl_ItemClicked(sender As Object, e As EventArgs) Handles AxObjectListControl.ItemClicked
    '    CheckDocView()
    'End Sub

    Sub Clear_Windream_ResultList()
        Try
            Dim sw As New Stopwatch
            sw.Start()

            'AxObjectListControl.RemoveAllColumnHeader()
            'Me.AxObjectListControl.ClearResultList()
            Dim stg As String = "Dateien"
            If USER_LANGUAGE <> "de-DE" Then
                stg = "files"
            End If
            TabWindream.Text = stg
            Dim elapsed As Double
            elapsed = sw.Elapsed.TotalSeconds
            sw.Stop()
            sw.Reset()
            If LogErrorsOnly = False Then ClassLogger.Add(" >> Clear Result List took " & Format(elapsed, "0.000000000") & " seconds", False)
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Clear Result List: ", ex.Message)
        End Try

    End Sub
    Sub CheckDocView()
        'Dim _index = AxObjectListControl.GetFirstSelectedObject
        'Dim path As String = AxObjectListControl.GetObjectPath(_index)
        'path = path.Replace("?", vWLaufwerk)
        'DocViewString = path

        If WD_ShowDocs = True Then
            CloseWDDocview()
            ShowDocView()
        End If
    End Sub
    Sub ShowDocView()
        Try
            CloseWDDocview()
            DocView = Nothing
            DocView = CreateObject("WMPViewXNG.Viewer")
            ' open the viewer
            DocView.ViewFile(DocViewString)
            OpenedFileString = DocViewString
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in ShowDocView: ", ex.Message)
        End Try

    End Sub
    Sub CloseWDDocview()
        Try
            If DocView Is Nothing = False Then
                DocView.CloseView(OpenedFileString, 0)
            End If

        Catch ex As Exception
            ClassLogger.Add(" ### Error in CloseDocView")
            ClassLogger.Add("### " & ex.Message & " ###")
        End Try

    End Sub
#End Region

#Region "GridViews"
    Private Sub ButtonQuickViewCarousel_Click(sender As Object, e As EventArgs) Handles ButtonQuickViewCarousel.Click
        GRID_TYPE = GridType.Carousel
        VIEW_ID_RUNTIME = 2
        GRID_TYPE_ID = 2
        grvwCarousel.OptionsView.ViewMode = DevExpress.XtraGrid.Views.Layout.LayoutViewMode.Carousel
        GridControlMain.MainView = grvwCarousel

        Load_Datafor_Entity()
    End Sub

    Private Sub ButtonQuickViewTiles_Click(sender As Object, e As EventArgs) Handles ButtonQuickViewTiles.Click
        GRID_TYPE = GridType.Tiles
        VIEW_ID_RUNTIME = 1
        GRID_TYPE_ID = 1
        GridControlMain.MainView = grvwTiles

        Load_Datafor_Entity()
    End Sub

    Private Sub ButtonDetailView_Click(sender As Object, e As EventArgs) Handles ButtonDetailView.Click
        GRID_TYPE = GridType.Grid
        VIEW_ID_RUNTIME = 3
        GRID_TYPE_ID = 3
        GridControlMain.MainView = grvwGrid

        Load_Datafor_Entity()
    End Sub

    Private Sub ButtonSetViewAsDefault_Click(sender As Object, e As EventArgs) Handles ButtonSetViewAsDefault.Click
        Dim VIEWTYPE_ID As Integer

        Select Case GRID_TYPE
            Case GridType.Tiles
                VIEWTYPE_ID = 1
            Case GridType.Carousel
                VIEWTYPE_ID = 2
            Case GridType.Grid
                VIEWTYPE_ID = 3

        End Select
        Dim upd = String.Format("UPDATE TBPMO_USER_CONSTR_VIEW_TYPE SET VIEW_ID = {0} WHERE CONSTRUCTOR_DETAIL_ID = {1} AND [ENTITY_ID] = {2} AND USER_ID = {3}", VIEWTYPE_ID, CURRENT_CONSTRUCTOR_DETAIL_ID, ENTITY_ID, USER_GUID)
        If ClassDatabase.Execute_non_Query(upd) = True Then
            ' VIEW_ID Override zurücksetzen!!
            VIEW_ID_RUNTIME = -1
            MsgBox("Stanard-View was saved successfully!", MsgBoxStyle.Information)
        End If
    End Sub
    Private Sub ButtonResetView_Click(sender As Object, e As EventArgs) Handles ButtonResetView.Click
        ' TODO: Ansicht zurücksetzen
        Try
            Dim XMLPath = Get_Grid_Layout_Filename()
            If File.Exists(XMLPath) Then
                File.Delete(XMLPath)
                Load_Entity_Data(ACT_EBENE)
            End If
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Reset Layout Grid: ", ex.Message)
        End Try
    End Sub
#End Region

    Private Sub TCDetails_DragDrop(sender As Object, e As DragEventArgs) Handles TCDetails.DragDrop
        Drag_Drop(e)
    End Sub

    Private Sub TCDetails_SelectedPageChanged(sender As Object, e As DevExpress.XtraTab.TabPageChangedEventArgs) Handles TCDetails.SelectedPageChanged

        Update_Status_Label(False, "")
        If TCDetails.SelectedTabPage.Name = "XtraTabPageVariant" Then
            XtraTabPageVariant_Open()
        End If
        Select Case TCDetails.SelectedTabPage.Name
            Case "TabDetails"
                If NODE_NAVIGATION = False Then
                    Column_Row_Handler(RECORD_ID, False, True)
                End If

                'If RECORD_NEEDS_REFRESH = True Then
                '    ClassControlValues.LoadControlValues(RECORD_ID, ENTITY_ID, CtrlBuilder.AllControls)
                '    '  UpdRECORD_NEEDS_REFRESH(False)
                'End If

                'Refresh_CreatedChangedRecordByID(RECORD_ID)
                ' RECORD_CHANGED = False
                If DOC_SEARCH_TAB1 = True Then
                    BACKGROUND_HELPER.PictureAlignment = ContentAlignment.BottomRight
                End If
            Case "TabWindream" 'Dateien
                BACKGROUND_HELPER.PictureAlignment = ContentAlignment.BottomRight
                If RECORD_ID = 0 Then
                    Exit Sub
                Else
                    RUN_WDSEARCH_GRID()
                End If
                Load_DocGrid_Layout()
            Case "TabFollowUp"
                'tsButtonEdit.Enabled = False
                Refresh_FollowUps()
                dtpFollowUp.Enabled = False
                lblWiedervorlage_Control.Text = "<< Waiting for Selection:"
            Case "TabPageVariant"
                Load_Variants()
            Case "TabPos"
                Dim stg As String
                'tsButtonEdit.Enabled = False
                If POS_ENABLED = True Then
                    tslblPoslocked.Visible = False
                    BindingNavigatorAddNewItem.Enabled = True
                    BindingNavigatorDeleteItem.Enabled = True
                    grvwGridPos.OptionsBehavior.ReadOnly = False
                    If USER_LANGUAGE = "de-DE" Then
                        stg = "Bearbeiten beenden"
                    Else
                        stg = "End Working"
                    End If

                Else
                    If USER_LANGUAGE = "de-DE" Then
                        stg = "Positionen bearbeiten"
                    Else
                        stg = "Edit positions"
                    End If
                    tslblPoslocked.Visible = True
                    BindingNavigatorAddNewItem.Enabled = False
                    BindingNavigatorDeleteItem.Enabled = False
                    grvwGridPos.OptionsBehavior.ReadOnly = True
                End If
                Me.tsbtnWork.Text = stg
                Load_Pos_Data()
                Load_POSGrid_Layout()
        End Select
    End Sub
    Sub XtraTabPageVariant_Open()
        Try

        Catch ex As Exception

        End Try
    End Sub
    Private Sub Refresh_FollowUps()

        Try
            If DT_FU_ENTITY.Rows.Count > 0 Then
                grpbxFU_Profile.Enabled = True
            End If
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Refresh_FollowUps: ", ex.Message)
        End Try

    End Sub
#Region "Dropping Files"
    Sub Drag_Enter(e As DragEventArgs)
        If act_FormViewID <> 0 Then
            ClassDragDrop.Drag_enter(e)
        End If
    End Sub
    Sub Drag_Drop(e As DragEventArgs)
        Try
            If ClassDragDrop.Drop_File(e) = False Then
                Exit Sub
            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 Sub
        End If
        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!")
            Exit Sub
        End If
        If act_FormViewID <> 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 = ClassDatabase.Execute_Scalar(sql, True)
            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 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 = ClassDatabase.Execute_Scalar(sql, True)
                If count_DT = 0 Then
                    MsgBox("No documenttypes for this entity configured! Indexing is not possible!" & vbNewLine & "Please check the configuration!", MsgBoxStyle.Exclamation)
                    Exit Sub
                End If
            End If
            If RECORD_CHANGED = True Then
                If Save_Record() = False Then
                    Exit Sub
                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(RECORD_ID, CONTROL_DOCTYPE_MATCH)
                Catch ex As Exception
                    CURRENT_CONTROL_DOCTYPE_MATCH = 0
                    CURRENT_CONTROL_DOCTYPE_MATCH = ""
                End Try

            End If
            CURRENT_RECORD_ID = RECORD_ID
            CURRENT_ENTITY_ID = ENTITY_ID
            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_PARENT_ENTITY_ID = PARENT_ENTITYID
                        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
                                frmWD_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
                RUN_WDSEARCH_GRID()
                TimerClearResultfiles.Start()
            Else
                If LogErrorsOnly = False Then ClassLogger.Add(" >> No new files were added or windream tab is not focused!", False)
            End If
            Me.Cursor = Cursors.Default
        Else
            'If RIGHT_RECORD_AND_FILE_READ_ONLY = True Then
            '    ClassLogger.Add(">> RIGHT_RECORD_AND_FILE_READ_ONLY is set! No DragDrop allowed", False)
            'End If
            If RIGHT_READ_ONLY_DOC = True Then
                ClassLogger.Add(">> RIGHT_WD_FORBIDDEN is set! No DragDrop allowed", False)
            End If

            End If
        Catch ex As Exception
            ClassLogger.Add("Unexpected Error in Drag_Drop: " & ex.Message)
        Finally

        End Try
    End Sub
    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 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
                            ClassLogger.Add(">> Check_Dropped_Files:" & Str.ToString, False)
                            Dim CURRENT_WORKFILE = Str.Substring(Str.LastIndexOf("@") + 1)
                            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 = ClassDatabase.Execute_Scalar(sql, True)
            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 = ClassDatabase.Execute_Scalar(sql, True)
                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
                            frmWD_IndexFile.ShowDialog()
                            'sql = String.Format("SELECT * FROM TBPMO_FILES_USER WHERE (UPPER(USER_WORK) = UPPER('{0}')) AND WORKED = 0", USER_USERNAME)
                            'CURRENT_TBPMO_FILES_USER = ClassDatabase.Return_Datatable(sql, True)
                            'If CURRENT_TBPMO_FILES_USER.Rows.Count > 0 Then
                            '    Check_Dropped_Files()
                            'End If
                        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 Sub GridControlMain_DragEnter(sender As Object, e As DragEventArgs) Handles GridControlMain.DragEnter
        Drag_Enter(e)
    End Sub
    Private Sub pnlDetails_DragEnter(sender As Object, e As DragEventArgs) Handles pnlDetails.DragEnter
        Drag_Enter(e)
    End Sub
    Private Sub GridControlMain_DragDrop(sender As Object, e As DragEventArgs) Handles GridControlMain.DragDrop
        Drag_Drop(e)
    End Sub
    Private Sub pnlDetails_DragDrop(sender As Object, e As DragEventArgs) Handles pnlDetails.DragDrop
        Drag_Drop(e)
    End Sub
    Private Sub TCDetails_DragEnter(sender As Object, e As DragEventArgs) Handles TCDetails.DragEnter
        Drag_Enter(e)
    End Sub
    Private Sub GridControlDocSearch_DragEnter(sender As Object, e As DragEventArgs) Handles GridControlDocSearch.DragEnter
        Drag_Enter(e)
    End Sub
#End Region

#Region "Follow Up"
    Private Sub ListViewFollowUps_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListViewFollowUps.SelectedIndexChanged
        If Me.ListViewFollowUps.SelectedItems.Count > 0 Then
            dtpFollowUp.Enabled = False
            FOLL_UP_ID = ListViewFollowUps.SelectedItems(0).Text
            lblFollowUp_save.Visible = False
            For Each DR As DataRow In DT_FU_ENTITY.Rows
                If FOLL_UP_ID = DR.Item("GUID") Then
                    grpbxFU_Profile.Enabled = True
                    FOLL_UP_DATE_CTRL_ID = DR.Item("DEPENDENT_DATE_CTRL_ID")
                    Dim datevalue = ClassControlValues.Get_Control_Value_for_ID(DR.Item("DEPENDENT_DATE_CTRL_ID"), RECORD_ID)
                    If Not IsNothing(datevalue) Then
                        dtpFollowUp.Enabled = True
                        If datevalue = "00:00:00" Then
                            dtpFollowUp.Value = ClassHelper.Convert_Date(Now, CURRENT_DATE_FORMAT)
                        End If
                        FOLL_UP_RECORD_DEFINED = True
                        Try
                            dtpFollowUp.Value = ClassHelper.Convert_Date(datevalue, CURRENT_DATE_FORMAT)
                        Catch ex As Exception
                            dtpFollowUp.Value = ClassHelper.Convert_Date(Now, CURRENT_DATE_FORMAT)
                        End Try

                    Else
                        dtpFollowUp.Value = ClassHelper.Convert_Date(Now, CURRENT_DATE_FORMAT)
                        FOLL_UP_RECORD_DEFINED = False
                    End If

                    Dim caption = ClassDatabase.Execute_Scalar("SELECT COL_NAME FROM TBPMO_CONTROL WHERE GUID = " & DR.Item("DEPENDENT_DATE_CTRL_ID"), True)
                    If Not IsNothing(caption) Then
                        lblWiedervorlage_Control.Text = CStr(caption)

                    Else
                        lblWiedervorlage_Control.Text = "Wiedervorlage:"
                    End If
                    FOLL_UP_DONE_CTRL_ID = DR.Item("DEPENDENT_DONE_CTRL_ID")
                    Dim checkvalue = ClassControlValues.Get_Control_Value_for_ID(DR.Item("DEPENDENT_DONE_CTRL_ID"), RECORD_ID)
                    If Not IsNothing(checkvalue) Then
                        chkFollowUp.Checked = CBool(checkvalue)
                    Else
                        chkFollowUp.Checked = False
                    End If
                    Dim SQL = String.Format("SELECT GUID FROM TBPMO_CONTROL_SCREEN WHERE CONTROL_ID = {0} AND SCREEN_ID = {1}", DR.Item("DEPENDENT_DONE_CTRL_ID"), CURRENT_SCREEN_ID)
                    Dim ctrl_screen_id = ClassDatabase.Execute_Scalar(SQL, True)
                    If ctrl_screen_id > 0 Then
                        SQL = String.Format("SELECT CAPTION FROM TBPMO_CONTROL_LANGUAGE WHERE CONTROL_SCREEN_ID = {0} AND LANGUAGE_TYPE = '{1}'", ctrl_screen_id, USER_LANGUAGE)
                        Dim captionCheck = ClassDatabase.Execute_Scalar(SQL, True)
                        If Not IsNothing(captionCheck) Then
                            chkFollowUp.Text = CStr(captionCheck)
                        End If
                    End If




                    Load_FUUser(FOLL_UP_ID)

                End If
            Next
        End If
    End Sub
    Sub Load_FUUser(ID As Integer)
        Try
            Dim sql = "SELECT T.GUID, T1.USERNAME FROM TBPMO_FOLLUPEMAIL_RECORD T, TBDD_USER T1 WHERE T.USER_ID = T1.GUID AND T.FOLLOW_UP_ID = " & ID & " AND T.RECORD_ID = " & RECORD_ID & " ORDER BY T1.USERNAME"
            Dim DT As DataTable = ClassDatabase.Return_Datatable(sql)
            ListBoxUser2Profile.DataSource = DT
            ListBoxUser2Profile.DisplayMember = DT.Columns(1).ColumnName
            ListBoxUser2Profile.ValueMember = DT.Columns(0).ColumnName
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Load Follow Up User: ", ex.Message)
        End Try
    End Sub
    Private Sub dtpWV_ValueChanged(sender As Object, e As EventArgs) Handles dtpFollowUp.ValueChanged
        If ENTITY_LOADED = False = False Then
            Exit Sub
        End If
        If ClassControlCommandsUI.UpdateControlValue(FOLL_UP_DATE_CTRL_ID, RECORD_ID, dtpFollowUp.Value) = True Then
            lblFollowUp_save.Text = "Follow Up saved - " & Now.ToString
            lblFollowUp_save.Visible = True
            'UpdRECORD_NEEDS_REFRESH(True)
        Else
            lblFollowUp_save.Visible = False
            'UpdRECORD_NEEDS_REFRESH(False)
        End If
    End Sub

    Private Sub chkFollowUp_CheckedChanged(sender As Object, e As EventArgs) Handles chkFollowUp.CheckedChanged
        If ENTITY_LOADED = False Then
            Exit Sub
        End If
        If ClassControlCommandsUI.UpdateControlValue(FOLL_UP_DONE_CTRL_ID, RECORD_ID, chkFollowUp.Checked.ToString) = True Then
            lblFollowUp_save.Text = "Follow Up saved - " & Now.ToString
            lblFollowUp_save.Visible = True
            ' UpdRECORD_NEEDS_REFRESH(True)
        Else
            lblFollowUp_save.Visible = False
            'UpdRECORD_NEEDS_REFRESH(False)
        End If
    End Sub

    Private Function Check_FOLLOWUP_IsConfigured(ENTITY_ID As Integer)
        Try

            Dim sql = "select * from TBPMO_FOLLOW_UP_EMAIL t where t.ACTIVE = 1 and t.DEPENDENT_DATE_CTRL_ID in (select guid from TBPMO_CONTROL where  CONTROL_TYPE_ID = 4 and form_id = " & ENTITY_ID & ")"
            DT_FU_ENTITY = ClassDatabase.Return_Datatable(sql)
            If DT_FU_ENTITY.Rows.Count > 0 Then
                'Die Userauswahl füllen
                Dim DTUser As DataTable = ClassDatabase.Return_Datatable("select guid, username from TBDD_USER t where T.EMAIL IS NOT NULL AND MODULE_RECORD_ORG = 1 order by USERNAME")
                cmbFollowUpUser.DataSource = DTUser
                cmbFollowUpUser.DisplayMember = DTUser.Columns(1).ColumnName
                cmbFollowUpUser.ValueMember = DTUser.Columns(0).ColumnName
                TabFollowUp.PageVisible = True
                FOLLOW_UPisActive = True

                'Die Wiedervorlageprofile in den Listview laden
                ListViewFollowUps.Items.Clear()
                Dim anz As Integer = 0
                For Each DR As DataRow In DT_FU_ENTITY.Rows
                    Dim name = DR.Item("NAME")
                    ListViewFollowUps.Items.Add(DR.Item("GUID"))
                    ListViewFollowUps.Items(anz).SubItems.Add(name)
                    anz += 1
                Next

            Else
                FOLLOW_UPisActive = False
                TabFollowUp.PageVisible = False
            End If
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Check Follow Up: ", ex.Message)
            windream_Docshow = False
        End Try
    End Function
#End Region
#Region "Tasks"
    'Private Sub tsButtonShowWorkflowTasks_Click(sender As Object, e As EventArgs) Handles tsButtonShowWorkflowTasks.Click
    '    If RECORD_ID > 0 Then
    '        CURRENT_RECORD_ID = RECORD_ID
    '        CURRENT_ENTITY_ID = ENTITY_ID
    '        frmTask_Editor.ShowDialog()
    '        Show_act_WFTask()
    '        Refresh_TaskOverview()
    '    End If
    'End Sub

    Private Sub tsButtonShowTaskOverview_Click(sender As Object, e As EventArgs) Handles tsButtonShowTaskOverview.Click
        ClassJumpRecord.JumpToRecord(2, RECORD_ID)
        JUMP_RECORD_ID = 0
    End Sub


    Sub Refresh_TaskOverview()
        Dim frmCollection As New FormCollection()
        frmCollection = Application.OpenForms()
        If frmTask_Overview.IsHandleCreated Then
            If Sett_TaskOverviewKeepInFront = True Then
                frmTask_Overview.Refresh()
            End If
            'Else
            '    Console.WriteLine("frmTaskOverview NICHT geladen")
        End If
    End Sub
    Sub Show_act_WFTask()
        Try
            Dim query = From table In DD_DMSDataSet.VWPMO_WF_ACTIVE.AsEnumerable()
                         Select table Where table.Item("ENTITY_ID") = ENTITY_ID
            Dim Entity_rows = query.ToList()
            If Entity_rows.Count > 0 Then
                tsButtonShowTaskOverview.Visible = True
                tsButtonShowTaskOverview.Enabled = True
                If _MANUAL_WORKFLOW = True Then
                    CreateWorkflowtaskstsmi.Enabled = True
                End If
                tsslblWorkflowstate.Visible = True
            Else
                tsButtonShowTaskOverview.Visible = False
                CreateWorkflowtaskstsmi.Enabled = False
                tsslblWorkflowstate.Visible = False
            End If
            For Each _row In Entity_rows
                If _row.Item("RECORD_ID") = RECORD_ID Then
                    CURRENT_TASK_ID = _row.Item("WF_TASK_ID")
                    Dim text = "Task: " & _row.Item("WF_TITLE")
                    text += " - " & _row.Item("STATE_TITLE")
                    text += " - " & _row.Item("DUE_DATE")
                    tsslblWorkflowstate.Text = text
                    'Direkten Zugriff auf RecordView Workflow erlauben

                    Dim Colorstring = _row.Item("COLOR")
                    If IsDBNull(Colorstring) Then
                        Exit Sub
                    End If
                    If Colorstring <> "" Then
                        'grvwSelection.Appearance.FocusedRow.BackColor = ColorTranslator.FromWin32(CInt(Colorstring))
                        'grvwSelection.Appearance.FocusedRow.ForeColor = Color.Yellow
                        tsslblWorkflowstate.BackColor = ColorTranslator.FromWin32(CInt(Colorstring))
                        Select Case tsslblWorkflowstate.BackColor
                            Case Color.Red
                                tsslblWorkflowstate.ForeColor = Color.White
                        End Select
                    Else
                        tsslblWorkflowstate.BackColor = Color.Transparent
                    End If
                End If
            Next

        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Show act WFTask: ", ex.Message)
        End Try
    End Sub
#End Region

    Private Sub ResetEbenenAuswahlToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ResetEbenenAuswahlToolStripMenuItem.Click
        ACT_EBENE = 0
        CURRENT_ACT_LEVEL = 0
        ACT_EBENE_STRING = ""
        EBENE1_ENTITY = ""
        EBENE1_RECID = 0
        EBENE2_ENTITY = ""
        EBENE2_RECID = 0
        EBENE3_ENTITY = ""
        EBENE3_RECID = 0
        NavPane.Categories.Clear()
        Load_Tree_View(CONSTRUCTORID)
    End Sub

    Private Sub DateiimportEntitätToolStripMenuItem_Click(sender As Object, e As EventArgs)
        If PARENT_ENTITYID = 0 Then
            Exit Sub
        End If
        CURRENT_ENTITYSTRING = _ENTITYSTRING
        CURRENT_ENTITY_ID = ENTITY_ID
        frmWD_EntityImport.ShowDialog()
    End Sub
    Private Sub FormDesignerToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles FormDesignerToolStripMenuItem.Click
        Try
            Dim SelectedNode As TreeNode = TryCast(TreeViewMain.SelectedNode, TreeNode)
            If SelectedNode IsNot Nothing Then
                Dim FormId As Integer = ClassNodeNavigation.Return_ENTITY_FOR_TAG(SelectedNode.Tag)
                If FormId > 0 Then
                    CURRENT_ENTITY_ID = FormId
                    OpenFormLevelDesigner()
                End If
            End If
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error inOpen Designer: ", ex.Message)
        End Try
    End Sub
    Private Sub ButtonExportToExcel_Click(sender As Object, e As EventArgs) Handles ButtonExportToExcel.Click
        Dim saveFileDialog1 As New SaveFileDialog
        saveFileDialog1.Filter = "Excel File|*.xlsx"
        saveFileDialog1.Title = "Export to Excel:"
        saveFileDialog1.ShowDialog()
        If saveFileDialog1.FileName <> "" Then
            Cursor = Cursors.WaitCursor
            GridControlMain.MainView.ExportToXlsx(saveFileDialog1.FileName)
            Dim result As MsgBoxResult
            Dim msg = String.Format("Datei wurde erstellt! Wollen Sie diese nun öffnen?")

            If USER_LANGUAGE <> "de-DE" Then
                msg = String.Format("File was created. Do You want to open excel?")
            End If
            result = MessageBox.Show(msg, "Exporting result:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
            If result = MsgBoxResult.Yes Then
                Process.Start(saveFileDialog1.FileName)
            End If
        End If
        Cursor = Cursors.Default
    End Sub


    Private Sub frmForm_Constructor_Main_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        If ERROR_FORM_LOAD = True Then
            Me.Close()
        End If
        Dim sw As Stopwatch = Stopwatch.StartNew()
        Dim elapsed As Double
        Me.BringToFront()
        ' LoadLayouts()
        Load_Level1()
        Jump_Record()
        sw.Stop()
        elapsed = sw.Elapsed.TotalSeconds
        If LogErrorsOnly = False Then ClassLogger.Add(String.Format(" >> Form Shown took {0} to load", Format(elapsed, "0.000000000") & " seconds"), False)
        FORM_SHOWN = True
    End Sub
    Sub Jump_Record()
        Try
            Dim sw As Stopwatch = Stopwatch.StartNew()
            Dim elapsed As Double
            If LogErrorsOnly = False Then ClassLogger.Add(" >> " & Now.ToString & " Jump_Record", False)
            If JUMP_RECORD_ID > 0 Then
                Dim sql = String.Format("SELECT FORM_ID FROM TBPMO_RECORD WHERE GUID = {0}", JUMP_RECORD_ID)
                Dim FormID = ClassDatabase.Execute_Scalar(sql, True)
                If FormID > 0 Then
                    Dim n As TreeNode
                    For Each n In TreeViewMain.Nodes
                        CheckNode(n, FormID)
                    Next
                End If
            End If

            ' wurde nicht zurückgesetzt, also 
            ' wurde der record nicht gefunden
            If JUMP_RECORD_ID <> 0 Then
                ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Jump Record: ", "Record-ID " & JUMP_RECORD_ID & " konnte nicht gefunden werden")
            End If


            elapsed = sw.Elapsed.TotalSeconds
            sw.Stop()
            If LogErrorsOnly = False Then ClassLogger.Add(String.Format(" >> Jump_Record took {0} to load", Format(elapsed, "0.000000000") & " seconds"), False)
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Jump-Record: ", ex.Message)
        End Try
    End Sub
    Private Sub CheckNode(ByVal n As TreeNode, FormID As Integer)
        Dim aNode As TreeNode

        If CInt(ClassNodeNavigation.Return_ENTITY_FOR_TAG(n.Tag)) = FormID Then
            'Gefunden also selektieren
            TreeViewMain.SelectedNode = n
            TreeViewMain.SelectedNode.EnsureVisible()
            TreeViewMain.Select()

            'Für Grid filtern wir die Aktuelle Ansicht nach der Record-ID,
            'für Carousel und Tiles markieren wir den Record
            LocateRecordById(JUMP_RECORD_ID)

            ' Jump Record-ID wieder zurücksetzen
            JUMP_RECORD_ID = 0
            Exit Sub
        End If

        For Each aNode In n.Nodes
            If CInt(ClassNodeNavigation.Return_ENTITY_FOR_TAG(aNode.Tag)) = FormID Then
                'Gefunden also selektieren
                TreeViewMain.SelectedNode = aNode
                TreeViewMain.SelectedNode.EnsureVisible()
                TreeViewMain.Select()

                'Für Grid filtern wir die Aktuelle Ansicht nach der Record-ID,
                'für Carousel und Tiles markieren wir den Record
                LocateRecordById(JUMP_RECORD_ID)

                ' Jump Record-ID wieder zurücksetzen
                JUMP_RECORD_ID = 0
                Exit For
                Exit Sub
            End If
            CheckNode(aNode, FormID)
        Next
    End Sub

    Public Sub LocateRecordById(RecordId As Integer)
        If GRID_TYPE = GridType.Grid Then
            Dim rowHandle = grvwGrid.LocateByValue(0, grvwGrid.Columns("Record-ID"), RecordId)
            grvwGrid.FocusedRowHandle = rowHandle
        ElseIf GRID_TYPE = GridType.Carousel Then
            Dim rowHandle = grvwCarousel.LocateByValue(0, grvwCarousel.Columns("Record-ID"), RecordId)
            grvwCarousel.FocusedRowHandle = rowHandle
        ElseIf GRID_TYPE = GridType.Tiles Then
            Dim rowHandle = grvwTiles.LocateByValue(0, grvwTiles.Columns("Record-ID"), RecordId)
            grvwTiles.FocusedRowHandle = rowHandle
        End If
    End Sub


    Sub Load_Templates()
        Try
            Dim sql As String = "SELECT * FROM VWPMO_TEMPLATE_ENTITY WHERE ENTITY_ID = " & ENTITY_ID & " ORDER BY TEMPLATE_NAME"
            Dim DT As DataTable = ClassDatabase.Return_Datatable(sql)
            If Not IsNothing(DT) Then
                If DT.Rows.Count > 0 Then
                    OfficeVorlagentsmi.Enabled = True
                    OfficeVorlagentsmi.DropDownItems.Clear()
                    For Each row As DataRow In DT.Rows
                        Dim item As ToolStripMenuItem = OfficeVorlagentsmi
                        Dim newItem As ToolStripMenuItem = New ToolStripMenuItem(row.Item("TEMPLATE_NAME").ToString, Nothing, AddressOf TemplateItem_Click)
                        newItem.Tag = row.Item("TEMPLATE_ID")
                        item.DropDownItems.Add(newItem) '                        subitem.DropDownItems.Add(newItem)
                    Next
                Else
                    OfficeVorlagentsmi.Enabled = False
                End If
            End If
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Load_Templates: ", ex.Message)
        End Try
    End Sub

    Private Sub TemplateItem_Click(sender As Object, e As EventArgs)
        Dim item As ToolStripMenuItem = DirectCast(sender, ToolStripMenuItem)
        Dim TemplateID As Integer = Integer.Parse(item.Tag)
        If RECORD_ID > 0 Then
            Dim SOLLENTITY_ID = ClassDatabase.Execute_Scalar("SELECT ENTITY_ID FROM VWPMO_TEMPLATE_ENTITY WHERE TEMPLATE_ID = " & TemplateID, True)
            Dim REC_ENTITY_ID = ClassDatabase.Execute_Scalar("SELECT FORM_ID FROM TBPMO_RECORD WHERE GUID = " & RECORD_ID, True)

            If Not IsNothing(SOLLENTITY_ID) Then
                If CInt(SOLLENTITY_ID) = REC_ENTITY_ID Then
                    Cursor = Cursors.WaitCursor
                    If ClassOfficeTemplate.Open_Word_Template(TemplateID, RECORD_ID) = True Then
                        RUN_WDSEARCH_GRID()
                        ' RUN_WD_SEARCH(WD_Suche, "RECORD")
                        Update_Status_Label(True, "Template file imported to windream", EditState.Insert)
                    End If
                    Cursor = Cursors.Default
                Else
                    Dim msg = "Bitte wählen Sie nochmal einen Datensatz aus."
                    If USER_LANGUAGE <> "de-DE" Then
                        msg = "Please choose a record again."
                    End If
                    MsgBox(msg, MsgBoxStyle.Exclamation)
                End If
            End If
        Else
            Dim msg = "Bitte wählen Sie zuerst einen Datensatz aus."
            If USER_LANGUAGE <> "de-DE" Then
                msg = "Please choose a record first."
            End If
            MsgBox(msg, MsgBoxStyle.Exclamation)
        End If


    End Sub

    Sub Load_Level1()
        Try

            Dim sw As Stopwatch = Stopwatch.StartNew()
            Dim elapsed As Double

            ' LINQ für Zugriff auf DT_VWPMO_CONSTRUCTOR_FORMS
            Dim result = From form In DT_VWPMO_CONSTRUCTOR_FORMS.AsEnumerable()
                         Select form
                         Order By form.Item("SEQUENCE")
                         Where form.Item("PARENT_ID") = 0

            If result.Count >= 1 Then
                Dim tn As TreeNode = TreeViewMain.Nodes(0)
                TreeViewMain.SelectedNode = tn
                TreeViewMain.Select()
            End If

            elapsed = sw.Elapsed.TotalSeconds
            sw.Stop()
            If LogErrorsOnly = False Then ClassLogger.Add(String.Format(" >> Load_Level1 took {0} to load", Format(elapsed, "0.000000000") & " seconds"), False)
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Load_Level1: ", ex.Message)
        End Try
    End Sub


    ' Call the procedure using the top nodes of the treeview.
    Private Sub CallRecursive(ByVal aTreeView As TreeView)

    End Sub


    Private Sub grvwGridPos_CellValueChanged(sender As Object, e As CellValueChangedEventArgs) Handles grvwGridPos.CellValueChanged
        Try
            Dim column = e.Column.FieldName
            Dim sql = String.Format("select guid from TBPMO_CONTROL where COL_NAME = '{0}' and FORM_ID = {1}", column, POS_ENTITY)
            Dim controlid = ClassDatabase.Execute_Scalar(sql, True)
            If Not IsNothing(controlid) Then
                'Überprüfen ob schon value vorhanden
                sql = String.Format("SELECT CONTROL_ID FROM VWPMO_VALUES WHERE CONTROL_ID = {0} AND FORM_ID = {1} AND CONTROL_COLUMN = '{2}' AND RECORD_ID = {3}", controlid, POS_ENTITY, column, POS_RECORD_ID)
                Dim cId As Integer = ClassDatabase.Execute_Scalar(sql, True)
                If IsNothing(POS_RECORD_ID) Or IsDBNull(POS_RECORD_ID) Then
                    If ClassRecordCommands.CreateRecord(POS_ENTITY) = True Then
                        Dim recid = ClassRecordCommands.GetLastRecord
                        If Not IsNothing(recid) Then
                            'Die neue Record-ID setzen
                            POS_RECORD_ID = recid
                            ClassProxy.PRPROXY_RECORD_UPD_INS(POS_ENTITY, POS_RECORD_ID)
                            If ClassRecordCommands.ConnectRecord(PARENT_RECORDID, POS_RECORD_ID, "POS_LINK for Entity " & POS_ENTITY.ToString) = True Then
                                ClassProxy.PRPROXY_RECORD_CONNECT(PARENT_RECORDID, POS_RECORD_ID)
                            End If
                            Load_Pos_Data()
                        Else
                            MsgBox("Unexpected Error in Creating POS", MsgBoxStyle.Exclamation)
                        End If
                    End If
                End If
                ' Wenn cId = 0, existiert noch kein wert für diese controlId/FormId Kombination
                If cId = 0 Then
                    ClassControlCommandsUI.InsertControlValue(controlid, POS_RECORD_ID, e.Value)
                    Update_Status_Label(True, "Record was added!", EditState.Insert)
                Else
                    ClassControlCommandsUI.UpdateControlValue(controlid, POS_RECORD_ID, e.Value)
                    Update_Status_Label(True, "Record was updated!", EditState.Update)
                End If
            Else
                Update_Status_Label(False)
            End If
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in grvwGridPos_CellValueChanged: ", ex.Message)
        End Try



    End Sub

    Private Sub grvwGridPos_FocusedRowChanged(sender As Object, e As FocusedRowChangedEventArgs) Handles grvwGridPos.FocusedRowChanged
        Pos_COLROW_Changer()
    End Sub
    Sub Pos_COLROW_Changer()
        Try
            If TCDetails.SelectedTabPage.Text.StartsWith("Pos") Then
                Dim Grid_RecordID = Get_Focused_Row_Cell_Value_pos("Record-ID")
                If Not IsNothing(Grid_RecordID) Then
                    POS_RECORD_ID = Grid_RecordID
                End If
            End If
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in grvwGridPos_FocusedRowChanged: ", ex.Message)
        End Try
    End Sub
    Private Sub grvwGridPos_RowUpdated(sender As Object, e As RowObjectEventArgs) Handles grvwGridPos.RowUpdated

    End Sub

    Private Sub GridControlPos_Leave(sender As Object, e As EventArgs) Handles GridControlPos.Leave
        Save_POSGrid_Layout()
    End Sub

    Private Sub grvwGridPos_RowStyle(sender As Object, e As DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs) Handles grvwGridPos.RowStyle
        If e.RowHandle = DevExpress.XtraGrid.GridControl.AutoFilterRowHandle Then
            e.Appearance.BackColor = Color.Orange 'LemonChiffon
        End If
    End Sub

    Private Sub grvwGrid_RowStyle(sender As Object, e As DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs) Handles grvwGrid.RowStyle
        If e.RowHandle = -1 Then
            Exit Sub
        End If
        If e.RowHandle = DevExpress.XtraGrid.GridControl.AutoFilterRowHandle Then
            e.Appearance.BackColor = Color.Orange
        Else
            If GRID_TYPE = GridType.Grid Then

                Try
                    Dim rowCellValue = grvwGrid.GetRowCellValue(e.RowHandle, "ROW_COLOR")
                    If rowCellValue <> "" Then
                        Dim ColorRow As Color
                        Try
                            ColorRow = Color.FromName(rowCellValue)
                        Catch ex As Exception
                            ClassLogger.Add(">> RowBackColor '" & rowCellValue & "'could not be converted from name!", False)
                            Exit Sub
                        End Try
                        'Dim c As Color = DirectCast(rowCellValue, Color)
                        e.Appearance.BackColor = ColorRow
                        e.HighPriority = True
                    End If
                Catch ex As Exception
                    ClassLogger.Add(">> Unexpected Error in RowStyle: " & ex.Message, False)
                End Try
            End If
        End If
    End Sub
    Private Sub grvwGrid_MouseDown(sender As Object, e As MouseEventArgs) Handles grvwGrid.MouseDown, grvwTiles.MouseDown, grvwCarousel.MouseDown
        Try
            Dim view As BaseView = CType(sender, BaseView)

            If e.Button = Windows.Forms.MouseButtons.Right Then
                GRIDRightMouse_Clicked = True
            Else
                GRIDRightMouse_Clicked = False
            End If
            Dim hitInfo As GridHitInfo = view.CalcHitInfo(New Point(e.X, e.Y))
            If e.Button = Windows.Forms.MouseButtons.Left AndAlso hitInfo.InRow AndAlso hitInfo.HitTest <> GridHitTest.RowIndicator Then
                GRIDdownHitInfo = hitInfo
            End If
        Catch ex As Exception
            ClassLogger.Add(">> Unexpected Error in grvwGrid_MouseDown: " & ex.Message, False)
        End Try

    End Sub
    Private Sub grvwGrid_MouseMove(sender As Object, e As MouseEventArgs) Handles grvwGrid.MouseMove, grvwTiles.MouseMove, grvwCarousel.MouseMove
        Dim view As BaseView = CType(sender, BaseView)

        If e.Button = MouseButtons.Left And Not GRIDdownHitInfo Is Nothing Then
            Dim dragSize As Size = SystemInformation.DragSize

            Dim dragRect As Rectangle = New Rectangle(New Point(GRIDdownHitInfo.HitPoint.X - dragSize.Width / 2, GRIDdownHitInfo.HitPoint.Y - dragSize.Height / 2), dragSize)

            If Not dragRect.Contains(New Point(e.X, e.Y)) Then

                view.GridControl.DoDragDrop(GetDragData(view), DragDropEffects.All)

                GRIDdownHitInfo = Nothing

            End If

        End If
    End Sub
    Private Function GetDragData(ByVal view As GridView) As String()
        Dim selection() As Integer = view.GetSelectedRows()
        If selection Is Nothing Then
            Return Nothing
        End If
        Dim count As Integer = selection.Length
        Dim result(count - 1) As String
        For i As Integer = 0 To count - 1
            result(i) = view.GetRowCellDisplayText(selection(i), view.Columns("Record-ID"))
        Next i
        Return result
    End Function
    Private Sub btnAddUser_FollowUp_Click(sender As Object, e As EventArgs) Handles btnAddUser_FollowUp.Click
        If cmbFollowUpUser.SelectedIndex <> -1 And FOLL_UP_ID > 0 Then
            Try
                Dim ins = "INSERT INTO TBPMO_FOLLUPEMAIL_RECORD (FOLLOW_UP_ID,USER_ID,RECORD_ID,ADDED_WHO) VALUES (" & FOLL_UP_ID & ", " & cmbFollowUpUser.SelectedValue & ", " & RECORD_ID & ", '" & USER_USERNAME & "')"
                If ClassDatabase.Execute_non_Query(ins) = True Then
                    Load_FUUser(FOLL_UP_ID)
                    Update_Status_Label(True, "User added to Follow Up", EditState.Insert)
                End If
            Catch ex As Exception
                ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Add User2FollowUp_Record: ", ex.Message)
            End Try
        End If
    End Sub

    Private Sub btnRemoveUser_FollowUp_Click(sender As Object, e As EventArgs) Handles btnRemoveUser_FollowUp.Click
        If ListBoxUser2Profile.SelectedIndex <> -1 Then
            Try
                Dim del = "DELETE FROM TBPMO_FOLLUPEMAIL_RECORD WHERE GUID = " & ListBoxUser2Profile.SelectedValue
                If ClassDatabase.Execute_non_Query(del, False) = True Then
                    Update_Status_Label(True, "User removed from Follow Up", EditState.Update)
                    Load_FUUser(FOLL_UP_ID)
                End If
            Catch ex As Exception
                ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Delete Userlink FollowUp: ", ex.Message)
            End Try
        End If
    End Sub
    Sub Show_Verknuepfungen()
        Dim result As MsgBoxResult
        Dim msg = "Möchten Sie den Parent-Datensatz für den aktuellen Datensatz wirklich aktualisieren?"
        If USER_LANGUAGE <> "de-DE" Then
            msg = "Would You like to change the parent-record?"
        End If
        result = MessageBox.Show(msg, "Change parent-record:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
        If result <> MsgBoxResult.Yes Then
            Exit Sub
        End If


        Dim sql
        sql = "select * from VWTEMP_PMO_FORM" & PARENT_ENTITYID.ToString
        CURRENT_PARENT_DT = ClassDatabase.Return_Datatable(sql, True)
        frmChooseParentRecord.ShowDialog()



        If CURRENT_PARENT_RECORD_ID = 0 Then
            MsgBox("No Parent-Record selected. Changing Process will be terminated", MsgBoxStyle.Exclamation)
            Exit Sub
        End If
        Dim del = "DELETE FROM TBPMO_RECORD_CONNECT WHERE RECORD2_ID = " & RECORD_ID
        If ClassDatabase.Execute_non_Query(del) = False Then
            MsgBox("Error in deleting old Record-Link. Check the logfile", MsgBoxStyle.Exclamation)
            Exit Sub
        End If
        If ClassRecordCommands.ConnectRecord(CURRENT_PARENT_RECORD_ID, RECORD_ID, "ReLInk ENTITY " & ENTITY_ID.ToString) = True Then
            'Save_GridViewParentEntityLayout()
            msg = "Die Parent-Entität wurde erfolgreich aktualisiert!"
            If USER_LANGUAGE <> "de-DE" Then
                msg = "The Parent-Record was changed successful!"
            End If
            MsgBox(msg, MsgBoxStyle.Information)
            Load_Entity_Data_Only()
        End If
    End Sub
    Private Sub DatenNeuLadenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles DatenNeuLadenToolStripMenuItem.Click
        Load_Datafor_Entity()
    End Sub
    Private Sub grvwGrid_ColumnFilterChanged(sender As Object, e As EventArgs) Handles grvwGrid.ColumnFilterChanged
        SET_ROWCOUNT_STRING()
    End Sub
    Sub SET_ROWCOUNT_STRING()
        Dim selnode As TreeNode = TreeViewMain.SelectedNode
        Dim origtext As String = selnode.Text
        If origtext.Contains(" (") Then
            Dim existingstring = origtext.Substring(0, origtext.IndexOf("(") - 1)
            selnode.Text = String.Format("{0} ({1})", existingstring, grvwGrid.RowCount)
        Else
            selnode.Text = String.Format("{0} ({1})", selnode.Text, grvwGrid.RowCount)
        End If
        Dim msg = "Anzahl Datensätze: "
        If USER_LANGUAGE <> "de-DE" Then
            msg = "number of records: "
        End If
        tslbldisplayRecords.Text = msg & grvwGrid.RowCount
    End Sub
    Public Sub New()
        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()

        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.
    End Sub

    'Private Sub AxObjectListControl_CausesValidationChanged(sender As Object, e As EventArgs) Handles AxObjectListControl.CausesValidationChanged
    '    Console.WriteLine("CausesValidationChanged")
    'End Sub

    'Private Sub AxObjectListControl_SettingFlagChanged(sender As Object, e As EventArgs) Handles AxObjectListControl.SettingFlagChanged
    '    Console.WriteLine("SettingFlagChanged")
    'End Sub

    'Private Sub AxObjectListControl_Validated(sender As Object, e As EventArgs) Handles AxObjectListControl.Validated
    '    Console.WriteLine("Validated")
    'End Sub

    Private Sub tslblLocked_VisibleChanged(sender As Object, e As EventArgs) Handles tslblLocked.VisibleChanged
        If tslblLocked.Visible = True Then
            Dim msg = "Datensatz - Nur lesenden Zugriff"
            If USER_LANGUAGE <> "de-DE" Then
                msg = "Record is read only"
            End If
            tslblLocked.Text = msg
        End If
    End Sub

    Private Sub tsmi_RecordDelete_Click(sender As Object, e As EventArgs) Handles tsmi_RecordDelete.Click
        Delete_Record()
    End Sub

    Private Sub KopierenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles docCM_Copy.Click
        If ClassWindreamDocGrid.SELECTED_DOC_PATH <> "" Then
            Try
                Dim selectedfile(0) As String

                selectedfile(0) = ClassWindreamDocGrid.SELECTED_DOC_PATH

                Dim dataobj As New DataObject

                dataobj.SetData(DataFormats.FileDrop, True, selectedfile)

                Clipboard.Clear()
                Clipboard.SetDataObject(dataobj, True)
            Catch ex As Exception
                ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Copy file:", ex.Message)
            End Try
            Cursor = Cursors.Default
        End If
    End Sub

    Private Sub GridViewDoc_Search_FocusedColumnChanged(sender As Object, e As FocusedColumnChangedEventArgs) Handles GridViewDoc_Search.FocusedColumnChanged
        GridViewDoc_Search.EndSelection()
        ClassWindreamDocGrid.GetDocItems(GridViewDoc_Search)
        Refresh_DocID()
    End Sub

    Private Sub GridViewDoc_Search_FocusedRowChanged(sender As Object, e As FocusedRowChangedEventArgs) Handles GridViewDoc_Search.FocusedRowChanged
        GridViewDoc_Search.EndSelection()
        ClassWindreamDocGrid.GetDocItems(GridViewDoc_Search)
        Refresh_DocID()
    End Sub
    Sub Refresh_DocID()
        If ClassWindreamDocGrid.SELECTED_DOC_ID <> 0 Then
            Dim msg = "Doc-ID: " & ClassWindreamDocGrid.SELECTED_DOC_ID.ToString
            tslblDocIDMain.Text = msg
            tslblDocIDTab1.Text = msg
        Else
            tslblDocIDMain.Text = "DocRow not selected"
            tslblDocIDTab1.Text = "DocRow not selected"
        End If
    End Sub

    Private Sub LöschenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles docCM_RemoveLink.Click
        If RECORD_ID = 0 Then
            ClassHelper.MSGBOX_Handler("INFO", "Attention", "Missing Selection:", "Please select a record!")
            Exit Sub
        End If
        If IsNothing(ClassWindreamDocGrid.DT_RESULTFILES) Then
            Exit Sub
        End If
        If ClassWindreamDocGrid.DT_RESULTFILES.Rows.Count > 0 Then
            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, "Confirmation:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
            If result = MsgBoxResult.Yes Then
                Try
                    For Each row As DataRow In ClassWindreamDocGrid.DT_RESULTFILES.Rows
                        Dim DT_INDICES As DataTable = ClassDatabase.Return_Datatable("SELECT * FROM TBPMO_WD_OBJECTTYPE WHERE OBJECT_TYPE = '" & row.Item("OBJECTTYPE") & "'", True)
                        If Not IsNothing(DT_INDICES) Then
                            If DT_INDICES.Rows.Count = 1 Then
                                'Record-Links entfernen
                                If clsWD_SET.REMOVE_VEKTOR_LINK(row.Item("DOC_PATH"), DT_INDICES.Rows(0).Item("IDXNAME_RECORDID"), RECORD_ID) = True Then
                                    'ENTITY-Links entfernen
                                    If clsWD_SET.REMOVE_VEKTOR_LINK(row.Item("DOC_PATH"), DT_INDICES.Rows(0).Item("IDXNAME_ENTITYID"), ENTITY_ID) = True Then
                                        If ClassFileResult.Delete_ResultFile(row.Item("DOC_ID"), RECORD_ID, 0) = True Then
                                            ClassHelper.InsertEssential_Log(row.Item("DOC_ID"), "DOC-ID", "RECORD LINK REMOVED FROM DOC-SEARCH")
                                            Cursor = Cursors.WaitCursor
                                            RUN_WDSEARCH_GRID()
                                        End If
                                    Else
                                        MsgBox("Could not remove Vektor-Link ENTITY! Check logfile.", MsgBoxStyle.Exclamation)
                                    End If
                                Else
                                    MsgBox("Could not remove Vektor-Link RECORD! Check logfile.", MsgBoxStyle.Exclamation)
                                End If
                            End If
                        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 If
    End Sub

    Private Sub EigenschaftenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles docCM_PropertiesFile.Click
        Show_File_Properties()
    End Sub
    Sub Show_File_Properties()
        If IsNothing(ClassWindreamDocGrid.DT_RESULTFILES) Then
            MsgBox("Could not read File Parameters(4)!", MsgBoxStyle.Exclamation)
            Exit Sub
        End If
        For Each row As DataRow In ClassWindreamDocGrid.DT_RESULTFILES.Rows
            If row.Item("DOC_PATH") <> "" Then
                Cursor = Cursors.WaitCursor
                Dim sei As New SHELLEXECUTEINFO
                sei.cbSize = Marshal.SizeOf(sei)
                sei.lpVerb = "properties"
                sei.lpFile = row.Item("DOC_PATH")
                sei.nShow = SW_SHOW
                sei.fMask = SEE_MASK_INVOKEIDLIST
                If Not ShellExecuteEx(sei) Then
                    Dim ex As New System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error())
                    ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Open file propertys:", ex.Message)
                End If
            End If
            Cursor = Cursors.Default
        Next
    End Sub
    Private Sub DateiÖffnenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles docCM_Open.Click
        Open_File()
    End Sub
    Private Sub GridControlDocSearch_DoubleClick(sender As Object, e As EventArgs) Handles GridControlDocSearch.DoubleClick
        Open_File()
    End Sub

    Private Sub TabWindream_Leave(sender As Object, e As EventArgs) Handles TabWindream.Leave
        Save_DocGrid_Layout()
    End Sub

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

    Private Sub tslblFileslocked_VisibleChanged(sender As Object, e As EventArgs) Handles tslblFileslocked.VisibleChanged
        If tslblFileslocked.Visible = True Then
            Dim msg = "Dateizugriffsrechte eingeschränkt"
            If USER_LANGUAGE <> "de-DE" Then
                msg = "File-accessrights limited"
            End If
            tslblFileslocked.Text = msg
        End If
    End Sub

    Private Sub tsButtonCancel_Click(sender As Object, e As EventArgs) Handles tsButtonCancel.Click
        If CtrlCommandUI.IsInsert = True Then
            If ClassHelper.DeleteRecord(SELECTED_RECORD_ID) = False Then
                Dim msg = "Der Datensatz '" & SELECTED_RECORD_ID & "' konnte nicht gelöscht werden. Überprüfen Sie das log"
                If USER_LANGUAGE <> "de-DE" Then
                    msg = "The record '" & SELECTED_RECORD_ID & "' could not be deleted. Check the log"
                End If
                MsgBox(msg, MsgBoxStyle.Exclamation)
            End If
        End If
        tsButtonCancel.Visible = False
        tsButtonAdd.Enabled = True
        CtrlCommandUI.IsInsert = False
        RECORD_CHANGED = False

        ' Den derzeitigen Record Neuladen
        Column_Row_Handler()
    End Sub

    Private Sub tsbtnRedo_Click(sender As Object, e As EventArgs) Handles tsbtnRedo.Click
        Me.Cursor = Cursors.WaitCursor
        Dim proc = String.Format("EXEC PRPMO_REDO_RECORD_CHANGES {0}", RECORD_ID)
        If ClassDatabase.Execute_non_Query_withConn(proc, 1) = True Then
            RECORD_ID = 0
            Column_Row_Handler()
            Me.Cursor = Cursors.Default
        End If

    End Sub

#Region "TrySave Funktionen"
    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()
        ' Record Speichern
        Dim ResultMessage = CtrlCommandUI.SaveRecord(SELECTED_RECORD_ID, ENTITY_ID, PARENT_RECORDID)
        ' Status anzeigen
        Update_Status_Label(True, ResultMessage)
        'Jetzt die für die Entität notwendigen Prroceduren ausführen
        Customer_Run_Procedures()
        ' RECORD_CHANGED zurücksetzen
        RECORD_CHANGED = False
    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
                        tsButtonAdd.Enabled = True
                        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
                        ClassHelper.DeleteRecord(SELECTED_RECORD_ID)
                    End If

                    ' Änderungen sollen nicht gespeichert werden
                    RECORD_CHANGED = False
                    tsButtonCancel.Visible = False
                    ' Hinzufügen Button wieder aktivieren
                    tsButtonAdd.Enabled = True

                    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 grvwGrid_CellValueChanged(sender As Object, e As CellValueChangedEventArgs) Handles grvwGrid.CellValueChanged

    End Sub

    Private Sub SucheAnzeigenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SucheAnzeigenToolStripMenuItem.Click
        grvwGrid.ShowFindPanel()
        grvwGrid.FindFilterText = ""
    End Sub

    Private Sub MassenänderungToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles MassenänderungToolStripMenuItem.Click
        Try
            Dim list As New ArrayList
            Dim collist As New ArrayList
            For i = 0 To grvwGrid.RowCount
                Dim recid = grvwGrid.GetRowCellValue(i, "Record-ID")
                If Not IsNothing(recid) Then
                    list.Add(recid)
                End If
            Next
            For Each col As DevExpress.XtraGrid.Columns.GridColumn In grvwGrid.VisibleColumns
                Dim name = col.Name
                If name.StartsWith("col") Then
                    name = name.Substring(3)
                End If
                collist.Add(name)
            Next
            MASS_COLUMN_LIST = collist
            MASS_RECORD_IDs2CHANGE = list
            CURRENT_ENTITY_ID = ENTITY_ID
            frmMass_Change.ShowDialog()
            If SUCCESSFULL = True Then
                Cursor = Cursors.WaitCursor
                Load_Datafor_Entity()
                Cursor = Cursors.Default
            End If
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in MassChange Collector:", ex.Message)
        End Try
    End Sub
    Private Sub GridViewDoc_Search_ColumnWidthChanged(sender As Object, e As ColumnEventArgs) Handles GridViewDoc_Search.ColumnWidthChanged
        Try

        Catch ex As Exception
            ClassLogger.Add(">> Unexpected Error in ColumnWidth-Change DocResult: " & ex.Message, False)
        End Try

    End Sub
    Private Sub UmbenennenToolStripMenuItem_MouseHover(sender As Object, e As EventArgs)
        Display_Filename()
    End Sub
    Sub Display_Filename()
        Try
            Dim RENAME_DOC_PATH
            Try
                RENAME_DOC_PATH = GridViewDoc_Search.GetFocusedRowCellValue(GridViewDoc_Search.Columns("FULLPATH"))
            Catch ex As Exception
                ClassLogger.Add(">> Attention: Could not set DocVariable RENAME_DOC_PATH: " & ex.Message, False)
                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 RENAME_DOC_PATH <> "" Then
                Dim FileToRename As String
                FileToRename = Path.GetFileNameWithoutExtension(RENAME_DOC_PATH)
                CMDoc_TextBoxRenameFile.Text = FileToRename
                CMDoc_TextBoxRenameFile.Enabled = True
            Else
                CMDoc_TextBoxRenameFile.Enabled = False
            End If
        Catch ex As Exception
            MsgBox("Unexpected Error in getting the filename: " & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub DateiMitDatensatzVerknüpfenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles docCM_linkRecord.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
            Refresh_Selected_Table()
            Dim frm As New frmDocLink_to_Record() 'fileName, ClassWindreamDocGrid.RESULT_OBJECTTYPE)
            frm.Show()
        Catch ex As Exception
            MsgBox("Unexpected Error in Linking Record: " & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub DetailAnsichtDatensatzToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles DetailAnsichtDatensatzToolStripMenuItem.Click
        ClassJumpRecord.JumpToRecord(0, RECORD_ID)
        JUMP_RECORD_ID = 0
    End Sub
    Private Sub GridViewDoc_Search_RowStyle(sender As Object, e As Views.Grid.RowStyleEventArgs) Handles GridViewDoc_Search.RowStyle
        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
                ClassLogger.Add(">> Unexpected Error in Checking Value In Work: " & ex.Message, False)
            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 = matchingRow.Item("COLOR")
                                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
                ClassLogger.Add(">> Unexpected Error in RowStyle-Color Dropdown: " & ex.Message, False)
            End Try

        End If
    End Sub
    Sub ContextMenu_Read()
        docCM_Open.Enabled = True
        docCM_Copy.Enabled = False
        docCM_RenameMain.Enabled = False
        docCM_InWork.Enabled = False
        docCM_linkRecord.Enabled = False
        docCM_CheckRights.Enabled = False
        docCM_DeleteFile.Enabled = False
        docCM_RemoveLink.Enabled = False
        WindreamToolStripMenuItem.Enabled = False
    End Sub
    Sub ContextMenu_Write()
        docCM_Open.Enabled = True
        docCM_Copy.Enabled = True
        docCM_RenameMain.Enabled = True
        docCM_InWork.Enabled = True
        docCM_linkRecord.Enabled = True
        docCM_CheckRights.Enabled = True
        docCM_DeleteFile.Enabled = True
        docCM_RemoveLink.Enabled = True
        WindreamToolStripMenuItem.Enabled = True
    End Sub
    Private Sub ContextMenuStripResultFiles_Opening(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles ContextMenuStripResultFiles.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
            GridViewDoc_Search.EndSelection()
            ClassWindreamDocGrid.GetDocItems(GridViewDoc_Search)
            If IsNothing(ClassWindreamDocGrid.DT_RESULTFILES) Then
                e.Cancel = True
            End If
            Refresh_DocID()
            If ClassWindreamDocGrid.DT_RESULTFILES.Rows.Count = 1 Then
                If ClassWindreamDocGrid.DT_RESULTFILES.Rows(0).Item("DOC_ID") = 0 Then
                    e.Cancel = True
                End If
            End If
            File_in_Work()
            Dim Result = clsWD_GET.Get_File_Rights(ClassWindreamDocGrid.SELECTED_DOC_PATH, USER_USERNAME)
            If Not IsNothing(Result) Then
                ROW_READ_ONLY = False
                Select Case Result.ToString
                    Case "R"
                        ContextMenu_Read()
                        ROW_READ_ONLY = True
                    Case "RW"
                        ContextMenu_Write()
                    Case "RWA"
                        ContextMenu_Write()
                    Case ""
                        ContextMenu_Read()
                        ROW_READ_ONLY = True
                End Select
            Else
                ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Getting rights - check the log")
                e.Cancel = True
            End If
            If ROW_READ_ONLY = False Then
                If RIGHT_READ_ONLY_DOC = True Then
                    ContextMenu_Read()
                End If
            End If
            If ClassWindreamDocGrid.DT_RESULTFILES.Rows.Count = 1 Then
                If ClassWindreamDocGrid.DT_RESULTFILES.Rows(0).Item("DISPLAYNAME") <> "" Then
                    docCM_RenameMain.Visible = True
                    Set_Displayname()
                Else
                    docCM_RenameMain.Visible = False
                End If
            Else
                docCM_RenameMain.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 File_in_Work()
        docCM_InWork.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
                IW_USER = foundRowsLevel0(0)("IN_WORK_USER")
                IW_COMMENT = foundRowsLevel0(0)("IN_WORK_COMMENT")
            Catch ex As Exception
                IW_USER = ""
                IW_COMMENT = ""
            End Try



            Dim displ As String

            If CBool(ClassWindreamDocGrid.SELECTED_INWORK) = True Then
                If IW_USER.ToUpper = USER_USERNAME.ToUpper Or USER_IS_ADMIN 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
            docCM_InWork.Text = displ
        Catch ex As Exception
            ClassLogger.Add(">> Unexpected Error in File-Work Info: " & ex.Message, False)
            docCM_InWork.Enabled = False
        End Try
    End Sub
    Private Sub TSMI_inWork_Click(sender As Object, e As EventArgs) Handles docCM_InWork.Click
        If IsNothing(ClassWindreamDocGrid.DT_RESULTFILES) Then
            MsgBox("Could not read File Parameters (3)!", MsgBoxStyle.Exclamation)
            Exit Sub
        End If
        ClassFileResult.DocID = ClassWindreamDocGrid.SELECTED_DOC_ID
        If ClassWindreamDocGrid.SELECTED_INWORK = 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 Then
                If ClassFileResult.Set_InWork(0, "") = True Then
                    RUN_WDSEARCH_GRID()
                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
            RUN_WDSEARCH_GRID()
        End If
    End Sub
    Private Sub AnsichtZurücksetzenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles docCM_ResetView.Click
        ' TODO: Ansicht zurücksetzen
        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()
                RUN_WDSEARCH_GRID()

            Else
                MsgBox("Set back of Layout not successfull - File not existing!", MsgBoxStyle.Information)
            End If
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Reset Layout DocGrid: ", ex.Message)
        End Try
        Me.Cursor = Cursors.Default
    End Sub
    Sub Set_Displayname()
        Try
            If ClassWindreamDocGrid.DT_RESULTFILES.Rows.Count = 1 Then
                If ClassWindreamDocGrid.DT_RESULTFILES.Rows(0).Item("DISPLAYNAME") <> "" Then
                    CMDoc_TextBoxRenameDisplay.Text = ClassWindreamDocGrid.DT_RESULTFILES.Rows(0).Item("DISPLAYNAME")
                    CMDoc_TextBoxRenameDisplay.Enabled = True
                End If
            Else
                CMDoc_TextBoxRenameDisplay.Enabled = False
            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 Sub TestToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles docCM_CheckRights.Click
        Dim msg = "Die Rechte wurden erfolgreich überprüft und aktualisiert!"
        CURRENT_RECORD_ID = RECORD_ID
        If IsNothing(ClassWindreamDocGrid.DT_RESULTFILES) Then
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Could not read file Parameters: ", "Could not read file Parameters (6)")
            Exit Sub
        End If
        Dim err As Boolean = False
        Cursor = Cursors.WaitCursor
        For Each row As DataRow In ClassWindreamDocGrid.DT_RESULTFILES.Rows
            If ClassDOC_SEARCH.SET_WD_RIGHTS(row.Item("DOC_ID"), row.Item("DOC_PATH")) = True Then

            Else
                err = True
                msg = String.Format("Datei '" & vbNewLine & "{0}'" & vbNewLine & "Bitte prüfen Sie die Logdatei!", row.Item("DOC_PATH"))
                If USER_LANGUAGE <> "de-DE" Then
                    msg = String.Format("file '" & vbNewLine & "{0}'" & vbNewLine & "Please check the logfile!", row.Item("DOC_PATH"))
                End If
                ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error Rights module", "Error while setting rights: (Scroll down) ", msg)
            End If
            'Create Session um Fehler bei windows Session icht zu erzeugen
            FAU_AD_USER = ""
            clsWindream.Create_Session()
        Next
        Cursor = Cursors.Default
        If err = False Then
            If USER_LANGUAGE <> "de-DE" Then
                msg = "The rights were successfully renewed!"
            End If
            MsgBox(msg, MsgBoxStyle.Information)
        End If

    End Sub

    Public Sub ActivateAllTabs()
        ' Alle Tabs aktivieren
        For Each tab As DevExpress.XtraTab.XtraTabPage In TCDetails.TabPages
            If (tab.Name <> "TabDetails") Then
                tab.PageEnabled = True
            End If
        Next
    End Sub

    Public Sub DeactivateTabs()
        ' Alle Tab Pages außer Detailansicht deaktivieren
        ' Zur Detailansicht springen
        For Each tab As DevExpress.XtraTab.XtraTabPage In TCDetails.TabPages
            If (tab.Name <> "TabDetails") And tab.Name <> "TabWindream" And tab.Name <> "TabPos" Then
                tab.PageEnabled = False
            Else
                TCDetails.SelectedTabPage = tab
            End If
        Next
    End Sub

    Private Sub TCDetails_SelectedPageChanging(sender As Object, e As DevExpress.XtraTab.TabPageChangingEventArgs) Handles TCDetails.SelectedPageChanging
        If EDIT_STATE = EditState.Insert Or EDIT_STATE = EditState.Update Then
            If Save_Record() = False Then
                e.Cancel = True
            End If
        End If

    End Sub

    Private Sub ToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles docCM_DeleteFile.Click
        If RECORD_ID = 0 And CURRENT_SEARCH_TYPE <> "ENTITY" Then
            MsgBox("Please select a record!", MsgBoxStyle.Exclamation)
            Exit Sub
        End If
        If IsNothing(ClassWindreamDocGrid.DT_RESULTFILES) Then
            MsgBox("Could not read File Parameters (DELETE FILES)!", MsgBoxStyle.Exclamation)
            Exit Sub
        End If
        If ClassWindreamDocGrid.DT_RESULTFILES.Rows.Count = 0 Then
            MsgBox("Please choose a file!", MsgBoxStyle.Exclamation)
            Exit Sub
        End If
        Dim msg = "Sind Sie sicher, dass Sie die Datei(en) endgültig löschen wollen?"
        If USER_LANGUAGE <> "de-DE" Then
            msg = "Are You sure You want to permanently delete this file(s)?"
        End If
        Dim result1 As MsgBoxResult
        result1 = MessageBox.Show(msg, "Confirmation:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
        If result1 = MsgBoxResult.Yes Then
            For Each row As DataRow In ClassWindreamDocGrid.DT_RESULTFILES.Rows
                If row.Item("DOC_PATH") <> "" Then
                    Try
                        If Not IsNothing(row.Item("DOC_ID")) Then
                            Dim Count As Integer = ClassDatabase.Execute_Scalar("SELECT COUNT(GUID) FROM TBPMO_DOC_RECORD_LINK WHERE DOC_ID = " & row.Item("DOC_ID"), True)
                            If Count > 1 And CURRENT_SEARCH_TYPE = "RECORD" Then
                                msg = "Diese Datei ist noch mit anderen Datensätzen verknüpft! Lediglich die Verknüpfung zum aktuellen Datensatz wird gelöscht!"
                                If USER_LANGUAGE <> "de-DE" Then
                                    msg = "This file is also linked to other records! Only the link for this Record will be deleted!"
                                End If
                                MsgBox(msg, MsgBoxStyle.Information)
                                If ClassFileResult.Delete_ResultFile(row.Item("DOC_ID"), RECORD_ID, 0) = True Then
                                    ClassHelper.InsertEssential_Log(row.Item("DOC_ID"), "DOC-ID", "FILE LINK DELETED BY USER")
                                End If
                            Else
                                If CURRENT_SEARCH_TYPE = "FULLTEXT" Or CURRENT_SEARCH_TYPE = "ENTITY" Then
                                    RECORD_ID = 0
                                End If
                                If ClassFileResult.Delete_ResultFile(row.Item("DOC_ID"), RECORD_ID, 1) = True Then
                                    If clsWD_SET.Delete_WDFile(row.Item("DOC_PATH")) = True Then
                                        ClassHelper.InsertEssential_Log(row.Item("DOC_ID"), "DOC-ID", "FILE DELETED BY USER")
                                    End If

                                Else
                                    msg = String.Format("Die Datei {0} konnte nicht gelöscht werden! Prüfen Sie die logfile!", row.Item("DOC_PATH"))
                                    If USER_LANGUAGE <> "de-DE" Then
                                        msg = String.Format("The file {0} could not be deleted! Check the logfile!", row.Item("DOC_PATH"))
                                    End If
                                    MsgBox(msg, MsgBoxStyle.Critical, "Attention:")

                                End If
                            End If

                        End If
                        If LICENSE_SITE_PROXY = True And DD_LIB_Standards.clsDatabase.DB_PROXY_INITIALIZED Then
                            Dim proc = String.Format("EXEC PRPROXY_DOC_CHECK_DELETE {0}", row.Item("DOC_ID"))
                            ClassDatabase.Execute_non_Query(proc, True)
                        End If
                    Catch ex As Exception
                        ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in delete file: ", ex.Message)
                    End Try

                End If
            Next
            If CURRENT_SEARCH_TYPE = "ENTITY" Then
                CURRENT_DT_DOC_ENTITY_SEARCH = Nothing
            End If
            RUN_WDSEARCH_GRID()
        End If



    End Sub

    Private Sub TreeViewMain_DragDrop(sender As Object, e As DragEventArgs) Handles TreeViewMain.DragDrop
        Try
            If Not IsNothing(e.Data) Then
                Me.Cursor = Cursors.WaitCursor
                Dim pt As Point
                Dim DestinationNode As TreeNode
                pt = CType(sender, TreeView).PointToClient(New Point(e.X, e.Y))
                DestinationNode = CType(sender, TreeView).GetNodeAt(pt)
                Dim node_tag
                Dim ENTITY_STRING
                Dim sql
                If Not IsNothing(DestinationNode) Then
                    node_tag = DestinationNode.Tag
                    If Not IsNumeric(node_tag) Then
                        MsgBox("Could not get a valid Entity!", MsgBoxStyle.Exclamation)
                        Me.Cursor = Cursors.Default
                        Exit Sub
                    End If
                    sql = String.Format("SELECT [dbo].[FNPMO_GETOBJECTCAPTION]('{0}','FORMVIEW_TITLE' + CONVERT(VARCHAR(5), FORM_VIEW_ID), {1}) AS 'CAPTION' " & _
                            "FROM VWPMO_CONSTRUCTOR_FORMS WHERE FORM_ID = {2}", USER_LANGUAGE, CURRENT_SCREEN_ID, node_tag.ToString)
                    ENTITY_STRING = ClassDatabase.Execute_Scalar(sql)
                    sql = String.Format("select count(guid) from TBPMO_CONTROL_ENTITY_LINK where ORIGIN_CTRL_ID in (SELECT GUID FROM TBPMO_CONTROL where FORM_ID = {0}) " & _
                    "AND LINKED_CTRL_ID IN (SELECT GUID FROM TBPMO_CONTROL where FORM_ID = {1})", ENTITY_ID, node_tag)
                    Dim count = ClassDatabase.Execute_Scalar(sql)
                    If Not IsNothing(count) Then
                        If count = 0 Then
                            MsgBox("No configuration for changing entity-link!" & vbNewLine & "Please inform Your ADDi-Admin", MsgBoxStyle.Exclamation)
                            Me.Cursor = Cursors.Default
                            Exit Sub
                        End If
                    End If
                    Dim msg As String = String.Format("Wollen Sie die ausgewählten Zeilen wirklich der Entität '{0}'zuordnen?", ENTITY_STRING.ToString)
                    If USER_LANGUAGE <> "de-DE" Then
                        msg = String.Format("Do You really want to change the entity-link of the selected record to '{0}'?", ENTITY_STRING.ToString)
                    End If
                    Dim result As MsgBoxResult
                    result = MessageBox.Show(msg, "Confirmation:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                    If result = MsgBoxResult.Yes Then
                        For Each _RECORD As String In e.Data.GetData(GetType(String()))
                            Dim upd = String.Format("UPDATE TBPMO_RECORD SET FORM_ID = {0} where GUID = {1}", node_tag, _RECORD)
                            If ClassDatabase.Execute_non_Query(upd) = True Then
                                msg = String.Format("ENTITY WAS CHANGED TO {0}-{1} by User: {2}", ENTITY_STRING, node_tag, USER_USERNAME)
                                ClassHelper.InsertEssential_Log(_RECORD, "RECORD-ID", msg)
                                sql = "SELECT T.* FROM VWPMO_DOC_SEARCH T, TBPMO_DOC_RECORD_LINK T1  WHERE T.DocID = T1.DOC_ID AND T1.RECORD_ID = " & _RECORD
                                Dim DT_DOCS As DataTable = ClassDatabase.Return_Datatable(sql, True)
                                For Each doc As DataRow In DT_DOCS.Rows
                                    Dim DT_INDICES As DataTable = ClassDatabase.Return_Datatable("SELECT * FROM TBPMO_WD_OBJECTTYPE WHERE OBJECT_TYPE = '" & doc.Item("OBJECTTYPE") & "'", True)
                                    clsWD_SET.REMOVE_VEKTOR_LINK(doc.Item("FULL_FILENAME"), DT_INDICES.Rows(0).Item("IDXNAME_ENTITYID"), ENTITY_ID)
                                Next

                                sql = String.Format("select ORIGIN_CTRL_ID,LINKED_CTRL_ID from TBPMO_CONTROL_ENTITY_LINK where ORIGIN_CTRL_ID in (SELECT GUID FROM TBPMO_CONTROL where FORM_ID = {0}) " & _
                                    "AND LINKED_CTRL_ID IN (SELECT GUID FROM TBPMO_CONTROL where FORM_ID = {1})", ENTITY_ID, node_tag)
                                Dim DT_CHANGE_CTR As DataTable = ClassDatabase.Return_Datatable(sql)
                                For Each row As DataRow In DT_CHANGE_CTR.Rows
                                    upd = String.Format("UPDATE TBPMO_CONTROL_VALUE SET CONTROL_ID = {0}, CHANGED_WHO = '{3}' WHERE CONTROL_ID = {1} AND RECORD_ID = {2}", row.Item("LINKED_CTRL_ID"), row.Item("ORIGIN_CTRL_ID"), _RECORD, USER_USERNAME)
                                    ClassDatabase.Execute_non_Query(upd)
                                Next
                            End If
                        Next
                        msg = String.Format("Der Datensatz wurde erfolgreich auf die Entität {0} verlinked!", ENTITY_STRING.ToString)
                        If USER_LANGUAGE <> "de-DE" Then
                            msg = String.Format("The record was successfully relinked with entity {0}", ENTITY_STRING.ToString)
                        End If
                        MsgBox(msg, MsgBoxStyle.Information)
                        Load_Datafor_Entity()
                    End If
                End If
            End If
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in DragDrop TreeView: ", ex.Message)
        End Try
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub TreeViewMain_DragOver(sender As Object, e As DragEventArgs) Handles TreeViewMain.DragOver
        e.Effect = DragDropEffects.Copy
    End Sub

    Private Sub AuswertungAnzeigenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AuswertungAnzeigenToolStripMenuItem.Click
        Dim frm As New frmDiagrams()
        'frm.MdiParent = MAIN_FORM
        frm.Show()
    End Sub

    Private Sub SucheAnzeigenToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles docCM_showGridSearch.Click
        GridViewDoc_Search.ShowFindPanel()
    End Sub
    Private Sub GridViewDoc_Search_ColumnFilterChanged(sender As Object, e As EventArgs) Handles GridViewDoc_Search.ColumnFilterChanged
        Try
            Dim origtext As String = tslblWindreamView.Text
            If origtext.Contains(" (") Then
                Dim existingstring = origtext.Substring(0, origtext.IndexOf("(") - 1)
                tslblWindreamView.Text = String.Format("{0} ({1})", existingstring, GridViewDoc_Search.RowCount)
            Else
                tslblWindreamView.Text = String.Format("{0} ({1})", tslblWindreamView.Text, GridViewDoc_Search.RowCount)
            End If
        Catch ex As Exception

        End Try
    End Sub
    Private Sub DateirechteFürUserToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles docCM_GetRights.Click
        Dim result = clsWD_GET.Get_File_Rights(ClassWindreamDocGrid.SELECTED_DOC_PATH, USER_USERNAME)
        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 CreateWorkflowtaskstsbtn_Click(sender As Object, e As EventArgs) Handles CreateWorkflowtaskstsmi.Click
        Dim result As MsgBoxResult
        Dim stg, caption As String
        If USER_LANGUAGE = "de-DE" Then
            stg = "Wollen Sie die Workflowtasks für diesen Datensatz erzeugen? Alte Workflows werden gelöscht!"
            caption = "Bestätigung erforderlich:"
        Else
            stg = "Do You really want to create workflowtasks for this record? Existing workflows will be deleted!"
            caption = "Confirmation needed:"
        End If
        result = MessageBox.Show(stg, caption, MessageBoxButtons.YesNo, MessageBoxIcon.Question)
        If result = MsgBoxResult.Yes Then
            Try
                CURRENT_ENTITY_ID = ENTITY_ID
                Dim sql = "EXEC	PRPMO_CREATE_WF_TASKS " & CURRENT_ENTITY_ID & ", " & RECORD_ID
                If ClassDatabase.Execute_non_Query(sql) = True Then
                    ' VWPMO_WF_ACTIVETableAdapter.Fill(Me.DD_DMSDataSet.VWPMO_WF_ACTIVE, USER_LANGUAGE, USER_USERNAME)
                    Show_act_WFTask()
                    If USER_LANGUAGE = "de-DE" Then
                        stg = "Workflows erzeugt! Wollen Sie die Workflowübersicht nun anzeigen?"
                        caption = "Erfolgreich:"
                    Else
                        stg = "Workflows created! Would You like to show the Workflow-Overview?"
                        caption = "Success:"
                    End If
                    result = MessageBox.Show(stg, caption, MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                    If result = MsgBoxResult.Yes Then
                        ClassJumpRecord.JumpToRecord(2, RECORD_ID)
                        JUMP_RECORD_ID = 0
                    End If
                Else
                    If USER_LANGUAGE = "de-DE" Then
                        stg = "Die Workflows konnten nicht erzeugt werden. Bitte prüfen Sie die Log-Datei!"
                    Else
                        stg = "Error in Creating Workflow-Tasks. Please check the logfile!"
                    End If
                    MsgBox(stg, MsgBoxStyle.Exclamation)
                End If
            Catch ex As Exception
                ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error inCreate Workflowtasks Record: ", ex.Message)
            End Try
        End If
    End Sub

    Private Sub ChangeParentLinktsbtn_Click(sender As Object, e As EventArgs) Handles ChangeParentLinktsmi.Click
        Show_Verknuepfungen()
    End Sub

    Private Sub CopyRecordtsbtn_Click(sender As Object, e As EventArgs) Handles CopyRecordtsmi.Click
        Dim msg As String
        If RIGHT_RECORD_AND_FILE_READ_ONLY = False Then
            Dim result As MsgBoxResult
            msg = "Möchten Sie den Datensatz wirklich kopieren?"
            If USER_LANGUAGE <> "de-DE" Then
                msg = "Would You like to copy the record?"
            End If
            result = MessageBox.Show(msg, "Copy Record:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
            If result = MsgBoxResult.Yes Then
                Dim SQL = String.Format("EXEC PRDD_COPY_RECORD {0}, '{1}'", RECORD_ID, USER_USERNAME)
                If ClassDatabase.Execute_non_Query_withConn(SQL, 1) = True Then
                    Load_Entity_Data(ACT_EBENE)
                End If
            End If
        Else
            msg = "Sie dürfen diesen Datensatz nicht löschen! (Rechtekonzept)!"
            If USER_LANGUAGE <> "de-DE" Then
                msg = "Due to right-privileges You are not allowed to delete this record!"
            End If
            MessageBox.Show(msg, "Warning:", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If

    End Sub

    Private Sub showRecordLogtsbtn_Click(sender As Object, e As EventArgs) Handles showRecordLogtsmi.Click
        CURRENT_RECORD_ID = RECORD_ID
        frmRecord_Changes.ShowDialog()
    End Sub
    Private Sub AnwendungscacheResettsbtn_Click(sender As Object, e As EventArgs) Handles AnwendungscacheResettsmi.Click
        Dim result As MsgBoxResult
        Dim msg = "Möchten Sie den Anwendungscache wirklich leeren?" & vbNewLine & "Die Entität wird dann automatisch neugeladen!"
        If USER_LANGUAGE <> "de-DE" Then
            msg = "Would You like to clear the applications-cache?" & vbNewLine & "All data will be loaded new!"
        End If
        result = MessageBox.Show(msg, "Clear cache:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
        If result = MsgBoxResult.Yes Then
            Try
                Cursor = Cursors.WaitCursor
                CURRENT_ENTITY_ID = ENTITY_ID
                ClassControlValueCache.ClearCache()
                DisableEditMode()
                Load_Entity_Data(ACT_EBENE)
                RECORD_CHANGED = False
            Catch ex As Exception
                ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Clear Cache: ", ex.Message)
            Finally
                Cursor = Cursors.Default
            End Try
        End If
    End Sub

    Private Sub OfficeVorlagenToolStripMenuItem_Click(sender As Object, e As EventArgs)

    End Sub

    Private Sub NewVarianttsmi_Click(sender As Object, e As EventArgs) Handles NewVarianttsmi.Click
        Dim msg As String
        If RIGHT_RECORD_AND_FILE_READ_ONLY = False Then
            CURRENT_ENTITY_ID = ENTITY_ID
            CURRENT_RECORD_ID = RECORD_ID
            Dim recid = CURRENT_RECORD_ID
            frmNewVariant.ShowDialog()
            If recid <> CURRENT_RECORD_ID Then
                Me.Cursor = Cursors.WaitCursor
                ClassProxy.PRPROXY_SYNC_DETAIL_OBJECT("TBPMO_RECORD_VARIANT")
                ClassProxy.PRPROXY_SYNC_DETAIL_OBJECT("TBPMO_RECORD")
                Me.Cursor = Cursors.Default
                Load_Datafor_Entity()
                LocateRecordById(CURRENT_RECORD_ID)
            End If
        Else
            msg = "Sie dürfen diesen Datensatz nicht löschen! (Rechtekonzept)!"
            If USER_LANGUAGE <> "de-DE" Then
                msg = "Due to right-privileges You are not allowed to delete this record!"
            End If
            MessageBox.Show(msg, "Warning:", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If

    End Sub

    Private Sub tsbtnRefresh_Entity_Click(sender As Object, e As EventArgs) Handles tsbtnRefresh_Entity.Click
        Refresh_Entity_Data()
    End Sub

    Private Sub RecordDeleteToolStripMenuItem_Click(sender As Object, e As EventArgs)
        Delete_Record()
    End Sub
    Private Sub docCMEntityWideSearch_Click(sender As Object, e As EventArgs) Handles docCMEntityWideSearch.Click
        CURRENT_SEARCH_TYPE = "ENTITY"
        RUN_WDSEARCH_GRID()
    End Sub

    Private Sub tsbtnDoc_Refresh_Click(sender As Object, e As EventArgs) Handles tsbtnDoc_Refresh.Click
        RUN_WDSEARCH_GRID()
    End Sub

    Private Sub Load_Variants()
        Try
            If LICENSE_SITE_PROXY = True And DD_LIB_Standards.clsDatabase.DB_PROXY_INITIALIZED Then
                Me.TBPMO_RECORD_VARIANTTableAdapter.Connection.ConnectionString = ClassProxy.MyPROXYConnectionString
            Else
                Me.TBPMO_RECORD_VARIANTTableAdapter.Connection.ConnectionString = MyConnectionString
            End If
            Me.TBPMO_RECORD_VARIANTTableAdapter.Fill(Me.DD_DMSDataSet.TBPMO_RECORD_VARIANT, ENTITY_ID, RECORD_ID)
        Catch ex As System.Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error while loading variants: ", ex.Message)
        End Try

    End Sub

    Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs) Handles ToolStripButton1.Click
        Load_Variants()
    End Sub

    Private Sub tsbtnVariantDetailView_Click(sender As Object, e As EventArgs) Handles tsbtnVariantDetailView.Click

        Load_Variant_Record()
    End Sub
    Sub Load_Variant_Record()
        Try
            Dim RECORD_ID = GridViewVariants.GetFocusedRowCellValue(GridViewVariants.Columns("RECORD_ID"))
            If Not IsNothing(RECORD_ID) Then
                ClassJumpRecord.JumpToRecord(0, RECORD_ID)
            End If
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Show_Detail_Record: ", ex.Message)
        End Try
        JUMP_RECORD_ID = 0
    End Sub
    Private Sub ToolStripButton2_Click(sender As Object, e As EventArgs) Handles tsbtnGeodata.Click
        ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Show_Detail_Record: ", "dsdfsdfdsfdsf")
        Dim frm As New frmGeodataNavigation(GridControlMain, CURRENT_ENTITY_ID)
        frm.Show()
    End Sub

    Private Sub GridControl1_DoubleClick(sender As Object, e As EventArgs) Handles GridControl1.DoubleClick
        Load_Variant_Record()
    End Sub

    Private Sub ChangeHidepanelToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ChangeHidepanelToolStripMenuItem.Click
        If SplitContainerDetails.CollapsePanel = SplitCollapsePanel.Panel1 Then
            SplitContainerDetails.CollapsePanel = SplitCollapsePanel.Panel2
        Else
            SplitContainerDetails.CollapsePanel = SplitCollapsePanel.Panel1
        End If

    End Sub

    Private Sub tsbtnPanel1Collapse_Click(sender As Object, e As EventArgs) Handles tsbtnPanel1Collapse.Click
        Collapse_Details()
    End Sub
    Sub Collapse_Details()
        If SplitContainerDetails.Collapsed = False Then
            SplitContainerDetails.CollapsePanel = SplitCollapsePanel.Panel1
            SplitContainerDetails.Collapsed = True
            Dim msg = "Detailbereich 'ausklappen'"
            If USER_LANGUAGE <> "de-DE" Then
                msg = "Maximize details"
            End If
            tsbtnPanel1Collapse.Text = msg
            tsbtnPanel1Collapse.Image = My.Resources.arrow_Forward_16xLG
        Else
            SplitContainerDetails.CollapsePanel = SplitCollapsePanel.Panel2
            SplitContainerDetails.Collapsed = False
            Dim msg = "Detailbereich 'einklappen'"
            If USER_LANGUAGE <> "de-DE" Then
                msg = "Collapse details"
            End If
            tsbtnPanel1Collapse.Text = msg
            tsbtnPanel1Collapse.Image = My.Resources.arrow_left
        End If
    End Sub
    Private Sub CMSEntity_Opening(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles cmsTreeView.Opening
        tsmiNodeDelete.Visible = False
        Dim control = Me.ActiveControl
        If Not IsNothing(control) Then
            If control.Name <> TreeViewMain.Name Then
                e.Cancel = True
            End If
            If CURRENT_NODE_CONFIGURABLE_ID <> 0 Then
                tsmi_NewNode.Visible = True
            Else
                tsmi_NewNode.Visible = False
            End If
            If Not IsNothing(TreeViewMain.SelectedNode) Then
                Dim nodetag = TreeViewMain.SelectedNode.Tag.ToString
                Console.WriteLine(nodetag)
                If nodetag.StartsWith("CONFIG_NODE") Then
                    tsmiNodeDelete.Visible = True
                End If
            End If
        End If
    End Sub
    Private Function FindFocussedControl(ByVal ctr As Control) As Control
        Dim container As ContainerControl = TryCast(ctr, ContainerControl)
        Do While (container IsNot Nothing)
            ctr = container.ActiveControl
            container = TryCast(ctr, ContainerControl)
        Loop
        Return ctr
    End Function

    Private Sub DateiVersionierenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles DateiVersionierenToolStripMenuItem.Click
        Refresh_Selected_Table()
        frmWD_CreateVersion.ShowDialog()
        RUN_WDSEARCH_GRID()
    End Sub
    Sub Refresh_Selected_Table()
        Dim table As New DataTable
        table.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 row As DataRow In ClassWindreamDocGrid.DT_RESULTFILES.Rows
            If row.Item("DOC_PATH") <> String.Empty Then
                'Set the ID column as the primary key column.
                Dim newRow As DataRow = table.NewRow()
                newRow("FILEPATH") = row.Item("DOC_PATH")
                newRow("DOC_ID") = row.Item("DOC_ID")
                newRow("OBJECTTYPE") = row.Item("OBJECTTYPE")
                table.Rows.Add(newRow)
            End If
        Next
        table.AcceptChanges()
        CURRENT_DT_SELECTED_FILES = table
    End Sub
    Private Sub DokumentartÄndernToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles DokumentartÄndernToolStripMenuItem.Click
        CURRENT_FORMVIEW_ID = FORMVIEW_ID
        Refresh_Selected_Table()
        frmWD_ChangeDoctype.ShowDialog()
        RUN_WDSEARCH_GRID()
    End Sub
    Private Sub NeuToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles NeuToolStripMenuItem.Click
        Display_Filename()
    End Sub

    Private Sub NeuToolStripMenuItem_MouseHover(sender As Object, e As EventArgs) Handles NeuToolStripMenuItem.MouseHover
        Display_Filename()
    End Sub

    Private Sub CMDoc_TextBoxRenameFile_KeyUp(sender As Object, e As KeyEventArgs) Handles CMDoc_TextBoxRenameFile.KeyUp
        If e.KeyCode = Keys.Return Then
            Try
                If CMDoc_TextBoxRenameFile.Text <> "" Then
                    Dim OldName, NewName, OnlyFilename As String
                    OldName = ClassWindreamDocGrid.SELECTED_DOC_PATH
                    ' Define file names.
                    NewName = CMDoc_TextBoxRenameFile.Text
                    OnlyFilename = NewName
                    Dim name1 = Path.Combine(Path.GetDirectoryName(ClassWindreamDocGrid.SELECTED_DOC_PATH), NewName)
                    NewName = NewName & Path.GetExtension(ClassWindreamDocGrid.SELECTED_DOC_PATH)
                    OnlyFilename &= Path.GetExtension(ClassWindreamDocGrid.SELECTED_DOC_PATH)
                    ' Rename file.
                    My.Computer.FileSystem.RenameFile(OldName, NewName)
                    Cursor = Cursors.WaitCursor
                    Dim upd = String.Format("UPDATE TBPMO_DOCRESULT_LIST SET Filename = '{0}', FULL_FILENAME = '{1}', CHANGED_WHO = '{2}', CHANGED_WHEN = GETDATE() WHERE DocID = {3}", _
                                               OnlyFilename, NewName, USER_USERNAME, ClassWindreamDocGrid.SELECTED_DOC_ID)
                    If DD_LIB_Standards.clsDatabase.Execute_non_Query(upd) Then
                        If LICENSE_SITE_PROXY = True And DD_LIB_Standards.clsDatabase.DB_PROXY_INITIALIZED Then
                            ClassDatabase.Execute_non_Query(upd, True)
                        End If
                    End If
                    Cursor = Cursors.Default
                    RUN_WDSEARCH_GRID()
                    ContextMenuStripResultFiles.Close()
                End If
            Catch ex As Exception
                ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Renaming files:", ex.Message)
            End Try
        End If
    End Sub

    Private Sub DisplaynameUmbenennenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles DisplaynameUmbenennenToolStripMenuItem.Click
        Set_Displayname()
    End Sub

    Private Sub DisplaynameUmbenennenToolStripMenuItem_MouseHover(sender As Object, e As EventArgs) Handles DisplaynameUmbenennenToolStripMenuItem.MouseHover
        Set_Displayname()
    End Sub

    Private Sub SToolStripMenuItem_KeyUp(sender As Object, e As KeyEventArgs) Handles CMDoc_TextBoxRenameDisplay.KeyUp
        If e.KeyCode = Keys.Return Then
            Try
                ClassFileResult.DocID = ClassWindreamDocGrid.SELECTED_DOC_ID
                If CMDoc_TextBoxRenameDisplay.Text <> "" Then
                    If ClassFileResult.Set_Displayname(CMDoc_TextBoxRenameDisplay.Text) Then
                        Cursor = Cursors.WaitCursor
                        RUN_WDSEARCH_GRID()
                        ContextMenuStripResultFiles.Close()
                    End If
                End If
            Catch ex As Exception
                ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Unexpected Error in  Setting Displayname Click: ", ex.Message)
            End Try
        End If
    End Sub

    Private Sub DateienDiesemUndToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles tsmiNodedownSearch.Click
        CURRENT_SEARCH_TYPE = "NODE_DOWN"
        RUN_WDSEARCH_GRID()
    End Sub

    Private Sub EnitätssucheToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles tsmientitySearch.Click
        CURRENT_SEARCH_TYPE = "ENTITY"
        RUN_WDSEARCH_GRID()
    End Sub

    Private Sub OberhalbToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OberhalbToolStripMenuItem.Click
        ADD_NODE("HERE")
    End Sub

    Private Sub ADD_NODE(where As String)
        Try
            If tsmINewText.Text = String.Empty Then
                MsgBox("Please type a nodetext!", MsgBoxStyle.Critical)
                tsmINewText.BackColor = Color.Red
                Exit Sub
            End If

            Dim PARENT_ID

            Dim expression As String
            expression = "ENTITY_ID = " & ENTITY_ID & " AND GUID = " & CURRENT_NODE_CONFIGURABLE_ID
            Dim foundRowsLevel0() As DataRow
            ' Use the Select method to find all rows matching the filter.
            foundRowsLevel0 = CURRENT_DT_NODE_CONFIGURABLE_NODES.Select(expression)
            Dim i As Integer
            Dim RECORD_CREATE As Boolean
            ' For each row create a Node
            For i = 0 To foundRowsLevel0.GetUpperBound(0)
                RECORD_CREATE = foundRowsLevel0(i)("CREATE_RECORD")
            Next
            If where = "HERE" Then
                PARENT_ID = ClassNodeNavigation.Return_NODEID_forTag(TreeViewMain.SelectedNode.Parent.Tag)
            ElseIf where = "BELOW" Then
                PARENT_ID = ClassNodeNavigation.Return_NODEID_forTag(TreeViewMain.SelectedNode.Tag)
            End If


            Dim NEWRECORD As Integer
            If RECORD_CREATE = True Then
                ClassRecordCommands.CreateRecord(ENTITY_ID)
                Try
                    NEWRECORD = ClassRecordCommands.GetLastRecord(ENTITY_ID)
                Catch ex As Exception
                    Dim SQL = "SELECT (MAX(GUID)) FROM TBPMO_RECORD where PARENT_RECORD = 0 AND ADDED_WHO = '" & USER_USERNAME & "'"
                    NEWRECORD = ClassDatabase.Execute_Scalar(SQL)
                End Try
            End If

            'Dim NEWRECORD As Integer = ClassControlCommandsUI.GetLastRecord(ENTITY_ID)
            Dim NEWNODE = New TreeNode(tsmINewText.Text)
            If Not IsNothing(NEWRECORD) Then
                ClassProxy.PRPROXY_RECORD_UPD_INS(ENTITY_ID, NEWRECORD)

                If Not IsNothing(CURRENT_NODE_CONFIGURABLE_ID) And CURRENT_NODE_CONFIGURABLE_ID > 0 Then
                    Dim index As Integer = 0
                    For Each img As String In TREEVIEW_IMAGELIST.Images.Keys
                        If img = CURRENT_NODE_CONFIGURABLE_ID.ToString & "#" & ENTITY_ID Then
                            Exit For
                        End If
                        index += 1
                    Next
                    NEWNODE.ImageIndex = index
                    NEWNODE.SelectedImageIndex = index
                End If
                Dim ins
                If RECORD_CREATE Then
                    ins = String.Format("INSERT INTO TBPMO_STRUCTURE_NODES (RECORD_ID,NODE_CONFIG_ID, NODE_CAPTION, ID1, PARENT_GUID, ADDED_WHO) VALUES (" & _
                                    "{0},{1},'{2}','{3}','{4}','{5}')", NEWRECORD, CURRENT_NODE_CONFIGURABLE_ID, tsmINewText.Text, "CONFIG " & NEWRECORD & "-" & CURRENT_NODE_CONFIGURABLE_ID, PARENT_ID, USER_USERNAME)
                Else
                    ins = String.Format("INSERT INTO TBPMO_STRUCTURE_NODES (NODE_CONFIG_ID, NODE_CAPTION, ID1, PARENT_GUID, ADDED_WHO) VALUES (" & _
                                        "{1},'{2}','{3}','{4}','{5}')", NEWRECORD, CURRENT_NODE_CONFIGURABLE_ID, tsmINewText.Text, "CONFIG " & NEWRECORD & "-" & CURRENT_NODE_CONFIGURABLE_ID, PARENT_ID, USER_USERNAME)
                End If
                If ClassDatabase.Execute_non_Query(ins) Then
                    Dim sel = String.Format("SELECT MAX(GUID) FROM TBPMO_STRUCTURE_NODES WHERE NODE_CONFIG_ID = {0} AND NODE_CAPTION = '{1}'", CURRENT_NODE_CONFIGURABLE_ID, tsmINewText.Text)

                    Dim NEW_GUID = ClassDatabase.Execute_Scalar(sel)
                    ClassNodeNavigation.Check_NODE_CONFIG_ID(ENTITY_ID)
                    NEWNODE.Tag = ClassNodeNavigation.CreateNODE_TAG(ENTITY_ID, NEW_GUID, NEWRECORD, CURRENT_NODE_CONFIGURABLE_ID)

                    If where = "HERE" Then
                        TreeViewMain.SelectedNode.Parent.Nodes.Add(NEWNODE)
                        TreeViewMain.SelectedNode.Parent.Expand()
                    Else

                        TreeViewMain.SelectedNode.Nodes.Add(NEWNODE)
                        TreeViewMain.SelectedNode.Expand()
                    End If
                End If
            End If
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Unexpected Error in Adding ConfigNode: ", ex.Message)
        End Try
    End Sub
    Private Sub tsmiNodeDelete_Click(sender As Object, e As EventArgs) Handles tsmiNodeDelete.Click
        Try
            Dim _tag = TreeViewMain.SelectedNode.Tag
            Dim REC_Exists As Boolean = False
            If _tag.ToString.ToString.Contains("RECORD-ID") Then
                REC_Exists = True
            End If
            Dim NODE_GUID = ClassNodeNavigation.Return_NODEID_forTag(_tag)
            If IsNumeric(NODE_GUID) Then
                Dim msg = "Sind Sie sicher, dass Sie den Knoten '" & TreeViewMain.SelectedNode.Text & "' löschen wollen?"
                If USER_LANGUAGE <> "de-DE" Then
                    msg = "Are You sure You want to delete the node'" & TreeViewMain.SelectedNode.Text & "'?"
                End If
                Dim result As MsgBoxResult
                result = MessageBox.Show(msg, "Confirmation:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                If result = MsgBoxResult.Yes Then
                    Dim delete = String.Format("DELETE FROM TBPMO_STRUCTURE_NODES WHERE GUID = {0}", NODE_GUID)
                    If ClassDatabase.Execute_non_Query(delete) Then
                        If REC_Exists = True Then
                            If ClassHelper.DeleteRecord(SELECTED_RECORD_ID) = True Then
                                ClassHelper.InsertEssential_Log(SELECTED_RECORD_ID, "RECORD-ID", "RECORD WAS DELETED MANUALLY by USER: " & USER_USERNAME)
                                TreeViewMain.Nodes.Remove(TreeViewMain.SelectedNode)
                            End If
                        End If
                    End If
                End If
            End If
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Unexpected Error in Deleting ConfigNode: ", ex.Message)
        End Try
    End Sub

    Private Sub UnterhalbToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles UnterhalbToolStripMenuItem.Click
        ADD_NODE("BELOW")
    End Sub

    Private Sub cmDoc1FileOpen_Click(sender As Object, e As EventArgs) Handles cmDoc1FileOpen.Click
        Open_File()
    End Sub
    Sub Open_File()
        Me.Cursor = Cursors.WaitCursor
        Dim allow_Open As Boolean = False
        ClassWindreamDocGrid.GetDocItems(GridViewDoc_Search)
        Dim Result = clsWD_GET.Get_File_Rights(ClassWindreamDocGrid.SELECTED_DOC_PATH, USER_USERNAME)
        If Not IsNothing(Result) Then
            Select Case Result.ToString
                Case "R"
                    ContextMenu_Read()
                    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
            For Each row As DataRow In ClassWindreamDocGrid.DT_RESULTFILES.Rows
                ClassHelper.File_open(row.Item("DOC_PATH"), row.Item("DOC_ID"))
            Next
        Else
            If clsWD_GET.WDFile_exists(ClassWindreamDocGrid.SELECTED_DOC_PATH, 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
    Private Sub cmDoc1FileProperties_Click(sender As Object, e As EventArgs) Handles cmDoc1FileProperties.Click
        Show_File_Properties()
    End Sub

    Private Sub tsbtnWork_Click(sender As Object, e As EventArgs) Handles tsbtnWork.Click
        Dim stg
        If POS_ENABLED = False Then
            POS_ENABLED = True
            tslblPoslocked.Visible = False
            BindingNavigatorAddNewItem.Enabled = True
            BindingNavigatorDeleteItem.Enabled = True
            grvwGridPos.OptionsBehavior.ReadOnly = False
            If USER_LANGUAGE = "de-DE" Then
                stg = "Bearbeiten beenden"
            Else
                stg = "End Working"
            End If
            Me.tsbtnWork.Text = stg
        Else
            POS_ENABLED = False
            tslblPoslocked.Visible = True
            BindingNavigatorAddNewItem.Enabled = False
            BindingNavigatorDeleteItem.Enabled = False
            grvwGridPos.OptionsBehavior.ReadOnly = True
            If USER_LANGUAGE = "de-DE" Then
                stg = "Positionen bearbeiten"
            Else
                stg = "Edit positions"
            End If
            Me.tsbtnWork.Text = stg
        End If
    End Sub

    Private Sub BindingNavigatorDeleteItem_Click(sender As Object, e As EventArgs) Handles BindingNavigatorDeleteItem.Click
        Try
            If POS_RECORD_ID > 0 Then
                Dim msg = "Sind Sie sicher, dass Sie diese Position löschen wollen?"
                If USER_LANGUAGE <> "de-DE" Then
                    msg = "Are You sure You want to delete this position?"
                End If
                Dim result As MsgBoxResult
                result = MessageBox.Show(msg, "Confirmation:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                If result = MsgBoxResult.Yes Then
                    If ClassHelper.DeleteRecord(POS_RECORD_ID) = True Then
                        Load_Pos_Data()
                    Else

                    End If
                End If
            End If
        Catch ex As Exception

        End Try



    End Sub

    Private Sub grvwGridPos_FocusedColumnChanged(sender As Object, e As FocusedColumnChangedEventArgs) Handles grvwGridPos.FocusedColumnChanged
        Pos_COLROW_Changer()
    End Sub

    Private Sub tsbtnStartFulltext_Click(sender As Object, e As EventArgs) Handles tsbtnStartFulltext.Click
        Open_FulltextSearch()
    End Sub

    Private Sub tsmiFulltext_Click(sender As Object, e As EventArgs) Handles tsmiFulltext.Click
        Open_FulltextSearch()
    End Sub
    Sub Open_FulltextSearch()
        CURRENT_SELECTED_NODE = Nothing
        If NODE_NAVIGATION = True Then
            If IsNothing(TreeViewMain.SelectedNode) Then
                MsgBox("Please select a node!", MsgBoxStyle.Critical)
                Exit Sub
            End If
            CURRENT_NAVIGATION_TYPE = "NODE"
            CURRENT_SELECTED_NODE = TreeViewMain.SelectedNode
        Else
            CURRENT_NAVIGATION_TYPE = "DEFAULT"
        End If
        frmWD_FulltextChoice.ShowDialog()
        If CURRENT_FULLTEXT_PATTERN <> "" Then
            RUN_WDSEARCH_GRID()
        End If
    End Sub

    Private Sub cmsResultFilesBasic_Opening(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles cmsResultFilesBasic.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 Result = clsWD_GET.Get_File_Rights(ClassWindreamDocGrid.SELECTED_DOC_PATH, USER_USERNAME)
            If Not IsNothing(Result) Then
                Select Case Result.ToString
                    Case "R"
                        ContextMenu_Read()
                    Case Else
                        ContextMenu_Write()
                End Select
            Else
                'cmDoc1FileProperties.Enabled = True
            End If
        Catch ex As Exception
            e.Cancel = True
        Finally
            Me.Cursor = Cursors.Default
        End Try

    End Sub

    Private Sub OrdnerÖffnenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OrdnerÖffnenToolStripMenuItem.Click
        If IsNothing(ClassWindreamDocGrid.DT_RESULTFILES) 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
    End Sub
    Private Sub ToolStripDropDownButton3_DropDownOpening(sender As Object, e As EventArgs) Handles ToolStripDropDownButton3.DropDownOpening
        Try
            Me.Cursor = Cursors.WaitCursor
            Dim Record_Changes As String = "SELECT count(GUID) FROM VWPMO_RECORD_CHANGES WHERE RECORD_ID = " & RECORD_ID
            Dim RC = ClassDatabase.Execute_Scalar(Record_Changes, True)
            showRecordLogtsmi.Enabled = False
            If Not RC Is Nothing Then
                If RC > 0 Then
                    showRecordLogtsmi.Enabled = True
                End If
            End If
            If RIGHT_RECORD_AND_FILE_READ_ONLY = True Then
                CopyRecordtsmi.Enabled = False
                NewVarianttsmi.Enabled = False
                ChangeParentLinktsmi.Enabled = False
                CreateWorkflowtaskstsmi.Enabled = False
            Else
                CopyRecordtsmi.Enabled = True
                NewVarianttsmi.Enabled = True
                ChangeParentLinktsmi.Enabled = True
                CreateWorkflowtaskstsmi.Enabled = True
            End If
        Catch ex As Exception
        Finally
            Me.Cursor = Cursors.Default
        End Try

    End Sub
    Private Sub TimerClearResultfiles_Tick(sender As Object, e As EventArgs) Handles TimerClearResultfiles.Tick
        Try
            For Each row As DataRow In CURRENT_TBPMO_FILES_USER.Rows
                If row.Item("WORKED") = True Then
                    If row.Item("DELETE_FILE") = True Then
                        If File.Exists(row.Item("FILENAME2WORK")) Then
                            File.Delete(row.Item("FILENAME2WORK"))
                            ClassHelper.DELETE_PMO_FILE_USER(row.Item("GUID"))
                            row.Delete()
                        End If
                    Else
                        ClassHelper.DELETE_PMO_FILE_USER(row.Item("GUID"))
                        row.Delete()
                    End If
                End If
            Next
            CURRENT_TBPMO_FILES_USER.AcceptChanges()
            ClassFolderWatcher.Check_Scan_Files()
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "", "Unexpected Error in clearing User-Files: " & ex.Message, ex.StackTrace)
        Finally
            TimerClearResultfiles.Stop()
        End Try
    End Sub

    Private Sub tsbtnPos_Refresh_Click(sender As Object, e As EventArgs) Handles tsbtnPos_Refresh.Click
        Load_Pos_Data()
    End Sub

    Private Sub frmConstructor_Main_KeyUp(sender As Object, e As KeyEventArgs) Handles MyBase.KeyUp
        If e.KeyCode = Keys.Tab Then
            If pnlDetails.Focused Then

            End If

        End If
    End Sub
End Class