Imports System.IO
Imports System.Globalization
Imports WINDREAMLib
Imports DD_LIB_Standards

Public Class ClassImport_Windream
    Public Shared Function Import_File(QuellDatei_Path As String, DOCTYPE_ID As Integer)
        Try
            Dim err As Boolean = False
            CURRENT_FILENAME = QuellDatei_Path
            Dim DT_DOCTYPE As DataTable = MYDB_ECM.GetDatatable("SELECT * FROM TBDD_DOKUMENTART WHERE GUID = " & DOCTYPE_ID)
            If Not IsNothing(DT_DOCTYPE) Then
                Dim Targetpath As String = DT_DOCTYPE.Rows(0).Item("ZIEL_PFAD")
                Dim Dokart As String = DT_DOCTYPE.Rows(0).Item("BEZEICHNUNG")
                clsWindream.MY_WDOBJECTTYPE = DT_DOCTYPE.Rows(0).Item("OBJEKTTYP")

                'Den Namen der Dokumentart generieren
                If ClassImport_Windream.Name_Generieren(DOCTYPE_ID) = False Then
                    err = True
                    Return False
                End If

                'Die Datei nach windream importieren
                Dim streamresult = clsWD_SET.Stream_File(QuellDatei_Path, Targetpath)
                If streamresult = True Then
                    Dim sql As String = String.Format("SELECT DocID FROM VWPMO_DOC_SYNC WHERE UPPER(FULL_FILENAME) = UPPER('{0}') AND CONVERT(DATE,Change_DateTime) = CONVERT(DATE,GETDATE())", CURRENT_FILEIN_WD)
                    CURRENT_DOC_ID = MYDB_ECM.GetScalarValue(SQL)
                    sql = $"SELECT * FROM TBDD_INDEX_AUTOM WHERE DOCTYPE_ID = {DOCTYPE_ID} AND ENTITY_ID = {CURRENT_ENTITY_ID}"
                    Dim dt As DataTable = MYDB_ECM.GetDatatable(sql)
                    Dim indexierung_erfolgreich As Boolean = False
                    If dt Is Nothing = False Then
                        If dt.Rows.Count > 0 Then
                            Dim Count As Integer = 0
                            For Each row As DataRow In dt.Rows
                                Dim indexname = row.Item("INDEXNAME").ToString
                                Dim idxvalue = row.Item("VALUE")
                                If idxvalue.ToString.StartsWith("@") Then
                                    Select Case idxvalue.ToString.ToUpper
                                        Case "@RECORD-ID"
                                            idxvalue = idxvalue.ToString.Replace("@Record-ID", CURRENT_RECORD_ID)
                                        Case "@DOKART"
                                            idxvalue = idxvalue.ToString.Replace("@Dokart", Dokart)
                                    End Select
                                End If
                                LOGGER.Debug("Indexvalue: " & idxvalue.ToString)
                                Count += 1
                                indexierung_erfolgreich = clsWD_SET.IndexFile(CURRENT_FILEIN_WD, indexname, idxvalue, clsWindream.MY_WDOBJECTTYPE)
                                If indexierung_erfolgreich = False Then
                                    ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error: ", "Unexpected Error in indexing '" & indexname & "') - Check logfile!")
                                    err = True
                                    Exit For
                                End If
                                'ByVal WD_File As String, ByVal _Indexname As String, ByVal _Value As String
                            Next
                            If err = True Then
                                Return False
                            End If
                            ''den Entity-Key auslesen
                            'sql = "Select Top 1 * from TBPMO_WD_OBJECTTYPE where Upper(object_type) = Upper('" & clsWindream.MY_WDOBJECTTYPE & "')"
                            'dt = MYDB_ECM.GetDatatable(sql)
                            'If Not dt Is Nothing Then
                            '    If dt.Rows.Count = 1 Then
                            '        Dim indexname = dt.Rows(0).Item("IDXNAME_ENTITYID").ToString
                            '        Dim idxvalue = CURRENT_ENTITY_ID
                            '        LOGGER.Debug("Entity-ID: " & idxvalue.ToString)
                            '        indexierung_erfolgreich = clsWD_SET.IndexFile(CURRENT_FILEIN_WD, indexname, idxvalue, clsWindream.MY_WDOBJECTTYPE)
                            '        If indexierung_erfolgreich = False Then
                            '            err = True
                            '            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error: ", "Unexpected Error in indexing Entity-ID '" & indexname & "') - Check logfile!")
                            '            Return False
                            '        End If
                            '        indexname = dt.Rows(0).Item("IDXNAME_PARENTID").ToString
                            '        idxvalue = CURRENT_PARENT_ENTITY_ID
                            '        LOGGER.Debug("Parent-ID: " & idxvalue.ToString)
                            '        indexierung_erfolgreich = clsWD_SET.IndexFile(CURRENT_FILEIN_WD, indexname, idxvalue, clsWindream.MY_WDOBJECTTYPE)
                            '        If indexierung_erfolgreich = False Then
                            '            err = True
                            '            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error: ", "Unexpected Error in indexing Parent-ID '" & indexname & "') - Check logfile!")
                            '            Return False
                            '        End If

                            '    End If
                            'End If
                            If indexierung_erfolgreich = True Then
                                Return True
                            Else
                                MsgBox("Unexpected Error in Indexing file. Please chek log!", MsgBoxStyle.Exclamation, "Achtung:")
                                Return False
                            End If
                        End If
                    End If
                End If
            Else
                Return False
            End If



        Catch ex As Exception
            MsgBox("Unexpected error in Import_File ClassImport_windream: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            Return False
        End Try

    End Function

    Public Shared Function Name_Generieren(DocTypeID As Integer)

        Try
            Dim FILE_DELIMITER, VERSION_DELIMITER, _WDOBJECTTYPE, _NewFileString As String
            Dim sql As String = "select VERSION_DELIMITER, FILE_DELIMITER FROM TBDD_MODULES where UPPER(NAME) = UPPER('Global-Indexer')"
            Dim DT1 As DataTable = MYDB_ECM.GetDatatable(sql)
            FILE_DELIMITER = DT1.Rows(0).Item("FILE_DELIMITER")
            VERSION_DELIMITER = DT1.Rows(0).Item("VERSION_DELIMITER")

            Dim err As Boolean = False
            Dim oWMTARGET_FOLDER As String
            Dim oExtension As String = Path.GetExtension(CURRENT_FILENAME)
            Dim oDT As DataTable = MYDB_ECM.GetDatatable("SELECT * FROM TBDD_DOKUMENTART WHERE GUID = " & DocTypeID)
            'sql_history_INSERT_INTO = "INSERT INTO TBGI_HISTORY (FILENAME_ORIGINAL,FILENAME_NEW"
            'sql_history_Index_Values = ""
            Dim AnzahlIndexe As Integer = 1
            _WDOBJECTTYPE = oDT.Rows(0).Item("OBJEKTTYP")

            ' Den Zielordner erstellen
            oWMTARGET_FOLDER = oDT.Rows(0).Item("ZIEL_PFAD")

            sql = $"SELECT * FROM TBPMO_WD_FORMVIEW_DOKTYPES WHERE FORMVIEW_ID = {CURRENT_FORMVIEW_ID} AND DOCTYPE_ID = {DocTypeID}"
            Dim oDTFW_DOCTYPES As DataTable = MYDB_ECM.GetDatatable(sql)
            Dim oDYNAMIC_FOLDER = oDTFW_DOCTYPES.Rows(0).Item("DYNAMIC_FOLDER")
            Dim oNAME_CONVENTION = oDTFW_DOCTYPES.Rows(0).Item("NAME_CONVENTION")
            Dim oROOTWM_FOLDER
            Try
                oROOTWM_FOLDER = oDTFW_DOCTYPES.Rows(0).Item("ROOT_FOLDER")
            Catch ex As Exception
                oROOTWM_FOLDER = ""
            End Try
            If oROOTWM_FOLDER <> String.Empty Then
                oROOTWM_FOLDER = ClassHelper.FORMAT_WM_PATH(oROOTWM_FOLDER)
                LOGGER.Debug($"oROOTWM_FOLDER '{oROOTWM_FOLDER}' will be used")
                oWMTARGET_FOLDER = oROOTWM_FOLDER
            End If

            'MYDB_ECM.GetScalarValue(SQL)
            If Not IsDBNull(oDYNAMIC_FOLDER) Then
                If oDYNAMIC_FOLDER <> String.Empty Then
                    If CREATE_FOLDER_INDEX(oDYNAMIC_FOLDER, DocTypeID) = True And CURRENT_VARIABLE_FOLDER <> "" Then

                        LOGGER.Debug("After CREATE_FOLDER_INDEX - oWMTARGET_FOLDER: " & oWMTARGET_FOLDER)
                            LOGGER.Debug("After CREATE_FOLDER_INDEX - CURRENT_VARIABLE_FOLDER: " & CURRENT_VARIABLE_FOLDER)

                            If oWMTARGET_FOLDER <> CURRENT_VARIABLE_FOLDER Then
                            oWMTARGET_FOLDER = oWMTARGET_FOLDER & "\" & CURRENT_VARIABLE_FOLDER.Replace(oWMTARGET_FOLDER, "")
                        Else
                            oWMTARGET_FOLDER = CURRENT_VARIABLE_FOLDER
                        End If

                        'End If

                    Else
                        MsgBox("Unexpected Error in Creating Variable Folder - Check logfile!", MsgBoxStyle.Critical)
                        Return False
                    End If
                End If
            End If

            LOGGER.Debug("oWMTARGET_FOLDER: " & oWMTARGET_FOLDER)
                LOGGER.Debug("CURRENT_SUBFOLDER: " & CURRENT_SUBFOLDER)


            'Untsserordner ja oder nein
            If CURRENT_CHECK_SUBFOLDER = True And CURRENT_SUBFOLDER <> "" Then
                oWMTARGET_FOLDER = oWMTARGET_FOLDER & "\" & CURRENT_SUBFOLDER
            End If
            oWMTARGET_FOLDER = oWMTARGET_FOLDER.Replace("\\", "\")
            If oWMTARGET_FOLDER.Contains("/") Then
                LOGGER.Info(String.Format("Targetpath contains /-sign. / will be replaced with _"))
                oWMTARGET_FOLDER = oWMTARGET_FOLDER.Replace("/", "_")
            End If


            Try
                Select Case clsWD_GET.WD_PATH_EXISTS(oWMTARGET_FOLDER.Substring(2))
                    Case False
                        LOGGER.Info(String.Format("Targetpath ({0}) is not existing or result of WD_PATH_EXISTS was false.", oWMTARGET_FOLDER.Substring(2)))
                        Dim split() As String = oWMTARGET_FOLDER.Split("\")
                        Dim Path_Combined As String = ""
                        For Each s As String In split
                            Path_Combined &= s & "\"
                            If Path_Combined <> "W:\" Then

                                Dim temppath = Path_Combined.Substring(2)

                                Try
                                    temppath = Path_Combined.Substring(2).Substring(0, temppath.Length)

                                    Select Case clsWD_GET.WD_PATH_EXISTS(temppath)
                                        Case False

                                            LOGGER.Debug("Trying to create folder-part: " & temppath)

                                            clsWindream.MY_WDSESSION.GetNewWMObjectFS(2, temppath, 0) 'WMEntityFolder,WMObjectEditModeNoEdit)
                                        Case -10
                                            LOGGER.Warn("WD_PATH_EXISTS returned -10 for: " & temppath)
                                            Return False
                                    End Select
                                Catch ex As Exception
                                    If Not ex.Message.Contains("Filename exists!") Then
                                        LOGGER.Warn(String.Format("Could not create folder-part: {0} - Complete path is: ({1})", temppath, oWMTARGET_FOLDER.Substring(2)))
                                        LOGGER.Warn(String.Format("ErrorMessage: {0}: ", ex.Message))
                                        Return False
                                    End If
                                End Try
                            End If
                        Next
                    Case -10
                        MsgBox("Attention: the folder of the doctype does not exist or there was an error while checking....", MsgBoxStyle.Critical)
                        Return False
                End Select
            Catch ex As Exception
                If Not ex.Message.Contains("Filename exists!") Then
                    LOGGER.Warn(String.Format("Could not create folder ({0}): " & ex.Message, oWMTARGET_FOLDER.Substring(2)))
                    Return False
                End If
            End Try
            '####
            ' Regulären Ausdruck zum Auslesen der Indexe definieren
            Dim preg As String = "\[%{1}[a-zA-Z0-9\!\$\&\/\(\)\=\?\,\.\-\;\:_öÖüÜäÄ\#\'\+\*\~\{\}\@\€\<\>\ ]+]{1}"
            'Namenkonvention laden
            If IsDBNull(oNAME_CONVENTION) Then
                LOGGER.Warn("Achtung: Namenskonvention is DBNull")
                oNAME_CONVENTION = Path.GetFileNameWithoutExtension(CURRENT_FILENAME)
            ElseIf oNAME_CONVENTION = String.Empty Then
                LOGGER.Warn("Achtung: Namenskonvention is String empty")
                oNAME_CONVENTION = Path.GetFileNameWithoutExtension(CURRENT_FILENAME)
            End If
            'schonmal den gesamten Pfad laden
            Dim oNewWM_Filename As String = oWMTARGET_FOLDER & "\" & oNAME_CONVENTION
            LOGGER.Debug("oNewWM_Filename: " & oNewWM_Filename)

            ' 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 elemente As System.Text.RegularExpressions.MatchCollection = regulärerAusdruck.Matches(oNewWM_Filename)
            '####
            ' alle Vorkommen innerhalbd er Namenkonvention durchlaufen
            For Each element As System.Text.RegularExpressions.Match In elemente

                LOGGER.Debug("element in RegeX: " & element.Value)
                Select Case element.Value.Substring(2, 1).ToUpper
                    'Nur automatische Indizes auswerten
                    Case "A"
                        Dim APattern = element.Value.Substring(3, element.Value.Length - 4)
                        Dim value As String

                        Select Case APattern
                            'Laufzeitvariable Record-ID
                            Case "RECORD_ID"
                                value = CURRENT_RECORD_ID
                            Case "DOKART"
                                'Laufzeitvariable Dokumentartstring
                                value = CURRENT_DOKARTSTRING
                            Case Else
                                'Ein Index der nur für die Namenkonvention herangezogen wird
                                If APattern.StartsWith("NC_") And APattern.Contains("#") Then
                                    Dim split() As String = APattern.Split("#")
                                    If split.Length = 2 Then
                                        'Die GUID des AutoIndex auslesen
                                        Dim INDEX_ID = split(1)
                                        If IsNumeric(INDEX_ID) Then
                                            Dim sql_AUTOindexresult = MYDB_ECM.GetScalarValue("SELECT SQL_RESULT FROM TBDD_INDEX_AUTOM WHERE GUID = " & INDEX_ID)
                                            If IsNothing(sql_AUTOindexresult) Then
                                                LOGGER.Debug("unexpected: sql_AUTOindexresult is nothing!!")
                                                value = ""
                                            Else
                                                If IsDBNull(sql_AUTOindexresult) Then
                                                    value = ""
                                                Else
                                                    sql_AUTOindexresult = sql_AUTOindexresult.ToString.ToUpper.Replace("@RECORD-ID", CURRENT_RECORD_ID)
                                                    Dim AUTOindexresult = MYDB_ECM.GetScalarValue(sql_AUTOindexresult)
                                                    If IsNothing(AUTOindexresult) Then
                                                        LOGGER.Warn("ATTENTION: unexpected: AUTOindexresult is nothing!!")
                                                        LOGGER.Warn("" & sql_AUTOindexresult)
                                                        value = ""
                                                    Else
                                                        If IsDBNull(AUTOindexresult) Then
                                                            value = ""
                                                        Else
                                                            value = AUTOindexresult
                                                        End If
                                                    End If

                                                End If
                                            End If
                                        Else
                                            LOGGER.Warn("INDEX_ID is not numeric:  " & INDEX_ID.ToString & "- APattern: " & APattern)
                                            value = ""
                                        End If
                                    Else
                                        LOGGER.Warn("split.Length <> 2 - APattern: " & APattern)
                                        value = ""
                                    End If

                                ElseIf APattern.Contains("#") Then
                                    LOGGER.Debug("element [" & APattern & "] filled with Record-Data...: ")
                                    Dim split() As String = APattern.Split("#")
                                    If split.Length = 2 Then
                                        Dim CONTROL_ID = split(1)
                                        If IsNumeric(CONTROL_ID) Then
                                            Dim CONTROLVALUE = ClassControlValues.Get_Control_Value_for_ID(CONTROL_ID, CURRENT_RECORD_ID)
                                            If IsNothing(CONTROLVALUE) Then
                                                Dim checktype = "SELECT CONTROL_TYPE_ID,SQL_COMMAND_1,CONNECTION_ID_1 FROM TBPMO_CONTROL WHERE GUID = " & CONTROL_ID
                                                Dim DTtype As DataTable = MYDB_ECM.GetDatatable(checktype)
                                                If DTtype.Rows.Count = 1 Then
                                                    Dim lblsql = DTtype.Rows(0).Item(1)
                                                    lblsql = lblsql.ToString.ToUpper.Replace("@RECORD_ID", CURRENT_RECORD_ID)
                                                    lblsql = lblsql.ToString.ToUpper.Replace("@RECORD-ID", CURRENT_RECORD_ID)
                                                    lblsql = lblsql.ToString.ToUpper.Replace("@ENTITY-ID", CURRENT_ENTITY_ID)
                                                    lblsql = lblsql.ToString.ToUpper.Replace("@ENTITY_ID", CURRENT_ENTITY_ID)
                                                    LOGGER.Debug("variable sql will be used for convention")
                                                    Dim result = MYDB_ECM.GetScalarValue(DTtype.Rows(0).Item(2))
                                                    If Not IsNothing(result) Then
                                                        value = result.ToString
                                                    Else
                                                        LOGGER.Warn("variable sqlresult is nothing - " & lblsql)
                                                        value = ""
                                                    End If
                                                Else
                                                    LOGGER.Warn("!!ATTENTION: NameConvention should be filled with value of Control-ID '" & CONTROL_ID & "', but result was nothing.")
                                                    LOGGER.Warn("SQL-Command: " & CURRENT_LAST_SQL)
                                                    value = ""
                                                End If

                                            Else
                                                If IsDBNull(CONTROLVALUE) Then
                                                    LOGGER.Warn("NameConvention should be filled with value of Control-ID '" & CONTROL_ID & "', but result was DBNULL.")
                                                    LOGGER.Warn("SQL-Command: " & CURRENT_LAST_SQL)
                                                    value = ""
                                                Else
                                                    Dim sql1 = "SELECT * FROM TBPMO_WD_NAMECONVENTION_FORMAT WHERE ID = (SELECT TOP 1 GUID FROM TBPMO_WD_FORMVIEW_DOKTYPES WHERE DOCTYPE_ID = " & DocTypeID & " AND FORMVIEW_ID = " & CURRENT_FORMVIEW_ID & ")"
                                                    Dim DT_FORMAT As DataTable = MYDB_ECM.GetDatatable(sql1)
                                                    If Not IsNothing(DT_FORMAT) Then
                                                        If DT_FORMAT.Rows.Count > 0 Then
                                                            Dim result
                                                            Try
                                                                result = (From FormatRow In DT_FORMAT.AsEnumerable
                                                                          Select FormatRow Where FormatRow.Item("PATTERN") = APattern).Single()
                                                            Catch ex As Exception

                                                            End Try

                                                            If Not IsNothing(result) Then
                                                                Dim _rule = result.Item("FORMAT_RULE")
                                                                If Not IsNothing(_rule) Then
                                                                    If IsDate(CONTROLVALUE) Then
                                                                        Dim _date As Date = CDate(CONTROLVALUE)
                                                                        'Dim _date = CDate(Format(CONTROLVALUE, "dd-MM-yyyy"))
                                                                        _rule = _rule.ToString.Replace("Y", "y")
                                                                        _rule = _rule.ToString.Replace("D", "d")
                                                                        _rule = _rule.ToString.Replace("m", "M")
                                                                        Dim convertedvalue = _date.ToString(_rule, CultureInfo.InvariantCulture)
                                                                        CONTROLVALUE = convertedvalue
                                                                    End If
                                                                End If
                                                            End If
                                                        End If
                                                    End If

                                                    value = CONTROLVALUE
                                                End If
                                            End If

                                        End If
                                    End If

                                End If
                        End Select

                        If value <> String.Empty Then
                            oNewWM_Filename = oNewWM_Filename.Replace(element.Value, value)
                            _NewFileString = oNewWM_Filename
                            LOGGER.Debug("Actual NEWFILESTRING: " & _NewFileString)
                            ' sql_history_INSERT_INTO = sql_history_INSERT_INTO & ", INDEX" & AnzahlIndexe.ToString
                            AnzahlIndexe += 1
                            ' sql_history_Index_Values = sql_history_Index_Values & ", '" & value & "'"
                        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 = element.Value '.ToUpper.Replace("[v%", "")
                        type = type.Replace("[%v", "")
                        type = type.Replace("]", "")

                        Select Case type.ToUpper
                            Case "YY_MM_DD"
                                datetemp = My.Computer.Clock.LocalTime.Year.ToString.Substring(2) & "_" & _Month & "_" & _day
                            Case "YYMMDD"
                                datetemp = My.Computer.Clock.LocalTime.Year.ToString.Substring(2) & _Month & _day
                            Case "YY_MM"
                                datetemp = My.Computer.Clock.LocalTime.Year.ToString.Substring(2) & "_" & _Month
                            Case "YYYY_MM_DD"
                                datetemp = My.Computer.Clock.LocalTime.Year & "_" & _Month & "_" & _day
                            Case "YYYYMM"
                                datetemp = My.Computer.Clock.LocalTime.Year & _Month
                            Case "YYYYMMDD"
                                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.ToString
                            Case "DD.MM.YY"
                                datetemp = _day & "." & _Month & "." & My.Computer.Clock.LocalTime.Year.ToString.Substring(2)
                            Case "DDMMYY"
                                datetemp = _day & _Month & My.Computer.Clock.LocalTime.Year.ToString.Substring(2)
                            Case "DDMMYYYY"
                                datetemp = _day & _Month & My.Computer.Clock.LocalTime.Year
                            Case "DD.MM.YYYY"
                                datetemp = _day & "." & _Month & "." & My.Computer.Clock.LocalTime.Year
                            Case "YYYY_MM"
                                datetemp = My.Computer.Clock.LocalTime.Year & "_" & _Month
                            Case "MM_YYYY"
                                datetemp = _Month & "_" & My.Computer.Clock.LocalTime.Year
                            Case "OFilename".ToUpper
                                oNewWM_Filename = oNewWM_Filename.Replace(element.Value, Path.GetFileNameWithoutExtension(CURRENT_FILENAME))
                            Case "Username".ToUpper
                                oNewWM_Filename = oNewWM_Filename.Replace(element.Value, USER_USERNAME)
                        End Select
                        If datetemp <> "" Then
                            oNewWM_Filename = oNewWM_Filename.Replace(element.Value, datetemp)
                        End If
                        _NewFileString = oNewWM_Filename
                    Case Else
                        Dim msg As String
                        msg = "In der Namenkonvention wurde ein Element gefunden welches nicht zugeordnet werden kann!" & vbNewLine & "Elementname: " & element.Value.ToUpper
                        If USER_LANGUAGE <> "de-DE" Then
                            msg = "In nameconvention an element was defined which could not be replaced." & vbNewLine & "elementname: " & element.Value.ToUpper
                        End If

                        LOGGER.Warn(msg)
                        MsgBox(msg, MsgBoxStyle.Exclamation, "Error in Name Convention:")
                End Select
            Next
            Try
                'ungültige Zeichen entfernen
                oNewWM_Filename = ClassHelper.CleanFilename(oNewWM_Filename, "")
                If oNewWM_Filename.Contains("/") Then
                    LOGGER.Info(String.Format("DATEINAME contains /-sign. / will be replaced with _"))
                    oNewWM_Filename = oNewWM_Filename.Replace("/", "_")
                End If
            Catch ex As Exception
                LOGGER.Warn(" - Error in Versioning file - Error: " & vbNewLine & ex.Message)
                MsgBox(ex.Message, MsgBoxStyle.Critical, "Error in Versioning file:")
                err = True
            End Try
            CURRENT_NEWFILENAME = oNewWM_Filename & oExtension


            'False oder True zurückgeben
            If err = False Then
                Return True
            Else
                Dim msg As String
                msg = "Fehler während der Dateinamengenerierung. Evtl. wurden Mussfelder nicht ausgefüllt?"
                If USER_LANGUAGE <> "de-DE" Then
                    msg = "Error in create variable filename. Reasons: unfilled control values. Check logfile."
                End If
                MsgBox(msg, MsgBoxStyle.Exclamation)
                Return False
            End If

        Catch ex As Exception
            LOGGER.Warn(" - Unexpected Error in FileName-Creating: " & vbNewLine & ex.Message)
            MsgBox(" - Unexpected Error in FileName-Creating: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            Return False
        End Try

    End Function
    Private Shared Function CREATE_FOLDER_INDEX(FolderConvention As String, DocTypeID As Integer)
        Try
            CURRENT_VARIABLE_FOLDER_OVERRIDE = False
            'Dim RootFolder As String = Path.GetDirectoryName(CURRENT_NEWFILENAME)
            CURRENT_VARIABLE_FOLDER = ""
            '######
            Dim p_reg As String = "\[%{1}[a-zA-Z0-9\!\$\&\/\(\)\=\?\,\.\-\;\:_öÖüÜäÄ\#\'\+\*\~\{\}\@\€\<\>\ ]+]{1}"
            ' einen Regulären Ausdruck laden
            Dim regularExpression As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex(p_reg)
            ' die Vorkommen im Folder-String auslesen
            Dim elemente As System.Text.RegularExpressions.MatchCollection = regularExpression.Matches(FolderConvention)
            '####
            ' alle Vorkommen innerhalb des Ordnerstrings durchlaufen
            For Each element As System.Text.RegularExpressions.Match In elemente
                LOGGER.Debug("Elementname in FolderString: '" & element.ToString & "'")
                Dim EL_SUBSTRING = element.Value.Substring(2, 1).ToUpper
                LOGGER.Debug("EL_SUBSTRING is: '" & EL_SUBSTRING & "'")
                Select Case EL_SUBSTRING
                    'Manueller Indexwert
                    Case "A"
                        Dim split() As String = element.Value.Substring(3, element.Value.Length - 4).Split("#")
                        If split.Length = 2 Then
                            'Die GUID des AutoIndex auslesen
                            Dim INDEX_ID = split(1)
                            If IsNumeric(INDEX_ID) Then
                                Dim sql = "SELECT SQL_RESULT FROM TBDD_INDEX_AUTOM WHERE GUID = " & INDEX_ID
                                Dim sql_command = MYDB_ECM.GetScalarValue(SQL)
                                If IsNothing(sql_command) Then
                                    LOGGER.Warn("unexpected: SQL_RESULT is nothing!!")
                                    LOGGER.Warn("" & sql)
                                Else
                                    If IsDBNull(sql_command) Then
                                        LOGGER.Warn("unexpected: sql_command is DBNULL!!")
                                    Else
                                        sql_command = sql_command.ToString.ToUpper.Replace("@RECORD-ID", CURRENT_RECORD_ID)
                                        sql_command = sql_command.ToString.ToUpper.Replace("@RECORD_ID", CURRENT_RECORD_ID)
                                        sql_command = sql_command.ToString.ToUpper.Replace("@ENTITY-ID", CURRENT_ENTITY_ID)
                                        sql_command = sql_command.ToString.ToUpper.Replace("@ENTITY_ID", CURRENT_ENTITY_ID)
                                        Dim AUTOindexresult = MYDB_ECM.GetScalarValue(sql_command)
                                        If IsNothing(AUTOindexresult) Then
                                            LOGGER.Warn("unexpected: AUTOindexresult is nothing!!")
                                            LOGGER.Warn("" & sql_command)
                                        Else
                                            If IsDBNull(AUTOindexresult) Then
                                                LOGGER.Warn("unexpected: AUTOindexresult is DBNULL - " & sql_command)
                                            Else
                                                LOGGER.Debug("AUTOindexresult is: '" & AUTOindexresult & "'")
                                                FolderConvention = FolderConvention.Replace(element.ToString, AUTOindexresult)
                                            End If
                                        End If

                                    End If
                                End If
                            Else
                                LOGGER.Warn("INDEX_ID is not numeric:  " & INDEX_ID.ToString & "- APattern: " & element.Value)
                            End If
                        Else
                            LOGGER.Warn("split.Length <> 2 - APattern: " & element.Value)
                        End If

                    Case "M"
                        LOGGER.Debug("Working on manual value......'")
                        Dim split() As String = element.Value.Substring(3, element.Value.Length - 4).Split("#")
                        If split.Length = 2 Then
                            'Die GUID des AutoIndex auslesen
                            Dim INDEX_ID = split(1)
                            If IsNumeric(INDEX_ID) Then
                                If element.Value.ToUpper.Contains("FOLDERSELECT") Then
                                    LOGGER.Debug("FOLDERSELECT......'")
                                    For Each row As DataRow In CURRENT_TBPMO_INDEX_MAN.Rows
                                        If row.Item("GUID") = INDEX_ID Then
                                            Dim manvalue = row.Item("MAN_VALUE")
                                            If manvalue <> String.Empty Then
                                                LOGGER.Debug("folder value is: '" & manvalue & "'")
                                                CURRENT_VARIABLE_FOLDER_OVERRIDE = True
                                                CURRENT_VARIABLE_FOLDER = manvalue
                                                Return True

                                            Else
                                                LOGGER.Warn("Attention: manvalue (from Input indexing is empty!!")
                                            End If
                                        End If
                                    Next
                                Else


                                    For Each row As DataRow In CURRENT_TBPMO_INDEX_MAN.Rows
                                        If row.Item("GUID") = INDEX_ID Then
                                            Dim manvalue = row.Item("MAN_VALUE")
                                            If manvalue <> String.Empty Then
                                                LOGGER.Debug("manvalue is: '" & manvalue & "'")
                                                FolderConvention = FolderConvention.Replace(element.ToString, manvalue)
                                                FolderConvention = FolderConvention.Replace("\\", "")
                                            Else
                                                LOGGER.Warn("Attention: manvalue (from Input indexing is empty!!")
                                            End If
                                        End If
                                    Next

                                End If
                            Else
                                LOGGER.Warn("INDEX_ID is not numeric:  " & INDEX_ID.ToString & "- APattern: " & element.Value)
                            End If
                        Else
                            LOGGER.Warn("split.Length <> 2 - APattern: " & element.Value)
                        End If


                    Case "V"
                        Dim elmt = element.Value.Substring(3, element.Value.Length - 4).Split("#")
                        Dim split() As String = elmt
                        If split.Length = 2 Then
                            Dim VARTYPE = split(0)
                            LOGGER.Debug("VARTYPE is: '" & VARTYPE & "'")
                            Select Case VARTYPE
                                Case "ARDoctype"
                                    FolderConvention = FolderConvention.Replace(element.ToString, CURRENT_DOKARTSTRING)
                            End Select
                        Else
                            Dim folder_temp 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 = element.Value.Substring(3, element.Value.Length - 4)
                            If type.StartsWith("_") Then
                                type = type.Replace("_", "")
                            End If
                            Select Case type
                                Case "YYYY/MM/DD"
                                    folder_temp = My.Computer.Clock.LocalTime.Year & "\" & _Month & "\" & _day
                                Case "YYYY/MM"
                                    folder_temp = My.Computer.Clock.LocalTime.Year & "\" & _Month
                                Case "YYYY"
                                    folder_temp = My.Computer.Clock.LocalTime.Year
                                Case "YYYY-MM"
                                    folder_temp = My.Computer.Clock.LocalTime.Year & "-" & _Month
                            End Select
                            FolderConvention = FolderConvention.Replace(element.ToString, folder_temp)
                        End If

                    Case "C"
                        'Füllen mit Controlwert
                        Dim elmt = element.Value.Substring(3, element.Value.Length - 4).Split("#")
                        Dim APattern = element.Value.Substring(3, element.Value.Length - 4)
                        Dim split() As String = elmt
                        If split.Length = 2 Then
                            Dim CONTROL_ID = split(1)
                            If IsNumeric(CONTROL_ID) Then
                                Dim CONTROLVALUE = ClassControlValues.Get_Control_Value_for_ID(CONTROL_ID, CURRENT_RECORD_ID)
                                If IsNothing(CONTROLVALUE) Then
                                    Dim checktype = "SELECT CONTROL_TYPE_ID,SQL_COMMAND_1,CONNECTION_ID_1 FROM TBPMO_CONTROL WHERE SQL_COMMAND_1 is not null and SQL_COMMAND_1 <> '' AND GUID = " & CONTROL_ID
                                    Dim DTtype As DataTable = MYDB_ECM.GetDatatable(checktype)
                                    If DTtype.Rows.Count = 1 Then
                                        Dim lblsql = DTtype.Rows(0).Item(1)
                                        lblsql = lblsql.ToString.ToUpper.Replace("@RECORD_ID", CURRENT_RECORD_ID)
                                        lblsql = lblsql.ToString.ToUpper.Replace("@RECORD-ID", CURRENT_RECORD_ID)
                                        lblsql = lblsql.ToString.ToUpper.Replace("@ENTITY-ID", CURRENT_ENTITY_ID)
                                        lblsql = lblsql.ToString.ToUpper.Replace("@ENTITY_ID", CURRENT_ENTITY_ID)
                                        LOGGER.Debug("variable sql will be used for convention")
                                        Dim result = MYDB_ECM.GetScalarValue(DTtype.Rows(0).Item(2))
                                        If Not IsNothing(result) Then
                                            FolderConvention = FolderConvention.Replace(element.ToString, result.ToString)
                                        Else
                                            LOGGER.Warn("variable sqlresult is nothing - " & lblsql)
                                        End If
                                    Else
                                        LOGGER.Warn("Variable folder should be filled with value of Control-ID '" & CONTROL_ID & "', but result was nothing.")
                                        LOGGER.Warn("SQL-Command: " & checktype)
                                    End If

                                Else
                                    If IsDBNull(CONTROLVALUE) Then
                                        LOGGER.Warn("Variable folder should be filled with value of Control-ID '" & CONTROL_ID & "', but result was DBNULL.")
                                        LOGGER.Warn("SQL-Command: " & CURRENT_LAST_SQL)
                                    Else
                                        Dim sql1 = "SELECT * FROM TBPMO_WD_NAMECONVENTION_FORMAT WHERE ID = (SELECT TOP 1 GUID FROM TBPMO_WD_FORMVIEW_DOKTYPES WHERE DOCTYPE_ID = " & DocTypeID & " AND FORMVIEW_ID = " & CURRENT_FORMVIEW_ID & ")"
                                        Dim DT_FORMAT As DataTable = MYDB_ECM.GetDatatable(sql1)
                                        If Not IsNothing(DT_FORMAT) Then
                                            If DT_FORMAT.Rows.Count > 0 Then
                                                Dim result

                                                result = (From FormatRow In DT_FORMAT.AsEnumerable
                                                          Select FormatRow Where FormatRow.Item("PATTERN") = APattern).Single()
                                                If Not IsNothing(result) Then
                                                    Dim _rule = result.Item("FORMAT_RULE")
                                                    If Not IsNothing(_rule) Then
                                                        If IsDate(CONTROLVALUE) Then
                                                            Dim _date As Date = CDate(CONTROLVALUE)
                                                            'Dim _date = CDate(Format(CONTROLVALUE, "dd-MM-yyyy"))
                                                            _rule = _rule.ToString.Replace("Y", "y")
                                                            _rule = _rule.ToString.Replace("D", "d")
                                                            _rule = _rule.ToString.Replace("m", "M")
                                                            Dim convertedvalue = _date.ToString(_rule, CultureInfo.InvariantCulture)
                                                            CONTROLVALUE = convertedvalue
                                                        End If
                                                    End If
                                                End If
                                            End If
                                        End If
                                        FolderConvention = FolderConvention.Replace(element.ToString, CONTROLVALUE.ToString)
                                    End If
                                End If

                            End If
                        End If
                    Case "V"


                    Case Else
                        LOGGER.Warn(" -Undefined pattern found in folderconvention" & vbNewLine & "Elementname: " & element.Value.ToUpper)
                        MsgBox("Achtung - in der Namenkonvention wurde ein Element gefunden welches nicht zugeordnet werden kann!" & vbNewLine & "Elementname: " & element.Value.ToUpper, MsgBoxStyle.Exclamation, "Unexpected error in Name generieren:")
                End Select
                LOGGER.Debug($"FolderConvention so far is: '{FolderConvention}'")
            Next
            CURRENT_VARIABLE_FOLDER = FolderConvention
            Return True

        Catch ex As Exception
            MsgBox("Unexpected Error in CreateFolderforIndex-Method:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            LOGGER.Warn("Fehler in CrFolderForIndex: " & ex.Message, True)
            Return False
        End Try
    End Function
    Public Shared Function Version_Ueberprüfen(Dateiname As String)
        Dim extension
        Dim _NewFileString
        Try
            Dim version As Integer = 2

            Dim Stammname As String = Path.GetDirectoryName(Dateiname) & "\" & Path.GetFileNameWithoutExtension(Dateiname)
            extension = Path.GetExtension(Dateiname)

            Dim _neuername As String = Stammname
            'Dim MoveFilename As String = DATEINAME.Replace(element.Value, "")
            'Überprüfen ob File existiert
            If File.Exists(_neuername & extension) = False Then
                _NewFileString = _neuername
            Else
                Do While File.Exists(_neuername & extension)
                    version = version + 1
                    _neuername = Stammname & "~" & version
                    _NewFileString = _neuername
                Loop
            End If
            CURRENT_NEWFILENAME = _NewFileString & extension
            Return True
        Catch ex As Exception
            LOGGER.Warn(" - Error in versioning file - error: " & vbNewLine & ex.Message)
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error in versioning file:")
            Return False
        End Try

    End Function


End Class
