Imports System.ComponentModel
Imports WINDREAMLib
Imports DD_LIB_Standards

Public Class frmWD_Import_Doc_Record
    Private bwsearch As New BackgroundWorker
    Private windreamSucheErgebnisse As WMObjects
    Private aktivesDokument As WMObject

    Private PROFILE_WD_SEARCH, PROFILE_SQL_DOCTYPE, PROFILE_SQL_UNIQUE, PROFILE_OBJECTTYPE, PROFILE_IDX_WORKED, PROFILE_SQL_PARENT, PROFILE_NEW_OT As String
    Private PROFILE_ENTITY As Integer
    Private PROFILE_ONLY_RECORD As Boolean = False
    Private Search_Completed As Boolean = False
    Private _Filesimported As Integer = 0
    Private _RecordsAdded As Integer = 0
    Private IMPORT_REC_ID
    Private IMP_REC_EXISTS As Boolean = False
    Private REC_ADDED As Boolean = False
    Private IMP_PARENT_REC_ID

    Private Sub TBPMO_WD_IMPORT_PROFILEBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles TBPMO_WD_IMPORT_PROFILEBindingNavigatorSaveItem.Click
        save_Profile()
    End Sub
    Sub save_Profile()
        Try
            Dim msg = "Profil gespeichert - " & Now.ToString
            If USER_LANGUAGE <> "de-DE" Then
                msg = "profile saved - " & Now.ToString
            End If
            lblSaveProfile.Text = msg
            Me.TBPMO_WD_IMPORT_PROFILEBindingSource.EndEdit()
            If DD_DMSDataSet.TBPMO_WD_IMPORT_PROFILE.GetChanges Is Nothing = False Then
                Me.CHANGED_WHOTextBox.Text = USER_USERNAME
                Me.TBPMO_WD_IMPORT_PROFILEBindingSource.EndEdit()
                Me.TBPMO_WD_IMPORT_PROFILETableAdapter.Update(Me.DD_DMSDataSet.TBPMO_WD_IMPORT_PROFILE)
                Me.lblSaveProfile.Visible = True
            Else
                Me.lblSaveProfile.Visible = False
            End If
        Catch ex As Exception
            MsgBox("Error in Save Profiles:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Private Sub frmWD_Import_Doc_Recordvb_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        If clsWindream.Create_Session = True Then
            ObjektTypenEintragen()
        Else
            MsgBox("Could not create a windream-session!!", MsgBoxStyle.Critical)
        End If
        Try
            Me.TBPMO_WD_IMPORT_PROFILETableAdapter.Connection.ConnectionString = MyConnectionString
            Me.TBDD_CONNECTIONTableAdapter.Connection.ConnectionString = MyConnectionString
            Me.TBDD_CONNECTIONTableAdapter.Fill(Me.DD_DMSDataSet.TBDD_CONNECTION)
        Catch ex As Exception
            MsgBox("Error in Loading form:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
        Laod_Profiles()
        Load_Profiles_ComboBox()

    End Sub
    Sub Laod_Profiles()
        Try
            Me.TBPMO_WD_IMPORT_PROFILETableAdapter.Fill(Me.DD_DMSDataSet.TBPMO_WD_IMPORT_PROFILE)
            Dim sql = String.Format("SELECT T.GUID, T1.FORM_TITLE,[dbo].[FNPMO_GETOBJECTCAPTION]('{0}','FORMVIEW_TITLE' + CONVERT(VARCHAR(5), T1.GUID), {1}) AS 'CAPTION' FROM " & _
                                       "TBPMO_FORM T, TBPMO_FORM_VIEW T1 WHERE T.GUID = T1.FORM_ID AND T.GUID IN (select DISTINCT ENTITY_ID FROM TBPMO_CLIENT_ENTITY WHERE CLIENT_ID IN (select client_Id from TBDD_CLIENT_USER where USER_ID = {2}))", USER_LANGUAGE, CURRENT_SCREEN_ID, USER_GUID)
            Dim DT As DataTable = ClassDatabase.Return_Datatable(sql)
            cmbentity.DataSource = DT
            cmbentity.DisplayMember = DT.Columns(1).ColumnName
            cmbentity.ValueMember = DT.Columns(0).ColumnName
        Catch ex As Exception
            MsgBox("Error in Loading Profiles:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Sub Load_Profiles_ComboBox()
        Try
            Dim DT = ClassDatabase.Return_Datatable("SELECT T.GUID, T.NAME FROM TBPMO_WD_IMPORT_PROFILE T ORDER BY T.NAME")
            cmbImportProfile.DataSource = DT
            cmbImportProfile.DisplayMember = DT.Columns(1).ColumnName
            cmbImportProfile.ValueMember = DT.Columns(0).ColumnName

        Catch ex As Exception
            MsgBox("Error in Loading Profiles to Combobox:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
  
    Private Sub ObjektTypenEintragen()
        Try
            Dim oDokumentTyp As WINDREAMLib.WMObject
            ' Combobox leeren
            Me.NEW_OBJECTTYPEComboBox.Items.Clear()
            Me.OLD_OBJECTTYPEComboBox.Items.Clear()
            ' alle Objekttypen durchlaufen
            For Each oDokumentTyp In clsWD_GET.GetObjecttypesAsObjects
                ' und in die Combobox eintragen
                Me.NEW_OBJECTTYPEComboBox.Items.Add(oDokumentTyp.aName)
                Me.OLD_OBJECTTYPEComboBox.Items.Add(oDokumentTyp.aName)
            Next
        Catch ex As Exception
            MsgBox("Error in loading Objecttypes:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub

    Private Sub btnWDSearch_Click(sender As Object, e As EventArgs) Handles btnWDSearch.Click
        If Not Me.WD_SEARCHTextBox.Text = "" Then
            Me.dlgWindreamsuche.FileName = Me.WD_SEARCHTextBox.Text
        End If

        If Me.dlgWindreamsuche.ShowDialog = Windows.Forms.DialogResult.OK Then
            Me.WD_SEARCHTextBox.Text = Me.dlgWindreamsuche.FileName
        End If
    End Sub

    Private Sub TBPMO_WD_IMPORT_PROFILEBindingSource_AddingNew(sender As Object, e As System.ComponentModel.AddingNewEventArgs) Handles TBPMO_WD_IMPORT_PROFILEBindingSource.AddingNew
        Me.DD_DMSDataSet.TBPMO_WD_IMPORT_PROFILE.ADDED_WHOColumn.DefaultValue = USER_USERNAME
    End Sub

    Private Sub btnStartStop_Click(sender As Object, e As EventArgs) Handles btnStartStop.Click
        Start_Threads()
    End Sub
    Sub Start_Threads()
        If bwsearch.IsBusy Then
            MsgBox("Sorry but Import is still running!", MsgBoxStyle.Exclamation)
            Exit Sub
        End If
        Try
            Dim sql = "select * FROM TBPMO_WD_IMPORT_PROFILE where GUID = " & cmbImportProfile.SelectedValue.ToString
            Dim DT As DataTable = ClassDatabase.Return_Datatable(sql)

            PROFILE_WD_SEARCH = DT.Rows(0).Item("WD_SEARCH")
            PROFILE_SQL_DOCTYPE = DT.Rows(0).Item("SQL_DOCTYPE")
            PROFILE_SQL_UNIQUE = DT.Rows(0).Item("UNIQUE_DOC_SQL")
            PROFILE_ENTITY = DT.Rows(0).Item("ENTITY_ID")
            PROFILE_OBJECTTYPE = DT.Rows(0).Item("OLD_OBJECTTYPE")
            PROFILE_IDX_WORKED = DT.Rows(0).Item("IDX_FILE_WORKED")
            PROFILE_SQL_PARENT = DT.Rows(0).Item("SQL_PARENT_RECORD")
            PROFILE_ONLY_RECORD = DT.Rows(0).Item("ONLY_RECORD_CREATING")
            If PROFILE_ONLY_RECORD = True Then
                ClassLogger.Add(">> Only Records shall be created", False)
            End If
            PROFILE_NEW_OT = DT.Rows(0).Item("NEW_OBJECTTYPE")
        Catch ex As Exception
            MsgBox("Error in getting Profile Parameters:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
        windreamSucheErgebnisse = Nothing
        'Die NI wird ganz normal gestartet
        Me.btnStartStop.Text = "Import stoppen"
        Search_Completed = False
        'Variable für den Fall Programmabbruch und Neustart!
        bwsearch = New BackgroundWorker

        AddHandler bwsearch.DoWork, AddressOf Work_Search
        AddHandler bwsearch.RunWorkerCompleted, AddressOf bwsearch_RunWorkerCompleted
        bwsearch.WorkerSupportsCancellation = True
        bwsearch.WorkerReportsProgress = True
        ' den Indexierungsvorgang direkt (zum ersten Mal) durchführen
        Me.Start_Profile()
        Me.btnStartStop.Text = "Import starten"
        Me.lblStatusThread.Text = "Status: Import beendet"
    End Sub
    Public Sub Start_Profile()
        Try
            If clsWindream.SESSION_CREATED = False Then
                MsgBox("windream could not be init'ed!!", MsgBoxStyle.Critical)
                Exit Sub
            End If
            'nur weiter machen wenn kein BackgroundWorker mehr läuft
            If Not Me.bwsearch.IsBusy Then
                ClassLogger.Add("======================================================================", False)
                ClassLogger.Add("Import RecordFiles started                                    ", False)
                ClassLogger.Add(Now, False)
                ClassLogger.Add("======================================================================", False)
                Me.lblStatusThread.Text = "Status: Import läuft"

                bwsearch.RunWorkerAsync()

                Do While Search_Completed = False

                Loop
                If Not IsNothing(windreamSucheErgebnisse) Then
                    If windreamSucheErgebnisse.Count > 0 Then
                        Me.ProgressBar1.Minimum = 0
                        Me.ProgressBar1.Maximum = windreamSucheErgebnisse.Count
                        Me.ProgressBar1.Value = 0
                        Me.Refresh()
                        clsWindream.MY_WDOBJECTTYPE = PROFILE_NEW_OT
                        _Filesimported = 0
                        _RecordsAdded = 0
                        Work_Files()
                        MsgBox(_Filesimported.ToString & " Files were imported to ADDI!" & vbNewLine & _
                               _RecordsAdded.ToString & " Records were added!", MsgBoxStyle.Information)
                    Else
                        MsgBox("No Results for windream-Search!", MsgBoxStyle.Information)
                    End If
                   
                End If
            Else
                If Me.bwsearch.IsBusy Then
                    ClassLogger.Add(">> Attention: Thread Search still working - Threads will be aborted.", False)
                    Me.bwsearch.CancelAsync()
                    MsgBox("Threads were cancelled!", MsgBoxStyle.Information)
                End If
            End If
        Catch ex As Exception
            MsgBox("Unexpexted error in Start_Profile: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            ClassLogger.Add("Unexpexted error in Start_Profile: " & ex.Message, True)
        End Try
    End Sub
    Sub Work_Search()
        Try
            RUN_SEARCH()
        Catch ex As Exception
            MsgBox("Unexpexted error in Start_Search: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            ClassLogger.Add("Unexpexted error in Start_Search: " & ex.Message, True)
        End Try
    End Sub
    Sub RUN_SEARCH()
        Try
            windreamSucheErgebnisse = clsWD_GET.GetSearchDocuments(PROFILE_WD_SEARCH)
            ClassLogger.Add(">> Files Result: " & windreamSucheErgebnisse.Count, False)
            Search_Completed = True
        Catch ex As Exception
            ClassLogger.Add("Error in RUN_SEARCH - Error: " & ex.Message)
        End Try
    End Sub
    Private Sub bwsearch_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs)

        'Dim minutes = CInt(System.DateTime.Now.Subtract(CURRENT_START_DATETIME).Minutes)
            'If minutes >= 1 Then
            '    Logger(" >> Suchdauer >= 1 Minute aber letzendlich ausgeführt (" & Now & ")", True)
            'End If

    End Sub
    Sub Work_Files()
        Try
            IMP_PARENT_REC_ID = Nothing
            IMPORT_REC_ID = Nothing
            'Liefert nur den Pfad des aktiven Dokumens
            Dim Folder As String
            For Each dok As WMObject In windreamSucheErgebnisse
                Dim REC_EXISTS As Boolean = False
                ' aktuelles Dokument der Klasse mitteilen
                Me.aktivesDokument = dok
                Dim filename = "W:" & aktivesDokument.aPath
                Dim DOK_FOLDER As String = IO.Path.GetDirectoryName(filename)

                If LogErrorsOnly = False Then ClassLogger.Add(" >> Working on file '" & IO.Path.GetFileName(filename) & "'", False)
                If Folder <> DOK_FOLDER Then
                    If LogErrorsOnly = False Then ClassLogger.Add(" >> Folderpath '" & DOK_FOLDER & "'", False)
                    Folder = DOK_FOLDER
                End If

                If Create_Record() = True Then
                    If PROFILE_SQL_PARENT <> "" Then
                        If Create_Parent_Record() = False Then
                            ClassLogger.Add(">> Create Parent-Record not successful!", False)
                        End If
                    End If
                    If PROFILE_ONLY_RECORD = False Then 'Es sollen auch Dateien importiert werden
                        If Import_File() = False Then
                            ClassLogger.Add(">> No import of file! Exit For each!", False)
                            Continue For
                        End If
                    End If
                    If IMP_REC_EXISTS = False Then
                        Dim sql As String
                        sql = "SELECT * FROM TBPMO_WD_IMPORT_PROFILE_IDX WHERE STRING1 NOT IN ('DOCTYPE_ORIGIN','INDEX_RECORD_ID','INDEX_DOCTYPE','INDEX_ENTITY_ID') AND PROFILE_ID = " & cmbImportProfile.SelectedValue
                        Dim DT As DataTable = ClassDatabase.Return_Datatable(sql)
                        If DT Is Nothing = False Then 'CHECK DD
                            If DT.Rows.Count >= 0 Then
                                If LogErrorsOnly = False Then ClassLogger.Add(" >> " & DT.Rows.Count & " Control-Index-Rows", False)
                                Dim err As Boolean = False
                                For Each row As DataRow In DT.Rows
                                    'Den Wert aus dem Index des Dokuments auslesen und in den ControlValue schreiben
                                    Dim idxvalue
                                    Dim indexname_old = row.Item("STRING2").ToString
                                    If LogErrorsOnly = False Then ClassLogger.Add(" >> Read Value 2 for windream-index: '" & indexname_old & "'", False)
                                    Try
                                        idxvalue = aktivesDokument.GetVariableValue(indexname_old)
                                        If LogErrorsOnly = False Then ClassLogger.Add(" >> idxvalue from windream: '" & idxvalue.ToString & "'", False)
                                    Catch ex As Exception
                                        err = True
                                        ClassLogger.Add(">> Error Reading Value 2 for windream-index '" & indexname_old & "' - Error: " & ex.Message, False)
                                        Continue For
                                    End Try

                                    Dim CONTROL_ID = row.Item("STRING1").ToString
                                    If CONTROL_ID = -1 Then
                                        Continue For
                                    End If
                                    Dim ins = String.Format("INSERT INTO TBPMO_CONTROL_VALUE (CONTROL_ID,RECORD_ID,VALUE,ADDED_WHO) VALUES ({0},{1},'{2}','{3}')", CONTROL_ID, IMPORT_REC_ID, idxvalue, USER_USERNAME)
                                    ClassDatabase.Execute_non_Query(ins, False)
                                    'ByVal WD_File As String, ByVal _Indexname As String, ByVal _Value As String
                                Next
                            Else
                                ClassLogger.Add(">>There are no control-index relations defined!", False)
                            End If
                        Else
                            If LogErrorsOnly = False Then ClassLogger.Add(" >> No control-values configured!", False)
                        End If
                    Else
                        If LogErrorsOnly = False Then ClassLogger.Add(" >> REC_EXISTS = True - no control values to be set!", False)
                    End If

                Else
                    ClassLogger.Add(">> Create Record not successful!", False)
                End If

                ' 
                '####### Go für das Dokument ##########
                ProgressBar1.Value += 1
                '  bwsearch.ReportProgress(-1)
            Next
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical)
        End Try


    End Sub
    Function Import_File()
        Try
            Dim Sql As String
            Dim SQL_FILE_DOCTYPE = PROFILE_SQL_DOCTYPE
            'Regulären Ausdruck zum Auslesen der windream-Indexe definieren
            Dim preg As String = "\[%{1}[a-zA-Z0-9\!\$\&\/\(\)\=\?\,\.\-\;\:_öÖüÜäÄ\#\'\+\*\~\{\}\@\€\<\>\ ]+]{1}"
            ' 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(SQL_FILE_DOCTYPE)
            ' alle Vorkommen der windream-Indexe im SQL-String durchlaufen
            '#####
            ' alle Vorkommen der windream-Indexe im SQL-String durchlaufen
            For Each element As System.Text.RegularExpressions.Match In elemente
                Dim elementohneSZ = element.Value.Replace("[%", "")
                elementohneSZ = elementohneSZ.Replace("]", "")
                ' für den Platzhalter den WErt aus windream auslesen
                If LogErrorsOnly = False Then ClassLogger.Add(" >> Read value for windream-index: '" & elementohneSZ & "'", False)
                Dim idxvalue
                Try
                    idxvalue = aktivesDokument.GetVariableValue(elementohneSZ)
                    If LogErrorsOnly = False Then ClassLogger.Add(" >> idxvalue from windream: '" & idxvalue.ToString & "'", False)
                Catch ex As Exception
                    ClassLogger.Add(">> Regex Doctype SQL: Error reading Value for windream-index '" & elementohneSZ & "' - Error: " & ex.Message, False)
                    Continue For
                End Try
                ' den Platzhalter für den auszulesenden View durch den Viewnamen ersetzen
                SQL_FILE_DOCTYPE = SQL_FILE_DOCTYPE.Replace(element.Value, idxvalue.ToString)
            Next
            If LogErrorsOnly = False Then ClassLogger.Add(" >> Executing Doctype SQL: " & SQL_FILE_DOCTYPE, False)
            Dim DokTYPE_ID = ClassDatabase.Execute_Scalar(SQL_FILE_DOCTYPE)
            '#####

            If Not IsNothing(DokTYPE_ID) Then
                Sql = "SELECT ZIEL_PFAD, OBJEKTTYP FROM TBDD_DOKUMENTART WHERE GUID = " & DokTYPE_ID
                Dim DT As DataTable = clsDatabase.Return_Datatable(Sql)
                If DT.Rows.Count <> 1 Then
                    Return False
                End If
                Dim Targetpath = DT.Rows(0).Item(0)
                Dim document_ID
                Try
                    document_ID = aktivesDokument.GetVariableValue("dwDocID")
                Catch ex As Exception
                End Try
                Dim ww
                Try
                    ww = aktivesDokument.GetVariableValue("Dokument-ID")
                Catch ex As Exception
                End Try
                If ClassImport_Windream.Version_Ueberprüfen(Targetpath & "\" & IO.Path.GetFileName("W:" & aktivesDokument.aPath)) = True Then
                    'CURRENT_NEWFILENAME = Targetpath & "\" & IO.Path.GetFileName("W:" & aktivesDokument.aPath)
                    Dim streamresult = clsWD_SET.Stream_File("W:" & aktivesDokument.aPath, Targetpath, True)
                    If streamresult = True Then
                        'Die EntitätsID indexieren
                        Sql = "SELECT STRING2 FROM TBPMO_WD_IMPORT_PROFILE_IDX WHERE STRING1 = 'INDEX_ENTITY_ID' AND PROFILE_ID = " & cmbImportProfile.SelectedValue
                        Dim ENTITY_INDEX As String = ClassDatabase.Execute_Scalar(Sql)
                        If Not IsNothing(ENTITY_INDEX) Then
                            clsWD_SET.IndexFile(CURRENT_FILEIN_WD, ENTITY_INDEX, PROFILE_ENTITY, DT.Rows(0).Item(1))
                        End If
                        Try
                            If Not IsNothing(IMP_PARENT_REC_ID) Then
                                'Die Parent-Entität indexieren
                                Sql = "SELECT IDXNAME_PARENTID FROM TBPMO_WD_OBJECTTYPE WHERE OBJECT_TYPE = '" & PROFILE_NEW_OT & "'"
                                Dim PIDENT As String = ClassDatabase.Execute_Scalar(Sql)
                                If Not IsNothing(PIDENT) Then
                                    clsWD_SET.IndexFile(CURRENT_FILEIN_WD, PIDENT, IMP_PARENT_REC_ID.ToString, DT.Rows(0).Item(1))
                                End If
                            End If
                        Catch ex As Exception

                        End Try

                        Try
                            If Not IsNothing(PROFILE_ENTITY) Then
                                'Die Parent-Entität indexieren
                                Sql = "SELECT IDXNAME_ENTITYID FROM TBPMO_WD_OBJECTTYPE WHERE OBJECT_TYPE = '" & PROFILE_NEW_OT & "'"
                                Dim IDXENTITY As String = ClassDatabase.Execute_Scalar(Sql)
                                If Not IsNothing(IDXENTITY) Then
                                    clsWD_SET.IndexFile(CURRENT_FILEIN_WD, IDXENTITY, PROFILE_ENTITY.ToString, DT.Rows(0).Item(1))
                                End If
                            End If
                        Catch ex As Exception

                        End Try

                        'Die Dokumentart indexieren
                        Sql = String.Format("SELECT dbo.FNPMO_GETOBJECTCAPTION('{0}', 'DOCTYPE_TITLE' + CONVERT(VARCHAR(5), GUID), 1) FROM TBDD_DOKUMENTART WHERE GUID = {1}", USER_LANGUAGE, DokTYPE_ID)
                        Dim DOCTYPE_STRING = ClassDatabase.Execute_Scalar(Sql)

                        Sql = "SELECT IDXNAME_DOCTYPE FROM TBPMO_WD_OBJECTTYPE WHERE OBJECT_TYPE = '" & PROFILE_NEW_OT & "'"
                        Dim DoctypeIndex As String = ClassDatabase.Execute_Scalar(Sql)
                        If Not IsNothing(DoctypeIndex) Then
                            clsWD_SET.IndexFile(CURRENT_FILEIN_WD, DoctypeIndex, DOCTYPE_STRING.ToString, DT.Rows(0).Item(1))
                        Else
                            Sql = "SELECT STRING2 FROM TBPMO_WD_IMPORT_PROFILE_IDX WHERE STRING1 = 'INDEX_DOCTYPE' AND PROFILE_ID = " & cmbImportProfile.SelectedValue
                            DoctypeIndex = ClassDatabase.Execute_Scalar(Sql)
                            If Not IsNothing(DoctypeIndex) Then
                                clsWD_SET.IndexFile(CURRENT_FILEIN_WD, DoctypeIndex, DOCTYPE_STRING, DT.Rows(0).Item(1))
                            End If
                        End If
                        '#####

                        Sql = "SELECT IDXNAME_RECORDID FROM TBPMO_WD_OBJECTTYPE WHERE OBJECT_TYPE = '" & PROFILE_NEW_OT & "'"
                        Dim RecordIndex As String = ClassDatabase.Execute_Scalar(Sql)
                        If Not IsNothing(RecordIndex) Then
                            clsWD_SET.IndexFile(CURRENT_FILEIN_WD, RecordIndex, IMPORT_REC_ID, DT.Rows(0).Item(1))
                        Else
                            Sql = "SELECT STRING2 FROM TBPMO_WD_IMPORT_PROFILE_IDX WHERE STRING1 = 'INDEX_RECORD_ID' AND PROFILE_ID = " & cmbImportProfile.SelectedValue
                            RecordIndex = ClassDatabase.Execute_Scalar(Sql)
                            If clsWD_SET.IndexFile(CURRENT_FILEIN_WD, RecordIndex, IMPORT_REC_ID, DT.Rows(0).Item(1)) Then
                                If LogErrorsOnly = False Then ClassLogger.Add(" >> Record Index was written", False)
                            End If
                        End If

                        If PROFILE_IDX_WORKED <> "" Then
                            If LogErrorsOnly = False Then ClassLogger.Add(" >> Setting the Exported to ADDI-Flag - windream-index '" & PROFILE_IDX_WORKED & "'", False)
                            clsWD_SET.File_SetBooleanIndex(True, aktivesDokument, PROFILE_IDX_WORKED, False)
                        End If
                        _Filesimported += 1
                        Return True
                    Else
                        ClassLogger.Add(">> File was not imported!", False)
                        Return False
                    End If
                End If
            Else
                ClassLogger.Add(">> No doctype-ID found", False)
                ClassLogger.Add(">> SQL: " & SQL_FILE_DOCTYPE, False)
                If REC_ADDED = True Then
                    ClassHelper.DeleteRecord(IMPORT_REC_ID)
                    Return False
                End If
            End If
        Catch ex As Exception
            ClassLogger.Add(">> Unexpected Error in Import/IndexFile: " & ex.Message, False)
            MsgBox("Unexpected Error in Import/IndexFile: " & ex.Message, MsgBoxStyle.Critical)
            Return False
        End Try

    End Function
    Function Create_Record()
        Try
            IMP_REC_EXISTS = False
            REC_ADDED = False
            Dim SQL_UNIQUE_FILE
            If PROFILE_SQL_UNIQUE <> "" Then
                SQL_UNIQUE_FILE = PROFILE_SQL_UNIQUE
                'Regulären Ausdruck zum Auslesen der windream-Indexe definieren
                Dim preg As String = "\[%{1}[a-zA-Z0-9\!\$\&\/\(\)\=\?\,\.\-\;\:_öÖüÜäÄ\#\'\+\*\~\{\}\@\€\<\>\ ]+]{1}"
                ' 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(SQL_UNIQUE_FILE)
                ' alle Vorkommen der windream-Indexe im SQL-String durchlaufen
                For Each element As System.Text.RegularExpressions.Match In elemente
                    Dim elementohneSZ = element.Value.Replace("[%", "")
                    elementohneSZ = elementohneSZ.Replace("]", "")
                    ' für den Platzhalter den WErt aus windream auslesen
                    If LogErrorsOnly = False Then ClassLogger.Add(" >> Read value 1 for windream-index: '" & elementohneSZ & "'", False)
                    Dim idxvalue
                    Try
                        idxvalue = aktivesDokument.GetVariableValue(elementohneSZ)
                        If LogErrorsOnly = False Then ClassLogger.Add(" >> idxvalue from windream: '" & idxvalue.ToString & "'", False)
                    Catch ex As Exception
                        ClassLogger.Add(">> Regex Unique SQL: Error reading Value 1 for windream-index '" & elementohneSZ & "' - Error: " & ex.Message, False)
                        Continue For
                    End Try
                    ' den Platzhalter für den auszulesenden View durch den Viewnamen ersetzen
                    SQL_UNIQUE_FILE = SQL_UNIQUE_FILE.Replace(element.Value, idxvalue.ToString)
                Next
                If LogErrorsOnly = False Then ClassLogger.Add(" >> Executing Unique SQL: " & SQL_UNIQUE_FILE, False)
                IMPORT_REC_ID = ClassDatabase.Execute_Scalar(SQL_UNIQUE_FILE)
            End If
            If IMPORT_REC_ID = Nothing Then
                If LogErrorsOnly = False Then ClassLogger.Add(" >> Record is new!", False)
                'Den Record inserten
                ClassRecordCommands.CreateRecord(PROFILE_ENTITY)
                IMPORT_REC_ID = ClassRecordCommands.GetLastRecord()
                REC_ADDED = True
                If LogErrorsOnly = False Then ClassLogger.Add(" >> New Record-ID: " & IMPORT_REC_ID.ToString, False)
                _RecordsAdded += 1
            Else
                ClassLogger.Add(">> ## RECORD already exists - Record-ID: '" & IMPORT_REC_ID.ToString & "' ##", False)
                If LogErrorsOnly = True Then ClassLogger.Add(">> Unique SQL: " & SQL_UNIQUE_FILE, False)
                IMP_REC_EXISTS = True
            End If
            Return True
        Catch ex As Exception
            ClassLogger.Add(">> Unexpected Error in Create-Record: " & ex.Message, False)
            MsgBox("Unexpected Error in Create-Record: " & ex.Message, MsgBoxStyle.Critical)
            Return False
        End Try

    End Function
    Function Create_Parent_Record()
        Try
            Dim SQL_PARENT As String
            SQL_PARENT = PROFILE_SQL_PARENT
            'Regulären Ausdruck zum Auslesen der windream-Indexe definieren
            Dim preg As String = "\[%{1}[a-zA-Z0-9\!\$\&\/\(\)\=\?\,\.\-\;\:_öÖüÜäÄ\#\'\+\*\~\{\}\@\€\<\>\ ]+]{1}"
            ' 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(SQL_PARENT)
            ' alle Vorkommen der windream-Indexe im SQL-String durchlaufen
            For Each element As System.Text.RegularExpressions.Match In elemente
                Dim elementohneSZ = element.Value.Replace("[%", "")
                elementohneSZ = elementohneSZ.Replace("]", "")
                ' für den Platzhalter den WErt aus windream auslesen
                If LogErrorsOnly = False Then ClassLogger.Add(" >> Read parent value for windream-index: '" & elementohneSZ & "'", False)
                Dim idxvalue
                Try
                    idxvalue = aktivesDokument.GetVariableValue(elementohneSZ)
                    If LogErrorsOnly = False Then ClassLogger.Add(" >> parent idxvalue from windream: '" & idxvalue.ToString & "'", False)
                Catch ex As Exception
                    ClassLogger.Add(">> Regex Unique SQL: Error reading parent Value for windream-index '" & elementohneSZ & "' - Error: " & ex.Message, False)
                    Continue For
                End Try
                ' den Platzhalter für den auszulesenden View durch den Viewnamen ersetzen
                SQL_PARENT = SQL_PARENT.Replace(element.Value, idxvalue.ToString)
            Next
            If LogErrorsOnly = False Then ClassLogger.Add(" >> Executing parent SQL: " & SQL_PARENT, False)
            IMP_PARENT_REC_ID = ClassDatabase.Execute_Scalar(SQL_PARENT)
            If IMP_PARENT_REC_ID = Nothing Then
                If LogErrorsOnly = False Then ClassLogger.Add(" >> No PARENT_RECORD found!", False)
                'Den Record inserten
                ClassRecordCommands.CreateRecord(PROFILE_ENTITY)
                IMP_PARENT_REC_ID = ClassRecordCommands.GetLastRecord()
                If LogErrorsOnly = False Then ClassLogger.Add(" >> New PARENT_RECORD-ID: " & IMP_PARENT_REC_ID.ToString, False)
                _RecordsAdded += 1
            Else
                ClassLogger.Add(">> ## PARENT_RECORD already exists - PARENT_RECORD-ID: '" & IMP_PARENT_REC_ID.ToString & "' ##", False)
                If LogErrorsOnly = True Then ClassLogger.Add(">> parent SQL: " & SQL_PARENT, False)
            End If
            Dim sql = String.Format("SELECT GUID FROM TBPMO_RECORD_CONNECT WHERE RECORD1_ID = {0} AND  RECORD2_ID = {1}", IMP_PARENT_REC_ID, IMPORT_REC_ID)
            Dim result = ClassDatabase.Execute_Scalar(sql)
            If result Is Nothing Then
                ClassRecordCommands.ConnectRecord(IMP_PARENT_REC_ID, IMPORT_REC_ID, "IMP CONNECT")
            End If
            Return True
        Catch ex As Exception
            ClassLogger.Add(">> Unexpected Error in Create-Parent-Record: " & ex.Message, False)
            MsgBox("Unexpected Error in Create-Parent-Record: " & ex.Message, MsgBoxStyle.Critical)
            Return False
        End Try
    End Function

       

    Private Sub Load_INDEXE()
        If GUIDTextBox.Text = "" Then Exit Sub
        Try
            Me.TBPMO_WD_IMPORT_PROFILE_IDXTableAdapter.Connection.ConnectionString = MyConnectionString
            Me.TBPMO_WD_IMPORT_PROFILE_IDXTableAdapter.Fill(Me.DD_DMSDataSet.TBPMO_WD_IMPORT_PROFILE_IDX, CType(GUIDTextBox.Text, Integer))
        Catch ex As System.Exception
            MsgBox("Error loading INDEX-Relations: " & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub

    Private Sub TBDD_CONNECTIONBindingSource_CurrentChanged(sender As Object, e As EventArgs) Handles TBDD_CONNECTIONBindingSource.CurrentChanged

        Load_INDEXE()
    End Sub

    Private Sub frmWD_Import_Doc_Record_Shown(sender As Object, e As EventArgs) Handles Me.Shown

    End Sub

    Private Sub TabControl1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles TabControl1.SelectedIndexChanged
        If TabControl1.SelectedIndex = 1 Then
            Load_INDEXE()
        End If
    End Sub

    Private Sub cmbentity_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbentity.SelectedIndexChanged
        If cmbentity.SelectedIndex = -1 Or cmbentity.Text = "" Then Exit Sub
        Load_StringBox1()
    End Sub

    Private Sub TBPMO_WD_IMPORT_PROFILEBindingSource_CurrentChanged(sender As Object, e As EventArgs) Handles TBPMO_WD_IMPORT_PROFILEBindingSource.CurrentChanged
        If Not cmbentity.SelectedIndex = -1 And Not cmbentity.Text = "" Then
            Load_StringBox1()
        End If
        If Not OLD_OBJECTTYPEComboBox.Text = "" Then
            Load_StringBox2()
        End If

    End Sub

    Sub Load_StringBox2()
        Try
            Me.STRING2ComboBox.Items.Clear()
            Dim indexe = clsWD_GET.GetIndicesByObjecttype(OLD_OBJECTTYPEComboBox.Text)
            If indexe IsNot Nothing Then
                For Each index As String In indexe
                    Me.STRING2ComboBox.Items.Add(index)
                Next
            End If
        Catch ex As Exception
            MsgBox("Error in Loading String 2 Combobox:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Sub Load_StringBox1()
        Try
            '  STRING1ComboBox.Items.Clear()
            Dim Type = cmbentity.SelectedValue.GetType.ToString
            If Type = "System.Data.DataRowView" Then
                Exit Sub
            End If
            Dim sql = "SELECT CONVERT(VARCHAR(5),GUID) AS GUID, NAME FROM TBPMO_CONTROL where FORM_ID = " & cmbentity.SelectedValue & " UNION ALL SELECT 'DOCTYPE_ORIGIN','DOCTYPE_ORIGIN' UNION ALL " & _
                                                    "SELECT 'INDEX_RECORD_ID','INDEX_RECORD_ID' UNION ALL " & _
                                                    "SELECT 'INDEX_ENTITY_ID','INDEX_ENTITY_ID' UNION ALL " & _
                                                    "SELECT 'INDEX_DOCTYPE','INDEX_DOCTYPE'"
            Dim DT = ClassDatabase.Return_Datatable(sql)
            STRING1ComboBox.DataSource = DT
            STRING1ComboBox.DisplayMember = DT.Columns(1).ColumnName
            STRING1ComboBox.ValueMember = DT.Columns(0).ColumnName

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

    Private Sub OLD_OBJECTTYPEComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles OLD_OBJECTTYPEComboBox.SelectedIndexChanged
        If Not OLD_OBJECTTYPEComboBox.Text = "" Then
            Load_StringBox2()
        End If
    End Sub

    Private Sub ToolStripButton7_Click(sender As Object, e As EventArgs) Handles ToolStripButton7.Click
        Try
            Dim msg = "Index Zuordnung gespeichert - " & Now.ToString
            If USER_LANGUAGE <> "de-DE" Then
                msg = "Index Mapping saved- " & Now.ToString
            End If
            lblSaveProfile.Text = msg
            Me.TBPMO_WD_IMPORT_PROFILE_IDXBindingSource.EndEdit()
            If DD_DMSDataSet.TBPMO_WD_IMPORT_PROFILE_IDX.GetChanges Is Nothing = False Then
                Me.CHANGED_WHOTextBox1.Text = USER_USERNAME
                Me.TBPMO_WD_IMPORT_PROFILE_IDXBindingSource.EndEdit()
                Me.TBPMO_WD_IMPORT_PROFILE_IDXTableAdapter.Update(Me.DD_DMSDataSet.TBPMO_WD_IMPORT_PROFILE_IDX)
                Me.lblSaveIDX.Visible = True
            Else
                Me.lblSaveIDX.Visible = False
            End If
        Catch ex As Exception
            MsgBox("Error in Save Index-Mapping:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub NEW_OBJECTTYPEComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles NEW_OBJECTTYPEComboBox.SelectedIndexChanged
        If NEW_OBJECTTYPEComboBox.Text = "" Or NEW_OBJECTTYPEComboBox.SelectedIndex = -1 Then Exit Sub
        Dim indexe = clsWD_GET.GetIndicesByObjecttype(OLD_OBJECTTYPEComboBox.Text)
        If indexe IsNot Nothing Then
            Me.IDX_FILE_WORKEDComboBox.Items.Add("")
            For Each index As String In indexe
                Select Case clsWD_GET.GetTypeOfIndexAsIntByName(index)
                    Case 4
                        Me.IDX_FILE_WORKEDComboBox.Items.Add(index)
                        'Case 1
                        '    Me.cmbCrFolderIndex.Items.Add(index)
                        '    cmbMOREDokumentart.Items.Add(index)
                        '    cmbMoReKundenindex.Items.Add(index)
                        'Case 2
                        '    Me.cmbCrFolderIndex.Items.Add(index)
                        '    cmbMOREDokumentart.Items.Add(index)
                        '    cmbMoReKundenindex.Items.Add(index)
                        'Case 5
                        '    Me.cmbCrFolderIndex.Items.Add(index)
                        '    cmbMOREDokumentart.Items.Add(index)
                        '    cmbMoReKundenindex.Items.Add(index)
                        'Case Else
                        'MsgBox(_windream.GetTypeOfIndexAsIntByName(index) & vbNewLine & index)

                End Select

            Next
            'Me.cmbIndexValidierung.SelectedIndex = -1
            'Me.cmbIndexValidierung.SelectedItem = 0
            'Me.cmbIndexFehler.SelectedIndex = -1
            'Me.cmbIndexFehler.SelectedItem = 0
            'Me.cmbCrFolderIndex.SelectedIndex = -1
            'Me.cmbCrFolderIndex.SelectedValue = 0
        End If
    End Sub
End Class