Imports System.IO
Imports System.Runtime.InteropServices
Imports DevExpress.XtraEditors
Imports DD_LIB_Standards

Public Class frmRecordView
    Private recordView As ClassRecordView
    Private ENTITY_ID, FORMVIEW_ID, PARENT_ENTITY_ID, WF_TASK_ID, RECORD_ID As Integer
    Private Const SEE_MASK_INVOKEIDLIST = &HC
    Private Const SEE_MASK_NOCLOSEPROCESS = &H40
    Private Const SEE_MASK_FLAG_NO_UI = &H400
    Public Const SW_SHOW As Short = 5
    Private DT_RESULTLIST_OPTIONS As DataTable
    Private DT_RESULTLIST_VARIABLE_VALUE As DataTable
    Private DT_WINDREAM_RESULTLIST As DataTable
    Private DT_DOCRESULT_DROPDOWN_ITEMS As DataTable
    Private _Changed As Boolean = False

    <DllImport("Shell32", CharSet:=CharSet.Auto, SetLastError:=True)> _
    Public Shared Function ShellExecuteEx(ByRef lpExecInfo As SHELLEXECUTEINFO) As Boolean
    End Function
    Public Structure SHELLEXECUTEINFO
        Public cbSize As Integer
        Public fMask As Integer
        Public hwnd As IntPtr
        <MarshalAs(UnmanagedType.LPTStr)> Public lpVerb As String
        <MarshalAs(UnmanagedType.LPTStr)> Public lpFile As String
        <MarshalAs(UnmanagedType.LPTStr)> Public lpParameters As String
        <MarshalAs(UnmanagedType.LPTStr)> Public lpDirectory As String
        Dim nShow As Integer
        Dim hInstApp As IntPtr
        Dim lpIDList As IntPtr
        <MarshalAs(UnmanagedType.LPTStr)> Public lpClass As String
        Public hkeyClass As IntPtr
        Public dwHotKey As Integer
        Public hIcon As IntPtr
        Public hProcess As IntPtr
    End Structure

    Private Sub frmRecordView_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        ClassWindowLocation.SaveFormLocationSize(Me, 0, CURRENT_SCREEN_ID, "frmRecordView")
        My.Settings.Save()
    End Sub

    Private Sub frmRecordView_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Try
            If USER_LANGUAGE <> "de-DE" Then
                Me.Text = "Detailview Record"
            Else
                Me.Text = "Detailansicht Record"
            End If
            recordView = New ClassRecordView(pnlDetails)
            RECORD_ID = JUMP_RECORD_ID
            recordView.LoadRecord(RECORD_ID)

            'Titel updaten
            Me.Text &= " " + RECORD_ID.ToString()
            Dim sql = "SELECT FORM_ID FROM TBPMO_RECORD WHERE GUID = " & RECORD_ID
            ENTITY_ID = ClassDatabase.Execute_Scalar(sql, True)
            ClassRightManagement.Check_Set_Rights(RECORD_ID, ENTITY_ID)
            ClassProxy.Refresh_Workflow_Data()

            sql = String.Format("select * from TBPMO_DOCSEARCH_VARIABLE_CONTROLS WHERE ENTITY_ID = {0}", ENTITY_ID) 'TBPMO_WINDREAM_RESULTLIST_CONFIG"
            DT_RESULTLIST_OPTIONS = ClassDatabase.Return_Datatable(sql, True)
            sql = String.Format("select * from TBPMO_DOCSEARCH_RESULTLIST_CONFIG WHERE VISIBLE = 1 AND ENTITY_ID = {0} AND LANGUAGE = '{1}' AND COLUMN_VIEW LIKE 'VALUE%'", ENTITY_ID, USER_LANGUAGE)
            DT_RESULTLIST_VARIABLE_VALUE = ClassDatabase.Return_Datatable(sql, True)
            Dim sql_ResultList = String.Format("select * from TBPMO_DOCSEARCH_RESULTLIST_CONFIG WHERE ENTITY_ID = {0} AND LANGUAGE = '{1}'", ENTITY_ID, USER_LANGUAGE) 'TBPMO_WINDREAM_RESULTLIST_CONFIG"
            DT_WINDREAM_RESULTLIST = ClassDatabase.Return_Datatable(sql_ResultList, True)
            sql_ResultList = String.Format("select * from TBPMO_DOCRESULT_DROPDOWN_ITEMS WHERE CONFIG_ID IN (SELECT GUID FROM TBPMO_DOCSEARCH_RESULTLIST_CONFIG WHERE ENTITY_ID = {0} AND TYPE_ID = 4 AND LANGUAGE = '{1}')", ENTITY_ID, USER_LANGUAGE)
            DT_DOCRESULT_DROPDOWN_ITEMS = ClassDatabase.Return_Datatable(sql_ResultList, True)
            TBPMO_WORKFLOW_TASK_HISTORYTableAdapter.Connection.ConnectionString = MyConnectionString
            ClassWindowLocation.LoadFormLocationSize(Me, 0, CURRENT_SCREEN_ID, "frmRecordView")

        Catch ex As Exception
            MsgBox("Unexpected error in loading form: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

        RUN_WDSEARCH_GRID()
        Load_Task_Data()
    End Sub

    Private Sub OnCBSelectedValueChanged(sender As Object, e As EventArgs)
        Try
            Dim ComboBox As DevExpress.XtraEditors.ComboBoxEdit = sender
            'Dim ItemComboBox As RepositoryItemComboBox
            'ItemComboBox = sender
            Dim item As ClassWindreamDocGrid.WindreamDocGridComboboxItem = ComboBox.SelectedItem
            Dim value As String = item.Value
            Dim configId As Integer = item.ConfigID
            Dim docId As Integer = ClassWindreamDocGrid.SELECTED_DOC_ID
            Dim user As String = USER_USERNAME

            Dim Sql As String = String.Format("EXEC PRPMO_DOC_VALUE {0}, {1}, '{2}', '{3}'", docId, configId, value, USER_USERNAME)
            ClassDatabase.Execute_non_Query(Sql, False)
        Catch ex As Exception
            MsgBox("Error:" & vbNewLine & ex.Message)
        End Try
        'Perform your actions
    End Sub

    Private Sub OnDateSelectedValueChanged(sender As Object, e As EventArgs)
        Try
            Dim DatePicker As DateEdit = sender
            Dim value As DateTime = DatePicker.EditValue
            Dim colTitle = DirectCast(GridControlDocSearch.MainView, DevExpress.XtraGrid.Views.Grid.GridView).FocusedColumn.FieldName
            Dim configId As Integer = ClassWindreamDocGrid.RESULT_CONFIG_IDS.Item(colTitle)
            Dim docId As Integer = ClassWindreamDocGrid.SELECTED_DOC_ID
            Dim user As String = USER_USERNAME
            Dim dateString = value.ToString("yyyy-MM-dd") 'hh:mm:ss.fff

            Dim Sql As String = String.Format("EXEC PRPMO_DOC_VALUE {0}, {1}, '{2}', '{3}'", docId, configId, dateString, user)
            ClassDatabase.Execute_non_Query(Sql, False)
        Catch ex As Exception
            MsgBox("Error in OnDateSelectedValueChanged:" & vbNewLine & ex.Message)
        End Try
    End Sub

    Private Sub OnTextSelectedValueChanged(sender As Object, e As EventArgs)
        Try
            Dim TextBox As TextEdit = sender
            Dim value = TextBox.EditValue
            Dim colTitle = DirectCast(GridControlDocSearch.MainView, DevExpress.XtraGrid.Views.Grid.GridView).FocusedColumn.FieldName
            Dim configId As Integer = ClassWindreamDocGrid.RESULT_CONFIG_IDS.Item(colTitle)
            Dim docId As Integer = ClassWindreamDocGrid.SELECTED_DOC_ID
            Dim user As String = USER_USERNAME

            Dim Sql As String = String.Format("EXEC PRPMO_DOC_VALUE {0}, {1}, '{2}', '{3}'", docId, configId, value, user)
            ClassDatabase.Execute_non_Query(Sql, False)
        Catch ex As Exception
            MsgBox("Error in OnTextSelectedValueChanged:" & vbNewLine & ex.Message)
        End Try
    End Sub

    Private Sub OnCheckboxValueChanged(sender As Object, e As EventArgs)
        'TODO Save Checkboxvalue
    End Sub

    Private Sub RUN_WDSEARCH_GRID()
        Me.Cursor = Cursors.WaitCursor
        Try
            Dim sw As New Stopwatch
            sw.Start()
            Dim elapsed As Double
            Dim DT_RESULT As DataTable = ClassDOC_SEARCH.Get_DOC_RESULTTABLE(DT_RESULTLIST_OPTIONS, DT_RESULTLIST_VARIABLE_VALUE, DT_WINDREAM_RESULTLIST, ENTITY_ID, RECORD_ID)
            If IsNothing(DT_RESULT) Then
                Dim msg = "wrong DocSearch-Configuration - Check logfile and contact Digital Data"
                tslblWindreamView.Text = msg
                Me.Cursor = Cursors.Default
                Exit Sub
            End If
            If DT_RESULT.Rows.Count > 0 Then 'Es gibt Suchergebnisse
                Dim msg = "Windream-Dokumente für Record: " & RECORD_ID
                If USER_LANGUAGE <> "de-DE" Then
                    msg = "windream-files for record: " & RECORD_ID
                End If

                tslblWindreamView.Text = msg

                If DT_RESULT.Rows.Count > 0 Then
                    ClassWindreamDocGrid.FillColumns(
                        GridViewDoc_Search,
                        DT_RESULT,
                        DT_WINDREAM_RESULTLIST,
                        DT_DOCRESULT_DROPDOWN_ITEMS,
                        AddressOf OnCBSelectedValueChanged,
                        AddressOf OnDateSelectedValueChanged,
                        AddressOf OnTextSelectedValueChanged,
                        AddressOf OnCheckboxValueChanged,
                        "RECORD", RECORD_ID)
                End If
            Else
                Dim msg = "Keine Windream-Dokumente für Record: " & RECORD_ID & " gefunden"
                If USER_LANGUAGE <> "de-DE" Then
                    msg = "No windream-files found for record: " & RECORD_ID
                End If


                tslblWindreamView.Text = msg
                GridControlDocSearch.DataSource = Nothing
                'Clear_Windream_ResultList()
            End If
            elapsed = sw.Elapsed.TotalSeconds
            sw.Stop()
            sw.Reset()
            If LogErrorsOnly = False Then ClassLogger.Add(" >> Run RUN_WDSEARCH_GRID took " & Format(elapsed, "0.000000000") & " seconds", False)
        Catch ex As Exception
            MsgBox("Unexpected Error in Run WD-Search Database: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
        Cursor = Cursors.Default
    End Sub
    Private Sub Load_Task_Data()
        Try
            Dim query = From table In CURRENT_VWPMO_WF_ACTIVE.AsEnumerable()
                        Select table Where table.Item("RECORD_ID") = RECORD_ID
            Dim RECORD_ROW = query.ToList()
            If RECORD_ROW.Count = 1 Then
                lblTaskState.Visible = False
                TabControlBottom.TabPages(1).Appearance.Header.BackColor = Color.Red
                For Each _row In RECORD_ROW
                    TITLETextBox.Text = _row.Item("WF_TITLE")
                    txtStateActual.Text = _row.Item("STATE_TITLE")
                    WF_IDTextBox.Text = _row.Item("WF_ID")
                    WF_TASK_IDTextBox.Text = _row.Item("WF_TASK_ID")
                    If Not IsDBNull(_row.Item("COMMENT")) Then
                        COMMENTTextBox.Text = _row.Item("COMMENT")
                    Else
                        COMMENTTextBox.Text = ""
                    End If
                    If Not IsDBNull(_row.Item("COMMENT")) Then

                    End If
                    If Not IsDBNull(_row.Item("CHANGED_WHO")) Then
                        CHANGED_WHOTextBox.Text = _row.Item("CHANGED_WHO")
                    End If

                    If Not IsDBNull(_row.Item("CHANGED_WHEN")) Then
                        CHANGED_WHENTextBox.Text = _row.Item("CHANGED_WHEN")
                    End If

                    If Not IsDBNull(_row.Item("TASK_DATE")) Then
                        DateTimePickerTASK_DATE.Text = _row.Item("TASK_DATE")
                    End If

                    If Not IsDBNull(_row.Item("DUE_DATE")) Then
                        DUE_DATEDateTimePicker.Text = _row.Item("DUE_DATE")
                    End If


                Next
            Else
                TITLETextBox.Text = ""
                txtStateActual.Text = ""
                WF_IDTextBox.Text = ""
                WF_TASK_IDTextBox.Text = ""
                COMMENTTextBox.Text = ""
                CHANGED_WHOTextBox.Text = ""
                CHANGED_WHENTextBox.Text = ""

                COMMENTTextBox.Enabled = False
                DUE_DATEDateTimePicker.Enabled = False
                DateTimePickerTASK_DATE.Enabled = False
                STATE_IDComboBox.Enabled = False
                lblTaskState.Visible = True
                btnSaveWorkflow.Enabled = False
                TabControlBottom.TabPages(1).Appearance.Header.BackColor = Nothing
            End If

            Dim Sql = "SELECT GUID FROM TBPMO_FORM_VIEW WHERE SCREEN_ID = 1 AND FORM_ID = " & ENTITY_ID
            FORMVIEW_ID = ClassDatabase.Execute_Scalar(Sql, True)
            Sql = "SELECT PARENT_ID FROM TBPMO_FORM WHERE GUID = " & ENTITY_ID
            PARENT_ENTITY_ID = ClassDatabase.Execute_Scalar(Sql, True)


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

    Private Sub TabControl1_SelectedPageChanged(sender As Object, e As DevExpress.XtraTab.TabPageChangedEventArgs) Handles TabControlBottom.SelectedPageChanged
        Try
            If TabControlBottom.SelectedTabPageIndex = 1 Then
                Load_Task_Data()
                If WF_TASK_IDTextBox.Text <> "" Then
                    WF_TASK_ID = WF_TASK_IDTextBox.Text
                    btnSaveWorkflow.Enabled = True
                Else
                    WF_TASK_ID = 0
                    btnSaveWorkflow.Enabled = False
                End If
                Try
                    If WF_TASK_ID > 0 Then
                        lblTaskState.Text = "No active workflows"
                        lblTaskState.Visible = False
                        Dim sel = ClassDatabase.Execute_Scalar("SELECT USER_SELECT FROM TBPMO_WORKFLOW_TASK WHERE GUID = " & WF_TASK_ID, True)
                        If Not IsNothing(sel) Then
                            Load_Selectable_Users(sel)
                        End If
                    End If
                Catch ex As Exception
                    MsgBox("Error in load States:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
                End Try
                Load_TASK_USER()
                Load_States()
                Check_end()
                _Changed = False
            End If
        Catch ex As Exception

        End Try


    End Sub
    Sub Check_end()
        Try
            Dim sql As String = String.Format("SELECT FINISHED FROM TBPMO_WORKFLOW_TASK WHERE GUID = {0}", WF_TASK_ID)
            Dim finished = ClassDatabase.Execute_Scalar(sql, True)
            If Not IsNothing(finished) Then
                If CBool(finished) = True Then
                    lblTaskState.Text = "Workflow-Ende erreicht!"
                    If USER_LANGUAGE <> "de-DE" Then
                        lblTaskState.Text = "Workflow End is reached!"
                    End If
                    lblTaskState.Visible = True
                    STATE_IDComboBox.Enabled = False
                    btnSaveWorkflow.Enabled = False
                Else
                    STATE_IDComboBox.Enabled = True
                    btnSaveWorkflow.Enabled = True
                End If
            Else
                STATE_IDComboBox.Enabled = True
                btnSaveWorkflow.Enabled = True
            End If
        Catch ex As Exception
            MsgBox("Error in Check_end:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub
    Sub Load_States()
        Try
            Dim sql As String = String.Format("SELECT STATE_ID, dbo.FNPMO_GETOBJECTCAPTION('{0}', 'WF_STATE_TITLE' + CONVERT(VARCHAR(5), STATE_ID), 1) AS STATE_DESC FROM TBPMO_WORKFLOW_ENTITY_STATE WHERE " &
                                              "INACTIVE = 0 AND ENTITY_ID = {1} AND STATE_ID NOT IN (" & _
                                              "SELECT STATE_ID FROM TBPMO_WORKFLOW_TASK_HISTORY WHERE WF_TASK_ID = {2})", USER_LANGUAGE, ENTITY_ID, WF_TASK_ID)
            Dim DT As DataTable = ClassDatabase.Return_Datatable(sql, True)
            If DT.Rows.Count > 0 Then
                STATE_IDComboBox.Enabled = True
                STATE_IDComboBox.DataSource = DT
                STATE_IDComboBox.DisplayMember = DT.Columns(1).ColumnName
                STATE_IDComboBox.ValueMember = DT.Columns(0).ColumnName
            Else
                lblTaskState.Text = "Workflow-Ende erreicht!"
                If USER_LANGUAGE <> "de-DE" Then
                    lblTaskState.Text = "Workflow End is reached!"
                End If
                lblTaskState.Visible = True
                STATE_IDComboBox.Enabled = False
            End If

        Catch ex As Exception
            MsgBox("Error in Getting States for Workflow:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub
    Sub Load_Selectable_Users(sel As String)
        Try
            DD_ECMAdmin.TBAD_Users.Clear()
            Dim DT As DataTable = ClassDatabase.Return_Datatable(sel, True)
            For Each userrow As DataRow In DT.Rows
                Dim newUserRow As DD_ECMAdmin.TBAD_UsersRow
                newUserRow = DD_ECMAdmin.TBAD_Users.NewTBAD_UsersRow

                newUserRow.Username = userrow.Item(1)
                Try
                    newUserRow.Email = userrow.Item(2)
                Catch ex As Exception
                    newUserRow.Email = ""
                End Try

                newUserRow.ID = userrow.Item(0)
                DD_ECMAdmin.TBAD_Users.Rows.Add(newUserRow)
                'clbUsersGroups.Items.Add(New MyListBoxItem() With {.Text = userrow.Item(1), .ExtraData = userrow.Item(0)})
            Next
        Catch ex As Exception
            MsgBox("Error in Load_Selectable_Users_for_Groups:" & vbNewLine & ex.Message & vbNewLine & "Check wether User is listed in User Client Relation!", MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub btnSaveWorkflow_Click(sender As Object, e As EventArgs) Handles btnSaveWorkflow.Click
        Try
            If _Changed = False Then
                Exit Sub
            End If
            Dim upd
            Dim ins
            Dim STATE_id As Integer
            Try
                STATE_id = STATE_IDComboBox.SelectedValue
            Catch ex As Exception
                STATE_id = 0
            End Try

            Dim sql = String.Format("SELECT dbo.FNPMO_GETOBJECTCAPTION('{0}', 'WF_STATE_TITLE' + CONVERT(VARCHAR(5), GUID), 1) AS STATE_DESC FROM TBPMO_WORKFLOW_TASK_STATE WHERE GUID = {1}", USER_LANGUAGE, STATE_IDComboBox.SelectedValue)
            Dim State_DESC = ClassDatabase.Execute_Scalar(sql, True)
            Dim Comment
            If COMMENTTextBox.Text <> "" Then
                Comment = String.Format(COMMENTTextBox.Text & vbNewLine & ">> " & Now.ToString & ": User {0} changed the state to: {1}", Environment.UserName, State_DESC)
            Else
                Comment = String.Format(">> " & Now.ToString & ": User {0} Changed the state to: {1}", Environment.UserName, State_DESC)
            End If
            upd = String.Format("UPDATE TBPMO_WORKFLOW_TASK SET COMMENT = '{0}', DUE_DATE = '{1}',CHANGED_WHO = '{2}', TASK_DATE = '{3}' " & _
                              "WHERE GUID = {4}", Comment, DUE_DATEDateTimePicker.Value, USER_USERNAME, DateTimePickerTASK_DATE.Value, WF_TASK_ID)
            ClassDatabase.Execute_non_Query(upd, True)


            If STATE_id > 0 Then
                ins = String.Format("INSERT INTO TBPMO_WORKFLOW_TASK_HISTORY (WF_TASK_ID,STATE_ID,STATE_DESC,COMMENT,ADDED_WHO) VALUES" & _
                                    "({0},{1},'{2}','{3}','{4}')", WF_TASK_ID, STATE_id, State_DESC, Comment, USER_USERNAME)
                STATE_IDComboBox.SelectedIndex = -1
            Else

                STATE_IDComboBox.SelectedIndex = -1
            End If
            If ClassDatabase.Execute_non_Query(ins, True) Then
                ClassWorkflow.Refresh_Workflows_Entity()
                ClassProxy.Refresh_Workflow_Data()
                Load_Task_Data()
                Load_States()
                Check_end()
                If XtraTabControl1.SelectedTabPageIndex = 1 Then
                    Load_History()
                End If
                _Changed = False
            Else
                MsgBox("Update not successfull. Please check logfile.", MsgBoxStyle.Exclamation)
            End If
            '  Me.TBPMO_WORKFLOW_TASKTableAdapter.cmdUpdate(COMMENTTextBox.Text, DUE_DATEDateTimePicker.Value, STATE_IDComboBox.SelectedValue, 1, USER_USERNAME, DateTimePicker1.Value, Me.GUIDTextBox.Text)
        Catch ex As Exception
            MsgBox("Error in save Workflow:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub frmRecordView_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        Try
            Select Case JUMP_STATE
                Case 2
                    TabControlBottom.SelectedTabPageIndex = 1
            End Select
            SplitContainerMain.SplitterDistance = My.Settings.frmRecordViewSplitter
        Catch ex As Exception

        End Try
        Me.BringToFront()
    End Sub

    Private Sub GridViewDoc_Search_FocusedRowChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs)
        ClassWindreamDocGrid.GetDocItems(GridViewDoc_Search)
        'Try
        '    ClassWindreamDocGrid.RESULT_DOC_PATH = GridViewDoc_Search.GetFocusedRowCellValue(GridViewDoc_Search.Columns("FULLPATH"))
        'Catch ex As Exception
        '    ClassWindreamDocGrid.RESULT_DOC_PATH = Nothing
        'End Try
    End Sub

    Private Sub GridControlDocSearch_DoubleClick(sender As Object, e As EventArgs)
        ClassWindreamDocGrid.GetDocItems(GridViewDoc_Search)
        'Try
        '    ClassWindreamDocGrid.RESULT_DOC_PATH = GridViewDoc_Search.GetFocusedRowCellValue(GridViewDoc_Search.Columns("FULLPATH"))
        'Catch ex As Exception
        '    ClassWindreamDocGrid.RESULT_DOC_PATH = Nothing
        'End Try
        If IsNothing(ClassWindreamDocGrid.DT_RESULTFILES) Then
            MsgBox("Could not read File Parameters(DoubleClick)!", MsgBoxStyle.Exclamation)
            Exit Sub
        End If
        For Each row As DataRow In ClassWindreamDocGrid.DT_RESULTFILES.Rows
            ClassHelper.File_open(row.Item("DOC_PATH"), 0)
        Next

    End Sub

    Private Sub DateiÖffnenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles DateiÖffnenToolStripMenuItem.Click
        If IsNothing(ClassWindreamDocGrid.DT_RESULTFILES) Then
            MsgBox("Could not read File Parameters(DoubleClick)!", MsgBoxStyle.Exclamation)
            Exit Sub
        End If
        For Each row As DataRow In ClassWindreamDocGrid.DT_RESULTFILES.Rows
            ClassHelper.File_open(row.Item("DOC_PATH"), 0)
        Next

    End Sub
    Private Sub PropertiesToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles PropertiesToolStripMenuItem.Click
        If IsNothing(ClassWindreamDocGrid.DT_RESULTFILES) Then
            MsgBox("Could not read File Parameters(Properties RecordView)!", MsgBoxStyle.Exclamation)
            Exit Sub
        End If
        For Each row As DataRow In ClassWindreamDocGrid.DT_RESULTFILES.Rows
            If row.Item("DOC_PATH") <> "" Then
                Cursor = Cursors.WaitCursor
                Dim sei As New SHELLEXECUTEINFO
                sei.cbSize = Marshal.SizeOf(sei)
                sei.lpVerb = "properties"
                sei.lpFile = row.Item("DOC_PATH")
                sei.nShow = SW_SHOW
                sei.fMask = SEE_MASK_INVOKEIDLIST
                If Not ShellExecuteEx(sei) Then
                    Dim ex As New System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error())
                    MsgBox("Unexpected Error in Open file propertys:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
                End If
            End If
        Next

        Cursor = Cursors.Default
    End Sub

    Private Sub pnlDetails_DragDrop(sender As Object, e As DragEventArgs) Handles pnlDetails.DragDrop
        Drag_Drop(e)
    End Sub

    Private Sub GridControlDocSearch_DragDrop(sender As Object, e As DragEventArgs)
        Drag_Drop(e)
    End Sub

    Private Sub pnlDetails_DragEnter(sender As Object, e As DragEventArgs) Handles pnlDetails.DragEnter
        Drag_Enter(e)
    End Sub

    Private Sub GridControlDocSearch_DragEnter(sender As Object, e As DragEventArgs)
        Drag_Enter(e)
    End Sub
    Sub Drag_Enter(e As DragEventArgs)
        If FORMVIEW_ID <> 0 Then
            ClassDragDrop.Drag_enter(e)
        End If
    End Sub
    Sub Drag_Drop(e As DragEventArgs)
        If FORMVIEW_ID <> 0 Then
            Dim sql = "select count(*) from VWPMO_DOKUMENTTYPES where FORMVIEW_ID = " & FORMVIEW_ID
            If ClassDatabase.Execute_Scalar(sql, True) = 0 Then
                MsgBox("No documenttypes for this entity configured! Indexing is not possible!" & vbNewLine & "Please check the configuration!", MsgBoxStyle.Exclamation)
                Exit Sub
            End If
            CURRENT_FORMVIEW_ID = FORMVIEW_ID
            CURRENT_CONTROL_DOCTYPE_MATCH = 0

            If e.Data.GetDataPresent(DataFormats.StringFormat) Then
                Dim Wert As String = CType(e.Data.GetData(DataFormats.StringFormat), Object)
                Console.WriteLine("DragDrop-Wert: " & Wert)
                If Wert.Contains("SCAN") Then
                    Exit Sub
                    'Dim split() = Wert.Split(";")
                    'If IsNumeric(split(1)) Then
                    '    CURRENT_FILEID = split(1)
                    '    CURRENT_PARENT_ENTITY_ID = ClassDatabase.Execute_Scalar("SELECT PARENT_ID FROM TBPMO_FORM WHERE GUID = " & ENTITY_ID)
                    '    CURRENT_RECORD_ID = JUMP_RECORD_ID
                    '    CURRENT_FORMVIEW_ID = FORMVIEW_ID
                    '    frmWD_Index_Dokart.ShowDialog()
                    '    RUN_WDSEARCH_GRID()
                    'End If
                ElseIf (e.Data.GetDataPresent("FileGroupDescriptor")) AndAlso (e.Data.GetDataPresent("FileContents")) Then
                    CURRENT_RECORD_ID = RECORD_ID
                    If ClassDragDrop.Drop_File(e) = True Then
                        Check_Dropped_Files()
                    End If
                ElseIf e.Data.GetDataPresent("FileGroupDescriptor") Then
                    CURRENT_RECORD_ID = RECORD_ID
                    If ClassDragDrop.Drop_File(e) = True Then
                        Check_Dropped_Files()
                    End If
                End If
            Else
                CURRENT_RECORD_ID = RECORD_ID
                If ClassDragDrop.Drop_File(e) = True Then
                    Check_Dropped_Files()
                End If

            End If
        End If
    End Sub
    Sub Check_Dropped_Files()
        Try
            For Each Str As Object In ClassDragDrop.files_dropped
                If Not IsNothing(Str) Then
                    Dim DropType = Str.Substring(0, Str.LastIndexOf("@") + 1)
                    If DropType.ToString.Contains("SCAN") = False Then
                        ClassLogger.Add(">> Check_Dropped_Files:" & Str.ToString, False)
                        Dim CURRENT_WORKFILE = Str.Substring(Str.LastIndexOf("@") + 1)
                        Dim insert = String.Format("INSERT INTO TBPMO_FILES_USER(FILENAME2WORK, USER_WORK, HANDLE_TYPE) VALUES('{0}','{1}','{2}')", CURRENT_WORKFILE, USER_USERNAME, DropType)
                        If ClassDatabase.Execute_non_Query(insert, True) = False Then
                            Exit Sub
                        End If
                    End If
                End If

            Next
            Dim sql = "select count(*) from VWPMO_DOKUMENTTYPES where FORMVIEW_ID = " & FORMVIEW_ID
            If ClassDatabase.Execute_Scalar(sql, True) >= 1 Then
                ClassHelper.Create_USER_FILE_TABLE()
                If Not IsNothing(CURRENT_TBPMO_FILES_USER) Then
                   
                    If CURRENT_TBPMO_FILES_USER.Rows.Count > 0 Then
                        For Each Filerow As DataRow In CURRENT_TBPMO_FILES_USER.Rows
                            'Dim datei = Str.ToString.Replace("@DROPFROMFSYSTEM@", "")
                            CURRENT_FILEID = Filerow.Item("GUID")
                            CURRENT_PARENT_ENTITY_ID = PARENT_ENTITY_ID
                            CURRENT_RECORD_ID = RECORD_ID
                            CURRENT_ENTITY_ID = ENTITY_ID
                            CURRENT_FORMVIEW_ID = FORMVIEW_ID
                            If CURRENT_TBPMO_FILES_USER.Rows.Count = 1 Then
                                frmWD_IndexFile.ShowDialog()
                            Else
                                If LogErrorsOnly = False Then ClassLogger.Add(" >> File was deleted or worked meanwhile!")
                            End If
                        Next
                        RUN_WDSEARCH_GRID()
                    End If
                End If
            Else
                MsgBox("No documenttypes for this entity configured! Indexing is not possible!" & vbNewLine & "Please check the configuration!", MsgBoxStyle.Exclamation)
                Exit Sub
            End If
        Catch ex As Exception
            MsgBox("Check_Dropped_Files: " & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub

    Private Sub btnAddUser_Click(sender As Object, e As EventArgs) Handles btnAddUser.Click
        For Each row As DataRow In DD_ECMAdmin.TBAD_Users.Rows
            If row.Item(0) = CBool(True) Then
                Dim sql = "select count(*) from TBPMO_WORKFLOW_TASK_USER Where USER_ID = " & row.Item(5) & " AND WF_TASK_ID = " & WF_TASK_ID
                If ClassDatabase.Execute_Scalar(sql, True) = 0 Then
                    '##
                    Dim Ins = "Insert INTO TBPMO_WORKFLOW_TASK_USER (WF_TASK_ID,[USER_ID],ADDED_WHO) VALUES (" & WF_TASK_ID & ", " & row.Item(5) & ",'" & USER_USERNAME & "')"
                    If ClassDatabase.Execute_non_Query(Ins, False) = False Then
                        MsgBox(String.Format("Error in Adding User {0} to Task", row.Item(1)), MsgBoxStyle.Critical)
                    Else
                        ClassProxy.Refresh_Workflow_Data()
                        Load_TASK_USER()
                    End If

                End If
            End If
        Next
        For Each row As DataRow In DD_ECMAdmin.TBAD_Users.Rows
            row.Item(0) = CBool(False)
        Next
    End Sub
    Sub Load_TASK_USER()
        Try
            'Dim sql = "SELECT * FROM VWPMO_WF_USER WHERE LOWER(USERNAME) = '" & USER_USERNAME & "' AND WF_TASK_ID = " & Me.GUIDTextBox.Text
            Dim sql = "SELECT * FROM VWPMO_WF_USER WHERE WF_TASK_ID = " & WF_TASK_ID
            Dim DT As DataTable = ClassDatabase.Return_Datatable(sql, True)
            Dim count As Integer = 0
            If DT Is Nothing = False Then
                ListViewExclusiveUser.Items.Clear()
                For Each row As DataRow In DT.Rows
                    ListViewExclusiveUser.Items.Add(row.Item("GUID").ToString)
                    ListViewExclusiveUser.Items(count).SubItems.Add(row.Item("USERNAME").ToString)
                    count += 1
                Next
            End If
        Catch ex As Exception
            MsgBox("Error in Load_TASK_USER:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub STATE_IDComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles STATE_IDComboBox.SelectedIndexChanged
        Try
            If IsNumeric(STATE_IDComboBox.SelectedValue) Then
                Get_Description()
                _Changed = True
            End If
        Catch ex As Exception

        End Try

    End Sub

    Private Sub STATE_IDComboBox_SelectedValueChanged(sender As Object, e As EventArgs) Handles STATE_IDComboBox.SelectedValueChanged
        Try
            If IsNumeric(STATE_IDComboBox.SelectedValue) Then
                _Changed = True
                Get_Description()
            End If
        Catch ex As Exception

        End Try
    End Sub
    Sub Get_Description()
        Try
            Dim sql = String.Format("SELECT COMMENT FROM TBPMO_WORKFLOW_ENTITY_STATE WHERE WF_ID = {0} AND STATE_ID = {1} AND ENTITY_ID = {2}", WF_IDTextBox.Text, STATE_IDComboBox.SelectedValue, ENTITY_ID)
            Dim result = ClassDatabase.Execute_Scalar(sql, True)
            txtDescriptionStep.Text = result
        Catch ex As Exception

        End Try

    End Sub

    Private Sub DateTimePickerTASK_DATE_ValueChanged(sender As Object, e As EventArgs) Handles DateTimePickerTASK_DATE.ValueChanged
        Try
            _Changed = True
        Catch ex As Exception
            _Changed = False
        End Try

    End Sub

    Private Sub DUE_DATEDateTimePicker_ValueChanged(sender As Object, e As EventArgs) Handles DUE_DATEDateTimePicker.ValueChanged
        Try
            _Changed = True
        Catch ex As Exception
            _Changed = False
        End Try
    End Sub

    Private Sub COMMENTTextBox_TextChanged(sender As Object, e As EventArgs) Handles COMMENTTextBox.TextChanged
        Try
            _Changed = True
        Catch ex As Exception
            _Changed = False
        End Try
    End Sub

    Private Sub XtraTabControl1_SelectedPageChanged(sender As Object, e As DevExpress.XtraTab.TabPageChangedEventArgs) Handles XtraTabControl1.SelectedPageChanged
        Select Case XtraTabControl1.SelectedTabPageIndex
            Case 1
                Load_History()
        End Select
    End Sub
    Sub Load_History()
        Try
            Me.TBPMO_WORKFLOW_TASK_HISTORYTableAdapter.Fill(Me.DD_DMSDataSet.TBPMO_WORKFLOW_TASK_HISTORY, WF_TASK_ID)
        Catch ex As System.Exception
            MsgBox("Error in Load History:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub btndeleteuser_Click(sender As Object, e As EventArgs) Handles btndeleteuser.Click
        Try
            If (Me.ListViewExclusiveUser.SelectedItems.Count > 0) Then
                Dim sql = "DELETE FROM TBPMO_WORKFLOW_TASK_USER WHERE GUID = " & Me.ListViewExclusiveUser.SelectedItems.Item(0).Text
                ClassDatabase.Execute_non_Query(sql, False)
                ClassProxy.Refresh_Workflow_Data()
                Load_TASK_USER()
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error in btndeleteuser:")
        End Try
    End Sub

    Private Sub GridViewDoc_Search_RowStyle(sender As Object, e As DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs) Handles GridViewDoc_Search.RowStyle
        If e.RowHandle = DevExpress.XtraGrid.GridControl.AutoFilterRowHandle Then
            e.Appearance.BackColor = Color.Yellow
        End If
    End Sub

    Private Sub GridViewDoc_Search_FocusedRowChanged_1(sender As Object, e As DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs) Handles GridViewDoc_Search.FocusedRowChanged
        ClassWindreamDocGrid.GetDocItems(GridViewDoc_Search)
    End Sub

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

    Private Sub GridControlDocSearch_DoubleClick_1(sender As Object, e As EventArgs) Handles GridControlDocSearch.DoubleClick
        'Get_Doc_Items()
        ClassWindreamDocGrid.GetDocItems(GridViewDoc_Search)
        If IsNothing(ClassWindreamDocGrid.DT_RESULTFILES) Then
            MsgBox("Could not read File Parameters(5)!", MsgBoxStyle.Exclamation)
            Exit Sub
        End If
        For Each row As DataRow In ClassWindreamDocGrid.DT_RESULTFILES.Rows
            ClassHelper.File_open(row.Item("DOC_PATH"), row.Item("DOC_ID"))
        Next

    End Sub

    Private Sub ContextMenuStripResultFiles_Opening(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles ContextMenuStripResultFiles.Opening
        ClassWindreamDocGrid.GetDocItems(GridViewDoc_Search)
        Dim Result = clsWD_GET.Get_File_Rights(ClassWindreamDocGrid.SELECTED_DOC_PATH, USER_USERNAME)
        If Not IsNothing(Result) Then

            Select Case Result.ToString
                Case "R"
                    PropertiesToolStripMenuItem.Enabled = False
                Case "RW"
                    PropertiesToolStripMenuItem.Enabled = True
                Case "RWA"
                    PropertiesToolStripMenuItem.Enabled = True
            End Select
        Else
            PropertiesToolStripMenuItem.Enabled = True
        End If
    End Sub
End Class