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 = ClassDatabase.Return_Datatable("SELECT * FROM TBDD_DOKUMENTART WHERE GUID = " & DOCTYPE_ID, True)
            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 = ClassDatabase.Execute_Scalar(sql)
                    sql = "SELECT * FROM TBDD_INDEX_AUTOM WHERE DOCTYPE_ID = " & DOCTYPE_ID
                    Dim dt As DataTable = ClassDatabase.Return_Datatable(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
                                If LogErrorsOnly = False Then ClassLogger.Add(" >> Indexvalue: " & idxvalue.ToString, False)
                                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 = ClassDatabase.Return_Datatable(sql, True)
                            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
                                    If LogErrorsOnly = False Then ClassLogger.Add(" >> Entity-ID: " & idxvalue.ToString, False)
                                    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
                                    If LogErrorsOnly = False Then ClassLogger.Add(" >> Parent-ID: " & idxvalue.ToString, False)
                                    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 = ClassDatabase.Return_Datatable(sql)
            FILE_DELIMITER = DT1.Rows(0).Item("FILE_DELIMITER")
            VERSION_DELIMITER = DT1.Rows(0).Item("VERSION_DELIMITER")

            Dim err As Boolean = False
            Dim Zielordner As String
            Dim extension As String = Path.GetExtension(CURRENT_FILENAME)
            Dim DT As DataTable = ClassDatabase.Return_Datatable("SELECT * FROM TBDD_DOKUMENTART WHERE GUID = " & DocTypeID, True)
            'sql_history_INSERT_INTO = "INSERT INTO TBGI_HISTORY (FILENAME_ORIGINAL,FILENAME_NEW"
            'sql_history_Index_Values = ""
            Dim AnzahlIndexe As Integer = 1
            _WDOBJECTTYPE = DT.Rows(0).Item("OBJEKTTYP")

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

            sql = "SELECT FOLDER_FOR_INDEX FROM TBDD_DOKUMENTART WHERE GUID = " & DocTypeID
            Dim Folder_for_index = ClassDatabase.Execute_Scalar(sql)
            If Not IsDBNull(Folder_for_index) Then
                If Folder_for_index <> String.Empty Then
                    If CREATE_FOLDER_INDEX(Folder_for_index, DocTypeID) = True And CURRENT_VARIABLE_FOLDER <> "" Then
                        Zielordner = Zielordner & "\" & CURRENT_VARIABLE_FOLDER
                    Else
                        MsgBox("Unexpected Error in Creating Variable Folder - Check logfile!", MsgBoxStyle.Critical)
                        Return False
                    End If
                End If
            End If

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


            Try
                Select Case clsWD_GET.WD_PATH_EXISTS(Zielordner.Substring(2))
                    Case False
                        ClassLogger.Add(String.Format(">> Targetpath ({0}) is not existing or result of WD_PATH_EXISTS was false.", Zielordner.Substring(2)))
                        Dim split() As String = Zielordner.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
                                            clsWindream.MY_WDSESSION.GetNewWMObjectFS(2, temppath, 0) 'WMEntityFolder,WMObjectEditModeNoEdit)
                                        Case -10
                                            Return False
                                    End Select
                                Catch ex As Exception
                                    If Not ex.Message.Contains("Filename exists!") Then
                                        ClassLogger.Add(String.Format(">> Could not create folder-part: {0} - Complete path is: ({1})", temppath, Zielordner.Substring(2)))
                                        ClassLogger.Add(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
                    ClassLogger.Add(String.Format(">> Could not create folder ({0}): " & ex.Message, Zielordner.Substring(2)), False)
                    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
            Dim NameConv = ClassDatabase.Execute_Scalar("SELECT TOP 1 NAME_CONVENTION FROM TBPMO_WD_FORMVIEW_DOKTYPES WHERE DOCTYPE_ID = " & DocTypeID & " AND FORMVIEW_ID = " & CURRENT_FORMVIEW_ID, True)
            If IsDBNull(NameConv) Then
                ClassLogger.Add(">> Achtung: Namenskonvention is DBNull", False)
                NameConv = Path.GetFileNameWithoutExtension(CURRENT_FILENAME)
            ElseIf NameConv = String.Empty Then
                ClassLogger.Add(">> Achtung: Namenskonvention is String empty", False)
                NameConv = Path.GetFileNameWithoutExtension(CURRENT_FILENAME)
            End If
            'schonmal den gesamten Pfad laden
            Dim DATEINAME As String = Zielordner & "\" & NameConv
            If LogErrorsOnly = False Then ClassLogger.Add(" >> DATEINAME: " & DATEINAME, False)

            ' 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(DATEINAME)
            '####
            ' alle Vorkommen innerhalbd er Namenkonvention durchlaufen
            For Each element As System.Text.RegularExpressions.Match In elemente

                If LogErrorsOnly = False Then ClassLogger.Add(" >> element in RegeX: " & element.Value, False)
                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 = ClassDatabase.Execute_Scalar("SELECT SQL_RESULT FROM TBDD_INDEX_AUTOM WHERE GUID = " & INDEX_ID, True)
                                            If IsNothing(sql_AUTOindexresult) Then
                                                If LogErrorsOnly = False Then ClassLogger.Add(" >> unexpected: sql_AUTOindexresult is nothing!!", False)
                                                value = ""
                                            Else
                                                If IsDBNull(sql_AUTOindexresult) Then
                                                    value = ""
                                                Else
                                                    sql_AUTOindexresult = sql_AUTOindexresult.ToString.ToUpper.Replace("@RECORD-ID", CURRENT_RECORD_ID)
                                                    Dim AUTOindexresult = ClassDatabase.Execute_Scalar(sql_AUTOindexresult, True)
                                                    If IsNothing(AUTOindexresult) Then
                                                        ClassLogger.Add(">> ATTENTION: unexpected: AUTOindexresult is nothing!!", False)
                                                        ClassLogger.Add(">> " & sql_AUTOindexresult, False)
                                                        value = ""
                                                    Else
                                                        If IsDBNull(AUTOindexresult) Then
                                                            value = ""
                                                        Else
                                                            value = AUTOindexresult
                                                        End If
                                                    End If

                                                End If
                                            End If
                                        Else
                                            ClassLogger.Add(">> INDEX_ID is not numeric:  " & INDEX_ID.ToString & "- APattern: " & APattern, False)
                                            value = ""
                                        End If
                                    Else
                                        ClassLogger.Add(">> split.Length <> 2 - APattern: " & APattern, False)
                                        value = ""
                                    End If

                                ElseIf APattern.Contains("#") Then
                                    If LogErrorsOnly = False Then ClassLogger.Add(" >> element filled with Record-Data.......: ", False)
                                    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 = ClassDatabase.Return_Datatable(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)
                                                    If LogErrorsOnly = False Then ClassLogger.Add(" >> variable sql will be used for convention", False)
                                                    Dim result = ClassDatabase.Execute_ScalarWithConnection(DTtype.Rows(0).Item(2), lblsql)
                                                    If Not IsNothing(result) Then
                                                        value = result.ToString
                                                    Else
                                                        ClassLogger.Add(">> variable sqlresult is nothing - " & lblsql, False)
                                                        value = ""
                                                    End If
                                                Else
                                                    ClassLogger.Add(">> NameConvention should be filled with value of Control-ID '" & CONTROL_ID & "', but result was nothing.", False)
                                                    ClassLogger.Add(">> SQL-Command: " & CURRENT_LAST_SQL)
                                                    value = ""
                                                End If

                                            Else
                                                If IsDBNull(CONTROLVALUE) Then
                                                    ClassLogger.Add(">> NameConvention should be filled with value of Control-ID '" & CONTROL_ID & "', but result was DBNULL.", False)
                                                    ClassLogger.Add(">> 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 = ClassDatabase.Return_Datatable(sql1, True)
                                                    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
                            DATEINAME = DATEINAME.Replace(element.Value, value)
                            _NewFileString = DATEINAME
                            If LogErrorsOnly = False Then ClassLogger.Add(" >> Actual NEWFILESTRING: " & _NewFileString, False)
                            ' 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
                                DATEINAME = DATEINAME.Replace(element.Value, Path.GetFileNameWithoutExtension(CURRENT_FILENAME))
                            Case "Username".ToUpper
                                DATEINAME = DATEINAME.Replace(element.Value, USER_USERNAME)
                        End Select
                        If datetemp <> "" Then
                            DATEINAME = DATEINAME.Replace(element.Value, datetemp)
                        End If
                        _NewFileString = DATEINAME
                    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

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


            '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
            ClassLogger.Add(" - 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
            '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
                If LogErrorsOnly = False Then ClassLogger.Add(" >> Elementname in FolderString: '" & element.ToString & "'", False)
                Dim EL_SUBSTRING = element.Value.Substring(2, 1).ToUpper
                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 = ClassDatabase.Execute_Scalar(sql)
                                If IsNothing(sql_command) Then
                                    ClassLogger.Add(" >> unexpected: SQL_RESULT is nothing!!", False)
                                    ClassLogger.Add(" >> " & sql, False)
                                Else
                                    If IsDBNull(sql_command) Then
                                        ClassLogger.Add(" >> unexpected: sql_command is DBNULL!!", False)
                                    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 = ClassDatabase.Execute_Scalar(sql_command, True)
                                        If IsNothing(AUTOindexresult) Then
                                            ClassLogger.Add(">> unexpected: AUTOindexresult is nothing!!", False)
                                            ClassLogger.Add(">> " & sql_command, False)
                                        Else
                                            If IsDBNull(AUTOindexresult) Then
                                                ClassLogger.Add(">> unexpected: AUTOindexresult is DBNULL - " & sql_command, False)
                                            Else
                                                FolderConvention = FolderConvention.Replace(element.ToString, AUTOindexresult)
                                            End If
                                        End If

                                    End If
                                End If
                            Else
                                ClassLogger.Add(">> INDEX_ID is not numeric:  " & INDEX_ID.ToString & "- APattern: " & element.Value, False)
                            End If
                        Else
                            ClassLogger.Add(">> split.Length <> 2 - APattern: " & element.Value, False)
                        End If

                    Case "M"
                        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
                                For Each row As DataRow In CURRENT_TBPMO_INDEX_MAN.Rows
                                    If row.Item("GUID") = INDEX_ID Then
                                        Dim manvalue = row.Item("MAN_VALUE")
                                        FolderConvention = FolderConvention.Replace(element.ToString, manvalue)
                                    End If
                                Next
                            Else
                                ClassLogger.Add(">> INDEX_ID is not numeric:  " & INDEX_ID.ToString & "- APattern: " & element.Value, False)
                            End If
                        Else
                            ClassLogger.Add(">> split.Length <> 2 - APattern: " & element.Value, False)
                        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)
                            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 = ClassDatabase.Return_Datatable(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)
                                        If LogErrorsOnly = False Then ClassLogger.Add(" >> variable sql will be used for convention", False)
                                        Dim result = ClassDatabase.Execute_ScalarWithConnection(DTtype.Rows(0).Item(2), lblsql)
                                        If Not IsNothing(result) Then
                                            FolderConvention = FolderConvention.Replace(element.ToString, result.ToString)
                                        Else
                                            ClassLogger.Add(">> variable sqlresult is nothing - " & lblsql, False)
                                        End If
                                    Else
                                        ClassLogger.Add(">> Variable folder should be filled with value of Control-ID '" & CONTROL_ID & "', but result was nothing.", False)
                                        ClassLogger.Add(">> SQL-Command: " & checktype)
                                    End If

                                Else
                                    If IsDBNull(CONTROLVALUE) Then
                                        ClassLogger.Add(">> Variable folder should be filled with value of Control-ID '" & CONTROL_ID & "', but result was DBNULL.", False)
                                        ClassLogger.Add(">> 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 = ClassDatabase.Return_Datatable(sql1, True)
                                        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
                        ClassLogger.Add(" -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
            Next
            CURRENT_VARIABLE_FOLDER = FolderConvention
            Return True

        Catch ex As Exception
            MsgBox("Unexpected Error in CreateFolderforIndex-Method:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            ClassLogger.Add(" >> 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
            ClassLogger.Add(" - 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
