Imports DevExpress.Utils
Imports DevExpress.XtraBars.Navigation
Imports DevExpress.XtraEditors
Imports DevExpress.XtraEditors.Repository
Imports DevExpress.XtraGrid.Views.Base
Imports DevExpress.XtraGrid.Views.Tile
Imports DevExpress.XtraScheduler
Imports System.Text
Imports WINDREAMLib
Imports System.IO

Public Class frmForm_Constructor_Main

#Region "Laufzeitvariablen & Konstanten"
    Public CONSTRUCTORID As Integer
    Private CONSTRUCTOR_DETAIL_ID As Integer
    Public DT_CONSTRUCT_VIEW As DataTable
    Public EBENE2_PARENT_ID As Integer
    Public EBENE3_PARENT_ID As Integer
    Public ACT_EBENE As Integer
    Public ACT_EBENE_STRING As String
    Public SELECTED_RECORD_ID As Integer
    Public PARENT_RECORDID As Integer
    Public thisFORMVIEW_ID As Integer

    Private VIEW_ID
    Private VIEW_ID_RUNTIME As Integer = -1

    Public RECORD_ENABLED As Boolean = False

    Public EBENE1_ENTITY
    Public EBENE2_ENTITY
    Public EBENE3_ENTITY
    Public EBENE1_COLUMNNAME
    Public EBENE2_COLUMNNAME
    Public EBENE3_COLUMNNAME
    Public EBENE1_RECID
    Public EBENE2_RECID
    Public EBENE3_RECID
    Public EBENE1_GRID_RESULT
    Public EBENE2_GRID_RESULT
    Public EBENE3_GRID_RESULT
    Public act_FormViewID
    Public DT_SELECTION As DataTable
    Public EDIT_STATE As EditState = EditState.None
    Public GRID_TYPE As GridType = GridType.Tiles
    Public GRID_TYPE_ID As Integer = 1
    Public FORM_LOADED As Boolean = False
    Public RECORD_CHANGED As Boolean = False
    Public 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 _windream As New ClassWindream
    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 FOLLOW_UPisActive As Boolean = False
    Private DT_FU_Record As DataTable
    Private DT_FU_ENTITY 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



    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
        _FormClosing = True
        ' Check_Record_Changed()
        CloseWDDocview()
        Save_Grid_Layout()
        ClassWindowLocation.SaveFormLocationSize(Me, CONSTRUCTORID, CURRENT_SCREEN_ID, "CONSTRUCTOR_MAIN")
    End Sub


    Private Sub frmForm_Constructor_Main_Load(sender As Object, e As EventArgs) Handles Me.Load
        _FormClosing = False
        CONSTRUCTORID = CURRENT_CONSTRUCTOR_ID
        Me.Cursor = Cursors.WaitCursor

        Init_Grid_Control()

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

        Try
            'SplitCont_Details.Collapsed = True
            CONSTRUCTORID = CURRENT_CONSTRUCTOR_ID
            ClassWindowLocation.LoadFormLocationSize(Me, CONSTRUCTORID, CURRENT_SCREEN_ID, "CONSTRUCTOR_MAIN")
            VWPMO_WF_USER_ACTIVETableAdapter.Connection.ConnectionString = MyConnectionString
            Me.TBPMO_FILES_USERTableAdapter.Connection.ConnectionString = MyConnectionString
            Me.VWPMO_WF_ACTIVETableAdapter.Connection.ConnectionString = MyConnectionString
            DT_CONSTRUCT_VIEW = ClassDatabase.Return_Datatable("SELECT * FROM TBPMO_FORM_CONSTRUCTOR WHERE GUID = " & CONSTRUCTORID)
            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
            Load_Tree_View(CONSTRUCTORID)
            FORM_LOADED = True

        Catch ex As System.Exception
            MsgBox("Error while Loading Form" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            System.Windows.Forms.MessageBox.Show(ex.Message)
        End Try
        Me.Cursor = Cursors.Default

    End Sub

#Region "Layout"

    Sub Save_Grid_Layout()
        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")
    End Sub

    Sub Load_Grid_Layout()
        Dim XMLPath = Get_Grid_Layout_Filename()
        If File.Exists(XMLPath) And GRID_TYPE = GridType.Grid Then
            grvwGrid.RestoreLayoutFromXml(XMLPath)
            grvwGrid.ClearColumnsFilter()
            'grvwGrid.ClearGrouping()
            grvwGrid.ClearSelection()
            grvwGrid.OptionsView.ShowPreview = False

            Update_Status_Label(True, "Grid Layout Loaded")
        End If
    End Sub

    Private Function Get_Grid_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, EntityName, CONSTRUCTORID)
        Return System.IO.Path.Combine(Application.UserAppDataPath(), Filename)
    End Function
#End Region

#Region "NavPane"

    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
                    Load_Tree_View_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_Tree_View_Data()
                End If
            End If

        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
        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 Sub Hide_Grid_Columns()
        Dim DefaultHiddenColumns As New List(Of String) From {"Record-ID", "Form-ID"}
        Dim QuickHiddenColumns As New List(Of String) From {"AddedWho", "AddedWhen", "ChangedWho", "ChangedWhen"}

        If GRID_TYPE = GridType.Carousel Or GRID_TYPE = GridType.Tiles Then
            DefaultHiddenColumns.AddRange(QuickHiddenColumns)
        End If

        For Each colname As String In DefaultHiddenColumns
            Dim col = grvwTiles.Columns.Item(colname)
            If col IsNot Nothing Then
                col.Visible = False
            End If
        Next
    End Sub

    Public Function Get_Grid_Sql(ConstructorId As Integer, FormId As Integer)
        If GRID_TYPE = GridType.Grid Then
            CURRENT_ENTITYSQL = "SELECT T.* FROM VWTEMP_PMO_FORM" & FormId.ToString & " T"
        Else 'Tiles und Carousel bekommen Quick View
            CURRENT_ENTITYSQL = String.Format("SELECT SQL_QUICK_VIEW FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = {0} AND FORM_ID = {1}", ConstructorId, FormId)
            CURRENT_ENTITYSQL = ClassDatabase.Execute_Scalar(CURRENT_ENTITYSQL, True)
            If CURRENT_ENTITYSQL = String.Empty Then
                CURRENT_ENTITYSQL = "SELECT T.* FROM VWTEMP_PMO_FORM" & FormId.ToString & " T"
                GRID_TYPE = GridType.Grid
                GridControlMain.MainView = grvwGrid
                VIEW_ID = 3
                ' GridControlMain.MainView = grvwGrid
            End If
        End If
    End Function

    Public Sub Clear_Grid_View()
        GridControlMain.DataSource = Nothing

        If GRID_TYPE = GridType.Grid Then
            If grvwGrid.Columns.Count > 0 Then

            End If
            grvwGrid.Columns.Clear()
        ElseIf GRID_TYPE = GridType.Tiles Then
            grvwTiles.Columns.Clear()
        Else
            grvwCarousel.Columns.Clear()
        End If
    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
    Private Sub grvwGrid_FocusedColumnChanged(sender As Object, e As FocusedColumnChangedEventArgs) Handles grvwGrid.FocusedColumnChanged
        If ENTITY_LOADED = False Then
            Exit Sub
        End If
        Load_Record_Data()
    End Sub

    Private Sub GridView_FocusedRowChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs) Handles grvwGrid.FocusedRowChanged, grvwTiles.FocusedRowChanged, grvwCarousel.FocusedRowChanged
        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
        'Check_Record_Changed()

        Load_Record_Data()
        Hide_Grid_Columns()

        'If dataloaded = True Then
        '    If LogErrorsOnly = False Then ClassLogger.Add(">> grvwSelection_FocusedRowChanged - EditState: " & EDIT_STATE, False)
        '    Dim selRecID = GetSelected_RecordID()
        '    If Not selRecID Is Nothing And selRecID <> SelectedRecordID Or EDIT_STATE = "insert" Then
        '        Focused_Row_Column_Changed()
        '    Else
        '        'Console.WriteLine("SelRecordID identisch")
        '    End If
        'End If
    End Sub


#End Region

#Region "TreeView"

    Public Sub SetSelectedNodeStyle(tncoll As TreeNodeCollection)
        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
        TreeViewMain.Refresh()
    End Sub

    Private Sub TreeViewMain_AfterSelect(sender As Object, e As TreeViewEventArgs) Handles TreeViewMain.AfterSelect
        SetSelectedNodeStyle(TreeViewMain.Nodes)
        Load_Tree_View_Data()
    End Sub

    Private Sub TreeViewMain_BeforeSelect(sender As Object, e As TreeViewCancelEventArgs) Handles TreeViewMain.BeforeSelect
        If grvwGrid.Columns.Count > 0 Then
            Save_Grid_Layout()
        End If
    End Sub

    Sub Load_Tree_View(ConstructorId As Integer)

        Dim LEVEL1_NODE As TreeNode
        Dim LEVEL2_NODE As TreeNode
        Dim LEVEL3_NODE As TreeNode
        Dim SQL As String
        Dim DT, DT2, DT3 As DataTable

        ' Daten für Level1 Nodes Laden
        SQL = "SELECT * from VWPMO_CONSTRUCTOR_FORMS WHERE PARENT_ID = 0 AND CONSTRUCT_ID = " & ConstructorId & " ORDER BY SEQUENCE"
        DT = ClassDatabase.Return_Datatable(SQL)

        If DT Is Nothing Then
            Exit Sub
        End If

        If DT.Rows.Count = 1 Then
            Dim LEVEL1_TITLE = DT.Rows(0).Item("FORM_TITLE").ToString
            Dim LEVEL1_ID = DT.Rows(0).Item("FORM_ID").ToString

            ' Rootnode erstellen und taggen
            LEVEL1_NODE = New TreeNode(LEVEL1_TITLE)
            LEVEL1_NODE.Tag = LEVEL1_ID

            ' TreeView leeren und Rootnode einfügen
            TreeViewMain.Nodes.Clear()
            TreeViewMain.Nodes.Add(LEVEL1_NODE)

            ' Daten für Level2 Nodes Laden
            SQL = String.Format("SELECT * from VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = {0} AND PARENT_ID = {1} ORDER BY SEQUENCE", ConstructorId, LEVEL1_ID)
            DT2 = ClassDatabase.Return_Datatable(SQL)

            If DT2 Is Nothing Or DT2.Rows.Count = 0 Then
                Exit Sub
            End If

            For Each row As DataRow In DT2.Rows
                Dim LEVEL2_TITLE As String = row.Item("FORM_TITLE").ToString
                Dim LEVEL2_ID As Integer = row.Item("FORM_ID")
                Dim LEVEL2_PARENT_ID As Integer = row.Item("PARENT_ID")

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

                ' Daten für Level3 Nodes laden
                SQL = String.Format("SELECT * from VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = {0} AND PARENT_ID = {1} ORDER BY SEQUENCE", ConstructorId, LEVEL2_ID)
                DT3 = ClassDatabase.Return_Datatable(SQL)

                If DT3 Is Nothing Or DT3.Rows.Count = 0 Then
                    Exit Sub
                End If

                For Each subrow As DataRow In DT3.Rows
                    Dim LEVEL3_TITLE As String = subrow.Item("FORM_TITLE")
                    Dim LEVEL3_ID As Integer = subrow.Item("FORM_ID")

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

            Next

            TreeViewMain.ExpandAll()
            TreeViewMain.Nodes(0).EnsureVisible()
        End If

    End Sub


    Sub Load_Tree_View_Data()

        Dim SelectedNode As TreeNode = TryCast(TreeViewMain.SelectedNode, TreeNode)

        If SelectedNode IsNot Nothing Then
            ENTITY_LOADED = False
            Dim FormId As Integer = SelectedNode.Tag
            Dim parentNode As TreeNode = TryCast(SelectedNode.Parent, TreeNode)

            ACT_EBENE = 2

            If parentNode IsNot Nothing Then
                Dim grandParentNode As TreeNode = TryCast(parentNode.Parent, TreeNode)

                If grandParentNode IsNot Nothing Then
                    ACT_EBENE = 3
                End If
            Else
                ACT_EBENE = 1
            End If
            CURRENT_FORM_ID = FormId
            Dim Sql = "SELECT GUID from VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND FORM_ID = " & CURRENT_FORM_ID
            CONSTRUCTOR_DETAIL_ID = ClassDatabase.Execute_Scalar(Sql, True)
            Load_Entity_Data(ACT_EBENE)
        End If
    End Sub

    Sub Get_RecordCounts_Nodes()
        Try
            Dim selnode As TreeNode = TreeViewMain.SelectedNode
            Dim a As Integer = 0
            For Each childNodeLevel1 As TreeNode In selnode.Nodes
                Dim PARENT_ID As Integer
                Dim TYPE_ID 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 = " & childNodeLevel1.Tag
                    Dim DT As DataTable = ClassDatabase.Return_Datatable(sql, "ShowNodeAmounts")
                    PARENT_ID = DT.Rows(0).Item(0)
                    TYPE_ID = DT.Rows(0).Item(1)
                End If
                If TYPE_ID <> 5 Then
                    If childNodeLevel1.Text = "Allgemein" Then
                        Console.WriteLine("Allgemein-Reiter")
                    End If
                    Dim result As Integer = ReturnAmountofRecords(childNodeLevel1.Tag, PARENT_ID)
                    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
            MsgBox("Error in Get_RecordCounts_Nodes:" & vbNewLine & ex.Message, MsgBoxStyle.Exclamation)
        End Try
    End Sub
    Function ReturnAmountofRecords(EntityID As Integer, PARENT_ID As Integer)
        Dim _sql As String
        'Abhängig von der Entität dieAnzahl der Datensätze laden
        _sql = ClassDatabase.Execute_Scalar("SELECT SQL_SELECT_EBENE2 FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND FORM_ID = " & EntityID)
        Select Case ACT_EBENE
            Case 1
                If EBENE1_RECID = 0 Then
                    Return 99999999
                End If

                _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)
            Case 3
                If EBENE3_RECID = 0 Then
                    Return 99999999
                End If
                _sql = _sql.Replace("@RecordID", EBENE2_RECID)

        End Select

        Dim DT2 As DataTable = ClassDatabase.Return_Datatable(_sql, "ReturnAmountofRecords 1")
        Return DT2.Rows.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)
        Dim SQL As String = "SELECT 'Added by ' + ADDED_WHO + ' when ' + CONVERT(VARCHAR(16),ADDED_WHEN,20) + ', Changed by ' + COALESCE(CHANGED_WHO,'') + ' when ' + COALESCE(CONVERT(VARCHAR(16),CHANGED_WHEN,20),'') FROM TBPMO_RECORD WHERE GUID = " & RecordId
        Dim result = ClassDatabase.Execute_Scalar(SQL)

        If IsDBNull(result) Or IsNothing(result) Then
            tsslblRecord.Visible = False
        Else
            If CURRENT_FORM_TYPE = 5 Then
                tsslblRecord.Text = String.Format("Group-Record ({0}) - {1}", RecordId, result.ToString)
            Else
                tsslblRecord.Text = String.Format("Record ({0}) - {1}", RecordId, result.ToString)
            End If
            tsslblRecord.Text = tsslblRecord.Text.Replace(", Changed by  when ", "")
            tsslblRecord.Visible = True
        End If
    End Sub

#End Region

#Region "Controls"
    Sub Load_Controls(FORM_VIEW_ID As Integer)
        thisFORMVIEW_ID = FORM_VIEW_ID
        CURRENT_FORM_ID = ClassDatabase.Execute_Scalar("SELECT FORM_ID FROM TBPMO_FORM_VIEW WHERE GUID = " & FORM_VIEW_ID)
        CtrlBuilder = New ClassControlBuilder(pnlDetails, ttToolTip)
        'LoadControls(thisFormId)
        CtrlCommandUI = New ClassControlCommandsUI(CtrlBuilder,
                                                   ContextMenuDetails,
                                                   AddressOf NewEditAppointment,
                                                   AddressOf OpenFormData)
        CtrlCommandUI.LoadControls(CURRENT_FORM_ID)
        pnlDetails.Enabled = False
        AddHandler CtrlBuilder.OnRecordChanged, AddressOf OnRecordChanged
    End Sub

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

    Sub OpenFormData(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
        Try
            Dim Control As Control = sender
            Dim ControlName As String = Control.Name
            Dim ControlId As Integer = GetControlID_for_Name(ControlName, CURRENT_FORM_ID)

            Dim dr As DataRow = ClassFunctionCommands.LoadFunction(ControlId)

            If IsDBNull(dr.Item("INTEGER1")) OrElse dr.Item("INTEGER1") = 0 Then
                MsgBox("FormId ist nicht definiert für " & ControlName)
                Exit Sub
            End If

            If IsDBNull(dr.Item("INTEGER2")) OrElse dr.Item("INTEGER2") = 0 Then
                MsgBox("ScreenId ist nicht definiert für " & ControlName)
                Exit Sub
            End If

            Dim FormId As Integer = dr.Item("INTEGER1")
            Dim ScreenId As Integer = dr.Item("INTEGER2")

            Cursor = Cursors.WaitCursor
            OpenFormInputFor(FormId, ScreenId)

            Cursor = Cursors.Default
        Catch ex As Exception
            MsgBox("Error in OpenFormData:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub


#End Region

#Region "DetailView - Toolstrip"

    Private Sub tsButtonAdd_Click(sender As Object, e As EventArgs) Handles tsButtonAdd.Click
        If CtrlCommandUI.IsInsert Then
            Exit Sub
        End If

        RECORD_CHANGED = True
        pnlDetails.Enabled = True
        tsButtonShowWorkflowTasks.Enabled = True

        ClassControlValues.LoadDefaultValues(CURRENT_FORM_ID, SELECTED_RECORD_ID, pnlDetails.Controls)
        CtrlCommandUI.IsInsert = True
    End Sub

    Private Sub tsButtonSave_Click(sender As Object, e As EventArgs) Handles tsButtonSave.Click
        Try

            SAVE_ROUTINE_ACTIVE = True

            If CtrlCommandUI.IsInsert Then
                EDIT_STATE = EditState.Insert
            Else
                EDIT_STATE = EditState.Update
                NEW_RECORD_ID = 0
                If Not RECORD_CHANGED Then
                    Update_Status_Label(True, "KEINE Änderungen an Datensatz.")
                    Exit Sub
                End If
            End If

            Dim ResultMessage = Update_Record_OnChange()
            Dim recid As Integer
            Update_Status_Label(True, ResultMessage, EDIT_STATE)

            If EDIT_STATE = EditState.Update Then
                recid = CURRENT_RECORD_ID
            Else
                recid = NEW_RECORD_ID
            End If

            SELECTED_RECORD_ID = recid
            CURRENT_RECORD_ID = recid

            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!
                            MsgBox("Achtung es wurde noch keine Parent-Verknüpfung angelegt!", MsgBoxStyle.Exclamation)
                            'Show_Verknuepfungen()
                        End If
                End Select
            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
                                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
                                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

            'Jetzt den Record nochmal laden
            Show_Selected_Record_Data("Record-ID", SELECTED_RECORD_ID)
            Update_Status_Label(True, "Record gespeichert - " & Now)
            Update_Record_Label(SELECTED_RECORD_ID)


            If EDIT_STATE = EditState.Insert Then
                'Die Daten neu laden
                Load_Entity_Data_Only()
                Get_Grid_Row_Handle(NEW_RECORD_ID)
            Else
                'Die Daten neu laden
                Load_Entity_Data_Only()
                Get_Grid_Row_Handle(CURRENT_RECORD_ID)
                'Die Daten auf dem Panel laden
                ClassControlValues.LoadControlValuesNeu(CURRENT_RECORD_ID, CURRENT_PARENTID, CURRENT_FORM_ID, CtrlBuilder.AllControls)
                pnlDetails.Enabled = True
            End If

        Catch ex As Exception
            MsgBox("Error in Save Data:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

        EDIT_STATE = EditState.None
        RECORD_CHANGED = False
        SAVE_ROUTINE_ACTIVE = False
    End Sub

    Private Sub tsButtonDelete_Click(sender As Object, e As EventArgs) Handles tsButtonDelete.Click
        Dim result As MsgBoxResult
        result = MessageBox.Show("Möchten Sie den Datensatz wirklich löschen?", "Bestätigung erforderlich:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
        If result = MsgBoxResult.Yes Then
            EDIT_STATE = EditState.Delete
            If CtrlCommandUI.DeleteRecord(SELECTED_RECORD_ID) = True Then
                Update_Status_Label(True, "Der Datensatz " & SELECTED_RECORD_ID & " wurde erfolgreich gelöscht - " & Now)
                Update_Record_Label(SELECTED_RECORD_ID)
                Load_Tree_View_Data()
            End If
        End If
        EDIT_STATE = EditState.None
    End Sub

    Private Sub tsButtonEditMode_Click(sender As Object, e As EventArgs) Handles tsButtonEditMode.Click
        If RECORD_ENABLED = False Then
            RECORD_ENABLED = True
            Me.pnlDetails.Enabled = True
            Me.tsButtonDelete.Enabled = True
            Me.tsButtonAdd.Enabled = True
            Me.tsButtonSave.Enabled = True
            Me.tsButtonEditMode.Text = "Bearbeiten beenden"
            'Funktion zum Vollständigen load der Inhalte

            ClassControlValues.LoadControlValuesList(SELECTED_RECORD_ID, CURRENT_PARENTID, CURRENT_FORM_ID, CtrlBuilder.AllControls)
        Else
            RECORD_ENABLED = False
            Me.pnlDetails.Enabled = False
            Me.tsButtonDelete.Enabled = False
            Me.tsButtonAdd.Enabled = False
            Me.tsButtonSave.Enabled = False
            Me.tsButtonEditMode.Text = "Bearbeiten"
            'Funktion nur zum load der Inhalte

            'ClassControlValues.UnloadControlValuesList(SELECTED_RECORD_ID, CURRENT_RECORD_ID, CtrlBuilder.AllControls)

        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, CURRENT_FORM_ID, CURRENT_RECORD_ID, pnlDetails.Controls)
        Catch ex As Exception
            MsgBox("Error in OpenEditAppointment:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        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
            MsgBox("Error in EditAppointment:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        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
            Me.Cursor = Cursors.WaitCursor
            CURRENT_RECORD_ID = 0
            Dim IS_SINGLE_RECORD As Boolean
            Dim LOAD_DIRECT As Boolean
            'VerknüpfungenToolStripMenuItem.Enabled = False
            CURRENT_FORM_TYPE = ClassDatabase.Execute_Scalar("SELECT FORM_TYPE_ID FROM TBPMO_FORM WHERE GUID = " & CURRENT_FORM_ID)
            IS_SINGLE_RECORD = ClassDatabase.Execute_Scalar("SELECT SINGLE_RECORD FROM TBPMO_FORM WHERE GUID = " & CURRENT_FORM_ID)
            LOAD_DIRECT = ClassDatabase.Execute_Scalar("SELECT LOAD_DIRECT FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND FORM_ID = " & CURRENT_FORM_ID)
            CURRENT_CONSTRUCTOR_DETAIL_ID = ClassDatabase.Execute_Scalar("SELECT GUID FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND FORM_ID = " & CURRENT_FORM_ID)


            If VIEW_ID_RUNTIME <> -1 Then
                GRID_TYPE_ID = VIEW_ID_RUNTIME
            Else
                Dim VIEW_ID = ClassDatabase.Execute_Scalar(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, CURRENT_FORM_ID, USER_GUID), 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 & "," & CURRENT_FORM_ID & ")", True)
                    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
            Dim DT As DataTable
            Dim sql As String = "SELECT PARENT_ID FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND FORM_ID = " & CURRENT_FORM_ID
            Dim PARENT_ID = ClassDatabase.Execute_Scalar(sql)
            If PARENT_ID Is Nothing Then
                MsgBox("Error in GetParentID for selectedNode - Check Logfile", MsgBoxStyle.Exclamation)
                Exit Sub
            End If

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


            Select Case ClickedLevel
                Case 1
                    PARENT_RECORDID = 0
                    CURRENT_PARENTID = 0
                    EBENE1_ENTITY = TreeViewMain.SelectedNode.Text
                    ACT_EBENE_STRING = EBENE1_ENTITY
                    If LogErrorsOnly = False Then ClassLogger.Add(">> Ebene 1 in TreeView selektiert", False)
                    EBENE2_ENTITY = ""
                    EBENE3_ENTITY = ""
                    'tslblEntity2.Visible = False
                    'tslblEntity3.Visible = False

                    EBENE1_COLUMNNAME = ClassDatabase.Execute_Scalar("SELECT COLUMN_NAME1 FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND FORM_ID = " & CURRENT_FORM_ID)
                    EBENE2_COLUMNNAME = ""
                    EBENE3_COLUMNNAME = ""
                    EBENE2_GRID_RESULT = Nothing
                    EBENE3_GRID_RESULT = Nothing
                    '_sql = ClassDatabase.Execute_Scalar("SELECT SQL_QUICK_VIEW FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND FORM_ID = " & CURRENT_FORM_ID)

                Case 2
                    'Dim Level1Select = ClassDatabase.Execute_Scalar(Get_Grid_Sql(CONSTRUCTORID, CURRENT_FORM_ID)) 'ClassDatabase.Execute_Scalar("SELECT LEVEL1_SELECT FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND FORM_ID = " & CURRENT_FORM_ID)
                    'If CBool(Level1Select) = False And CURRENT_FORM_TYPE <> 5 And EBENE1_RECID = 0 Then
                    '    MsgBox("Entität '" & TreeViewLevelSelect.SelectedNode.Text & "' kann nicht ohne Auswahl eines Ebene 1 Datensatzes gewählt werden!", MsgBoxStyle.Exclamation)
                    '    TreeViewLevelSelect.SelectedNode = TreeViewLevelSelect.SelectedNode.Parent
                    '    Exit Sub
                    'End If
                    EBENE2_ENTITY = TreeViewMain.SelectedNode.Text
                    ACT_EBENE_STRING = EBENE2_ENTITY
                    If LogErrorsOnly = False Then ClassLogger.Add(">> Ebene 2 in TreeView selektiert", 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
                        CURRENT_PARENTID = EBENE1_RECID
                        Console.WriteLine("PARENT_RECORDID: " & PARENT_RECORDID)
                        If GRID_TYPE = GridType.Grid Then
                            CURRENT_ENTITYSQL = "SELECT T.* FROM VWTEMP_PMO_FORM" & CURRENT_FORM_ID.ToString & " T, TBPMO_RECORD_CONNECT t1 where T.[Record-ID] = T1.RECORD2_ID AND T1.RECORD1_ID = " & CURRENT_PARENTID
                        Else
                            CURRENT_ENTITYSQL = CURRENT_ENTITYSQL.Replace("@RecordID", EBENE2_RECID)
                            CURRENT_ENTITYSQL = CURRENT_ENTITYSQL.ToString.Replace("TBPMO_FORM T1", "TBPMO_FORM T1 ,TBPMO_RECORD_CONNECT T2")
                            CURRENT_ENTITYSQL = CURRENT_ENTITYSQL & " AND T.GUID = T2.RECORD2_ID  AND T2.RECORD1_ID = @T2.RECORD1_ID"
                            CURRENT_ENTITYSQL = CURRENT_ENTITYSQL.ToString.Replace("@T2.RECORD1_ID", PARENT_RECORDID)
                        End If
                    End If
                    'tslblEntity3.Visible = False
                    Select Case CURRENT_FORM_TYPE
                        Case 5
                            If GET_GROUP_RECORD() = True Then
                                EBENE2_RECID = CURRENT_RECORD_ID
                            End If
                    End Select

                    EBENE2_COLUMNNAME = ClassDatabase.Execute_Scalar("SELECT COLUMN_NAME1 FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND FORM_ID = " & CURRENT_FORM_ID)
                    EBENE3_COLUMNNAME = ""
                    EBENE2_GRID_RESULT = Nothing
                    EBENE3_GRID_RESULT = Nothing

                Case 3
                    Select Case CURRENT_FORM_TYPE
                        Case 5
                            If GET_GROUP_RECORD() = True Then
                                EBENE3_RECID = CURRENT_RECORD_ID
                            End If
                    End Select

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



                    EBENE3_COLUMNNAME = ClassDatabase.Execute_Scalar("SELECT COLUMN_NAME1 FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND FORM_ID = " & CURRENT_FORM_ID)
                    '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
                        CURRENT_PARENTID = EBENE2_RECID
                        Console.WriteLine("PARENT_RECORDID: " & PARENT_RECORDID)
                        Try
                            If GRID_TYPE = GridType.Grid Then
                                CURRENT_ENTITYSQL = "SELECT T.* FROM VWTEMP_PMO_FORM" & CURRENT_FORM_ID.ToString & " T, TBPMO_RECORD_CONNECT t1 where T.[Record-ID] = T1.RECORD2_ID AND T1.RECORD1_ID = " & CURRENT_PARENTID
                            Else
                                CURRENT_ENTITYSQL = CURRENT_ENTITYSQL.Replace("@RecordID", EBENE2_RECID)
                                CURRENT_ENTITYSQL = CURRENT_ENTITYSQL.ToString.Replace("TBPMO_FORM T1", "TBPMO_FORM T1 ,TBPMO_RECORD_CONNECT T2")
                                CURRENT_ENTITYSQL = CURRENT_ENTITYSQL & " AND T.GUID = T2.RECORD2_ID  AND T2.RECORD1_ID = @T2.RECORD1_ID"
                                CURRENT_ENTITYSQL = CURRENT_ENTITYSQL.ToString.Replace("@T2.RECORD1_ID", PARENT_RECORDID)
                            End If
                        Catch ex As Exception

                        End Try
                    Else

                    End If
                    EBENE3_GRID_RESULT = Nothing
            End Select


            CURRENT_ENTITYSTRING = ACT_EBENE_STRING
            CURRENT_PARENTID = PARENT_RECORDID
            act_FormViewID = ClassDatabase.Execute_Scalar("SELECT GUID FROM TBPMO_FORM_VIEW where FORM_ID = " & CURRENT_FORM_ID)

            If EDIT_STATE = EditState.None Then
                'Die Controls der Entität laden
                Load_Controls(act_FormViewID)
                'set_pnlsize()
            End If

            CURRENT_FORMVIEW_ID = act_FormViewID

            'Überprüfen ob windream Dos angezeigt werden sollen?
            Check_windream_Show(act_FormViewID)



            If windream_Docshow = True Then
                Clear_Windream_ResultList()
                If WD_ShowEnitityDocs = True Then
                    RUN_WD_SEARCH("", "ENTITY")
                End If
            End If




            Select Case CURRENT_FORM_TYPE
                Case 5
                    'Nur eine Gruppen-Entität: d.h. es wird nur die Dateientab angezeigt
                    Console.WriteLine("OnlyGroupType")
                    GridControlMain.Visible = False
                Case Else
                    GridControlMain.Visible = True

                    Dim DTEntity As DataTable = ClassDatabase.Return_Datatable(CURRENT_ENTITYSQL, "LoadEntityData - Get DTEntity")
                    Dim primaryKey(1) As DataColumn
                    primaryKey(0) = DTEntity.Columns("Record-ID")
                    DTEntity.PrimaryKey = primaryKey
                    DT_SELECTION = DTEntity
                    LoadGrid_Selection()

                    'If LOAD_DIRECT = True Or IS_SINGLE_RECORD Then
                    '    Dim sql1 = CURRENT_ENTITYSQL
                    '    sql1.Replace("T.*", "TOP 1 [Record-ID]")
                    '    Dim id = ClassDatabase.Execute_Scalar(sql1, True)
                    '    If Not id Is Nothing Then
                    '        If LogErrorsOnly = False Then ClassLogger.Add(">> Load Record directly - RecordID: " & CURRENT_RECORD_ID, False)
                    '        Load_Record_Data()
                    '    End If
                    'End If
                    'Überprüfen ob es für diese Entität Wiedervorlagen gibt?
                    Check_FOLLOWUP_IsConfigured(CURRENT_FORM_ID)
            End Select

            Load_Templates()

            Me.Cursor = Cursors.Default

            Load_Grid_Layout()


            
            'Zurücksetzen
            ENTITY_LOADED = True
        Catch ex As Exception
            MsgBox("Error in Load_Entity_Data:" & vbNewLine & ex.Message, MsgBoxStyle.Exclamation)
        End Try
    End Sub

    Sub Load_Entity_Data_Only()
        Try
            Dim DTEntity As DataTable = ClassDatabase.Return_Datatable(CURRENT_ENTITYSQL, "Load_Entity_Data_Only")
            Dim primaryKey(1) As DataColumn
            primaryKey(0) = DTEntity.Columns("Record-ID")
            DTEntity.PrimaryKey = primaryKey
            DT_SELECTION = DTEntity
            LoadGrid_Selection()
        Catch ex As Exception
            MsgBox("Error in Load_Entity_Data_Only:" & vbNewLine & ex.Message, MsgBoxStyle.Exclamation)
        End Try
    End Sub

    Sub CreateTile()
        Dim ImageIndex As Integer = -1
        Dim i As Integer = 0
        Dim j As Integer = 0
        Dim DT As DataTable = DirectCast(DT_SELECTION, DataTable)

        Dim PrimaryFont As New Font("Segoe UI", 12, FontStyle.Bold)
        Dim SecondaryFont As New Font("Segoe UI", 10)

        ' Datatable laden
        GridControlMain.DataSource = DT

        If DT Is Nothing Then
            MsgBox("Daten können nicht geladen werden")
            Exit Sub
        End If

        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
                        .Column.Caption = "Record-ID"
                    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)
                            .ImageScaleMode = TileItemImageScaleMode.Squeeze
                            .ImageAlignment = TileItemContentAlignment.BottomLeft
                        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(140, 40 + (OffsetIndex * 50))
                        .Appearance.Normal.Font = SecondaryFont
                        .Appearance.Normal.ForeColor = Color.Gray
                    End With

                    With TextColumn
                        .Column = grvwTiles.Columns(index)
                        .TextAlignment = TileItemContentAlignment.Manual
                        .TextLocation = New Point(140, 40 + 15 + (OffsetIndex * 50))
                        .Appearance.Normal.Font = SecondaryFont
                    End With

                    grvwTiles.TileTemplate.Add(TextHeaderColumn)
                    grvwTiles.TileTemplate.Add(TextColumn)
            End Select


        Next

    End Sub

    Private Function GET_GROUP_RECORD()
        Dim sqlRecord As String = "SELECT RECORD2_ID FROM TBPMO_RECORD_CONNECT WHERE RECORD1_ID = " & CURRENT_PARENTID

        Dim recid = ClassDatabase.Execute_Scalar(sqlRecord, True)
        If IsNothing(recid) Then
            If ClassControlCommandsUI.CreateRecord(CURRENT_FORM_ID) = True Then
                recid = ClassControlCommandsUI.GetLastRecord
                If Not IsNothing(recid) Then
                    'Die neue Record-ID setzen
                    CURRENT_RECORD_ID = recid
                    ClassControlCommandsUI.ConnectRecord(CURRENT_PARENTID, CURRENT_RECORD_ID, "Group-Entity Link")
                Else
                    Return False
                End If
            Else
                Return False
            End If
        Else
            Try
                CURRENT_RECORD_ID = CInt(recid)

            Catch ex As Exception
                MsgBox("Error while getting CURRENT_RECORDID: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
                Return False
            End Try
        End If
        Dim SQL1 As String = "SELECT COUNT(*) FROM TBPMO_RECORD_CONNECT WHERE RECORD1_ID = " & CURRENT_PARENTID & " AND RECORD2_ID = " & CURRENT_RECORD_ID

        If ClassDatabase.Execute_Scalar(SQL1) = 0 Then
            ClassControlCommandsUI.ConnectRecord(CURRENT_PARENTID, CURRENT_RECORD_ID)
        End If
        Update_Record_Label(CURRENT_RECORD_ID)
        Return True
    End Function

    Private Function LoadGrid_Selection()
        Try
            If GRID_TYPE = GridType.Tiles Then
                CreateTile()
            Else
                ' Alle Checkboxen für aktuelle Ansicht heraussuchen
                ' Dim sqlcheck As String = "SELECT CONTROL_COLUMN FROM VWPMO_VALUES WHERE CONTROL_TYPE_ID in (10,11) AND FORM_ID = " & CURRENT_FORM_ID
                ' Dim dtcheck As DataTable = ClassDatabase.Return_Datatable(sqlcheck)
                '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

                'Duplikate entfernen
                ' listcheck = listcheck.Distinct().ToList()

                'Grid leeren
                Clear_Grid_View()

                'Databinding Neu
                BindingSource_Entity.DataSource = DT_SELECTION
                GridControlMain.DataSource = BindingSource_Entity


                ' 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
                '    grvwSelection.GridControl.RepositoryItems.Add(CheckBoxEditorForDisplay)

                '    If Not IsNothing(grvwSelection.Columns(col)) Then
                '        grvwSelection.Columns(col).ColumnEdit = CheckBoxEditorForDisplay
                '    End If
                'Next
                'grvwGrid.Columns("Record-ID").OptionsColumn.AllowShowHide = False

            End If
           

            HideColumns()
            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
        Catch ex As Exception
            MsgBox("Error in LoadGrid_Selection:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            Return False
        End Try

        Return True
    End Function
    Sub HideColumns()
        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 = " & CURRENT_FORM_ID
            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

                ' FormID und RecordID immer ausblenden
                grvwGrid.Columns.Item("Record-ID").Visible = False
                grvwGrid.Columns.Item("Form-ID").Visible = False
            End If
        Catch ex As Exception
            MsgBox("Error in HideColumns:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Sub Show_Selected_Record_Data(GridColumn_String As String, Optional DirectRecID As Integer = 0)
        Try
            'Me.pnlDetails.Visible = True
            ZeigeRecordLogsToolStripMenuItem.Enabled = False
            If DirectRecID = 0 Then
                If LogErrorsOnly = False Then ClassLogger.Add(">> Record wird über Datagrid focusedRow geladen", False)
                'Überhaupt Columns in Grid?
                If Get_Grid_Column_Count() = 0 Then
                    Me.pnlDetails.Enabled = False
                    Me.tsButtonShowWorkflowTasks.Enabled = False

                    'tsstatus_Detail_show(True, "Keine Columns in Grid")
                    Exit Sub
                Else
                    Me.pnlDetails.Enabled = True
                End If
                'Überhaupt Rows in Grid?
                If Get_Grid_Row_Count() > 0 Then
                    Dim Grid_RecordID = Get_Focused_Row_Cell_Value(GridColumn_String)
                    If Grid_RecordID Is Nothing = False Then
                        SELECTED_RECORD_ID = Grid_RecordID
                        CURRENT_RECORD_ID = 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)
                        Exit Sub
                    End If
                End If

            Else 'Record wird direkt geladen
                If LogErrorsOnly = False Then ClassLogger.Add(">> Record wird DIREKT geladen", False)
                SELECTED_RECORD_ID = DirectRecID
                CURRENT_RECORD_ID = DirectRecID
            End If

            Dim Record_Changes As String = "SELECT count(GUID) FROM VWPMO_RECORD_CHANGES WHERE RECORD_ID = " & CURRENT_RECORD_ID
            Dim RC = ClassDatabase.Execute_Scalar(Record_Changes)
            If Not RC Is Nothing Then
                If RC > 0 Then
                    ZeigeRecordLogsToolStripMenuItem.Enabled = True
                End If
            End If
            'Die aktuelle Ebene überprüfen und den Datensatz übergeben, ebenso den PARENT-Record setzen
            Select Case ACT_EBENE
                Case 1
                    PARENT_RECORDID = 0
                    EBENE1_RECID = SELECTED_RECORD_ID
                    CURRENT_PARENTID = EBENE1_RECID
                    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
                    EBENE2_RECID = SELECTED_RECORD_ID
                    If Not EBENE2_COLUMNNAME Is Nothing Then
                        EBENE2_GRID_RESULT = Get_GridResult(EBENE2_COLUMNNAME)
                        'Dim sql As String = "select @p " & EBENE_SQLRESULT & " where [Record-ID] = " & SelectedRecordID
                        'sql = sql.Replace("@p", EBENE2_COLUMNNAME)
                        'Dim result = ClassDatabase.Execute_Scalar(sql)
                        'EBENE2_GRID_RESULT = result 'grvwSelection.GetFocusedRowCellValue(grvwSelection.Columns(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
                    If EBENE1_RECID > 0 Then
                        PARENT_RECORDID = EBENE1_RECID
                        CURRENT_PARENTID = EBENE1_RECID
                    Else
                        CURRENT_PARENTID = EBENE2_RECID
                    End If
                Case 3
                    EBENE3_RECID = SELECTED_RECORD_ID
                    If Not EBENE3_COLUMNNAME Is Nothing Then
                        EBENE3_GRID_RESULT = Get_GridResult(EBENE3_COLUMNNAME)
                        'EBENE3_GRID_RESULT = grvwSelection.GetFocusedRowCellValue(grvwSelection.Columns(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
                    If EBENE2_RECID > 0 Then
                        PARENT_RECORDID = EBENE2_RECID
                        CURRENT_PARENTID = EBENE2_RECID
                    End If
            End Select



            Me.tsButtonShowWorkflowTasks.Enabled = True
            Me.tsButtonShowTaskOverview.Enabled = True
            'tsstatus_Detail_show(False, "")
        Catch ex As Exception
            MsgBox("Error in SelectedRecord_ShowData:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub

    Function Get_GridResult(Columnname As String)
        Dim result = Get_Focused_Row_Cell_Value(Columnname)
        If IsDBNull(result) OrElse result = "" Then
            Return "No Column configured"
        Else
            Return result
        End If
    End Function

    Function GetSelected_RecordID()
        Try
            If Get_Grid_Column_Count() = 0 Then
                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
    Sub Load_Record_Data()
        Select Case EDIT_STATE
            Case EditState.None
                'Ganz normalerDatensatzwechsel Wechsel
                Show_Selected_Record_Data("Record-ID")
                'Refresh_Treeview_SelectedData()

                Update_Status_Label(False)
                'tslblStatusMain_show(False, "")
            Case EditState.Insert
                'Refresh_Treeview_SelectedData()
            Case EditState.Update
                ' Refresh_Treeview_SelectedData()
        End Select
        Select Case TCDetails.SelectedTabPageIndex
            Case 0
                'Die Values in die Controls laden
                If EDIT_STATE = EditState.None Then
                    'TabPageDetails.Text = "Detaileingabe zu '" & ACT_EBENE_STRING & "' - Record(" & SelectedRecordID & ")"
                    'Die Daten auf dem Panel laden
                    ClassControlValues.LoadControlValuesNeu(SELECTED_RECORD_ID, CURRENT_PARENTID, CURRENT_FORM_ID, CtrlBuilder.AllControls)
                    'Load_Control_Values(CtrlBuilder.AllControls)
                    'Refresh_Treeview_SelectedData()
                    RECORD_CHANGED = False
                End If
            Case 1
                RUN_WD_SEARCH(WD_Suche, "RECORD")
            Case 2
                'If FOLLOW_UPisActive = True Then Refresh_FollowUps()
        End Select
        'DT_FU_Record = Nothing
        'VerknüpfungenToolStripMenuItem.Enabled = True
        Update_Record_Label(SELECTED_RECORD_ID)

        If FOLLOW_UPisActive = True Then Refresh_FollowUp_TabHeader()

        Show_act_WFTask()
        Get_RecordCounts_Nodes()
        pnlDetails.Enabled = False

        Refresh_TaskOverview()
    End Sub

    Private Sub Refresh_FollowUp_TabHeader()
        Try
            DT_FU_Record = ClassDatabase.Return_Datatable("select * from VWPMO_FOLLOW_UP_EMAIL_ENTITY_RECORD where Record_ID = " & CURRENT_RECORD_ID, "Refresh FollowUp TabHeader")
            If IsNothing(DT_FU_Record) Then
                TabFollowUp.Text = "Wiedervorlage (Nicht Abrufbar)"
                Exit Sub
            End If
            If DT_FU_Record.Rows.Count = 0 Then
                TabFollowUp.Text = "Wiedervorlage (Nicht aktiviert)"
            Else
                TabFollowUp.Text = "Wiedervorlage (Aktive Profile)"
            End If
        Catch ex As Exception
            MsgBox("Error in Refresh_FollowUp_TabHeader:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub

    Private Function Update_Record_OnChange() As String
        ' Record Speichern
        Dim ResultMessage = CtrlCommandUI.SaveRecord(SELECTED_RECORD_ID, CURRENT_FORM_ID, PARENT_RECORDID)
        'Jetzt die für die Entität notwendigen Prroceduren ausführen
        Customer_Run_Procedures()

        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 = " & CURRENT_FORM_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", CURRENT_FORM_ID)
                    prsql = prsql.ToUpper.Replace("@RECORD_ID", CURRENT_RECORD_ID)
                    ClassDatabase.Execute_non_Query(prsql, True)
                Next
            End If
        Catch ex As Exception
            MsgBox("Error in Customer_Run_Procedures:" & vbNewLine & ex.Message)
        End Try
    End Sub

#Region "WindreamSuche"
    Private Function 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)
            If DTWD.Rows.Count = 1 Then
                TabWindream.PageVisible = True

                If IsDBNull(DTWD.Rows(0).Item(0)) Then
                    windream_Docshow = False
                    WindreamSucheNeuLadenToolStripMenuItem.Visible = False
                    Exit Function
                End If
                WindreamSucheNeuLadenToolStripMenuItem.Visible = True
                windream_Docshow = True
            Else
                windream_Docshow = False
                TabWindream.PageVisible = False

                WindreamSucheNeuLadenToolStripMenuItem.Visible = False
            End If
        Catch ex As Exception
            MsgBox("Error in Check windream show:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            windream_Docshow = False
        End Try

    End Function
    Private Sub RUN_WD_SEARCH(BaseSearch As String, Type As String)
        Try
            Dim windream_temp_search
            If Not windream_Docshow = True Or Sett_LoadWD_Docs = False Or TCDetails.SelectedTabPageIndex <> 1 Then
                Exit Sub
            End If
            Cursor = Cursors.WaitCursor
            Dim DTWD As DataTable
            If Type = "ENTITY" Then
                Dim _sql = "SELECT WINDREAM_SEARCH,SEARCH_PATTERN1,SEARCH_PATTERN2,SEARCH_PATTERN3,SEARCH_PATTERN4,SEARCH_PATTERN5 FROM TBPMO_FORM_CONSTRUCTOR_DETAIL WHERE WINDREAM_SEARCH <> '' AND FORM_ID = " & CURRENT_FORM_ID
                DTWD = ClassDatabase.Return_Datatable(_sql)
                If DTWD.Rows.Count = 1 Then
                    If IsDBNull(DTWD.Rows(0).Item(0)) Then
                        Clear_Windream_ResultList()
                        Exit Sub
                    End If
                    tslblWindreamView.Text = "Windream-Dokumente für Entität: " & ACT_EBENE_STRING
                Else
                    Clear_Windream_ResultList()
                    Exit Sub
                End If
            Else
                Dim sql = "SELECT WINDREAM_SEARCH,SEARCH_PATTERN1,SEARCH_PATTERN2,SEARCH_PATTERN3,SEARCH_PATTERN4,SEARCH_PATTERN5 FROM TBPMO_FORM_VIEW WHERE WINDREAM_SEARCH <> '' AND FORM_ID = " & CURRENT_FORM_ID
                DTWD = ClassDatabase.Return_Datatable(sql)
                If DTWD.Rows.Count = 1 Then
                    If IsDBNull(DTWD.Rows(0).Item(0)) Then
                        Clear_Windream_ResultList()
                        Exit Sub
                    End If
                    tslblWindreamView.Text = "Windream-Dokumente für Record: " & CURRENT_RECORD_ID
                Else
                    Clear_Windream_ResultList()
                    Exit Sub
                End If
            End If
            'Die SearchPatterns durchlaufen und zwischenspeichern
            If IsDBNull(DTWD.Rows(0).Item(0)) Then
                Clear_Windream_ResultList()
                Exit Sub
            End If
            BaseSearch = DTWD.Rows(0).Item(0)
            SP1 = DTWD.Rows(0).Item(1)
            If IsDBNull(DTWD.Rows(0).Item(2)) Then
                SP2 = ""
            Else
                SP2 = DTWD.Rows(0).Item(2)
            End If
            If IsDBNull(DTWD.Rows(0).Item(3)) Then
                SP3 = ""
            Else
                SP3 = DTWD.Rows(0).Item(3)
            End If
            If IsDBNull(DTWD.Rows(0).Item(4)) Then
                SP4 = ""
            Else
                SP4 = DTWD.Rows(0).Item(4)
            End If
            If IsDBNull(DTWD.Rows(0).Item(5)) Then
                SP5 = ""
            Else
                SP5 = DTWD.Rows(0).Item(5)
            End If

            'Eine tempfile generieren
            Dim tempFilename1 = My.Computer.FileSystem.GetTempFileName()
            'Nur den Filenamen ohne Erweiterung
            Dim tempName = Path.GetFileNameWithoutExtension(tempFilename1)
            'tempfile lsöchen
            If My.Computer.FileSystem.FileExists(tempFilename1) Then
                My.Computer.FileSystem.DeleteFile(tempFilename1)
            End If
            Try
                Dim temppath = Path.GetTempPath

                Dim EncodingFormat As Encoding
                Dim WDUnicode = ClassDatabase.Execute_Scalar("SELECT WD_UNICODE FROM TBPMO_KONFIGURATION WHERE GUID = 1")
                If WDUnicode = True Then
                    EncodingFormat = Encoding.GetEncoding(1252) '1252
                    If LogErrorsOnly = False Then ClassLogger.Add(">> Unicode is used (Encoding.GetEncoding(1252))", False)
                Else
                    If LogErrorsOnly = False Then ClassLogger.Add(">> UTF8 (Encoding.GetEncoding(65001))", False)
                    EncodingFormat = Encoding.GetEncoding(65001)
                End If


                Dim fileContents As String
                If LogErrorsOnly = False Then ClassLogger.Add(">> ReadAlltext: " & windream_temp_search, False)
                fileContents = My.Computer.FileSystem.ReadAllText(BaseSearch, EncodingFormat) ', System.Text.Encoding.Unicode
                If LogErrorsOnly = False Then ClassLogger.Add(">> fileContents geladen", False)
                fileContents = fileContents.Replace("Í", "Ö")
                Dim _sp1 = SP1
                Dim _sp2 = SP2
                Dim _sp3 = SP3
                Dim _sp4 = SP4
                Dim _sp5 = SP5

                If _sp1.ToString <> String.Empty Then
                    _sp1 = Return_SearchPattern(_sp1.ToString)
                    fileContents = fileContents.Replace("%pattern1%", _sp1)
                    fileContents = fileContents.Replace("471101", _sp1)
                End If
                If _sp2.ToString <> String.Empty Then
                    _sp2 = Return_SearchPattern(_sp2.ToString)
                    If _sp2 = 0 Then
                        _sp2 = ""
                    End If
                    fileContents = fileContents.Replace("%pattern2%", _sp2)
                    fileContents = fileContents.Replace("471102", _sp2)
                End If
                If _sp3.ToString <> String.Empty Then
                    _sp3 = Return_SearchPattern(_sp3.ToString)
                    If _sp3 = 0 Then
                        _sp3 = ""
                    End If
                    fileContents = fileContents.Replace("%pattern3%", _sp3)
                    fileContents = fileContents.Replace("471103", _sp3)
                End If
                If _sp4.ToString <> String.Empty Then
                    _sp4 = Return_SearchPattern(_sp4.ToString)
                    If _sp4 = 0 Then
                        _sp4 = ""
                    End If
                    fileContents = fileContents.Replace("%pattern4%", _sp4)
                    fileContents = fileContents.Replace("471104", _sp4)
                End If
                If _sp5.ToString <> String.Empty Then
                    _sp5 = Return_SearchPattern(_sp5.ToString)
                    If _sp5 = 0 Then
                        _sp5 = ""
                    End If
                    fileContents = fileContents.Replace("%pattern5%", _sp5)
                    fileContents = fileContents.Replace("471105", _sp5)
                End If
                'Die windream File zusammensetzen
                windream_temp_search = temppath & tempName & ".wdf"
                TEMP_FILES.Add(windream_temp_search)
                'Die File schreiben
                My.Computer.FileSystem.WriteAllText(windream_temp_search, fileContents, False, EncodingFormat)
                My.Computer.FileSystem.WriteAllText(temppath & "SEARCH_COPY.wdf", fileContents, False, EncodingFormat)
                ' XML-Datei öffnen und laden
                Dim Stream As New IO.StreamReader(CStr(windream_temp_search), EncodingFormat)
                Dim Reader As New System.Xml.XmlTextReader(Stream)

                ' XML-Datei initialisieren
                Dim xml As New System.Xml.XmlDocument()
                ' XML-Datei öffnen und laden
                xml.Load(Reader)
                Reader.Close()
                xml.Save(windream_temp_search)
                If LogErrorsOnly = False Then ClassLogger.Add(">> Xml Generiert: " & windream_temp_search, False)

                Dim windreamSucheErgebnisse As WMObjects
                Try
                    windreamSucheErgebnisse = Me._windream.GetSearchDocuments(windream_temp_search)
                Catch ex As Exception
                    MsgBox("Error in windreamSucheErgebnisse:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
                End Try

                If windreamSucheErgebnisse.Count > 0 Then



                    TabWindream.Text = "windream-Dateien (" & windreamSucheErgebnisse.Count & ")"

                    AxObjectListControl.SetIconMode(True)
                    AxObjectListControl.RemoveAllColumnHeader()
                    Me.AxObjectListControl.SetSession(ClassWindream.oSession, "", "")
                    'Change the status icon
                    'ICON STATES:
                    Me.AxObjectListControl.SetStatusIcon(0)
                    'Change the icon
                    Me.AxObjectListControl.SetStatusIcon(2)

                    Try
                        Dim sql_ResultList = "select * from TBPMO_WINDREAM_RESULTLIST_CONFIG where guid = 1"
                        Dim DT As DataTable = ClassDatabase.Return_Datatable(sql_ResultList, "GET RESULTLIST KONFIG")
                        If Not DT Is Nothing And DT.Rows.Count = 1 Then
                            Dim anzparam As Integer = 1
                            For Each Column As DataColumn In DT.Columns
                                If Column.ColumnName.StartsWith("COLUMN") And Column.ColumnName.EndsWith("WIDTH") = False Then
                                    Dim sql = String.Format("select {0} from TBPMO_WINDREAM_RESULTLIST_CONFIG Where GUID = 1", Column.ColumnName)
                                    Dim ColumnName = ClassDatabase.Execute_Scalar(sql, True)
                                    If Not IsDBNull(ColumnName) Then
                                        If Not IsDBNull(ColumnName) Or IsNothing(ColumnName) Or ColumnName <> "" Or ColumnName <> "{}" Then
                                            'Jetzt die Spalten aus Array hinzufügen und Breite konfigurieren
                                            sql = String.Format("select COLUMN{0}_WIDTH from TBPMO_WINDREAM_RESULTLIST_CONFIG Where GUID = 1", anzparam)
                                            Dim Width = ClassDatabase.Execute_Scalar(sql, True)
                                            If IsNothing(Width) Or IsDBNull(Width) Then
                                                Width = 200
                                            End If
                                            'You need to use the column name here
                                            'Please note that some attributes or indices will not be displayed
                                            'Try not to add the same header twice, it will throw cause problems if you do that
                                            Me.AxObjectListControl.AddColumnHeader(ColumnName, Width)
                                            anzparam += 1
                                        End If
                                    End If
                                End If
                            Next
                        Else
                            Dim param As New List(Of String)
                            'The file name
                            param.Add("szLongName")
                            'The document-Type
                            param.Add("szText37")
                            'Versionsnummer
                            param.Add("dwVersionNumber")
                            'Datumsangaben
                            param.Add("dwCreationDate")
                            param.Add("dwCreation_Time")

                            'Add all search params
                            For Each spar As String In param
                                Dim width As Integer = 200
                                Select Case spar
                                    Case "szLongName"
                                        'Dateiname
                                        width = 300
                                    Case "szText37"
                                        'Dokumentart
                                        width = 160
                                    Case "dwCreationDate"
                                        'Erstelldatum
                                        width = 90
                                    Case "dwCreation_Time"
                                        'Erstell-Zeit
                                        width = 120
                                End Select
                                'You need to use the column name here
                                'Please note that some attributes or indices will not be displayed
                                'Try not to add the same header twice, it will throw cause problems if you do that
                                Me.AxObjectListControl.AddColumnHeader(spar, width)
                            Next

                        End If
                    Catch ex As Exception
                        MsgBox("Unexpected Error in Construct windreamResultList: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
                    End Try


                    If LogErrorsOnly = False Then ClassLogger.Add(">> AxObjectListControl geladen ", False)
                    'Execute the search
                    Dim results As WMObjects = windreamSucheErgebnisse
                    If LogErrorsOnly = False Then ClassLogger.Add(">> results geladen ", False)
                    'Set the contents without displaying them
                    AxObjectListControl.SetContentsEx(results)
                    'Change the icon
                    AxObjectListControl.SetStatusIcon(5)
                    'Display the results...
                    'The Previous Object Count
                    Dim poc As Integer = 0
                    'Display new objects, as long as the objectcount changes after displaying the objects

                    Do Until (poc <> AxObjectListControl.GetObjectCount)
                        poc = AxObjectListControl.GetObjectCount
                        'If you want, you can display more items at a timeRefresh_FollowUp_TabHeader
                        'But do not display to many at a time or the user interface could freeze
                        'Maybe try 50
                        AxObjectListControl.DisplayResults(WDResultListCount)
                    Loop
                    AxObjectListControl.SetStatusIcon(3)
                Else
                    Clear_Windream_ResultList()
                End If

            Catch ex As Exception
                MsgBox("Error in execute-windreamSearch:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            End Try

            Cursor = Cursors.Default
        Catch ex As Exception
            MsgBox("Error in RUN_WD_SEARCH:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            Cursor = Cursors.Default
        End Try

    End Sub
    Private Function Return_SearchPattern(ByVal content As String)
        Select Case content.ToUpper
            Case "@Record-ID".ToUpper
                Return CURRENT_RECORD_ID
            Case "@EntityID".ToUpper
                Return CURRENT_FORM_ID
            Case "@ParentID".ToUpper
                Return PARENT_RECORDID
            Case Else
                MsgBox("Undefinierter Pattern '" & content & "' in der Windream-SuchKonfiguration. Bitte den Administrator verständigen", MsgBoxStyle.Exclamation)
                ClassLogger.Add(" >> Undefinierter Such-Pattern: " & 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()
        AxObjectListControl.RemoveAllColumnHeader()
        Me.AxObjectListControl.ClearResultList()
        TabWindream.Text = "windream-Dateien"
    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
            MsgBox("Error in ShowDocView:" & vbNewLine & ex.Message, MsgBoxStyle.Exclamation)
        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_Tree_View_Data()
    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_Tree_View_Data()
    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_Tree_View_Data()
    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, CURRENT_FORM_ID, USER_GUID)
        If ClassDatabase.Execute_non_Query(upd, True) = 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
    End Sub
#End Region

    Private Sub TCDetails_SelectedPageChanged(sender As Object, e As DevExpress.XtraTab.TabPageChangedEventArgs) Handles TCDetails.SelectedPageChanged
        Select Case TCDetails.SelectedTabPageIndex
            Case 0
                'If RECORD_NEEDS_REFRESH = True Then
                '    ClassControlValues.LoadControlValues(CURRENT_RECORD_ID, CURRENT_FORM_ID, CtrlBuilder.AllControls)
                '    '  UpdRECORD_NEEDS_REFRESH(False)
                'End If

                'Refresh_CreatedChangedRecordByID(CURRENT_RECORD_ID)
                ' RECORD_CHANGED = False
            Case 1 'windream-Dokumente
                If CURRENT_RECORD_ID = 0 Then
                    RUN_WD_SEARCH(WD_Suche, "ENTITY")
                Else
                    RUN_WD_SEARCH(WD_Suche, "RECORD")
                End If

            Case 2
                Refresh_FollowUps()
        End Select
    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
            MsgBox("Error in Refresh_FollowUps:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        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)
        If act_FormViewID <> 0 Then
            ClassDragDrop.Drop_File(e)
            Check_Dropped_Files(act_FormViewID)
        End If
    End Sub
    Sub Check_Dropped_Files(FORMVIEW_ID As Integer)
        Try
            CURRENT_FORMVIEW_ID = FORMVIEW_ID
            For Each Str As Object In ClassDragDrop.files_dropped
                If Not IsNothing(Str) Then
                    ClassLogger.Add(">> Check_Dropped_Files:" & Str.ToString, False)
                    Dim DropType = Str.Substring(0, Str.LastIndexOf("@") + 1)
                    Dim CURRENT_WORKFILE = Str.Substring(Str.LastIndexOf("@") + 1)
                    TBPMO_FILES_USERTableAdapter.cmdInsert(CURRENT_WORKFILE, Environment.UserName, DropType)
                End If

            Next
            TBPMO_FILES_USERTableAdapter.Fill(DD_DMSDataSet.TBPMO_FILES_USER, Environment.UserName)
            For Each Filerow As DataRow In DD_DMSDataSet.TBPMO_FILES_USER.Rows
                Dim worked = ClassDatabase.Execute_Scalar("SELECT WORKED FROM TBPMO_FILES_USER WHERE GUID = " & Filerow.Item("GUID"))
                If worked = False Then
                    'Dim datei = Str.ToString.Replace("@DROPFROMFSYSTEM@", "")
                    CURRENT_FILEID = Filerow.Item(0)
                    frmWD_Index_Dokart.ShowDialog()
                    RUN_WD_SEARCH(WD_Suche, "RECORD")
                End If


            Next
        Catch ex As Exception
            MsgBox("Check_Dropped_Files: " & ex.Message, MsgBoxStyle.Critical)
        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
#End Region

#Region "Follow Up"
    Private Sub ListViewFollowUp_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListViewFollowUp.SelectedIndexChanged
        If Me.ListViewFollowUp.SelectedItems.Count > 0 Then
            FOLL_UP_ID = ListViewFollowUp.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"), CURRENT_RECORD_ID)
                    If Not IsNothing(datevalue) Then
                        If datevalue = "00:00:00" Then
                            dtpFollowUp.Value = CDate(Now)
                        End If
                        FOLL_UP_RECORD_DEFINED = True
                        dtpFollowUp.Value = CDate(datevalue)
                    Else
                        dtpFollowUp.Value = CDate(Now)
                        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
                        dtpFollowUp.Text = CStr(caption)
                    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"), CURRENT_RECORD_ID)
                    If Not IsNothing(checkvalue) Then
                        chkFollowUp.Checked = CBool(checkvalue)
                    Else
                        chkFollowUp.Checked = False
                    End If
                    Dim captionCheck = ClassDatabase.Execute_Scalar("SELECT CONTROL_TEXT FROM TBPMO_CONTROL_SCREEN WHERE SCREEN_ID = 1 AND CONTROL_ID = " & DR.Item("DEPENDENT_DONE_CTRL_ID"), True)
                    If Not IsNothing(captionCheck) Then
                        chkFollowUp.Text = CStr(captionCheck)
                    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 = " & CURRENT_RECORD_ID & " ORDER BY T1.USERNAME"
            Dim DT As DataTable = ClassDatabase.Return_Datatable(sql, "Load_FollowUpUser")
            ListBoxUser2Profile.DataSource = DT
            ListBoxUser2Profile.DisplayMember = DT.Columns(1).ColumnName
            ListBoxUser2Profile.ValueMember = DT.Columns(0).ColumnName
        Catch ex As Exception
            MsgBox("Fehler bei Load_FUUser:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        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, CURRENT_RECORD_ID, dtpFollowUp.Value) = True Then
            lblFollowUp_save.Text = "Wiedervorlage gespeichert - " & 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, CURRENT_RECORD_ID, chkFollowUp.Checked.ToString) = True Then
            lblFollowUp_save.Text = "Wiedervorlage gespeichert - " & 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
                ListViewFollowUp.Items.Clear()
                Dim anz As Integer = 0
                For Each DR As DataRow In DT_FU_ENTITY.Rows
                    Dim name = DR.Item("NAME")
                    ListViewFollowUp.Items.Add(DR.Item("GUID"))
                    ListViewFollowUp.Items(anz).SubItems.Add(DR.Item("NAME"))
                    anz += 1
                Next

            Else
                FOLLOW_UPisActive = False
                TabFollowUp.PageVisible = False
            End If
        Catch ex As Exception
            MsgBox("Error in Check Follow Up:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            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 CURRENT_RECORD_ID > 0 Then
            frmWF_TaskEditor.ShowDialog()
            Show_act_WFTask()
            Refresh_TaskOverview()
        End If
    End Sub

    Private Sub tsButtonShowTaskOverview_Click(sender As Object, e As EventArgs) Handles tsButtonShowTaskOverview.Click
        frmTaskOverview.Show()
    End Sub


    Sub Refresh_TaskOverview()
        Dim frmCollection As New FormCollection()
        frmCollection = Application.OpenForms()
        If frmTaskOverview.IsHandleCreated Then
            If Sett_TaskOverviewKeepInFront = True Then
                frmTaskOverview.Refresh()
            End If
            'Else
            '    Console.WriteLine("frmTaskOverview NICHT geladen")
        End If
    End Sub
    Sub Show_act_WFTask()
        Try
            Me.VWPMO_WF_ACTIVETableAdapter.FillByRecord(Me.DD_DMSDataSet.VWPMO_WF_ACTIVE, CURRENT_RECORD_ID, Environment.UserName)
            tsslblWorkflowstate.BackColor = Color.Black
            If DD_DMSDataSet.VWPMO_WF_ACTIVE.Rows.Count > 0 Then
                CURRENT_TASK_ID = Me.DD_DMSDataSet.VWPMO_WF_ACTIVE.Rows(0).Item("WF_TASK_ID")
                Dim text = "Task: " & Me.DD_DMSDataSet.VWPMO_WF_ACTIVE.Rows(0).Item("TITLE")
                text += " - " & Me.DD_DMSDataSet.VWPMO_WF_ACTIVE.Rows(0).Item("STATE_DESC")
                text += " - " & Me.DD_DMSDataSet.VWPMO_WF_ACTIVE.Rows(0).Item("DUE_DATE")
                tsslblWorkflowstate.Text = text
                tsslblWorkflowstate.Visible = True
                tsButtonShowWorkflowTasks.Visible = True
                tsButtonShowWorkflowTasks.Enabled = True

                Dim Colorstring = Me.DD_DMSDataSet.VWPMO_WF_ACTIVE.Rows(0).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
                End If

            Else
                tsslblWorkflowstate.Visible = False
                tsButtonShowWorkflowTasks.Visible = False
                ' grvwSelection.Appearance.FocusedRow.BackColor = Color.Fuchsia
            End If
            Dim sql1 As String = "SELECT COUNT(*) FROM TBPMO_WORKFLOW_FORM where FORM_ID = @FORM_ID"
            sql1 = sql1.Replace("@FORM_ID", CURRENT_FORM_ID)
            Dim result As Integer = ClassDatabase.Execute_Scalar(sql1)
            If result > 0 Then
                tsButtonShowWorkflowTasks.Visible = True
                tsButtonShowWorkflowTasks.Enabled = True
            End If


        Catch ex As Exception
            MsgBox("Error in Show act WFTask: " & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
#End Region

    Private Sub ResetEbenenAuswahlToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ResetEbenenAuswahlToolStripMenuItem.Click
        ACT_EBENE = 0
        ACT_EBENE_STRING = ""
        EBENE1_ENTITY = ""
        EBENE1_RECID = 0
        EBENE2_ENTITY = ""
        EBENE2_RECID = 0
        EBENE3_ENTITY = ""
        EBENE3_RECID = 0

        Load_Tree_View(CONSTRUCTORID)
    End Sub

    Private Sub DateiimportEntitätToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles DateiimportEntitätToolStripMenuItem.Click
        If CURRENT_PARENTID = 0 Then
            Exit Sub
        End If
        frmWD_EntityImport.ShowDialog()
    End Sub


    Private Sub WindreamsucheNeuLadenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles WindreamsucheNeuLadenToolStripMenuItem.Click
        RUN_WD_SEARCH(WD_Suche, "RECORD")
    End Sub

    Private Sub WorkflowTasksNeuErstellenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles WorkflowTasksNeuErstellenToolStripMenuItem.Click

    End Sub

    Private Sub ZeigeRecordLogsToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ZeigeRecordLogsToolStripMenuItem.Click
        frmRecord_Changes.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 = SelectedNode.Tag
                If FormId > 0 Then
                    CURRENT_FORM_ID = FormId
                    Cursor = Cursors.WaitCursor
                    OpenFormLevelDesigner()
                    Cursor = Cursors.Default
                End If
            End If
        Catch ex As Exception
            MsgBox("Unexpected Error in Open Designer: " & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Sub OpenFormLevelDesigner()
        Dim frm As New frmLevel_Designer
        frm = frmLevel_Designer.Instance
        'frm.MdiParent = frmMain
        'frmMain.tscMain.ContentPanel.Controls.Add(frm)
        frm.Show()

        Dim frm2 As New frmTool_ControlDesigner
        frm2 = frmTool_ControlDesigner.Instance
        If My.Settings.User_DesignPanels_areChild = True Then
            frm2.MdiParent = frmMain
        End If

        'frmMain.tscMain.ContentPanel.Controls.Add(frm2)
        frm2.Show()

        Dim frm3 As New frmTool_ControlProperties
        frm3 = frmTool_ControlProperties.Instance
        If My.Settings.User_DesignPanels_areChild = True Then
            frm3.MdiParent = frmMain
        End If
        'frmMain.tscMain.ContentPanel.Controls.Add(frm3)
        frm3.Show()
    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
            result = MessageBox.Show("Datei wurde erstellt! Wollen Sie diese nun öffnen?", "Erfolgsmeldung:", 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
        Me.BringToFront()
        ' LoadLayouts()
        Load_Level1()
        Jump_Record()
    End Sub
    Sub Jump_Record()
        Try
            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
        Catch ex As Exception
            MsgBox("Unexpected error in jump-Record: " & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Private Sub CheckNode(ByVal n As TreeNode, FormID As Integer)
        Dim aNode As TreeNode

        For Each aNode In n.Nodes
            If 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 FilterString As String = String.Format("[Record-ID] = {0}", JUMP_RECORD_ID)
            grvwGrid.ActiveFilterString = FilterString
        ElseIf GRID_TYPE = GridType.Carousel Then
            Dim rowHandle = grvwCarousel.LocateByValue(0, grvwCarousel.Columns("Record-ID"), JUMP_RECORD_ID)
            grvwCarousel.FocusedRowHandle = rowHandle
        ElseIf GRID_TYPE = GridType.Tiles Then
            Dim rowHandle = grvwTiles.LocateByValue(0, grvwTiles.Columns("Record-ID"), JUMP_RECORD_ID)
            grvwTiles.FocusedRowHandle = rowHandle
        End If
    End Sub


    Sub Load_Templates()
        Try
            Dim sql As String = "SELECT * FROM VWPMO_TEMPLATE_ENTITY WHERE ENTITY_ID = " & CURRENT_FORM_ID & " ORDER BY TEMPLATE_NAME"
            Dim DT As DataTable = ClassDatabase.Return_Datatable(sql, "Load_Templates")
            If Not IsNothing(DT) Then
                If DT.Rows.Count > 0 Then
                    OfficeVorlagenToolStripMenuItem.Enabled = True
                    OfficeVorlagenToolStripMenuItem.DropDownItems.Clear()
                    For Each row As DataRow In DT.Rows
                        Dim item As ToolStripMenuItem = OfficeVorlagenToolStripMenuItem
                        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
                    OfficeVorlagenToolStripMenuItem.Enabled = False
                End If
            End If
        Catch ex As Exception
            MsgBox("Error in Load_Templates:" & vbNewLine & ex.Message, MsgBoxStyle.Exclamation)
        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 CURRENT_RECORD_ID > 0 Then
            Dim SOLLENTITY_ID = ClassDatabase.Execute_Scalar("SELECT ENTITY_ID FROM  VWPMO_TEMPLATE_ENTITY WHERE TEMPLATE_ID = " & TemplateID)
            Dim REC_ENTITY_ID = ClassDatabase.Execute_Scalar("SELECT FORM_ID FROM TBPMO_RECORD WHERE GUID = " & CURRENT_RECORD_ID)

            If Not IsNothing(SOLLENTITY_ID) Then
                If CInt(SOLLENTITY_ID) = REC_ENTITY_ID Then
                    Cursor = Cursors.WaitCursor
                    If ClassOfficeTemplate.Open_Word_Template(TemplateID, CURRENT_RECORD_ID) = True Then
                        RUN_WD_SEARCH(WD_Suche, "RECORD")
                        Update_Status_Label(True, "Vorlagen-Datei erfolgreich nach windream importiert!")
                    End If
                    Cursor = Cursors.Default
                Else
                    MsgBox("Bitte wählen Sie nochmal einen Datensatz aus!", MsgBoxStyle.Exclamation)
                End If
            End If
        Else
            MsgBox("Bitte wählen Sie zuerst einen Datensatz aus.", MsgBoxStyle.Exclamation)
        End If


    End Sub

    Sub Load_Level1()
        Try
            Dim sql As String = "SELECT * from VWPMO_CONSTRUCTOR_FORMS WHERE PARENT_ID = 0 AND CONSTRUCT_ID = " & CONSTRUCTORID & " ORDER BY SEQUENCE"
            Dim dt As DataTable = ClassDatabase.Return_Datatable(sql)

            If Not IsNothing(dt) Then
                If dt.Rows.Count >= 1 Then
                    Dim tn As TreeNode = TreeViewMain.Nodes(0)
                    TreeViewMain.SelectedNode = tn
                    TreeViewMain.Select()
                End If
            End If
        Catch ex As Exception
            MsgBox("Error in Load_Level1:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        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 btnAddUser_FollowUp_Click(sender As Object, e As EventArgs) Handles btnAddUser_FollowUp.Click

    End Sub
End Class