Imports System.IO
Imports System.Security.AccessControl
Imports System.Text
Imports System.Text.RegularExpressions
Imports DevExpress.XtraEditors
Imports DevExpress.XtraEditors.Controls
Imports DigitalData.Controls.LookupGrid
Imports DigitalData.GUIs.Common
Imports DigitalData.GUIs.GlobalIndexer
Imports DigitalData.Modules.Base
Imports DigitalData.Modules.Logging
Imports DigitalData.Modules.Windream
Imports Limilabs.Mail

Public Class frmIndex
#Region "+++++ Variablen ++++++"
    Public vPathFile As String
    Private MULTIFILES As Integer
    Private ReadOnly akttxtbox As TextBox
    Dim DT_INDEXEMAN As DataTable
    Public FormLoaded As Boolean = False
    Private Shared ReadOnly _Instance As frmIndex = Nothing
    Dim DropType As String
    Private Shared WMDirect As Boolean = False

    Dim sql_history_INSERT_INTO As String
    Dim sql_history_Index_Values As String

    Private NewFileString As String
    Private CancelAttempts As Integer = 0
    Private Const MaxCancelAttempts = 2

    Private Property ViewerString As String

    Private Const TEXT_MISSING_INPUT_DE = "Bitte vervollständigen Sie die Eingaben!"
    Private Const TEXT_MISSING_INPUT_EN = "Please complete your entries!"

    Private Const TEXT_CHECK_MANUAL_INDEXES_DE = "Die Überprüfung der manuellen Indexe ist fehlerhaft. Bitte informieren Sie Ihrenm Systembetreuer."
    Private Const TEXT_CHECK_MANUAL_INDEXES_EN = "There is an error in the validation settings of the manual indexes. Please inform your administrator."

    Private Const TEXT_CATCH_BLOCK_DE = "Unvorhergesehener Fehler in {0}: Fehlermeldung {1}"
    Private Const TEXT_CATCH_BLOCK_EN = "Unexpected Error in {0}: Errormessage {1}"

    Private Const LANG_DE = "de-DE"

    Private Property DocTypes As New List(Of DocType)

    Private ReadOnly _Logger As Logger
    Private ReadOnly _FormHelper As FormHelper
    Private ReadOnly _PostProcessing As ClassPostprocessing

#End Region

    Public Class DocType
        Public Property Guid
        Public Property Name

        Public Overrides Function ToString() As String
            Return Name
        End Function
    End Class
    Private Sub ShowErrorMessage(Exception As Exception, MethodTitle As String, Optional MoreInfo As String = "")
        Dim oMessage As String
        Dim oMoreInfo As String = IIf(MoreInfo = "", "", "(" & MoreInfo & ")")

        If USER_LANGUAGE = LANG_DE Then
            oMessage = String.Format(TEXT_CATCH_BLOCK_DE, MethodTitle, Exception.Message) & oMoreInfo
        Else
            oMessage = String.Format(TEXT_CATCH_BLOCK_EN, MethodTitle, Exception.Message) & oMoreInfo
        End If

        _Logger.Warn(oMessage)
        _Logger.Error(Exception)

        MsgBox(oMessage, MsgBoxStyle.Critical, Text)
    End Sub

    Public Sub New()
        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()
        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.
        _Logger = LOGCONFIG.GetLogger()
        _Logger.Debug("frmIndex Logger initialized ...")
        _FormHelper = New FormHelper(LOGCONFIG, Me)
        _Logger.Debug("frmIndex FormHelper initialized ...")
        _PostProcessing = New ClassPostprocessing(LOGCONFIG)
        _Logger.Debug("frmIndex ClassPostprocessing initialized ...")

        Localizer.Active = New LookupGridLocalizer()
        _Logger.Debug("frmIndex LookupGridLocalizer initialized ...")
    End Sub

    Public Sub CloseViewer()
        If DocumentViewer1 Is Nothing Then
            LOGGER.Warn("DocumentViewer is already closed!")
        End If

        Try
            LOGGER.Debug("Calling CloseDocument on Viewer")
            DocumentViewer1.CloseDocument()
        Catch ex As Exception
            LOGGER.Warn("Calling CloseDocument on Viewer FAILED")
            LOGGER.Error(ex)
        End Try

        Try
            LOGGER.Debug("Calling Done on Viewer")
            DocumentViewer1?.Done()
        Catch ex As Exception
            LOGGER.Warn("Calling Done on Viewer FAILED")
            LOGGER.Error(ex)
        End Try
    End Sub

    Public Sub DisposeViewer()
        DocumentViewer1.Dispose()
    End Sub

    '#Region "+++++ Allgemeine Funktionen ++++++"
    Sub ShowError(text As String)
        labelError.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
        labelError.Caption = text
    End Sub

    Sub ClearError()
        labelError.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
        labelError.Caption = String.Empty
    End Sub

    Sub ShowNotice(text As String)
        labelNotice.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
        labelNotice.Caption = text
    End Sub

    Sub ClearNotice()
        labelNotice.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
        labelNotice.Caption = String.Empty
    End Sub

    Private Sub SetFilePreview(ShowPreview As Boolean)
        If ShowPreview Then
            SplitContainer1.Panel2Collapsed = False
            PreviewFile()
            checkItemPreview.Checked = True
        Else
            SplitContainer1.Panel2Collapsed = True
            checkItemPreview.Checked = False
        End If
    End Sub

    Sub addLabel(indexname As String, hinweis As String, ylbl As Integer, anz As String)
        Dim lbl As New Windows.Forms.Label With {
            .Name = "lbl" & indexname,
            .AutoSize = True,
            .Text = hinweis,
            .Location = New Point(11, ylbl)
        }

        pnlIndex.Controls.Add(lbl)
    End Sub

    Private Sub AddLabelAndControl(labelText As String, ctrl As Control, indexName As String)

        '--- Label vorbereiten ------------------------------------
        Dim lbl As New Windows.Forms.Label With {
        .Name = $"lbl_{indexName}",
        .Text = labelText,
        .AutoSize = True,
        .Anchor = AnchorStyles.Left,
        .Margin = New Padding(4, 4, 4, 4)
    }

        '--- Control vorbereiten ----------------------------------
        ctrl.Anchor = AnchorStyles.Left Or AnchorStyles.Right
        ctrl.Margin = New Padding(4, 4, 4, 4)
        ctrl.Width = 300 'falls AutoSize=False
        ctrl.Dock = DockStyle.Fill

        '--- Zeile dynamisch anlegen ------------------------------
        tlpIndex.RowCount += 1
        tlpIndex.RowStyles.Add(New RowStyle(SizeType.AutoSize))

        tlpIndex.Controls.Add(lbl, 0, tlpIndex.RowCount - 1) 'Spalte 0 = Label
        tlpIndex.Controls.Add(ctrl, 1, tlpIndex.RowCount - 1) 'Spalte 1 = Control
    End Sub

    Function Indexwert_checkValueDB(indexname As String, wert As String)
        Try
            Dim DR As DataRow
            For Each DR In DT_INDEXEMAN.Rows
                If DR.Item("NAME") = indexname Then
                    If DR.Item("SQL_CHECK").ToString <> String.Empty Then
                        Dim connectionString As String
                        Dim sql As String
                        connectionString = DATABASE_ECM.Get_ConnectionStringforID(DR.Item("CONNECTION_ID"))
                        If connectionString <> "" Then
                            Dim sqlscalar = DR.Item("SQL_CHECK")
                            Select Case DR.Item("DATENTYP")
                                Case ClassConstants.INDEX_TYPE_INTEGER
                                    sqlscalar = sqlscalar.ToString.Replace("@manValue", wert)
                                Case Else
                                    sqlscalar = sqlscalar.ToString.Replace("@manValue", "'" & wert & "'")
                            End Select

                            sql = sqlscalar
                            Dim ergebnis As Integer
                            If DR.Item("SQL_PROVIDER") = "Oracle" Then

                                ' ergebnis = ClassDatabase.OracleExecute_Scalar(sql, connectionString)
                                LOGGER.Warn("Oracle is not supported")
                            Else
                                'MSQL
                                ergebnis = DATABASE_ECM.GetScalarValueWithConnection(sql, connectionString)
                            End If

                            Select Case ergebnis
                                Case 1
                                    Return True
                                Case 2
                                    ShowNotice("Indexwert nicht eindeutig: " & sql)
                                    Return False
                                Case 99
                                    Return False
                            End Select

                        End If
                    Else
                        Return True
                    End If

                End If
            Next
        Catch ex As Exception
            ShowErrorMessage(ex, "Indexwert_checkValue")
            Return False
        End Try
    End Function

    Function GetManIndex_Value(indexname As String, RequestFor As String, opt As Boolean)
        Try
            Dim DT As DataTable
            Dim DR As DataRow
            DT = MyDataset.VWDDINDEX_MAN
            For Each DR In DT.Rows
                If DR.Item("INDEXNAME").ToString.ToLower = indexname.ToLower Then
                    If DR.Item("Indexiert") = True Then
                        _Logger.Info("## Manueller Index: " & indexname)
                        Select Case RequestFor
                            Case "FILE"
                                If DR.Item("Indexwert_File").ToString <> String.Empty Then
                                    _Logger.Info(" >>Es liegt ein separater nachbearbeiteter Wert für die Dateibenennung vor: " & DR.Item("Indexwert_File").ToString)
                                    _Logger.Info(" >>Zurückgegebener NachbearbeitungsWert: " & DR.Item("Indexwert_File"))
                                    Return DR.Item("Indexwert_File")
                                Else
                                    If DR.Item("Indexwert").ToString <> String.Empty Then
                                        _Logger.Info("Zurückgegebener manueller Indexwert: " & DR.Item("Indexwert"))
                                        Return DR.Item("Indexwert")
                                    Else
                                        If opt = False Then
                                            _Logger.Info("Achtung, der Indexwert des manuellen Indexes '" & indexname & "' ist String.empty!")
                                            ShowNotice("Indexiert = True - Der Index: " & DR.Item("INDEXNAME") & " wurde nicht ordnungsgemäss indexiert! - Automatischer Index konnte nicht gesetzt werden!")
                                            Return Nothing
                                        Else
                                            Return ""
                                        End If

                                    End If
                                End If
                            Case Else
                                If DR.Item("Indexwert").ToString <> String.Empty Then
                                    _Logger.Info(" >>Zurückgegebener manueller Indexwert: " & DR.Item("Indexwert"))
                                    Return DR.Item("Indexwert")
                                Else
                                    If opt = False Then
                                        _Logger.Info("Achtung, der Indexwert des manuellen Indexes '" & indexname & "' ist String.empty!")
                                        ShowNotice("Indexiert = True - Der Index: " & DR.Item("INDEXNAME") & " wurde nicht ordnungsgemäss indexiert! - Automatischer Index konnte nicht gesetzt werden!")
                                        Return Nothing
                                    Else
                                        Return ""
                                    End If
                                End If
                        End Select
                    Else
                        ShowNotice("Der Index: " & DR.Item("INDEXNAME") & " wurde nicht ordnungsgemäss indexiert! - Automatischer Index konnte nicht gesetzt werden!")
                        Return Nothing
                    End If
                    Exit For
                End If
            Next
        Catch ex As Exception
            ShowErrorMessage(ex, "GetManIndex_Value")
            Return Nothing
        End Try
    End Function
    Function GetAutoIndex_Value(indexname As String)
        Try
            Dim oDataTable As DataTable

            oDataTable = MyDataset.VWDDINDEX_AUTOM
            For Each oDataRow As DataRow In oDataTable.Rows
                If oDataRow.Item("INDEXNAME").ToString.ToLower = indexname.ToLower Then
                    Dim oIndexWert = oDataRow.Item("Indexwert")
                    Dim oIsIndexed = oDataRow.Item("Indexiert")

                    If oIsIndexed = True Then
                        If oIndexWert.ToString <> String.Empty Then
                            oIndexWert = oIndexWert.ToString

                            ' If Index is a vectorfield (read: Value contains the VECTORSEPARATOR character), use the first value
                            If oIndexWert.Contains(ClassConstants.VECTORSEPARATOR) Then
                                Return oIndexWert.ToString.Split(ClassConstants.VECTORSEPARATOR).FirstOrDefault()
                            Else
                                ' Else just return the normal value
                                Return oIndexWert
                            End If
                        Else
                            ShowNotice("Der Automatische Index: " & oDataRow.Item("INDEXNAME") & " wurde nicht ordnungsgemäss indexiert!")
                            Return ""
                        End If
                    Else
                        ShowNotice("Der Automatische Index: " & oDataRow.Item("INDEXNAME") & " wurde nicht ordnungsgemäss indexiert!")
                        Return ""
                    End If
                    Exit For
                End If
            Next
        Catch ex As Exception
            ShowErrorMessage(ex, "GetAutoIndex_Value")
            Return ""
        End Try
    End Function

    Function GetAutomaticIndexSQLValue(SQLCommand As String, vconnectionID As Integer, vProvider As String) As String
        Try
            Dim oConnectionString As String
            oConnectionString = DATABASE_ECM.Get_ConnectionStringforID(vconnectionID)
            If oConnectionString <> "" Then
                'NEU
                Dim oErgebnis
                'Welcher Provider? 
                If vProvider.ToLower = "oracle" Then
                    LOGGER.Warn("Oracle Database Queries are not supported")
                Else 'im Moment nur SQL-Server
                    oErgebnis = DATABASE_ECM.GetScalarValueWithConnection(SQLCommand, oConnectionString)
                End If

                If LogErrorsOnly = False Then
                    _Logger.Info(" >>SQL-ConnectionString: " & oConnectionString.Substring(0, oConnectionString.LastIndexOf("=")))
                End If

                If oErgebnis Is Nothing Then
                    Return ""
                Else
                    Return oErgebnis
                End If
            End If

        Catch ex As Exception
            ShowErrorMessage(ex, "GetAutomaticIndexSQLValue")
            Return ""
        End Try
    End Function

    Function CheckWrite_IndexeMan(oDocumentTypeId As Integer) As Boolean
        Try
            _Logger.Info("In CheckWrite_IndexeMan")

            DxErrorProvider1.ClearErrors()
            Dim oResult As Boolean = False

            For Each oControl As Control In Me.pnlIndex.Controls
                ' Labels überspringen
                If TypeOf oControl Is System.Windows.Forms.Label Then
                    Continue For
                End If

                ' Textboxen (TextEdit)
                If oControl.Name.StartsWith("txt") Then
                    Dim oBox As DevExpress.XtraEditors.TextEdit = DirectCast(oControl, DevExpress.XtraEditors.TextEdit)
                    Dim oIndexName = Replace(oBox.Name, "txt", "")
                    Dim oOptionalIndex As Boolean = DATABASE_ECM.GetScalarValue($"SELECT OPTIONAL FROM TBDD_INDEX_MAN WHERE DOK_ID = {oDocumentTypeId} AND NAME = '{oIndexName}'")

                    If String.IsNullOrWhiteSpace(oBox.Text) Then
                        If Not oOptionalIndex Then
                            DxErrorProvider1.SetError(oBox, If(USER_LANGUAGE = LANG_DE, TEXT_MISSING_INPUT_DE, TEXT_MISSING_INPUT_EN))
                            oBox.Focus()
                            Return False
                        End If
                        Indexwert_Postprocessing(oIndexName, "")
                    Else
                        If Not Indexwert_checkValueDB(oIndexName, oBox.Text) Then
                            Dim oMsg = If(USER_LANGUAGE = LANG_DE,
                                     "Der eingegebene Wert wurde nicht in der Datenbank gefunden!",
                                     "The value was not found in the Database!")
                            DxErrorProvider1.SetError(oBox, oMsg)
                            oBox.Focus()
                            Return False
                        End If
                        Indexwert_Postprocessing(oIndexName, oBox.Text)
                        _Logger.Debug($"Der Index: '{oIndexName}' wurde mit dem Wert '{oBox.Text}' beschrieben.")
                    End If
                    oResult = True
                    Continue For
                End If

                ' Mehrfachauswahl (LookupControl3)
                If oControl.Name.StartsWith("cmbMulti") Then
                    Dim lookup = DirectCast(oControl, DigitalData.Controls.LookupGrid.LookupControl3)
                    Dim values = lookup.Properties.SelectedValues
                    Dim indexName = Replace(lookup.Name, "cmbMulti", "")
                    Dim optionalIndex As Boolean = DATABASE_ECM.GetScalarValue($"SELECT OPTIONAL FROM TBDD_INDEX_MAN WHERE DOK_ID = {oDocumentTypeId} AND NAME = '{indexName}'")

                    If values.Count = 0 Then
                        If Not optionalIndex Then
                            DxErrorProvider1.SetError(lookup, If(USER_LANGUAGE = LANG_DE, TEXT_MISSING_INPUT_DE, TEXT_MISSING_INPUT_EN))
                            lookup.Focus()
                            Return False
                        End If
                        Indexwert_Postprocessing(indexName, "")
                    Else
                        Dim valueJoined = String.Join(ClassConstants.VECTORSEPARATOR, values)
                        Indexwert_Postprocessing(indexName, valueJoined)
                    End If
                    oResult = True
                    Continue For
                End If

                ' Einfachauswahl (TextBox)
                If oControl.Name.StartsWith("cmbSingle") Then
                    Dim cmbSingle = DirectCast(oControl, TextBox)
                    Dim indexName = Replace(cmbSingle.Name, "cmbSingle", "")
                    Dim optionalIndex As Boolean = DATABASE_ECM.GetScalarValue($"SELECT OPTIONAL FROM TBDD_INDEX_MAN WHERE DOK_ID = {oDocumentTypeId} AND NAME = '{indexName}'")

                    If String.IsNullOrWhiteSpace(cmbSingle.Text) Then
                        If Not optionalIndex Then
                            DxErrorProvider1.SetError(cmbSingle, If(USER_LANGUAGE = LANG_DE, TEXT_MISSING_INPUT_DE, TEXT_MISSING_INPUT_EN))
                            cmbSingle.Focus()
                            Return False
                        End If
                        Indexwert_Postprocessing(indexName, "")
                    Else
                        Indexwert_Postprocessing(indexName, cmbSingle.Text)
                    End If
                    oResult = True
                    Continue For
                End If

                ' ComboBox
                If oControl.Name.StartsWith("cmb") Then
                    Dim cmb = DirectCast(oControl, ComboBox)
                    Dim indexName = Replace(cmb.Name, "cmb", "")
                    Dim optionalIndex As Boolean = DATABASE_ECM.GetScalarValue($"SELECT OPTIONAL FROM TBDD_INDEX_MAN WHERE DOK_ID = {oDocumentTypeId} AND NAME = '{indexName}'")

                    If String.IsNullOrWhiteSpace(cmb.Text) Then
                        If Not optionalIndex Then
                            DxErrorProvider1.SetError(cmb, If(USER_LANGUAGE = LANG_DE, TEXT_MISSING_INPUT_DE, TEXT_MISSING_INPUT_EN))
                            cmb.Focus()
                            Return False
                        End If
                        Indexwert_Postprocessing(indexName, "")
                    Else
                        Indexwert_Postprocessing(indexName, cmb.Text)
                    End If
                    oResult = True
                    Continue For
                End If

                ' DateTimePicker
                If oControl.Name.StartsWith("dtp") Then
                    Dim dtp = DirectCast(oControl, DevExpress.XtraEditors.DateEdit)
                    Dim indexName = Replace(dtp.Name, "dtp", "")
                    Dim optionalIndex As Boolean = DATABASE_ECM.GetScalarValue($"SELECT OPTIONAL FROM TBDD_INDEX_MAN WHERE DOK_ID = {oDocumentTypeId} AND NAME = '{indexName}'")

                    If String.IsNullOrWhiteSpace(dtp.Text) Then
                        If Not optionalIndex Then
                            DxErrorProvider1.SetError(dtp, If(USER_LANGUAGE = LANG_DE, TEXT_MISSING_INPUT_DE, TEXT_MISSING_INPUT_EN))
                            dtp.Focus()
                            Return False
                        End If
                        Indexwert_Postprocessing(indexName, "")
                    Else
                        Indexwert_Postprocessing(indexName, dtp.Text)
                        _Logger.Debug($"Der Index '{indexName}' wurde mit dem Wert '{dtp.Text}' beschrieben.")
                    End If
                    oResult = True
                    Continue For
                End If

                ' Checkbox
                If oControl.Name.StartsWith("chk") Then
                    Dim chk = DirectCast(oControl, DevExpress.XtraEditors.CheckEdit)
                    Dim indexName = Replace(chk.Name, "chk", "")
                    Indexwert_Postprocessing(indexName, chk.Checked)
                    oResult = True
                    Continue For
                End If

                ' Buttons ignorieren
                If TypeOf oControl Is Button Then
                    Continue For
                End If
            Next

            If Not oResult Then
                _Logger.Info(TEXT_CHECK_MANUAL_INDEXES_EN)
            End If

            Return oResult
        Catch ex As Exception
            ShowErrorMessage(ex, "CheckWrite_IndexeMan")
            Return False
        End Try
    End Function

    Sub Indexwert_Postprocessing(indexname As String, wert_in As String)
        Try
            Dim DT As DataTable
            Dim DR As DataRow
            DT = MyDataset.VWDDINDEX_MAN
            Dim value_post As String = ""
            For Each DR In DT.Rows
                If DR.Item("INDEXNAME") = indexname Then
                    Dim idxid As Integer = DR.Item("GUID")
                    If idxid > 0 Then
                        ' In jedem Fall schon mal den Wert einfügen
                        DR.Item("Indexwert") = wert_in
                        'Die Nachbearbeitungsschritte laden
                        'FILE AND INDEX
                        'Zuerst nur die Fälle für die Variante ONLY FILE/FOLDER
                        Dim DTNB As DataTable = DATABASE_ECM.GetDatatable("SELECT * FROM TBDD_INDEX_MAN_POSTPROCESSING WHERE IDXMAN_ID = " & idxid & " AND VARIANT = 'ONLY FILE/FOLDER' ORDER BY SEQUENCE")
                        If DTNB Is Nothing = False Then
                            If DTNB.Rows.Count > 0 Then
                                value_post = _PostProcessing.Get_Nachbearbeitung_Wert(wert_in, DTNB)
                                DR.Item("Indexwert") = wert_in
                                DR.Item("Indexwert_File") = value_post
                            End If
                        End If
                        'Jetzt die Fälle für die Variante FILE AND INDEX
                        DTNB = Nothing
                        DTNB = DATABASE_ECM.GetDatatable("SELECT * FROM TBDD_INDEX_MAN_POSTPROCESSING WHERE IDXMAN_ID = " & idxid & " AND VARIANT = 'FILE AND INDEX' ORDER BY SEQUENCE")
                        If DTNB Is Nothing = False Then
                            If DTNB.Rows.Count > 0 Then
                                value_post = _PostProcessing.Get_Nachbearbeitung_Wert(wert_in, DTNB)
                                DR.Item("Indexwert") = value_post
                            End If
                        End If
                    End If
                    DR.Item("Indexiert") = True
                End If
            Next
        Catch ex As Exception
            ShowErrorMessage(ex, "Indexwert_Postprocessing")
        End Try
    End Sub

    Function Name_Generieren()
        Try
            _Logger.Debug("#### Name_Generieren ####")
            Dim sql As String = "select VERSION_DELIMITER, FILE_DELIMITER FROM TBDD_MODULES WHERE GUID = 1"
            Dim DT1 As DataTable = DATABASE_ECM.GetDatatable(sql)
            For Each row As DataRow In DT1.Rows
                FILE_DELIMITER = row.Item("FILE_DELIMITER")
                VERSION_DELIMITER = row.Item("VERSION_DELIMITER")
            Next

            Dim err As Boolean = False
            Dim folder_Created As Boolean = False
            Dim oRAWZielordner As String
            Dim extension As String = System.IO.Path.GetExtension(CURRENT_WORKFILE)
            Dim DT As DataTable = DATABASE_ECM.GetDatatable("SELECT * FROM TBDD_DOKUMENTART WHERE GUID = " & CURRENT_DOKART_ID)
            sql_history_INSERT_INTO = "INSERT INTO TBGI_HISTORY (FILENAME_ORIGINAL,FILENAME_NEW"
            sql_history_Index_Values = ""
            Dim AnzahlIndexe As Integer = 1
            CURR_DOKART_WD_DIRECT = DT.Rows(0).Item("WINDREAM_DIRECT")
            CURR_DOKART_OBJECTTYPE = DT.Rows(0).Item("OBJEKTTYP")
            CURR_WORKFILE_EXTENSION = extension

            oRAWZielordner = WINDREAM.GetNormalizedPath(DT.Rows(0).Item("ZIEL_PFAD"), True)
            oRAWZielordner = WINDREAM_BASEPATH & oRAWZielordner

            '####
            ' Regulären Ausdruck zum Auslesen der Indexe definieren
            Dim preg As String = "\[%{1}[a-zA-Z0-9ß\!\$\&\/\(\)\=\?\,\.\-\;\:_öÖüÜäÄ\#\'\+\*\~\{\}\@\€\<\>\ ]+]{1}"
            'schonmal den gesamten Pfad laden
            Dim oNamenkonvention As String = DT.Rows(0).Item("NAMENKONVENTION") & CURR_WORKFILE_EXTENSION 'oRAWZielordner & "\" & DT.Rows(0).Item("NAMENKONVENTION")
            NewFileString = oNamenkonvention
            ' einen Regulären Ausdruck laden
            Dim regulärerAusdruck As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex(preg)
            ' die Vorkommen im SQL-String auslesen
            Dim oMatchelements As System.Text.RegularExpressions.MatchCollection = regulärerAusdruck.Matches(oNamenkonvention)
            '####
            If oMatchelements.Count = 0 Then
                _Logger.Debug("No RegularExpression Files on Nameconvention!")
            End If
            ' alle Vorkommen innerhalbd er Namenkonvention durchlaufen
            For Each oElement As System.Text.RegularExpressions.Match In oMatchelements
                Select Case oElement.Value.Substring(2, 1).ToUpper
                    'Manueller Indexwert
                    Case "M"
                        _Logger.Debug("NameGenerieren: Manueller Index wird geprüft...")
                        Dim Indexname = oElement.Value.Substring(3, oElement.Value.Length - 4)
                        Dim optional_index As Boolean = DATABASE_ECM.GetScalarValue($"SELECT OPTIONAL FROM TBDD_INDEX_MAN WHERE DOK_ID = {CURRENT_DOKART_ID} AND UPPER(NAME) = UPPER('{Indexname}')")
                        Dim oManValue As String = GetManIndex_Value(Indexname, "FILE", optional_index)
                        If oManValue <> String.Empty Then
                            Dim firstVectorValue = oManValue.Split(ClassConstants.VECTORSEPARATOR).First()

                            oNamenkonvention = oNamenkonvention.Replace(oElement.Value, firstVectorValue)
                            NewFileString = oNamenkonvention
                            sql_history_INSERT_INTO = sql_history_INSERT_INTO & ", INDEX" & AnzahlIndexe.ToString
                            AnzahlIndexe += 1
                            sql_history_Index_Values = sql_history_Index_Values & ", '" & oManValue.Replace("'", "''") & "'"
                        Else

                            If optional_index = True Then
                                oNamenkonvention = oNamenkonvention.Replace("-" & oElement.Value & "-", "-")
                                oNamenkonvention = oNamenkonvention.Replace("_" & oElement.Value & "_", "_")
                                oNamenkonvention = oNamenkonvention.Replace("_" & oElement.Value & "-", "_")
                                oNamenkonvention = oNamenkonvention.Replace("-" & oElement.Value & "_", "-")

                                oNamenkonvention = oNamenkonvention.Replace("-" & oElement.Value, "-")
                                oNamenkonvention = oNamenkonvention.Replace("_" & oElement.Value, "_")
                                oNamenkonvention = oNamenkonvention.Replace(oElement.Value & "-", "-")
                                oNamenkonvention = oNamenkonvention.Replace(oElement.Value & "_", "_")

                                oNamenkonvention = oNamenkonvention.Replace(oElement.Value, oManValue)

                                Dim oFilenameWithoutExtension = Path.GetFileNameWithoutExtension(oNamenkonvention)
                                Dim oExtension = Path.GetExtension(oNamenkonvention)

                                If oFilenameWithoutExtension.EndsWith("-") Or oFilenameWithoutExtension.EndsWith("_") Then
                                    oFilenameWithoutExtension = oFilenameWithoutExtension.Substring(0, oFilenameWithoutExtension.Count - 1)
                                End If

                                NewFileString = oFilenameWithoutExtension & oExtension
                                sql_history_INSERT_INTO = sql_history_INSERT_INTO & ", INDEX" & AnzahlIndexe.ToString
                                AnzahlIndexe += 1
                                sql_history_Index_Values = sql_history_Index_Values & ", '" & oManValue.Replace("'", "''") & "'"
                            Else
                                _Logger.Debug("Der Indexvalue für Index '" & Indexname & "' ist String.Empty")
                                err = True
                            End If

                        End If
                    Case "A"
                        Dim value As String = GetAutoIndex_Value(oElement.Value.Substring(3, oElement.Value.Length - 4))
                        If value <> String.Empty Then
                            If value = "EMPTY_OI" Then
                                oNamenkonvention = oNamenkonvention.Replace(oElement.Value, "")
                                NewFileString = oNamenkonvention
                            Else
                                oNamenkonvention = oNamenkonvention.Replace(oElement.Value, value)
                                NewFileString = oNamenkonvention
                                sql_history_INSERT_INTO = sql_history_INSERT_INTO & ", INDEX" & AnzahlIndexe.ToString
                                AnzahlIndexe += 1
                                sql_history_Index_Values = sql_history_Index_Values & ", '" & value.Replace("'", "''") & "'"
                            End If
                        Else
                            err = True
                        End If
                    Case "V"
                        Dim datetemp As String
                        Dim _Month As String = My.Computer.Clock.LocalTime.Month
                        If _Month.Length = 1 Then
                            _Month = "0" & _Month
                        End If
                        Dim _day As String = My.Computer.Clock.LocalTime.Day
                        If _day.Length = 1 Then
                            _day = "0" & _day
                        End If
                        Dim type = oElement.Value
                        type = type.Replace("[%v_", "")
                        type = type.Replace("[%v", "")
                        type = type.Replace("]", "")
                        Select Case type
                            Case "YY_MM_DD"
                                datetemp = My.Computer.Clock.LocalTime.Year.ToString.Substring(2) & "_" & _Month & "_" & _day
                            Case "YYYY_MM_DD"
                                datetemp = My.Computer.Clock.LocalTime.Year & "_" & _Month & "_" & _day
                            Case "DD_MM_YY"
                                datetemp = _day & "_" & _Month & "_" & My.Computer.Clock.LocalTime.Year.ToString.Substring(2)
                            Case "DD_MM_YYYY"
                                datetemp = _day & "_" & _Month & "_" & My.Computer.Clock.LocalTime.Year
                            Case "YYMMDD"
                                datetemp = My.Computer.Clock.LocalTime.Year.ToString.Substring(2) & _Month & _day
                            Case "YYYYMMDD"
                                datetemp = My.Computer.Clock.LocalTime.Year & _Month & _day
                            Case "DDMMYY"
                                datetemp = _day & _Month & My.Computer.Clock.LocalTime.Year.ToString.Substring(2)
                            Case "DDMMYYYY"
                                datetemp = _day & _Month & My.Computer.Clock.LocalTime.Year
                            Case "OFilename"
                                oNamenkonvention = oNamenkonvention.Replace(oElement.Value, System.IO.Path.GetFileNameWithoutExtension(CURRENT_WORKFILE))
                            Case "Username".ToUpper
                                oNamenkonvention = oNamenkonvention.Replace(oElement.Value, Environment.UserName)
                            Case "Usercode".ToUpper
                                oNamenkonvention = oNamenkonvention.Replace(oElement.Value, USER_SHORTNAME)
                            Case ""
                        End Select
                        If datetemp <> "" Then
                            oNamenkonvention = oNamenkonvention.Replace(oElement.Value, datetemp)
                        End If
                        NewFileString = oNamenkonvention
                    Case "[%Version]".ToUpper
                        Try
                            Dim version As Integer = 1
                            Dim Stammname As String = oRAWZielordner & "\" & oNamenkonvention.Replace(oElement.Value, "")
                            Dim _neuername As String = oRAWZielordner & "\" & oNamenkonvention.Replace(oElement.Value, "")
                            Stammname = _neuername.Replace(VERSION_DELIMITER, "")
                            _neuername = _neuername.Replace(VERSION_DELIMITER, "")
                            'Überprüfen ob File existiert
                            If File.Exists(_neuername) = False Then
                                NewFileString = _neuername
                            Else
                                Do While File.Exists(_neuername)
                                    version += 1
                                    _neuername = Stammname.Replace(extension, "") & VERSION_DELIMITER & version & extension
                                    NewFileString = _neuername
                                Loop
                            End If
                        Catch ex As Exception
                            _Logger.Warn(" - Unexpected error in NameGenerieren - Fehler: " & vbNewLine & ex.Message)
                            _Logger.Error(ex.Message)
                            MsgBox(ex.Message, MsgBoxStyle.Critical, "Unexpected error in Umbenennnen der Datei:")
                            err = True
                        End Try
                    Case Else
                        _Logger.Info(" - Achtung - in der Namenkonvention wurde ein Element gefunden welches nicht zugeordnet werden kann!" & vbNewLine & "Elementname: " & oElement.Value.ToUpper)
                        MsgBox("Achtung - in der Namenkonvention wurde ein Element gefunden welches nicht zugeordnet werden kann!" & vbNewLine & "Elementname: " & oElement.Value.ToUpper, MsgBoxStyle.Exclamation, "Unexpected error in Name generieren:")
                End Select
            Next

            CURRENT_NEWFILENAME = FILESYSTEM.GetCleanFilename(NewFileString)
            CURRENT_NEWFILENAME = Path.Combine(oRAWZielordner, CURRENT_NEWFILENAME)

            _Logger.Debug("#### ENDE Name_Generieren ####")
            _Logger.Debug("")
            If err = False Then
                Return True
            Else
                Return False
            End If

        Catch ex As Exception
            ShowErrorMessage(ex, "Name_Generieren")
            Return False
        End Try

    End Function

    Private Function Write_Indizes() As Boolean
        Try
            _Logger.Info("Starting indexing for file [{0}] (DropType = {1})", CURRENT_NEWFILENAME, DropType)

            Dim indexierung_erfolgreich As Boolean = False

            ' ----------------------
            ' Manuelle Indizes
            ' ----------------------
            Dim DTMan As DataTable = MyDataset.VWDDINDEX_MAN
            If DTMan.Rows.Count > 0 Then
                _Logger.Info("Processing {0} manual indexes...", DTMan.Rows.Count)
                For Each row As DataRow In DTMan.Rows
                    Dim idxvalue = row.Item("Indexwert")
                    Dim indexname = row.Item("WD_INDEX").ToString
                    Dim optional_Index = CBool(row.Item("OPTIONAL"))
                    Dim indexiert = CBool(row.Item("Indexiert"))

                    If indexiert AndAlso Not String.IsNullOrEmpty(idxvalue.ToString) AndAlso idxvalue <> "EMPTY_OI" Then
                        If indexname <> String.Empty Then
                            _Logger.Debug("Manual Index: [{0}] Value: [{1}]", indexname, idxvalue)

                            ' Zwischenspeichern falls SAVE_VALUE
                            If row.Item("SAVE_VALUE") = True Then
                                Dim DTTemp As DataTable = MyDataset.TBTEMP_INDEXRESULTS
                                Dim rowexists As Boolean = DTTemp.Rows.Cast(Of DataRow)().Any(Function(r) r.Item("Dokumentart") = row.Item("DOKUMENTART") AndAlso r.Item("Indexname") = row.Item("INDEXNAME"))
                                If rowexists Then
                                    DTTemp.Rows.Cast(Of DataRow)().First(Function(r) r.Item("Dokumentart") = row.Item("DOKUMENTART") AndAlso r.Item("Indexname") = row.Item("INDEXNAME")).Item("Value") = idxvalue
                                Else
                                    Dim newRow As DataRow = DTTemp.NewRow()
                                    newRow("Dokumentart") = row.Item("DOKUMENTART").ToString
                                    newRow("Indexname") = row.Item("INDEXNAME").ToString
                                    newRow("Value") = idxvalue
                                    DTTemp.Rows.Add(newRow)
                                End If
                            End If

                            ' Indextyp prüfen
                            Dim oIndexType As Integer = WINDREAM.GetIndexType(indexname)
                            If oIndexType = 0 Then
                                LOGGER.Error("Could not get the Windream index type for [{0}]. Check configuration.", indexname)
                                MsgBox("Could not get the windream-indextype. Check Your Configuration", MsgBoxStyle.Information, "Attention")
                                Return False
                            End If

                            ' Vektor oder normal
                            If oIndexType > 4095 Then
                                _Logger.Debug("Index [{0}] is a vector type.", indexname)
                                Dim oSplitArray = Split(idxvalue, ClassConstants.VECTORSEPARATOR)
                                Dim oListOfString As New List(Of String)(oSplitArray)
                                indexierung_erfolgreich = WINDREAM.SetFileIndexLoS(CURRENT_NEWFILENAME, indexname, oListOfString, CURR_DOKART_OBJECTTYPE)
                            Else
                                indexierung_erfolgreich = WINDREAM.SetFileIndex(CURRENT_NEWFILENAME, indexname, idxvalue, CURR_DOKART_OBJECTTYPE)
                            End If

                            If indexierung_erfolgreich = False Then
                                LOGGER.Error("Failed to index manual field [{0}] with value [{1}]", indexname, idxvalue)
                                MsgBox("Error in Indexing file - See log", MsgBoxStyle.Critical)
                                Return False
                            End If
                        Else
                            _Logger.Warn("Skipping manual index: Indexname empty. Optional: {0}", optional_Index)
                        End If
                    Else
                        _Logger.Debug("Skipping manual index [{0}] - value empty or not indexed.", indexname)
                    End If
                Next
            Else
                _Logger.Debug("No manual indexes to process.")
            End If

            ' ----------------------
            ' Automatische Indizes
            ' ----------------------
            Dim DTAut As DataTable = MyDataset.VWDDINDEX_AUTOM
            If DTAut.Rows.Count > 0 Then
                _Logger.Info("Processing {0} automatic indexes...", DTAut.Rows.Count)
                For Each row As DataRow In DTAut.Rows
                    Dim oIsIndexed = CBool(row.Item("Indexiert"))
                    Dim oIndexValue = row.Item("Indexwert").ToString
                    Dim oIndexName = row.Item("INDEXNAME").ToString
                    Dim oOverwrite As Boolean = row.ItemEx("VKT_OVERWRITE", False)
                    Dim oPreventMultipleValues As Boolean = row.ItemEx("VKT_PREVENT_MULTIPLE_VALUES", False)

                    If oIsIndexed AndAlso Not String.IsNullOrEmpty(oIndexValue) AndAlso oIndexValue <> "EMPTY_OI" Then
                        _Logger.Info("Automatic Index: [{0}] Value: [{1}]", oIndexName, oIndexValue)
                        Dim oIndexType As Integer = WINDREAM.GetIndexType(oIndexName)
                        _Logger.Debug("WMIndexType for [{0}] = {1}", oIndexName, oIndexType)

                        If oIndexType > 4095 Then
                            _Logger.Debug("Index [{0}] is a vector type.", oIndexName)
                            Dim oExistingItems = WINDREAM.GetIndexValue(CURRENT_NEWFILENAME, oIndexName)
                            Dim oSplitArray = Split(oIndexValue, ClassConstants.VECTORSEPARATOR)
                            Dim oListOfString As New List(Of String)(oSplitArray)

                            If Not oOverwrite AndAlso oExistingItems.Count > 0 AndAlso oIndexType <> 4100 Then
                                oListOfString = oExistingItems.Concat(oListOfString).ToList()
                                _Logger.Debug("Concatenated existing values for vector index [{0}]", oIndexName)
                            End If

                            If oPreventMultipleValues Then
                                oListOfString = oListOfString.Distinct().ToList()
                                _Logger.Debug("Removed duplicate values for vector index [{0}]", oIndexName)
                            End If

                            indexierung_erfolgreich = WINDREAM.SetFileIndexLoS(CURRENT_NEWFILENAME, oIndexName, oListOfString, CURR_DOKART_OBJECTTYPE)
                        Else
                            indexierung_erfolgreich = WINDREAM.SetFileIndex(CURRENT_NEWFILENAME, oIndexName, oIndexValue, CURR_DOKART_OBJECTTYPE)
                        End If

                        If Not indexierung_erfolgreich Then
                            LOGGER.Error("Failed to index automatic field [{0}] with value [{1}]", oIndexName, oIndexValue)
                            MsgBox("Error in indexing file - See log", MsgBoxStyle.Critical)
                            Return False
                        End If
                    End If
                Next
            Else
                _Logger.Debug("No automatic indexes to process.")
            End If

            ' ----------------------
            ' E-Mail Indexing
            ' ----------------------
            If DropType = "|OUTLOOK_MESSAGE|" Or DropType = "|FW_MSGONLY|" Or DropType = "|MSGONLY|" Or CURRENT_NEWFILENAME.ToUpper.EndsWith(".MSG") Or CURRENT_NEWFILENAME.ToUpper.EndsWith(".EML") Then
                _Logger.Info("Indexing email content for main email.")
                indexierung_erfolgreich = SetEmailIndicies(False)
            ElseIf DropType = "|ATTMNTEXTRACTED|" Or DropType = "|OUTLOOK_ATTACHMENT|" Then
                _Logger.Info("Indexing email content for attachment.")
                indexierung_erfolgreich = SetEmailIndicies(True)
            End If

            If Not indexierung_erfolgreich Then
                LOGGER.Error("SetEmailIndices failed. See previous logs.")
                MsgBox("Error in SetEmailIndices - See log", MsgBoxStyle.Critical)
                Return False
            End If

            _Logger.Info("Indexing completed successfully for file [{0}].", CURRENT_NEWFILENAME)
            Return True
        Catch ex As Exception
            ShowErrorMessage(ex, "Write_Indizes")
            LOGGER.Error(ex, "Unexpected exception in Write_Indizes for file [{0}]", CURRENT_NEWFILENAME)
            Return False
        End Try
    End Function

    Private Function WriteIndex2File(pIndexName As String, pIndexValue As String)
        Try
            _Logger.Info($"Indexing with Name {pIndexName} and Value: {pIndexValue}")
            Return WINDREAM.SetFileIndex(CURRENT_NEWFILENAME, pIndexName, pIndexValue, CURR_DOKART_OBJECTTYPE)
        Catch ex As Exception
            ShowErrorMessage(ex, "WriteIndex2File")
            Return False
        End Try
    End Function

    Private Function SetEmailIndicies(pIndexAttachment As Boolean) As Boolean
        Try
            Dim oIndexNames As Dictionary(Of String, Object)

            Dim oSQL As String = $"SELECT * FROM TBGI_OBJECTTYPE_EMAIL_INDEX WHERE OBJECTTYPE = '{CURR_DOKART_OBJECTTYPE}'"
            Dim oTable As DataTable = DATABASE_ECM.GetDatatable(oSQL)

            If IsNothing(oTable) Then
                LOGGER.Error("Database returned NULL for Email Indicies query (OBJECTTYPE = [{0}]).", CURR_DOKART_OBJECTTYPE)
                Return False
            End If

            If oTable.Rows.Count = 0 Then
                LOGGER.Warn("No Email Indicies defined for OBJECTTYPE = [{0}].", CURR_DOKART_OBJECTTYPE)
                MsgBox($"Definition von Email Indizes für den Objekttyp [{CURR_DOKART_OBJECTTYPE}] fehlt." + vbNewLine + "Bitte informieren Sie Ihren Systembetreuer.", MsgBoxStyle.Critical)
                Return False
            End If

            If oTable.Rows.Count > 1 Then
                LOGGER.Warn("Multiple Email Indicies definitions found for OBJECTTYPE = [{0}]. Using none and exiting.", CURR_DOKART_OBJECTTYPE)
                Return False
            End If

            Dim oRow As DataRow = oTable.Rows.Item(0)

            If pIndexAttachment = False Then
                LOGGER.Info("Indexing main Email file for OBJECTTYPE = [{0}].", CURR_DOKART_OBJECTTYPE)
                LOGGER.Debug("Original filename: [{0}]", CURRENT_NEWFILENAME)

                Dim oMsgFilePath As String = CURRENT_NEWFILENAME
                If CURRENT_NEWFILENAME.StartsWith(WINDREAM_BASEPATH) = False Then
                    oMsgFilePath = WINDREAM_BASEPATH & oMsgFilePath
                End If

                LOGGER.Debug("Email file path: [{0}]", oMsgFilePath)

                Dim oMail As IMail = EMAIL.Load_Email(oMsgFilePath)
                LOGGER.Debug($"Load Email from path: {oMail}")

                Dim oMessageId As String = oMail.MessageID
                LOGGER.Debug($"MessageId: {oMessageId}")
                Dim oMessageFrom As String = EMAIL.Get_MessageSender(oMail)
                LOGGER.Debug($"MessageForm: {oMessageFrom}")
                Dim oMessageTo As String = EMAIL.Get_MessageReceiver(oMail)
                LOGGER.Debug($"Receiver: {oMessageTo}")
                Dim oDateIn As Date = EMAIL.Get_MessageDate(oMail)
                LOGGER.Debug($"Date: {oDateIn}")
                Dim oSubject As String = oMail.Subject
                LOGGER.Debug($"Subject: {oSubject}")

                LOGGER.Debug("Extracted Email fields → ID=[{0}], From=[{1}], To=[{2}], Date=[{3}], Subject=[{4}]",
                         oMessageId, oMessageFrom, oMessageTo, oDateIn, oSubject)

                CURRENT_MESSAGEID = oMessageId
                CURRENT_MESSAGEDATE = oDateIn

                If oSubject IsNot Nothing Then
                    CURRENT_MESSAGESUBJECT = oSubject
                Else
                    CURRENT_MESSAGESUBJECT = "<No Subject>"
                    LOGGER.Info("Email has no subject. Using default '<No Subject>'.")
                End If

                oIndexNames = New Dictionary(Of String, Object) From {
                {"IDX_EMAIL_ID", oMessageId},
                {"IDX_EMAIL_FROM", oMessageFrom},
                {"IDX_EMAIL_TO", oMessageTo},
                {"IDX_EMAIL_SUBJECT", CURRENT_MESSAGESUBJECT},
                {"IDX_EMAIL_DATE_IN", oDateIn}
            }
            Else
                LOGGER.Info("Indexing Email attachment for OBJECTTYPE = [{0}].", CURR_DOKART_OBJECTTYPE)

                oIndexNames = New Dictionary(Of String, Object) From {
                {"IDX_EMAIL_ID", CURRENT_MESSAGEID},
                {"IDX_EMAIL_SUBJECT", CURRENT_MESSAGESUBJECT},
                {"IDX_EMAIL_DATE_IN", CURRENT_MESSAGEDATE},
                {"IDX_CHECK_ATTACHMENT", True}
            }
            End If

            For Each oIndex In oIndexNames
                Try
                    If oIndex.Value Is Nothing Then
                        LOGGER.Warn("Skipping Index [{0}] because value was NULL.", oIndex.Key)
                        Continue For
                    End If

                    If TypeOf oIndex.Value Is String AndAlso oIndex.Value = String.Empty Then
                        LOGGER.Warn("Skipping Index [{0}] because value was empty.", oIndex.Key)
                        Continue For
                    End If

                    Dim oIndexingSuccessful = WriteIndex2File(oRow.Item(oIndex.Key), oIndex.Value)

                    If oIndexingSuccessful = False Then
                        LOGGER.Error("Indexing failed at Index [{0}] with value [{1}].", oIndex.Key, oIndex.Value)
                        MsgBox($"Error while Indexing Email at Index [{oIndex.Key}]", MsgBoxStyle.Critical)
                        Return False
                    End If

                    LOGGER.Debug("Index [{0}] successfully written with value [{1}].", oIndex.Key, oIndex.Value)
                Catch ex As Exception
                    LOGGER.Error(ex, "Exception while indexing Email at Index [{0}].", oIndex.Key)
                    Return False
                End Try
            Next

            LOGGER.Info("Successfully indexed Email (OBJECTTYPE = [{0}]).", CURR_DOKART_OBJECTTYPE)
            Return True
        Catch ex As Exception
            LOGGER.Error(ex, "Unexpected exception in SetEmailIndicies.")
            Return False
        End Try
    End Function

    Private Function SINGLEFILE_2_WINDREAM(_Objekttyp As String) As Boolean
        Try
            CURR_DOKART_OBJECTTYPE = _Objekttyp
            Dim oWMCheckPath = WINDREAM.VersionWMFilename(CURRENT_NEWFILENAME, System.IO.Path.GetExtension(CURRENT_NEWFILENAME))
            If CURRENT_NEWFILENAME.ToUpper <> oWMCheckPath.ToString.ToUpper Then
                _Logger.Info($"Target [{CURRENT_NEWFILENAME}] already existed!! - NewWMFilename [{oWMCheckPath}]")
                CURRENT_NEWFILENAME = oWMCheckPath
            End If

            Dim oStreamSuccessful = WINDREAM.NewFileStream(CURRENT_WORKFILE, CURRENT_NEWFILENAME, CURR_DOKART_OBJECTTYPE)
            Dim oTempPath As String = WINDREAM_BASEPATH & CURRENT_NEWFILENAME

            _Logger.Debug("Checks for file [{0}]", oTempPath)
            _Logger.Debug("File streamed to Windream: {0}", oStreamSuccessful)
            _Logger.Debug("File exists in Destination: {0}", File.Exists(oTempPath))

            Return oStreamSuccessful
        Catch ex As Exception
            ShowErrorMessage(ex, "SINGLEFILE_2_WINDREAM")
            Return False
        End Try
    End Function
    Function Move_Rename_Only(Quelle As String, _NewFilename As String, extension As String, _versionTz As String)
        'Überprüfen ob File existiert
        If File.Exists(_NewFilename) = False Then
            CURRENT_NEWFILENAME = _NewFilename
        Else
            'Versionieren
            Dim version As Integer = 1
            Dim Stammname As String = _NewFilename
            Dim neuername As String = _NewFilename
            Do While File.Exists(neuername)
                version += 1
                neuername = Stammname.Replace(extension, "") & _versionTz & version & extension
                CURRENT_NEWFILENAME = neuername
            Loop
        End If

        'Die Datei wird nun an den neuen Ort kopiert
        My.Computer.FileSystem.MoveFile(CURRENT_WORKFILE, CURRENT_NEWFILENAME)

        Dim Insert_String As String
        Try
            Dim oCurrentWorkfile = CURRENT_WORKFILE.Replace("'", "''")
            Dim oCurrentNewFilename = CURRENT_NEWFILENAME.Replace("'", "''")
            Dim oUser As String = $"{Environment.UserDomainName}\{Environment.UserName}"

            Insert_String = sql_history_INSERT_INTO & $",ADDED_WHO, ADDED_WHERE, FILE_HASH) VALUES ('{oCurrentWorkfile}','{oCurrentNewFilename}'{sql_history_Index_Values},'{oUser}','{Environment.MachineName}','{CURRENT_WORKFILE_HASH}')"
            If DATABASE_ECM.ExecuteNonQuery(Insert_String) = True Then
                If CURRENT_MESSAGEID <> "" Then
                    Dim max As String = "SELECT MAX(GUID) FROM TBGI_HISTORY"
                    Dim GUID = DATABASE_ECM.GetScalarValue(max)
                    Try
                        If GUID > 0 Then
                            Dim sql As String
                            If CURRENT_ISATTACHMENT = True Then
                                sql = "Update TBGI_HISTORY SET ATTACHMENT = 1, MSG_ID = '" & CURRENT_MESSAGEID & "' WHERE GUID = " & GUID
                                DATABASE_ECM.GetScalarValue(sql)
                            Else
                                sql = "Update TBGI_HISTORY SET ATTACHMENT = 0, MSG_ID = '" & CURRENT_MESSAGEID & "' WHERE GUID = " & GUID
                                DATABASE_ECM.GetScalarValue(sql)
                            End If
                        End If
                    Catch ex As Exception

                    End Try
                End If
            End If
            Return False
        Catch ex As Exception
            ShowErrorMessage(ex, "Move_Rename_Only")
            Return True
        End Try
    End Function

    Private Sub frmIndex_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        If File.Exists(CURRENT_FILENAME) Then
            Select Case CancelAttempts
                Case 0
                    If USER_LANGUAGE = LANG_DE Then
                        MsgBox($"Bitte indexieren Sie die Datei vollständig!{vbNewLine}(Abbruch 1 des Indexierungsvorgangs)", MsgBoxStyle.Information)
                    Else
                        MsgBox($"Please Index file completely{vbNewLine}(Abort 1 of Indexdialog)", MsgBoxStyle.Information)
                    End If
                    CancelAttempts += 1
                    e.Cancel = True
                Case 1
                    Dim result As MsgBoxResult
                    If USER_LANGUAGE = LANG_DE Then
                        result = MessageBox.Show($"Sie brechen nun zum zweiten Mal den Indexierungsvorgang ab!{vbNewLine}Wollen Sie die Indexierung aller Dateien abbrechen?", "Bestätigung erforderlich:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                    Else
                        result = MessageBox.Show($"You abort the indexdialog for the 2nd time!{vbNewLine}Do You want to abort indexing?", "Confirmation needed:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                    End If

                    If result = MsgBoxResult.Yes Then
                        Dim containsfw_file As Boolean = False
                        Try
                            ABORT_INDEXING = True
                            Dim sql As String = $"SELECT * FROM TBGI_FILES_USER WHERE WORKED = 0 AND UPPER(USER@WORK) = UPPER('{Environment.UserName}')"
                            Dim DT As DataTable = DATABASE_ECM.GetDatatable(sql)

                            Dim anz = DT.Rows.Count
                            For Each Filerow As DataRow In DT.Rows
                                Dim filestring As String = Filerow.Item("FILENAME2WORK")
                                Dim handletype As String = Filerow.Item("HANDLE_TYPE")

                                If handletype = "|MSGONLY|" Or handletype = "|ATTMNTEXTRACTED|" Then
                                    Try
                                        System.IO.File.Delete(filestring)
                                    Catch ex As Exception

                                    End Try

                                ElseIf handletype.StartsWith("|FW") Then
                                    containsfw_file = True
                                End If
                            Next
                            'Zuerst die Daten des Ablaufs löschen
                            If DATABASE_ECM.ExecuteNonQuery("DELETE FROM TBGI_FILES_USER WHERE UPPER(USER@WORK) = UPPER('" & Environment.UserName & "')") = True Then
                                If containsfw_file = True Then
                                    If USER_LANGUAGE = LANG_DE Then
                                        MsgBox("Der Indexierungsprozess beinhaltete (auch) Dateien per Folderwatch!" & vbNewLine & "Diese Dateien wurden nicht gelöscht und verbleiben im Folderwatch-Verzeichnis!" & vbNewLine & "Bitte verschieben Sie die Dateien ggfls.", MsgBoxStyle.Information, "Achtung - Hinweis:")
                                    Else
                                        MsgBox("The Indexingprocess contained (also) files from folderwatch!" & vbNewLine & "These files weren't deleted and will stay in the folderwatch-folder!" & vbNewLine & "Please move these files manually.", MsgBoxStyle.Information, "Achtung - Hinweis:")
                                    End If

                                End If
                            End If


                        Catch ex As Exception
                            _Logger.Error(ex)
                            MsgBox("Unexpected Error in Abort Indexing: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
                        End Try

                        Try
                            INDEXING_ACTIVE = False
                            CloseViewer()

                            ClassWindowLocation.SaveFormLocationSize(Me)
                            My.Settings.Save()
                        Catch ex As Exception
                            _Logger.Info(" - Unexpected error in Schliessen des Formulares - Fehler: " & vbNewLine & ex.Message)
                            _Logger.Error(ex.Message)
                            MsgBox(ex.Message, MsgBoxStyle.Critical, "Unexpected error in Schliessen des Formulares:")
                        End Try

                        e.Cancel = False
                    Else
                        e.Cancel = True
                    End If
                Case Else
                    Try
                        INDEXING_ACTIVE = False

                        CloseViewer()
                        ClassWindowLocation.SaveFormLocationSize(Me)
                        My.Settings.Save()
                    Catch ex As Exception
                        ShowErrorMessage(ex, "Form Close")
                    End Try
            End Select
        Else
            INDEXING_ACTIVE = False
        End If
    End Sub

    Private Sub frmIndex_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        ' Abbruchzähler zurücksetzen
        CancelAttempts = 0

        INDEXING_ACTIVE = True

        Try
            CURRENT_ISATTACHMENT = False
            DropType = DATABASE_ECM.GetScalarValue("SELECT HANDLE_TYPE FROM TBGI_FILES_USER WHERE GUID = " & CURRENT_WORKFILE_GUID)

            CURR_DELETE_ORIGIN = CONFIG.Config.DeleteOriginalFile
            checkItemDeleteSource.Enabled = True
            checkItemDeleteSource.Checked = CONFIG.Config.DeleteOriginalFile

            DocumentViewer1.Init(LOGCONFIG, VIEWER_LICENSE)

            If DropType Is Nothing Then
                _Logger.Debug("File with Id [{0}] was not found in TBGI_FILES_USER. Exiting.", CURRENT_WORKFILE_GUID)
                CancelAttempts = MaxCancelAttempts
                Close()
            Else
                CURRENT_DROPTYPE = DropType.Replace("|", "")

                If DropType.StartsWith("|FW") Then
                    ' Eine Datei aus FolderWatch wird IMMER gelöscht, egal wie die Einstellung in der Config lautet
                    CURR_DELETE_ORIGIN = True
                    checkItemDeleteSource.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
                ElseIf DropType.Contains("|OUTLOOK_MESSAGE|") Then
                    ' Eine (DragDrop)-Outlook Nachricht wird NIE gelöscht, egal wie die Einstellung in der Config lautet
                    CURR_DELETE_ORIGIN = False
                    checkItemDeleteSource.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
                Else
                    checkItemDeleteSource.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
                End If

                If DropType = "|DROPFROMFSYSTEM|" Then
                    If USER_LANGUAGE <> LANG_DE Then
                        Me.Text = "Indexing of dropped file"
                    Else
                        Me.Text = "Indexierung der gedroppten Datei"
                    End If
                ElseIf DropType = "|OUTLOOK_MESSAGE|" Or DropType = "|FW_MSGONLY|" Then
                    Select Case DropType
                        Case "|FW_MSGONLY|"
                            _Logger.Info(".msg-file from folderwatch")
                            If USER_LANGUAGE <> LANG_DE Then
                                Me.Text = "Indexing of msg-File (without Attachments) - from Folderwatch"
                            Else
                                Me.Text = "Indexierung der msg-Datei (ohne Anhang) - aus Folderwatch"
                            End If
                        Case "|OUTLOOK_MESSAGE|"
                            _Logger.Info(".msg-file through dragdrop")
                            If USER_LANGUAGE <> LANG_DE Then
                                Me.Text = "Indexing of msg-File (without Attachments)"
                            Else
                                Me.Text = "Indexierung der msg-Datei (ohne Anhang)"
                            End If
                    End Select

                ElseIf DropType = "|MSGONLY|" Then
                    If USER_LANGUAGE = LANG_DE Then
                        Me.Text = "Indexierung der msg-Datei (ohne Anhang)"
                    Else
                        Me.Text = "Indexing of msg-File (without Attachments)"
                    End If
                ElseIf DropType = "|ATTMNTEXTRACTED|" Or DropType = "|OUTLOOK_ATTACHMENT|" Then
                    CURRENT_ISATTACHMENT = True

                    If USER_LANGUAGE = LANG_DE Then
                        Me.Text = "Indexierung eines Email-Attachments"
                    Else
                        Me.Text = "Indexing of email-Attachment"
                    End If
                ElseIf DropType = "|FW_SIMPLEINDEXER|" Then

                    If USER_LANGUAGE = LANG_DE Then
                        Me.Text = "Indexierung einer Folderwatch-Datei"
                    Else
                        Me.Text = "Indexing of Folderwatch-File"
                    End If
                End If

                labelFilePath.Caption = CURRENT_WORKFILE

                ClassWindowLocation.LoadFormLocationSize(Me)

                SetFilePreview(CONFIG.Config.FilePreview)

                SplitContainer1.SplitterDistance = CONFIG.Config.SplitterDistanceViewer

                Load_String()

                DTTBGI_REGEX_DOCTYPE = DATABASE_ECM.GetDatatable("SELECT DISTINCT T1.DOCTYPE as DocType, T.* FROM TBGI_REGEX_DOCTYPE T, VWGI_DOCTYPE T1 WHERE T.DOCTYPE_ID = T1.DOCTYPE_ID")
                MULTIFILES = DATABASE_ECM.GetScalarValue("SELECT COUNT(*) FROM TBGI_FILES_USER WHERE WORKED = 0 AND GUID <> " & CURRENT_WORKFILE_GUID & " AND UPPER(USER@WORK) = UPPER('" & Environment.UserName & "')")
                Dim allFiles As Integer = MULTIFILES + 1
                MULTIINDEXING_ACTIVE = False

                If allFiles < 2 Then
                    BarCheckItem_MultiIndexing.Caption = "Multi-Indexing"
                    BarCheckItem_MultiIndexing.Enabled = False
                    BarButtonItem1.Enabled = False
                Else
                    If USER_LANGUAGE = LANG_DE Then
                        BarCheckItem_MultiIndexing.Caption = "Multi-Indexing - (" & allFiles & ") zu indexierende Dateien"
                    Else
                        BarCheckItem_MultiIndexing.Caption = "Multi-Indexing - (" & allFiles & ") files to be indexed"
                    End If
                    BarCheckItem_MultiIndexing.Checked = False
                    BarCheckItem_MultiIndexing.Enabled = True
                    BarButtonItem1.Enabled = True
                End If
            End If

        Catch ex As Exception
            ShowErrorMessage(ex, "Form Open")
        End Try
    End Sub

    Sub Load_String()
        Try
            Me.VWDDINDEX_MANTableAdapter.Connection.ConnectionString = MyConnectionString
            Me.VWINDEX_AUTOMTableAdapter.Connection.ConnectionString = MyConnectionString
        Catch ex As Exception
            _Logger.Warn(" - Unexpected error in Speichern der Verbindung - Fehler: " & vbNewLine & ex.Message)
            _Logger.Error(ex.Message)
            MsgBox("Unexpected error in Speichern der Verbindung: " & vbNewLine & ex.Message, MsgBoxStyle.Exclamation)
        End Try
    End Sub

    Private Sub frmIndex_Shown(sender As Object, e As System.EventArgs) Handles Me.Shown
        BringToFront()
        Focus()
        Cursor = Cursors.Default
        Refresh_Dokart()
        pnlIndex.Controls.Clear()

        checkItemTopMost.Checked = CONFIG.Config.TopMost
        TopMost = CONFIG.Config.TopMost
        BringToFront()

        FormLoaded = True

        Try
            _Logger.Info("Profile Preselected enabled: {0}", CONFIG.Config.ProfilePreselection)
            ' Letzte Auswahl merken überschreibt die automatische selektion
            If CONFIG.Config.ProfilePreselection Then
                checkItemPreselection.Checked = True

                If CURRENT_LASTDOKART <> "" Then
                    _Logger.Info("Last Saved DocType: {0}", CURRENT_LASTDOKART)

                    Dim oDocTypes As List(Of DocType) = DocTypes
                    Dim oFoundDocType = oDocTypes.
                        Where(Function(dt) dt.Name = CURRENT_LASTDOKART).
                        FirstOrDefault()

                    If oFoundDocType IsNot Nothing Then
                        _Logger.Info("Setting Last Saved DocType: {0}", CURRENT_LASTDOKART)

                        ComboboxDoctype.EditValue = oFoundDocType
                        ComboboxDoctype.SelectNextControl(ComboboxDoctype, forward:=True, tabStopOnly:=True, nested:=True, wrap:=False)
                    End If

                End If
            End If

            Dim oApplyRegex = ComboboxDoctype.EditValue Is Nothing And DTTBGI_REGEX_DOCTYPE.Rows.Count > 0
            _Logger.Info("Applying Profile Selection Regex: [{0}]", oApplyRegex)

            If oApplyRegex Then
                For Each oRoW As DataRow In DTTBGI_REGEX_DOCTYPE.Rows
                    Dim oOnlyFilename = Path.GetFileName(CURRENT_WORKFILE)
                    If Regex.IsMatch(oOnlyFilename, oRoW.Item("Regex"), RegexOptions.IgnoreCase) Then

                        _Logger.Debug("There is a match on REGEX_DOCTYPE: [{0}]", oRoW.Item("DOCTYPE"))
                        _Logger.Debug("Regex: [{0}], FileName: [{1}]", oRoW.Item("Regex"), oOnlyFilename)

                        Dim oDoctypes As List(Of DocType) = DocTypes
                        Dim oFoundDocType As DocType = oDoctypes.
                            Where(Function(dt) dt.Guid = oRoW.Item("DOCTYPE_ID")).
                            FirstOrDefault()

                        If oFoundDocType IsNot Nothing Then
                            _Logger.Debug("DocType found: [{0}]", oFoundDocType)
                            ComboboxDoctype.EditValue = oFoundDocType
                            ComboboxDoctype.SelectNextControl(ComboboxDoctype, forward:=True, tabStopOnly:=True, nested:=True, wrap:=False)

                            Exit For
                        End If
                    End If
                Next
            End If

            If ComboboxDoctype.EditValue Is Nothing Then
                ComboboxDoctype.Select()
            End If
        Catch ex As Exception
            ShowErrorMessage(ex, "Form Shown")
        End Try
    End Sub
    Sub Refresh_Dokart()
        Try
            Dim sql = String.Format("SELECT DISTINCT DOCTYPE_ID, DOCTYPE, SEQUENCE FROM VWGI_DOCTYPE where USERNAME = '{0}' ORDER BY SEQUENCE", Environment.UserName)
            _Logger.Info("SQL DoctypeList: " & sql)
            Dim oDoctypes = DATABASE_ECM.GetDatatable(sql)

            ComboboxDoctype.EditValue = Nothing
            ComboboxDoctype.Properties.DataSource = Nothing

            DocTypes.Clear()
            For Each oRow As DataRow In oDoctypes.Rows
                Dim oDocType = New DocType With {
                    .Guid = oRow.Item("DOCTYPE_ID"),
                    .Name = oRow.Item("DOCTYPE")
                }
                DocTypes.Add(oDocType)
            Next

            ComboboxDoctype.Properties.DataSource = DocTypes
        Catch ex As Exception
            ShowErrorMessage(ex, "Refresh_Dokart")
        End Try
    End Sub

    Private Sub ComboBoxEdit1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboboxDoctype.EditValueChanged
        If ComboboxDoctype.EditValue IsNot Nothing And FormLoaded = True Then

            WINDREAM = New Windream(LOGCONFIG, False, WMDrive, WINDREAM_BASEPATH, True, "", "", "", "")
            If Not IsNothing(WINDREAM) Then
                If WINDREAM.SessionLoggedin Then

                    Dim oSelectedItem As DocType = ComboboxDoctype.EditValue

                    CURRENT_DOKART_ID = oSelectedItem.Guid
                    CURRENT_LASTDOKART = oSelectedItem.Name

                    ClearNotice()

                    ClearError()

                    pnlIndex.Controls.Clear()
                    Dim sql As String = "Select WINDREAM_DIRECT, ZIEL_PFAD, DUPLICATE_HANDLING from TBDD_DOKUMENTART WHERE GUID = " & oSelectedItem.Guid
                    Dim oDoctypes As DataTable = DATABASE_ECM.GetDatatable(sql)

                    Dim oDocType As DataRow = oDoctypes.Rows.Item(0)
                    WMDirect = oDocType.Item("WINDREAM_DIRECT")
                    Dim oDestination As String = oDocType.Item("ZIEL_PFAD")
                    Dim oNewDestination As String
                    If WMDirect Then
                        Dim oNormalized As String = WINDREAM.GetNormalizedPath(oDestination, False)
                        oNewDestination = Path.Combine(WINDREAM.ClientBasePath, oNormalized)
                    Else
                        oNewDestination = oDestination
                    End If

                    LOGGER.Debug("Path from Database is [{0}]", oDestination)
                    LOGGER.Debug("Checking for path [{0}]", oNewDestination)
                    Dim oPathExists As Boolean
                    If WMDirect Then
                        oPathExists = WINDREAM.TestFolderExists(oNewDestination)
                    Else
                        oPathExists = Directory.Exists(oNewDestination)
                    End If

                    If oPathExists = False Then
                        Dim oMessage As String

                        If USER_LANGUAGE = "de-DE" Then
                            oMessage = $"Der Pfad für das ausgewählte Profil ist nicht erreichbar:{vbNewLine}[{oNewDestination}].{vbNewLine}{vbNewLine}Bitte wählen Sie ein anderes Profil."
                        Else
                            oMessage = $"Profile Path is not available:{vbNewLine}[{oNewDestination}].{vbNewLine}{vbNewLine}Please select another profile."
                        End If

                        MsgBox(oMessage, MsgBoxStyle.Information, Text)
                        ComboboxDoctype.EditValue = Nothing
                    Else

                        CURRENT_DOKART_DUPLICATE_HANDLING = oDocType.Item("DUPLICATE_HANDLING")
                        Refresh_IndexeMan(oSelectedItem.Guid)
                    End If

                Else
                    MsgBox("Es konnte keine Session aufgebaut werden.")
                End If
            Else
                MsgBox("Es konnte keine Windream-Verbindung aufgebaut werden.")
            End If
        End If
    End Sub

    Private Sub Refresh_IndexeMan(dokartid As Integer)
        Dim sql
        Try
            sql = "select T1.BEZEICHNUNG AS DOKUMENTART,T.* from TBDD_INDEX_MAN T, TBDD_DOKUMENTART T1 where T.ACTIVE = 1 AND T.DOK_ID = T1.GUID AND T.DOK_ID = " & dokartid & " ORDER BY T.SEQUENCE"
            DT_INDEXEMAN = DATABASE_ECM.GetDatatable(sql)
            pnlIndex.Visible = True
            LoadIndexe_Man()
        Catch ex As System.Exception
            ShowErrorMessage(ex, "Refresh_IndexeMan", "DOKART-ID: " & dokartid)
        End Try
    End Sub

    Function Check_HistoryValues(Indexname As String, Dokart As String) As String
        Try
            Dim result = Nothing
            Dim DT As DataTable = MyDataset.TBTEMP_INDEXRESULTS
            If DT.Rows.Count > 0 Then
                For Each row As DataRow In DT.Rows
                    If row.Item("Indexname") = Indexname And row.Item("Dokumentart") = Dokart Then
                        result = row.Item("Value")
                        Return result
                    End If
                Next
            Else
                Return Nothing
            End If
        Catch ex As Exception
            ShowErrorMessage(ex, "Check_HistoryValues")
            Return Nothing
        End Try
    End Function

    Private Sub LoadIndexe_Man()
        Try
            Dim oScreen As New DigitalData.Modules.Windows.Screen()
            Dim oDpiscale = oScreen.GetScreenScaling(Me)

            Dim oRowTop As Integer = 20 * oDpiscale
            Dim oLabelLeft As Integer = 20
            Dim oControlLeft As Integer = 250
            Dim oControlWidth As Integer = 420
            Dim oZeilenhoehe As Integer = 30 * oDpiscale

            _Logger.Info("Loading Indicies for Screen Scaling Factor [{0}]", oDpiscale)

            Dim oControls As New ControlCreator(LOGCONFIG, pnlIndex, Me) With {
            .OnControlChanged = AddressOf PrepareDependingControl,
            .OnLookupData = AddressOf GetLookupData
        }

            If DT_INDEXEMAN.Rows.Count = 0 Then
                ShowError("Keine Manuellen Indizes für die " & vbNewLine & "Dokumentart " & ComboboxDoctype.Text & " definiert")
                _Logger.Info(" - Keine Manuellen Indizes für die " & vbNewLine & "Dokumentart " & ComboboxDoctype.Text & " definiert")
            End If

            For Each oRow As DataRow In DT_INDEXEMAN.Rows
                Dim oDataType = oRow.Item("DATATYPE")
                Dim MultiSelect As Boolean = oRow.Item("MULTISELECT")
                Dim AddNewItems As Boolean = oRow.Item("VKT_ADD_ITEM")
                Dim PreventDuplicates As Boolean = oRow.Item("VKT_PREVENT_MULTIPLE_VALUES")
                Dim oControlName As String = oRow.Item("NAME")
                Dim oConnectionId = oRow.ItemEx("CONNECTION_ID", 0)
                Dim oSQLSuggestion = oRow.Item("SUGGESTION")
                Dim oSQLResult = oRow.Item("SQL_RESULT")

                LOGGER.Debug("IndexName: {0}", oControlName)
                LOGGER.Debug("SQL: {0}", oSQLResult)

                Dim DefaultValue = Check_HistoryValues(oControlName, oRow.Item("DOKUMENTART"))
                If DefaultValue Is Nothing Then
                    DefaultValue = GetPlaceholderValue(oRow.Item("DEFAULT_VALUE"), CURRENT_WORKFILE, USER_SHORTNAME)
                End If

                Dim ctrl As Control = Nothing

                Dim lbl As Windows.Forms.Label = Nothing

                ' Label nur anzeigen, wenn nicht BOOLEAN
                If oDataType <> ClassConstants.INDEX_TYPE_BOOLEAN Then
                    lbl = New Windows.Forms.Label()
                    lbl.Text = oRow.Item("COMMENT").ToString()
                    lbl.Left = oLabelLeft
                    lbl.Top = oRowTop
                    lbl.Width = oControlLeft - oLabelLeft - 10
                    lbl.AutoSize = True
                    lbl.MaximumSize = New Size(lbl.Width, 0) ' Max Breite, Höhe unbegrenzt
                    lbl.Height = lbl.PreferredHeight
                    lbl.TextAlign = ContentAlignment.MiddleLeft
                    lbl.UseCompatibleTextRendering = True
                    pnlIndex.Controls.Add(lbl)
                End If

                ' Control erzeugen und platzieren
                Select Case oDataType
                    Case ClassConstants.INDEX_TYPE_BOOLEAN
                        Dim chk As CheckEdit = oControls.AddCheckBox(oControlName, oRowTop, DefaultValue, oRow.Item("COMMENT").ToString)
                        If chk IsNot Nothing Then
                            chk.Left = oControlLeft
                            chk.Top = oRowTop
                            chk.Width = oControlWidth
                            chk.Margin = New Padding(0, 4, 0, 4)
                            pnlIndex.Controls.Add(chk)
                        End If
                    Case ClassConstants.INDEX_TYPE_INTEGER, ClassConstants.INDEX_TYPE_VARCHAR
                        If (oSQLSuggestion = True AndAlso oSQLResult.ToString.Length > 0) OrElse MultiSelect = True Then
                            ctrl = oControls.AddLookupControl(oControlName, oRowTop, MultiSelect, oDataType, oSQLResult, oConnectionId, DefaultValue, AddNewItems, PreventDuplicates)
                        Else
                            If oControlName.ToLower() = "dateiname" Then
                                ctrl = oControls.AddTextBox(oControlName, oRowTop, System.IO.Path.GetFileNameWithoutExtension(CURRENT_WORKFILE), oDataType)
                            Else
                                ctrl = oControls.AddTextBox(oControlName, oRowTop, DefaultValue, oDataType)
                            End If
                        End If
                    Case "DATE"
                        ctrl = oControls.AddDateTimePicker(oControlName, oRowTop, DefaultValue)
                    Case Else
                        MsgBox("Bitte überprüfen Sie den Datentyp des hinterlegten Indexwertes!", MsgBoxStyle.Critical, "Achtung:")
                        _Logger.Warn(" - Datentyp nicht hinterlegt - LoadIndexe_Man")
                End Select

                If ctrl IsNot Nothing Then
                    ctrl.Left = oControlLeft
                    ctrl.Top = oRowTop
                    ctrl.Width = oControlWidth
                    pnlIndex.Controls.Add(ctrl)

                    If IsNotNullOrEmpty(DefaultValue) Then

                        Me.BeginInvoke(
                        Sub()
                            _Logger.Debug("Triggering PrepareDependingControl for [{0}] via BeginInvoke", ctrl.Name)
                            PrepareDependingControl(ctrl)
                        End Sub)

                    End If
                End If

                Dim zeilenhoeheAktuell As Integer

                If oDataType <> ClassConstants.INDEX_TYPE_BOOLEAN Then
                    ' Verwende die Höhe vom Label oder Mindesthöhe
                    zeilenhoeheAktuell = Math.Max(lbl.Height, 30 * oDpiscale)
                Else
                    ' Für Boolean Controls kannst du die Standardhöhe nehmen
                    zeilenhoeheAktuell = 30 * oDpiscale
                End If

                oRowTop += zeilenhoeheAktuell
            Next

            ' Panel- und Formhöhe anpassen, wenn nötig
            Dim oPanelHeight = oRowTop + 10
            If pnlIndex.Height < oPanelHeight Then
                If (Me.Height - 315) < oPanelHeight Then
                    Me.Height = (Me.Height - 315) + oPanelHeight
                End If
                pnlIndex.Height = oPanelHeight
            End If

            SendKeys.Send("{TAB}")

        Catch ex As Exception
            ShowErrorMessage(ex, "LoadIndexe_Man")
        End Try
    End Sub

    Private Function GetLookupData(pLookup As LookupControl3, pSQLCommand As String, pConnectionId As Integer)
        Dim oConnectionString = DATABASE_ECM.Get_ConnectionStringforID(pConnectionId)

        If oConnectionString IsNot Nothing And pSQLCommand.Length > 0 Then
            LOGGER.Debug("Connection String (redacted): [{0}]", oConnectionString.Substring(0, 30))

            If ClassPatterns.HasComplexPatterns(pSQLCommand) Then
                LOGGER.Debug(" >>sql enthält Platzhalter und wird erst während der Laufzeit gefüllt!", False)
                Return Nothing
            Else
                pSQLCommand = ClassPatterns.ReplaceInternalValues(pSQLCommand)
                pSQLCommand = ClassPatterns.ReplaceUserValues(pSQLCommand, USER_PRENAME, USER_SURNAME, USER_SHORTNAME, USER_LANGUAGE, USER_EMAIL, USER_ID, CURRENT_DOKART_ID)

                Dim oDatatable = DATABASE_ECM.GetDatatableWithConnection(pSQLCommand, oConnectionString)
                Return oDatatable
            End If
        Else
            LOGGER.Warn("Connection String for control [{0}] is empty!", pLookup.Name)
            Return Nothing
        End If
    End Function

    Private Sub PrepareDependingControl(Control As Control)
        If TypeOf Control Is Windows.Forms.Label Then
            Exit Sub
        End If

        Try
            Dim oMeta = DirectCast(Control.Tag, ControlCreator.ControlMeta)
            Dim oIndexName As String = oMeta.IndexName
            Dim oSQL = $"SELECT * FROM TBDD_INDEX_MAN WHERE SQL_RESULT LIKE '%{oIndexName}%' AND DOK_ID = {CURRENT_DOKART_ID}"
            Dim oDatatable As DataTable = DATABASE_ECM.GetDatatable(oSQL)

            If Not IsNothing(oDatatable) Then
                LOGGER.Debug("Found [{0}] depending controls for [{1}]", oDatatable.Rows.Count, Control.Name)

                For Each oRow As DataRow In oDatatable.Rows
                    Dim oControlName As String = oRow.ItemEx("NAME", "")
                    Dim oConnectionId As Integer = oRow.ItemEx("CONNECTION_ID", -1)
                    Dim oControlSql As String = oRow.ItemEx("SQL_RESULT", "")

                    If oConnectionId = -1 Or oControlSql = String.Empty Then
                        LOGGER.Warn("Missing SQL Query or ConnectionId for Control [{0}]! Continuing.", oControlName)
                        Continue For
                    End If

                    oControlSql = ClassPatterns.ReplaceUserValues(oControlSql, USER_PRENAME, USER_SURNAME, USER_SHORTNAME, USER_LANGUAGE, USER_EMAIL, USER_ID, CURRENT_DOKART_ID)
                    oControlSql = ClassPatterns.ReplaceInternalValues(oControlSql)
                    oControlSql = ClassPatterns.ReplaceControlValues(oControlSql, pnlIndex)
                    LOGGER.Debug("Setting new value for [{0}]", oControlName)
                    SetDependingControlResult(oControlName, oControlSql, oConnectionId)
                Next
            End If
        Catch ex As Exception
            LOGGER.Error(ex)
        End Try
    End Sub

    Private Sub SetDependingControlResult(IndexName As String, SqlCommand As String, SqlConnectionId As Integer)
        Try
            If String.IsNullOrWhiteSpace(SqlCommand) OrElse SqlCommand.Contains("''") OrElse SqlCommand.Contains("IN ()") Then
                LOGGER.Warn("Skipped SQL execution for Index [{0}]: Invalid or empty SQL: [{1}]", IndexName, SqlCommand)
                Exit Sub
            End If

            Dim oConnectionString = DATABASE_ECM.Get_ConnectionStringforID(SqlConnectionId)
            Dim oDatatable As DataTable = DATABASE_ECM.GetDatatableWithConnection(SqlCommand, oConnectionString)
            Dim oFoundControl As Control = Nothing

            For Each oControl As Control In pnlIndex.Controls
                If TypeOf oControl Is Windows.Forms.Label Then
                    Continue For
                End If

                Dim oMeta = DirectCast(oControl.Tag, ControlCreator.ControlMeta)
                Dim oIndex As String = oMeta.IndexName

                If oIndex = IndexName Then
                    oFoundControl = oControl
                    Exit For
                End If
            Next

            If oFoundControl Is Nothing Then
                LOGGER.Warn("Depending Control for Index [{0}] not found!", IndexName)
                Exit Sub
            End If

            If oDatatable Is Nothing Then
                LOGGER.Warn("Error in SQL Command: {0}", SqlCommand)
                Exit Sub
            End If

            Select Case oFoundControl.GetType.Name
                Case GetType(TextEdit).Name
                    If oDatatable.Rows.Count > 0 Then
                        Dim oFirstRow As DataRow = oDatatable.Rows.Item(0)

                        If oFirstRow.ItemArray.Length > 0 Then
                            Dim oValue = oFirstRow.Item(0).ToString()

                            LOGGER.Debug("Setting Value for TextEdit [{0}]: [{1}]", oFoundControl.Name, oValue)
                            DirectCast(oFoundControl, TextEdit).Text = oValue
                        End If
                    End If
                Case GetType(LookupControl3).Name
                    LOGGER.Debug("Setting Value for LookupControl [{0}]: [{1}]", oFoundControl.Name, "DATATABLE")
                    Dim oLookupControl = DirectCast(oFoundControl, LookupControl3)
                    oLookupControl.Properties.DataSource = oDatatable

                    If oDatatable.Columns.Count > 0 Then
                        oLookupControl.Properties.ValueMember = oDatatable.Columns.Item(0).ColumnName
                        oLookupControl.Properties.DisplayMember = oDatatable.Columns.Item(0).ColumnName
                    End If
                Case GetType(Windows.Forms.ComboBox).Name
                    LOGGER.Debug("Setting Value for Combobox [{0}]: [{1}]", oFoundControl.Name, "DATATABLE")
                    DirectCast(oFoundControl, Windows.Forms.ComboBox).DataSource = oDatatable
                Case Else
                    LOGGER.Debug("Could not set depending control result for [{0}]", oFoundControl.GetType.Name)
            End Select
        Catch ex As Exception
            LOGGER.Error(ex)
        End Try
    End Sub

    Function GetPlaceholderValue(InputValue As String, FileName As String, UserShortName As String) As String
        Dim oResult As String

        Try
            Select Case InputValue.ToString.ToUpper
                Case "$filename_ext".ToUpper
                    oResult = Path.GetFileName(FileName)
                Case "$filename".ToUpper
                    oResult = Path.GetFileNameWithoutExtension(FileName)
                Case "$extension".ToUpper
                    oResult = Path.GetExtension(FileName).Replace(".", "")
                Case "$FileCreateDate".ToUpper
                    Dim oFileInfo As New FileInfo(FileName)
                    Dim oCreationDate As Date = oFileInfo.CreationTime
                    oResult = oCreationDate.ToShortDateString
                Case "$FileCreatedWho".ToUpper

                    Dim fileInfo As FileInfo = New FileInfo(FileName)
                    Dim fileSecurity As FileSecurity = fileInfo.GetAccessControl()

                    ' Ersteller auslesen
                    Dim oOwner As System.Security.Principal.NTAccount = DirectCast(fileSecurity.GetOwner(GetType(System.Security.Principal.NTAccount)), System.Security.Principal.NTAccount)
                    oResult = oOwner.Value
                Case "$DateDDMMYYY".ToUpper
                    oResult = System.DateTime.Now.ToShortDateString
                Case "$Username".ToUpper
                    oResult = Environment.UserName
                Case "$Usercode".ToUpper
                    oResult = UserShortName
                Case Else
                    oResult = InputValue
            End Select
        Catch ex As Exception
            _Logger.Warn("Error in ReplacePlaceholders: " & ex.Message)
            _Logger.Error(ex.Message)
            oResult = Nothing
        End Try

        Return oResult
    End Function

    Function StripPlaceholder(Placeholder As String) As String
        Dim oResult = Placeholder
        oResult = Regex.Replace(oResult, "^\[%", "")
        oResult = Regex.Replace(oResult, "\]$", "")
        Return oResult
    End Function

    Function FillIndexe_Autom(dokart_id As Integer) As Boolean
        Try
            VWINDEX_AUTOMTableAdapter.Fill(MyDataset.VWDDINDEX_AUTOM, dokart_id)
            Dim oDatatable = MyDataset.VWDDINDEX_AUTOM
            Dim placeholderRegex As New Regex("\[%{1}[a-zA-Z0-9\!\$\&\/\(\)\=\?\,\.\-\;\:_öÖüÜäÄ\#\'\+\*\~\{\}\@\€\<\>\ ]+]{1}")

            If oDatatable.Rows.Count = 0 Then Return True

            For Each oRow As DataRow In oDatatable
                Dim indexName = oRow.Item("INDEXNAME").ToString
                _Logger.Info($"Working on AutomaticIndex: {indexName}...")

                Dim sql = oRow.ItemEx("SQL_RESULT", "")
                Dim sqlActive = oRow.ItemEx("SQL_ACTIVE", False)
                Dim connId = oRow.ItemEx("CONNECTION_ID", -1)
                Dim provider = oRow.ItemEx("SQL_PROVIDER", "")
                Dim value = oRow.ItemEx("VALUE", "")
                Dim endResult As New List(Of String)

                ' #### Fall: Kein SQL oder SQL ist nicht aktiv
                If String.IsNullOrWhiteSpace(sql) OrElse Not sqlActive Then
                    Dim resolved = GetPlaceholderValue(value, CURRENT_WORKFILE, USER_SHORTNAME)
                    oRow("Indexiert") = True
                    oRow("Indexwert") = If(resolved, value)
                    Continue For
                End If

                ' #### Fall: SQL aktiv – einfache Platzhalter ersetzen
                Dim matches = placeholderRegex.Matches(sql)

                For Each match As Match In matches
                    Dim ph = StripPlaceholder(match.Value)
                    Dim resolvedPH = GetPlaceholderValue(ph, CURRENT_WORKFILE, USER_SHORTNAME)
                    If Not String.IsNullOrWhiteSpace(resolvedPH) Then
                        sql = sql.Replace(match.Value, resolvedPH)
                        Continue For
                    End If

                    Dim isOptional = DATABASE_ECM.GetScalarValue($"SELECT OPTIONAL FROM TBDD_INDEX_MAN WHERE DOK_ID = {dokart_id} AND UPPER(NAME) = UPPER('{ph}')")
                    Dim manIndex = GetManIndex_Value(ph, "IDX_AUTO", isOptional)

                    If Not String.IsNullOrWhiteSpace(manIndex) AndAlso Not manIndex.Contains(ClassConstants.VECTORSEPARATOR) Then
                        sql = sql.Replace(match.Value, manIndex)
                    End If
                Next

                ' #### Platzhalter durch Umgebungsvariablen ersetzen
                sql = ClassPatterns.ReplaceControlValues(sql, pnlIndex)
                sql = ClassPatterns.ReplaceInternalValues(sql)
                sql = ClassPatterns.ReplaceUserValues(sql, USER_PRENAME, USER_SURNAME, USER_SHORTNAME, USER_LANGUAGE, USER_EMAIL, USER_ID, dokart_id)

                If Not String.IsNullOrWhiteSpace(sql) Then _Logger.Debug("SQL after Replace: " & sql)

                ' #### Fall: Vektor-Platzhalter oder Vektor-Index
                If placeholderRegex.Matches(sql).Count > 0 OrElse indexName.Contains("Vektor") Then
                    Try
                        Dim connString = DATABASE_ECM.Get_ConnectionStringforID(connId)
                        Dim resultDT = DATABASE_ECM.GetDatatableWithConnection(sql, connString)

                        If resultDT IsNot Nothing Then
                            For Each resultRow As DataRow In resultDT.Rows
                                endResult.Add(resultRow.Item(0).ToString())
                            Next

                            If endResult.Count > 0 Then
                                oRow("Indexiert") = True
                                oRow("Indexwert") = String.Join(ClassConstants.VECTORSEPARATOR, endResult)
                            End If
                        End If
                    Catch ex As Exception
                        ShowErrorMessage(ex, $"FillIndexe_Autom - Vektorfield [{indexName}]")
                    End Try
                Else
                    ' #### Fall: Nur einfacher SQL ohne Vektor
                    Dim result = GetAutomaticIndexSQLValue(sql, connId, provider)
                    _Logger.Info($"Got simple SQLResult: {result}")
                    oRow("Indexiert") = True
                    oRow("Indexwert") = result
                End If
            Next

            Return True

        Catch ex As Exception
            ShowErrorMessage(ex, "FillIndexe_Autom")
            Return False
        End Try
    End Function

    Private Sub btnVorschau_Click(sender As System.Object, e As System.EventArgs)
        PreviewFile()
    End Sub

    Sub PreviewFile()
        Try
            DocumentViewer1.LoadFile(CURRENT_WORKFILE)
        Catch ex As Exception
            ShowErrorMessage(ex, "PreviewFile")
        End Try
    End Sub
    Private Function UnicodeBytesToString(ByVal bytes() As Byte) As String
        Return System.Text.Encoding.UTF8.GetString(bytes)
    End Function
    Public Function TextStringToByteArray(ByRef str As String) As Byte()
        Dim enc As System.Text.Encoding = Encoding.GetEncoding(65001)

        Return enc.GetBytes(str)
    End Function
    Public Shared Function encode(ByVal str As String) As String
        'supply True as the construction parameter to indicate
        'that you wanted the class to emit BOM (Byte Order Mark)
        'NOTE: this BOM value is the indicator of a UTF-8 string
        Dim utf8Encoding As New System.Text.UTF8Encoding(True)
        Dim encodedString() As Byte

        encodedString = utf8Encoding.GetBytes(str)

        Return utf8Encoding.GetString(encodedString)
    End Function
    Private Function WORK_FILE() As Boolean
        Try
            Me.VWDDINDEX_MANTableAdapter.Fill(Me.MyDataset.VWDDINDEX_MAN, CURRENT_DOKART_ID)
            _Logger.Debug("Manuelle Indexe geladen")

            If MyDataset.VWDDINDEX_MAN.Rows.Count > 0 Then
                Dim oDokart As DocType = ComboboxDoctype.EditValue

                CURRENT_DOKART_ID = oDokart.Guid
                If CheckWrite_IndexeMan(oDokart.Guid) = True Then
                    '##### Manuelle Indexe indexiert #####
                    _Logger.Info("Datei [" & CURRENT_WORKFILE & "] wird nun indexiert...")
                    If FillIndexe_Autom(oDokart.Guid) = True Then
                        _Logger.Debug(" ...FillIndexe_Autom durchlaufen")

                        'Den Zielnamen zusammenbauen
                        If Name_Generieren() = True Then
                            'Die Datei verschieben
                            If Move_File_and_Index() = True Then
                                _Logger.Debug(" ...Move_File2_Target durchlaufen")

                                _Logger.Info("Datei '" & CURRENT_NEWFILENAME & "' erfolgreich erzeugt.")
                                Dim oDEL As String = "DELETE FROM TBGI_FILES_USER WHERE GUID = " & CURRENT_WORKFILE_GUID
                                DATABASE_ECM.ExecuteNonQuery(oDEL)

                                'Dokumentenviewer ausblenden um keinen Zugriffsfehler zu produzieren
                                CloseViewer()
                                _Logger.Debug(" ...Viewer geschlossen")

                                If CURR_DELETE_ORIGIN = True Then
                                    _Logger.Info("Datei [" & CURRENT_WORKFILE & "] wird gelöscht.")
                                    Try
                                        File.SetAttributes(CURRENT_WORKFILE, FileAttributes.Normal)
                                        File.Delete(CURRENT_WORKFILE)
                                    Catch ex As Exception
                                        _Logger.Error(ex)
                                    End Try
                                    _Logger.Info("Datei [" & CURRENT_WORKFILE & "] wurde gelöscht.")
                                End If

                                Return True
                            End If

                        Else
                            If USER_LANGUAGE = LANG_DE Then
                                MsgBox("Unerwarteter Fehler in Name_Generieren - Bitte überprüfen sie die Logdatei", MsgBoxStyle.Critical)
                            Else
                                MsgBox("Unexpected error in Name_Generieren - Please check the Logfile", MsgBoxStyle.Critical)
                            End If
                            Return False
                        End If
                    Else
                        If USER_LANGUAGE = LANG_DE Then
                            MsgBox("Unerwarteter Fehler in FillIndexe_Autom - Bitte überprüfen sie die Logdatei", MsgBoxStyle.Critical)
                        Else
                            MsgBox("Unexpected error in FillIndexe_Autom - Please check the Logfile", MsgBoxStyle.Critical)
                        End If
                        Return False
                    End If
                End If
            Else
                If USER_LANGUAGE = LANG_DE Then
                    MsgBox("Bitte überprüfen Sie die Konfiguration dieser Dokumentart." & vbNewLine & "Es sind KEINE manuellen Indizes konfiguriert oder aktiv geschaltet!", MsgBoxStyle.Exclamation)
                Else
                    MsgBox("Please check the configuration for this document-type." & vbNewLine & "There are NO manual indicies that are either configured or set to active!", MsgBoxStyle.Exclamation)
                End If
                Return False
            End If
        Catch ex As Exception
            ShowErrorMessage(ex, "WORK_FILE")
            Return False
        End Try
    End Function

    Private Function Move_File_and_Index()
        Dim oError As Boolean
        Try
            CURRENT_DOC_ID = 0
            Dim oSQL As String = "SELECT FOLDER_FOR_INDEX FROM TBDD_DOKUMENTART WHERE GUID = " & CURRENT_DOKART_ID
            Dim oFolderForIndex = DATABASE_ECM.GetScalarValue(oSQL)
            If Not IsDBNull(oFolderForIndex) Then
                CreateFolderForIndex(oFolderForIndex)
            Else
                CreateFolderForIndex(String.Empty)
            End If

            If CURR_DOKART_WD_DIRECT = False Then
                'Datei verschieben
                oError = Move_Rename_Only(CURRENT_WORKFILE, CURRENT_NEWFILENAME, CURR_WORKFILE_EXTENSION, VERSION_DELIMITER)
            Else
                Dim oExportSuccessful As Boolean = False
                'Variable Folder
                If DropType = "|DROPFROMFSYSTEM|" Or DropType = "|OUTLOOK_ATTACHMENT|" Or DropType = "|ATTMNTEXTRACTED|" Or DropType = "|FW_SIMPLEINDEXER|" Then
                    oExportSuccessful = SINGLEFILE_2_WINDREAM(CURR_DOKART_OBJECTTYPE)
                ElseIf DropType = "|OUTLOOK_MESSAGE|" Or DropType = "|FW_MSGONLY|" Or DropType = "|MSGONLY|" Or DropType = "|FW_OUTLOOK_MESSAGE|" Then
                    oExportSuccessful = SINGLEFILE_2_WINDREAM(CURR_DOKART_OBJECTTYPE)
                End If
                If oExportSuccessful = True Then
                    Dim ofilename = Path.GetFileName(CURRENT_NEWFILENAME)
                    Dim odwDocID As Int64
                    If WM_DB_SERVER <> "" Then
                        oSQL = $"select max(dwdocid) from {WM_DB_SERVER}.dbo.BaseAttributes where szLongName = '{ofilename}'"
                        Dim oDocID = DATABASE_ECM.GetScalarValue(oSQL)
                        If Not IsNothing(oDocID) Then
                            CURRENT_DOC_ID = oDocID
                        End If
                    End If

                    'Kein Fehler in Export2windream
                    oError = False
                    If Write_Indizes() = True Then
                        'Kein Fehler in Setzen der windream-Indizes
                        Dim Insert_String As String
                        Try
                            Dim tempCur_WF = CURRENT_WORKFILE.Replace("'", "''")
                            Dim tempCur_New_FN = CURRENT_NEWFILENAME.Replace("'", "''")
                            Dim oUser As String = $"{Environment.UserDomainName}\{Environment.UserName}"

                            Insert_String = sql_history_INSERT_INTO & $",ADDED_WHO, ADDED_WHERE, FILE_HASH) VALUES ('{tempCur_WF}','{tempCur_New_FN}'{sql_history_Index_Values},'{oUser}','{Environment.MachineName}','{CURRENT_WORKFILE_HASH}')"
                            DATABASE_ECM.GetScalarValue(Insert_String)
                            If DropType.Contains("MSG") Or DropType = "|ATTMNTEXTRACTED|" Or DropType = "|OUTLOOK_ATTACHMENT|" Then
                                If CURRENT_MESSAGEID <> "" Then
                                    Dim max As String = "SELECT MAX(GUID) FROM TBGI_HISTORY"
                                    Dim GUID = DATABASE_ECM.GetScalarValue(max)
                                    Try
                                        If GUID > 0 Then
                                            Dim sqlUpdate As String
                                            If DropType = "|ATTMNTEXTRACTED|" Or DropType = "|OUTLOOK_ATTACHMENT|" Then
                                                sqlUpdate = "Update TBGI_HISTORY SET ATTACHMENT = 1, MSG_ID = '" & CURRENT_MESSAGEID & "' WHERE GUID = " & GUID
                                                DATABASE_ECM.ExecuteNonQuery(sqlUpdate)
                                            Else
                                                sqlUpdate = "Update TBGI_HISTORY SET ATTACHMENT = 0, MSG_ID = '" & CURRENT_MESSAGEID & "' WHERE GUID = " & GUID
                                                DATABASE_ECM.ExecuteNonQuery(sqlUpdate)
                                            End If
                                        End If
                                    Catch ex As Exception
                                        _Logger.Error(ex)
                                    End Try
                                End If
                            End If

                        Catch ex As Exception
                            _Logger.Error(ex)
                            MsgBox("Error in Insert-History - View logfile: " & ex.Message, MsgBoxStyle.Critical)
                            _Logger.Warn(" - Unexpected error in Insert-History - Fehler: " & vbNewLine & ex.Message)
                            _Logger.Warn(" - Unexpected error in Insert-History - SQL: " & Insert_String)
                            oError = True
                        End Try
                    Else
                        oError = True
                    End If
                Else
                    oError = True

                    If USER_LANGUAGE = LANG_DE Then
                        MsgBox("Der Export nach windream war nicht erfolgreich - Check LogFile", MsgBoxStyle.Exclamation)
                    Else
                        MsgBox("Export to windream was unsucessful - Check LogFile", MsgBoxStyle.Exclamation)
                    End If
                End If
            End If
            'False oder True zurückgeben
            'Kein Fehler aufgetreten
            If oError = False Then
                Return True
            Else
                'Fehler aufgetreten
                Return False
            End If
        Catch ex As Exception
            ShowErrorMessage(ex, "Move_File2_Target")
            Return False
        End Try
    End Function

    Private Function CreateFolderForIndex(DynamicFolderConfig As String)
        Try
            Dim oRootFolder As String = Path.GetDirectoryName(CURRENT_NEWFILENAME)

            If DynamicFolderConfig <> String.Empty Then
                '######
                Dim oRegexString As String = "\[%{1}[a-zA-Z0-9\!\$\&\/\(\)\=\?\,\.\-\;\:_öÖüÜäÄ\#\'\+\*\~\{\}\@\€\<\>\ ]+]{1}"
                ' einen Regulären Ausdruck laden
                Dim oRegex As Regex = New Regex(oRegexString)
                ' die Vorkommen im Folder-String auslesen
                Dim oMatches As MatchCollection = oRegex.Matches(DynamicFolderConfig)
                '####

                ' alle Vorkommen innerhalb des Ordnerstrings durchlaufen
                For Each oMatch As Match In oMatches
                    _Logger.Info("Elementname in FolderString: '" & oMatch.ToString & "'")
                    Select Case oMatch.Value.Substring(2, 1).ToUpper

                    'Manueller Indexwert
                        Case "M"
                            Dim oManIndexName = oMatch.Value.Substring(3, oMatch.Value.Length - 4)
                            Dim oIsOptional As Boolean = DATABASE_ECM.GetScalarValue("SELECT OPTIONAL FROM TBDD_INDEX_MAN WHERE DOK_ID = " & CURRENT_DOKART_ID & " AND UPPER(NAME) = UPPER('" & oManIndexName & "')")
                            _Logger.Info("Versuch den Indexwert aus '" & oManIndexName & "' auszulesen.")
                            Dim oManIndexValue As String = GetManIndex_Value(oManIndexName, "FILE", oIsOptional)
                            _Logger.Info("Ergebnis/Wert für neuen Ordner: '" & oManIndexName & "'")
                            If Not oManIndexValue = String.Empty Then
                                If IsDate(oManIndexValue) Then
                                    oManIndexValue = CDate(oManIndexValue).ToString("yyyyMMdd")
                                End If

                                oManIndexValue = FILESYSTEM.GetCleanPath(oManIndexValue)
                                DynamicFolderConfig = DynamicFolderConfig.Replace(oMatch.ToString, oManIndexValue)

                                _Logger.Info("FolderPattern: '" & DynamicFolderConfig & "'")
                            Else

                                If oIsOptional = True Then
                                    _Logger.Info("Optionaler Indexwert ist NICHT gefüllt")
                                    DynamicFolderConfig = DynamicFolderConfig.Replace(oMatch.ToString, String.Empty)
                                Else
                                    _Logger.Info(" - Achtung Ausnahme in 'CrFolderForIndex': der Index ist leer!")
                                    Return True
                                End If
                            End If
                        Case "A"
                            Dim oAutoIndexName = oMatch.Value.Substring(3, oMatch.Value.Length - 4)
                            _Logger.Info("Versuch den Auto-Indexwert aus '" & oAutoIndexName & "' auszulesen.")
                            Dim oAutoIndexValue As String = GetAutoIndex_Value(oAutoIndexName)
                            _Logger.Info("Ergebnis/Wert für neuen Ordner: '" & oAutoIndexName & "'")
                            If Not oAutoIndexValue = String.Empty Then

                                oAutoIndexValue = FILESYSTEM.GetCleanPath(oAutoIndexValue)
                                If oAutoIndexValue = "EMPTY_OI" Then
                                    DynamicFolderConfig = DynamicFolderConfig.Replace(oMatch.ToString, "")
                                Else
                                    DynamicFolderConfig = DynamicFolderConfig.Replace(oMatch.ToString, oAutoIndexValue)
                                    _Logger.Info("FolderPattern: '" & DynamicFolderConfig & "'")
                                End If

                            Else
                                _Logger.Info(" - Achtung Ausnahme in 'CrFolderForIndex': der Index ist leer!")
                            End If
                        Case "V"
                            Dim oElementTemp As String
                            Dim _Month As String = My.Computer.Clock.LocalTime.Month
                            If _Month.Length = 1 Then
                                _Month = "0" & _Month
                            End If
                            Dim _day As String = My.Computer.Clock.LocalTime.Day
                            If _day.Length = 1 Then
                                _day = "0" & _day
                            End If
                            Dim type = oMatch.Value.Substring(3, oMatch.Value.Length - 4)
                            If type.StartsWith("_") Then
                                type = type.Replace("_", "")
                            End If
                            Select Case type
                                Case "YYYY/MM/DD"
                                    oElementTemp = My.Computer.Clock.LocalTime.Year & "\" & _Month & "\" & _day
                                Case "YYYY/MM"
                                    oElementTemp = My.Computer.Clock.LocalTime.Year & "\" & _Month
                                Case "YYYY"
                                    oElementTemp = My.Computer.Clock.LocalTime.Year
                                Case "YYYY-MM"
                                    oElementTemp = My.Computer.Clock.LocalTime.Year & "-" & _Month
                            End Select
                            DynamicFolderConfig = DynamicFolderConfig.Replace(oMatch.ToString, oElementTemp)
                            _Logger.Info("FolderPatter nach V-Element: '" & DynamicFolderConfig & "'")
                        Case Else
                            _Logger.Warn(" - Achtung - in der Namenkonvention wurde ein Element gefunden welches nicht zugeordnet werden kann!" & vbNewLine & "Elementname: " & oMatch.Value.ToUpper)

                            If USER_LANGUAGE = LANG_DE Then
                                MsgBox("Achtung - in der Namenkonvention wurde ein Element gefunden welches nicht zugeordnet werden kann!" & vbNewLine & "Elementname: " & oMatch.Value.ToUpper, MsgBoxStyle.Exclamation, "Unexpected error in Name generieren:")
                            Else
                                MsgBox("Attention - One element in Namingconvention could not be matched!" & vbNewLine & "Elementname: " & oMatch.Value.ToUpper, MsgBoxStyle.Exclamation, "Unexpected error in Name generieren:")
                            End If
                    End Select
                Next
            End If

            _Logger.Info("Den Root-Folder zusammenfügen>> ")

            Dim oNewFullPath As String = System.IO.Path.Combine(oRootFolder, DynamicFolderConfig)

            _Logger.Info("Fullpath (mit evtl. Sonderzeichen (SZ)) '" & oNewFullPath & "'")
            Dim invalidPathChars() As Char = Path.GetInvalidPathChars()
            For Each sonderChar As Char In invalidPathChars
                'Sonderzeichen ausser Whitespace entfernen
                If Char.IsWhiteSpace(sonderChar) = False Then
                    If oNewFullPath.Contains(sonderChar) Then
                        oNewFullPath = oNewFullPath.Replace(sonderChar, "")
                    End If
                End If
            Next sonderChar
            oNewFullPath = WINDREAM.GetCleanedPath(oNewFullPath)

            _Logger.Info("Fullpath (ohne SZ) '" & oNewFullPath & "'")
            If Directory.Exists(oNewFullPath) = False Then
                Try
                    Dim oCreatedPath = Directory.CreateDirectory(oNewFullPath)
                    oNewFullPath = oCreatedPath.FullName
                    _Logger.Info("Folder '" & oNewFullPath & "' wurde angelegt")
                Catch ex As Exception
                    _Logger.Info("Error in CreateFolderforIndex-Method - Root Folder '" & oNewFullPath & "' could not be created. " & ex.Message)
                    _Logger.Error(ex.Message)
                    MsgBox("Attention: Root Folder '" & oNewFullPath & "' could not be created." & vbNewLine & ex.Message, MsgBoxStyle.Critical)
                    Return False
                End Try
            End If

            CURRENT_NEWFILENAME = Path.Combine(oNewFullPath, Path.GetFileName(CURRENT_NEWFILENAME))

            Return True
        Catch ex As Exception
            ShowErrorMessage(ex, "CreateFolderForIndex")
            Return False
        End Try
    End Function

    Private Sub Button1_Click(sender As Object, e As EventArgs)
        If File.Exists(CURRENT_FILENAME) Then
            Select Case CancelAttempts
                Case 0
                    If USER_LANGUAGE = LANG_DE Then
                        MsgBox("Bitte indexieren Sie die Datei vollständig!" & vbNewLine & "(Abbruch 1 des Indexierungsvorgangs)", MsgBoxStyle.Information)
                    Else
                        MsgBox("Please Index file completely" & vbNewLine & "(Abort 1 of Indexdialog)", MsgBoxStyle.Information)
                    End If
                    CancelAttempts += 1
                Case 1
                    Dim result As MsgBoxResult
                    If USER_LANGUAGE = LANG_DE Then
                        result = MessageBox.Show("Sie brechen nun zum zweiten Mal den Indexierungsvorgang ab!" & vbNewLine & "Wollen Sie die Indexierung aller Dateien abbrechen?", "Bestätigung erforderlich:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                    Else
                        result = MessageBox.Show("You are aborting the indexdialog for the 2nd time!" & vbNewLine & "Do You want to abort indexing?", "Confirmation needed:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                    End If

                    If result = MsgBoxResult.Yes Then
                        Dim containsfw_file As Boolean = False
                        Try
                            ABORT_INDEXING = True
                            Dim sql As String = "SELECT * FROM TBGI_FILES_USER WHERE WORKED = 0 AND UPPER(USER@WORK) = UPPER('" & Environment.UserName & "')"

                            Dim DT As DataTable = DATABASE_ECM.GetDatatable(sql)

                            Dim anz = DT.Rows.Count
                            For Each Filerow As DataRow In DT.Rows
                                Dim filestring As String = Filerow.Item("FILENAME2WORK")
                                Dim handletype As String = Filerow.Item("HANDLE_TYPE")

                                If handletype = "|MSGONLY|" Or handletype = "|ATTMNTEXTRACTED|" Then
                                    Try
                                        System.IO.File.Delete(filestring)
                                    Catch ex As Exception

                                    End Try

                                ElseIf handletype.StartsWith("|FW") Then
                                    containsfw_file = True
                                End If
                            Next
                            'Zuerst die Daten des Ablaufs löschen
                            If DATABASE_ECM.ExecuteNonQuery("DELETE FROM TBGI_FILES_USER WHERE UPPER(USER@WORK) = UPPER('" & Environment.UserName & "')") = True Then
                                If containsfw_file = True Then
                                    If USER_LANGUAGE = LANG_DE Then
                                        MsgBox("Der Indexierungsprozess beinhaltete (auch) Dateien per Folderwatch!" & vbNewLine & "Diese Dateien wurden nicht gelöscht und verbleiben im Folderwatch-Verzeichnis!" & vbNewLine & "Bitte verschieben Sie die Dateien ggfls.", MsgBoxStyle.Information, "Achtung - Hinweis:")
                                    Else
                                        MsgBox("The Indexingprocess contained (also) files from folderwatch!" & vbNewLine & "These files weren't deleted and will stay in the folderwatch-folder!" & vbNewLine & "Please move these files manually.", MsgBoxStyle.Information, "Achtung - Hinweis:")
                                    End If

                                End If
                            End If

                        Catch ex As Exception
                            _Logger.Error(ex)
                            MsgBox("Unexpected Error in Abort Indexing: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
                        End Try

                        Close()
                    End If
            End Select
        End If
    End Sub

    Private Sub BarCheckItem1_CheckedChanged(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles checkItemTopMost.CheckedChanged
        If FormLoaded = True Then
            TopMost = checkItemTopMost.Checked
            CONFIG.Config.TopMost = checkItemTopMost.Checked
            CONFIG.Save()
        End If
    End Sub

    Private Sub checkItemDeleteSource_CheckedChanged(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles checkItemDeleteSource.CheckedChanged
        If FormLoaded = True And checkItemDeleteSource.Visibility <> DevExpress.XtraBars.BarItemVisibility.Never Then
            CURR_DELETE_ORIGIN = checkItemDeleteSource.Checked
            CONFIG.Config.DeleteOriginalFile = checkItemDeleteSource.Checked
            CONFIG.Save()
        End If
    End Sub

    Private Sub labelFilePath_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles labelFilePath.ItemClick
        Clipboard.SetText(CURRENT_WORKFILE)

        If USER_LANGUAGE = LANG_DE Then
            MsgBox("Aktuellen Pfad in die Zwischenablage kopiert!", MsgBoxStyle.Information, Text)
        Else
            MsgBox("Current Path copied to Clipboard!", MsgBoxStyle.Information, Text)
        End If
    End Sub

    Private Sub checkItemPreview_CheckedChanged(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles checkItemPreview.CheckedChanged
        SetFilePreview(checkItemPreview.Checked)
        CONFIG.Config.FilePreview = checkItemPreview.Checked
        CONFIG.Save()
    End Sub

    Private Sub SplitContainer1_SplitterMoved(sender As Object, e As SplitterEventArgs) Handles SplitContainer1.SplitterMoved
        CONFIG.Config.SplitterDistanceViewer = SplitContainer1.SplitterDistance
    End Sub

    Private Sub BarButtonItem1_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem1.ItemClick
        DATABASE_ECM.ExecuteNonQuery($"DELETE FROM TBGI_FILES_USER WHERE GUID = {CURRENT_WORKFILE_GUID}")

        CancelAttempts = 2
        Close()
    End Sub

    Private Sub checkItemPreselection_CheckedChanged(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles checkItemPreselection.CheckedChanged
        CONFIG.Config.ProfilePreselection = checkItemPreselection.Checked
        CONFIG.Save()
    End Sub

    Private Sub BarButtonItem2_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem2.ItemClick
        Try
            MsgBox($"Deleting [{CURRENT_WORKFILE}]", MsgBoxStyle.Information, Text)

            File.SetAttributes(CURRENT_WORKFILE, FileAttributes.Normal)
            File.Delete(CURRENT_WORKFILE)

        Catch ex As Exception
            _Logger.Error(ex)
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub ComboboxDoctype_KeyUp(sender As Object, e As KeyEventArgs) Handles ComboboxDoctype.KeyUp
        If e.KeyCode = Keys.F2 Then
            Dim oCombo As SearchLookUpEdit = sender
            oCombo.ShowPopup()
        End If
    End Sub

    Private Sub BarCheckItem_MultiIndexing_CheckedChanged(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarCheckItem_MultiIndexing.CheckedChanged
        Dim item As DevExpress.XtraBars.BarCheckItem = CType(sender, DevExpress.XtraBars.BarCheckItem)
        If item.Checked Then
            BarButtonItem1.Enabled = False
            MULTIINDEXING_ACTIVE = True
            If USER_LANGUAGE = LANG_DE Then
                Me.BarButtonItem_OK.Caption = "Dateien indexieren"
            Else
                Me.BarButtonItem_OK.Caption = "Index Files"
            End If
        Else
            BarButtonItem1.Enabled = True
            MULTIINDEXING_ACTIVE = False
            If USER_LANGUAGE = LANG_DE Then
                Me.BarButtonItem_OK.Caption = "Datei indexieren"
            Else
                Me.BarButtonItem_OK.Caption = "Index File"
            End If
        End If
    End Sub

    Private Sub BarButtonItem_OK_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem_OK.ItemClick
        Try
            ClearError()
            ClearNotice()

            Me.Cursor = Cursors.WaitCursor
            CURRENT_DT_REGEX = DATABASE_ECM.GetDatatable("SELECT * FROM TBGI_FUNCTION_REGEX")
            For Each rowregex As DataRow In CURRENT_DT_REGEX.Rows
                If rowregex.Item("FUNCTION_NAME") = "CLEAN_FILENAME" Then
                    REGEX_CLEAN_FILENAME = rowregex.Item("REGEX")
                End If
            Next
            If BarCheckItem_MultiIndexing.Checked = True Then
                'Die erste Datei indexieren
                If WORK_FILE() = True Then
                    'Und nun die folgenden
                    Dim DTFiles2Work As DataTable = DATABASE_ECM.GetDatatable("SELECT * FROM TBGI_FILES_USER WHERE WORKED = 0 AND GUID <> " & CURRENT_WORKFILE_GUID & " AND UPPER(USER@WORK) = UPPER('" & Environment.UserName & "')")
                    If DTFiles2Work IsNot Nothing Then
                        Dim err = False
                        For Each oRow As DataRow In DTFiles2Work.Rows
                            CURRENT_WORKFILE_GUID = oRow.Item("GUID")
                            CURRENT_WORKFILE = oRow.Item("FILENAME2WORK")
                            CURRENT_WORKFILE_HASH = oRow.ItemEx("FILE_HASH", "")
                            DropType = oRow.Item("HANDLE_TYPE")

                            If WORK_FILE() = False Then
                                err = True
                                Exit For
                            End If
                        Next
                        Me.Cursor = Cursors.Default
                        If err = False Then
                            If USER_LANGUAGE = LANG_DE Then
                                MsgBox("Alle Dateien wurden mit Multiindexing erfolgreich verarbeitet!", MsgBoxStyle.Information, "Erfolgsmeldung:")
                            Else
                                MsgBox("All files were successfully processed through Multiindexing", MsgBoxStyle.Information, "Success")
                            End If

                            CloseViewer()

                            CancelAttempts = 2
                            Me.Close()
                        End If
                    End If
                End If
            Else
                If WORK_FILE() = True Then
                    Me.Cursor = Cursors.Default
                    If CONFIG.Config.ShowIndexResult = True Then
                        If USER_LANGUAGE = LANG_DE Then
                            _FormHelper.ShowSuccessMessage($"Die Datei wurde erfolgreich verarbeitet!{vbNewLine}Ablagepfad:{vbNewLine}{CURRENT_NEWFILENAME}", "Erfolgsmeldung")
                        Else
                            _FormHelper.ShowSuccessMessage($"File sucessfully processed!{vbNewLine}Path:{vbNewLine}{CURRENT_NEWFILENAME}", "Success")
                        End If

                    End If

                    CloseViewer()

                    CancelAttempts = 2
                    Me.Close()
                End If
            End If
        Catch ex As Exception
            MsgBox("Uncaught error while indexing: " & vbNewLine & ex.Message, MsgBoxStyle.Critical, Text)
        Finally
            Me.Cursor = Cursors.Default
        End Try
    End Sub

End Class
