
Option Compare Text
Imports Microsoft.VisualBasic
Imports System
Imports System.IO
Imports System.Collections.Generic
Imports System.Data

Imports JF.PlmJobManager
Imports JF.PlmJobManager.JobServer

'' Information for developer:
'' # ---------------------------------------------------------------------------------------
'' # Documentation:
'' # Description  : Script fuer das Importieren der eMatrix Daten in den PlmJobManager
'' # Parameters   : ## /DataImport_DoExec=MyDataImport_DoExec /DataSync_DoExec=MyDataSync_DoExec
'' # History:
'' # Date         Person        ChangeInfo
'' # 06.10.2009   J.Fes         createt
'' # 26.01.2011   J.Fes         Datasync eingebaut
'' # 18.06.2012   J.Fes         Update auf aktuelle Version
'' # 20.10.2012   J.Fes         Obj.Attr.01 ECTR + Obj.Attr.02 Darstellung erweitert
'' # 03.03.2015   J.Fes         Import ber�cksichtigt jetzt das UGPARTS nach MAMO - GEN den UGMastern zugeornet werden
'' # ---------------------------------------------------------------------------------------
'' # ---------------------------------------------------------------------------------------
'' # Dokumentation:
'' # Vereinbarungen:
'' # Die Import Files sind abzulegen in das Verzeichis: JS_ScriptingInterface.ServerSettings.Dir_DataRoot_DP_30DataBase_22ItemInfoLists
'' # Die Importfiles m�ssen mit der erweiterung: *.csv enden


Namespace JS_GrotzBeckertImportData


	Public Class ScriptingEngineClass

		' Classen weite deklarationen
		Private Import_Obj As New JF.PlmJobManager.JobServer.Datasets_and_Irs_cls
		' #New 2.2.2015/J.Fes
        Private DSnonMaster_Obj As New JF.PlmJobManager.JobServer.Datasets_and_Irs_cls
        Private DSnonMasterIr_Obj As New JF.PlmJobManager.JobServer.Datasets_and_Irs_cls
        Private DSmaster_Obj As New JF.PlmJobManager.JobServer.Datasets_and_Irs_cls
        Private DSmasterIr_Obj As New JF.PlmJobManager.JobServer.Datasets_and_Irs_cls

        ' ##Debug: Variablen
        Private DebugAktive As Boolean = False
        Private DebugTestAktive As Boolean = False

        Private MyScriptOutput_frm As JobServer_ScriptRun_frm
		Private MyScriptTitle As String = "Groz Beckert eMatrix Datenimport 10.2009..03.03.2015 V1.5 [DebugMode:" + Me.DebugAktive.ToString + "] [TestMode:" + Me.DebugTestAktive.ToString + "] Start:[" + Now().tostring + "]"

        Private iText As String = ""
        Private Debug_Nlog As NLog.Logger = NLog.LogManager.GetLogger("DataSync")
        Dim MyCls_DataSource_Obj As New MyAppl_DataSource_cls("DataSync")

        '-- haelt die Zeit fest die der SiteDef hinterlegt wird um die Imort Startzeit zu definieren
        Dim ImportBeginDataTimeNew As DateTime

        '!!!!!!!!!!!!!!!!!! ---------------- wichtige Konstanten 27.01.2011 J.Feuerstein ------------------ !!!!!!!!!!!!!!!!!!!!!!!!!!
        ''' <summary>
        ''' legt fest von welche SiteDef Daten eingelesen werden siehe auch Sites/Data Import --> SiteDef "mxgb"
        ''' </summary>
        Private Const SiteIDCurr As String = "mxgb"             '
        ''' <summary>
        ''' legt fest mit welcher Db MQL arbeitet siehe auch Sites/Data Import --> SiteDef "mxgb"
        ''' </summary>
        Private Const MatrixSiteId As String = "MATRIX-R.prod"

        ''' <summary>
        ''' legt fest um wieviel Minuten versetzt ein DataImport vom der Imp.DataModBegin Zeit wieder begonnen werden soll
        ''' </summary>
        Private DataImportStartRevertMinutes As Integer = 30

        Private FileItemRenameToAfterImportDone_DPNE As String

        Dim Headline_Return As New JF.Tools.JF_Return_cls
        Dim ImportRun_Return As New JF.Tools.JF_Return_cls
        Dim Footline_Return As New JF.Tools.JF_Return_cls
        Dim ResultReturn As New JF.Tools.JF_Return_cls

        Dim JS_ScriptingInterface As ScriptingInterface.Methodes

        '-- Typen des Import's
        Enum ImportType_enum
            UGMaster
            NonUGMaster
        End Enum

        Dim LogF_Protocol_DPNE As String
        Dim LogF_EntireData_DPNE As String
        Dim LogF_ActionInsertData_DPNE As String
        Dim LogF_ActionEctr_DPNE As String
        Dim LogF_ActionUpdateData_DPNE As String
        Dim LogF_ActionDeleteData_DPNE As String

        '-- Site Def
        Dim SiteDef_Obj As New SiteDef_cls

        '--------------------------------------------------------------------------------------
        Public Function ScriptMain(ByVal JS_ScriptingInterface_p As ScriptingInterface.Methodes) As JF.Tools.JF_Return_cls

            Me.JS_ScriptingInterface = JS_ScriptingInterface_p

            'Dim I As Integer

            '-- using "standard form" for printing script informations
            MyScriptOutput_frm = New JobServer_ScriptRun_frm(Me.JS_ScriptingInterface.ScriptDef)
            MyScriptOutput_frm.Show()
            MyScriptOutput_frm.Text = MyScriptTitle


            '-- Liste der LogFiles ----------------------------------
            LogF_Protocol_DPNE = LogFileGet_DPNE(LogFile_Enum.Protocol)
            LogF_EntireData_DPNE = LogFileGet_DPNE(LogFile_Enum.Entire)
            LogF_ActionInsertData_DPNE = LogFileGet_DPNE(LogFile_Enum.InsertData)
            LogF_ActionUpdateData_DPNE = LogFileGet_DPNE(LogFile_Enum.UpdateRequired)
            LogF_ActionDeleteData_DPNE = LogFileGet_DPNE(LogFile_Enum.DeleteData)
            LogF_ActionEctr_DPNE = LogFileGet_DPNE(LogFile_Enum.Ectr)

            '-- parsing parameters
            Dim DataImport_DoExec As String = JS_ScriptingInterface.ParameterValueGet("DataImport")
            Dim DataSync_DoExec As String = JS_ScriptingInterface.ParameterValueGet("DataSync")
            Dim DataSyncStart As String = JS_ScriptingInterface.ParameterValueGet("DataSyncStart")
            Dim DataSyncStartDateTime As DateTime

            If JS_ScriptingInterface.ParameterValueGet("DebugAktiv") = "true" Then DebugAktive = True
            If JS_ScriptingInterface.ParameterValueGet("DebugTestAktive") = "true" Then DebugTestAktive = True


            '-- handling Exeptions ---------------
            Try

                Me.MyScriptOutput_frm.InfoSysHeader.PrintInfoLine(MyScriptTitle)
                Me.MyScriptOutput_frm.InfoSysProtocol.PrintInfoLine(MyScriptTitle)

                '-- einlesen der aktuellen SiteDef_Obj Data
                SiteDef_Obj = MyCls_DataSource_Obj.Sites_tbl_SiteDefGet_by_SiteId(SiteIDCurr)
                ImportBeginDataTimeNew = SiteDef_Obj.ImportItemLastModifyDateBegin

                '-- ermittelt die DataSyncStart bzw legt diese fest
                '   Es gelten folgende Regeln:
                '       - wenn Datum aus Parameter /DataSyncStart="25.02.2011 08:00" geparst werden kann dann wird dieses genommen
                '       - ist der Parameter nicht angegeben oder kann das Datum nicht erfolgreich geparst werden so wird die Zeit aus SiteDef_Obj.ImportItemLastModifyDateBegin.AddMinutes(-??) genommen
                DataSyncStartDateTime = JF.Tools.CTypeTryDefault(Of DateTime)(DataSyncStart, SiteDef_Obj.ImportItemLastModifyDateBegin.AddMinutes(-2 * 60))

                '-- Header Info erzeugen
                LogF_AddLine(LogF_Protocol_DPNE, MyScriptTitle, True, True)
                LogF_AddLine(LogF_Protocol_DPNE, "----------------------------------------------------------------------------", True, True)
                LogF_AddLine(LogF_Protocol_DPNE, "Execute...: " + MyScriptTitle, True, True, True)
                LogF_AddLine(LogF_Protocol_DPNE, "Script....: " + JF.Tools.JF_ToolsFile.ParsePath_NE(JS_ScriptingInterface.ScriptDef.Script_DPNE), True, True, True)
                LogF_AddLine(LogF_Protocol_DPNE, "Params....: " + "/DataImport=" + DataImport_DoExec + " /DataSync=" + DataSync_DoExec + " /DataSyncStartDateTime=" + DataSyncStart, True, True, True)
                LogF_AddLine(LogF_Protocol_DPNE, "Param.....: ausgewertet: /DataSyncStartDateTime=" + DataSyncStartDateTime.ToString, True, True, True)
                LogF_AddLine(LogF_Protocol_DPNE, "SysLog....: " + JS_ScriptingInterface.ServerSettings.Dir_DataRoot_DP_10JobLogArchiv, True, True, True)
                LogF_AddLine(LogF_Protocol_DPNE, "JobLog....: " + JF.Tools.JF_ToolsFile.ParsePath_DP(LogF_Protocol_DPNE), True, True, True)
                LogF_AddLine(LogF_Protocol_DPNE, "DebugActiv: " + DebugAktive.ToString, True, True, True)
                LogF_AddLine(LogF_Protocol_DPNE, "DebugTest.: " + DebugTestAktive.ToString, True, True, True)
                LogF_AddLine(LogF_Protocol_DPNE, "----------------------------------------------------------------------------", True, True, True)

                If Not DebugTestAktive Then
                    If JF.Tools.JF_ToolsString.StringEnvironValuesGet("%MXHOME%") = "%MXHOME%" Then
                        'MyScriptOutput_frm.InfoSysProtocol.PrintEx(ex, Footline_Return.ExMsg)
                        iText = "ERR: cannot Run Script missing Environ Var:[%MXHOME%]"
                        Footline_Return.ResultMsgAdd(iText)
                        LogF_AddLine(LogF_Protocol_DPNE, iText, True, True)
                        GoTo EndOfScript
                    End If
                End If

                '-- LogFiles bereitstellen
                LogF_AddLine(LogF_EntireData_DPNE, MyScriptTitle)
                LogF_AddLine(LogF_ActionEctr_DPNE, MyScriptTitle)
                LogF_AddLine(LogF_ActionUpdateData_DPNE, MyScriptTitle)
                LogF_AddLine(LogF_ActionDeleteData_DPNE, MyScriptTitle)

                ' LogF_AddLine(LogF_Protocol_DPNE, "LogFile...: " + LogF_Protocol_DPNE, True, True)
                LogF_AddLine(LogF_Protocol_DPNE, "Protocol..: " + LogF_Protocol_DPNE, True, True)
                LogF_AddLine(LogF_EntireData_DPNE, LogF_EntireData_DPNE, True)
                LogF_AddLine(LogF_ActionEctr_DPNE, LogF_ActionEctr_DPNE, True)
                LogF_AddLine(LogF_ActionUpdateData_DPNE, LogF_ActionUpdateData_DPNE, True)
                LogF_AddLine(LogF_ActionDeleteData_DPNE, LogF_ActionDeleteData_DPNE, True)


                '-- CALL DataImport ------------------------------------
                If DataImport_DoExec.ToUpper = "TRUE" Then
                    Call Me.DataImport()
                End If

                If DataSync_DoExec.ToUpper = "TRUE" Then
                    Call Me.DataSync(DataSyncStartDateTime, now())
                End If

                '-- ImportItemLastModifyDateBegin in Db neu setzen
                If ImportBeginDataTimeNew > SiteDef_Obj.ImportItemLastModifyDateBegin Then
                    SiteDef_Obj.ImportItemLastModifyDateBegin = ImportBeginDataTimeNew.AddMinutes(0)
                    '#Doc Update 20.10.2014 MyCls_DataSource_Obj.Sites_tbl_SiteDef_InsertOrUpdate_by_PName(SiteDef_Obj)
                    MyCls_DataSource_Obj.Sites_tbl_SiteDef_InsertOrUpdate_by_SiteID(SiteDef_Obj)
                End If

                iText = String.Format(vbcrlf + "Exit: Imp.Data.ModBegin gesetzt auf:[{1}]", _
                    SiteDef_Obj.SiteInfoWith_SiteId_and_pName, _
                    SiteDef_Obj.ImportItemLastModifyDateBegin, _
                    now())
                LogF_AddLine(LogF_Protocol_DPNE, iText, True, True, True)



            Catch ex As Exception
                Footline_Return.Ex = ex
                Footline_Return.ExUp = True
                'Footline_Return.ExMsg = "ScriptTemplate"
                MyScriptOutput_frm.InfoSysProtocol.PrintEx(ex, Footline_Return.ExMsg)
                Footline_Return.ResultMsgAdd(Footline_Return.ResultMsgEvaluate)
                GoTo EndOfScript
            End Try

            '-- returning results


            '--------------------------------------------------------------------------
EndOfScript:

            Call MyScriptOutput_frm.InfoSysProtocol.PrintInfoLine("")
            Call LogF_AddLine(LogF_Protocol_DPNE, ResultReturn.ResultMsg)

            If DebugAktive Or DebugTestAktive Then
                MyScriptOutput_frm.Pause("##DebugAktive: click me and script will end")
            End If


            '-- setting the progress bar to idel
            Call MyScriptOutput_frm.InfoSysProtocol.StatusBarProgressBarSetIdle()

            '-- closing the ScriptRun form
            MyScriptOutput_frm.Close()
            MyScriptOutput_frm.Dispose()

            ResultReturn.ResultMsgClear()
            ResultReturn.ResultMsgAdd(Headline_Return.ResultMsg)
            ResultReturn.ResultMsgAdd(ImportRun_Return.ResultMsg)
            ResultReturn.ResultMsgAdd(Footline_Return.ResultMsg)


            Return ResultReturn
        End Function


        '-----------------------------------------------------------------------------------------------------------------
        ''' <summary>
        ''' Organisiert den Datenimport aus eMatrix nach JS Db (Stand 4.3.2011)
        ''' </summary>
        Private Sub DataImport()


            ' Beschreibung:
            '
            ' Dieses Script steuert den DatenImport von eMatrix in die JobMgr Db.
            '
            ' - zu importierenden Daten werden via MQL aus eMatrix in ein File exportiert.
            ' - die Daten diese Files wird in die JobMgr Db importiert
            ' - Welche Daten aus eMatric exportiert werden wird via Start Datum festgelegt.

            'System.Diagnostics.Debugger.Break()

            '-- starting the progress bar
            MyScriptOutput_frm.InfoSysProtocol.StatusBarProgressBarStart()
            MyScriptOutput_frm.InfoSysProtocol.StatusBarSetCurrActionInfo_Panel1("Import")

            '-- Headline Info schreiben
            iText = String.Format("Step: Import: SiteDef_Obj:{0} Import sucht Start ab Zeitpunkt:[{1}] P.StartTime:[{2}]", _
                SiteDef_Obj.SiteInfoWith_SiteId_and_pName, _
                SiteDef_Obj.ImportItemLastModifyDateBegin, _
                now())
            ' LogF_AddLine("DebugTest.: " + LogF_Protocol_DPNE, iText, True, True, True)
            LogF_AddLine(LogF_Protocol_DPNE, iText, True, True, True)

            '-- erstelle File Obj fuer "DataImport_ByTime.txt"
            Dim FileList As System.Collections.ObjectModel.ReadOnlyCollection(Of String)
            Dim ExportFileSearch_WildCard_NE As String = ""
            Dim DateImportStart As String
            Dim DataImport_TimeStartFile_Obj As New JF.Tools.JF_ToolsFile.JF_FileProcessing_cls( _
                path.Combine(JS_ScriptingInterface.ServerSettings.Dir_DataRoot_DP_30DataBase_22ItemInfoLists, "DataImport_ByStartDateTime.txt"))

            '-- MQL Eingabe File Import By Numbers
            Dim DataImport_ByNumbers_Obj As New JF.Tools.JF_ToolsFile.JF_FileProcessing_cls( _
                path.Combine(JS_ScriptingInterface.ServerSettings.Dir_DataRoot_DP_30DataBase_22ItemInfoLists, "DataImport_ByNumbers.txt"))

            '-- schreiben des MQL Start Datum in : ".\DataImport_ByTime.txt"
            '-- 11.10.2011 J.Fes DateImportStart verlegt vor if DataImport_ByNumbers_Obj.FileDef.File_Exists Then ...
            DateImportStart = ConvertDateTimeFor_eMatrix(SiteDef_Obj.ImportItemLastModifyDateBegin.AddMinutes(-1 * DataImportStartRevertMinutes))
            If Me.DebugTestAktive Then
                ' ## Debug:
                DateImportStart = ConvertDateTimeFor_eMatrix(now().AddMinutes(-30))
            End If


            If DataImport_ByNumbers_Obj.FileDef.File_Exists Then
                '-- Step: via:MQL Daten aus eMatrix exportieren
                ImportRun_Return = MqlExecute(String.Format("DataImport ByNumbers:[{0}]", DateImportStart), _
                    String.Format("exec prog SYS_RefilePart OBJECTINFO -i {0}", DataImport_ByNumbers_Obj.FileDef.File_DPNE), True)
                Call Me.FileItem_DPNE_MoveToArchiv(DataImport_ByNumbers_Obj.FileDef.File_DPNE)
            End If


            '-- Step: via:MQL aDaten ab Start DateTime in export Datei schreiben lassen
            If Not DateImportStart Is Nothing Then
                '-- Step: schreiben des StartDatum in die Datei
                DataImport_TimeStartFile_Obj.ListOfString_AddString(DateImportStart)
                DataImport_TimeStartFile_Obj.FileWriteAllText(False)
                'MyScriptOutput_frm.Pause(string.Format("#Debug: DateImportStart:[{0}] [{1}]" , DateImportStart, SiteDef_Obj.ImportItemLastModifyDateBegin.AddMinutes(-1 * DataImportStartRevertMinutes)))

                ImportRun_Return = MqlExecute(String.Format("DataImport begin:[{0}]", DateImportStart), _
                    String.Format("exec prog SYS_RefilePart OBJECTINFO -d {0}", DataImport_TimeStartFile_Obj.FileDef.File_DPNE), True)
            End If

            If DebugAktive Then
                ExportFileSearch_WildCard_NE = "*Test*.csv"
            Else
                '"DataImport_ByStartDateTime*.csv"
                ExportFileSearch_WildCard_NE = DataImport_TimeStartFile_Obj.FileDef.File_N + "*.csv" + ";" + _
                    DataImport_ByNumbers_Obj.FileDef.File_N + "*.csv"
            End If

            iText = "Step: Search ImportFiles:" + JS_ScriptingInterface.ServerSettings.Dir_DataRoot_DP_30DataBase_22ItemInfoLists + path.DirectorySeparatorChar + ExportFileSearch_WildCard_NE
            LogF_AddLine(LogF_Protocol_DPNE, iText)

            FileList = My.Computer.FileSystem.GetFiles(JS_ScriptingInterface.ServerSettings.Dir_DataRoot_DP_30DataBase_22ItemInfoLists, FileIO.SearchOption.SearchTopLevelOnly, _
                ExportFileSearch_WildCard_NE.Split(";"c))

            If FileList.Count > 0 Then

                Dim FileObj As New JF.Tools.JF_ToolsFile.JF_FileProcessing_cls("")

                '-- Step: Import:[UGMaster] aus allen Files
                For Each FileItem_DPNE As String In FileList
                    FileObj.ResetToDefaultVaule()
                    FileObj.FileDef.File_DPNE = FileItem_DPNE
                    iText = "Step: import UGMaster...:" + JF.Tools.JF_ToolsFile.ParsePath_NE(FileItem_DPNE)
                    LogF_AddLine(LogF_Protocol_DPNE, iText)
                    Me.MyScriptOutput_frm.InfoSysHeader.Print(iText)
                    Me.MyScriptOutput_frm.InfoSysProtocol.Print_and_StatusBarSetCurrActionStatusInfo_Panel3(iText)
                    Call Me.ObjectsDoImport(FileObj, ImportType_enum.UGMaster)
                Next

                '-- Step: Import:[NON UGMaster] aus allen Files
                For Each FileItem_DPNE As String In FileList
                    FileObj.ResetToDefaultVaule()
                    FileObj.FileDef.File_DPNE = FileItem_DPNE
                    iText = "Step: import NonMaster..:" + FileObj.FileDef.File_NE
                    LogF_AddLine(LogF_Protocol_DPNE, iText)
                    MyScriptOutput_frm.InfoSysHeader.Print(iText)
                    MyScriptOutput_frm.InfoSysProtocol.Print_and_StatusBarSetCurrActionStatusInfo_Panel3(iText)
                    Call Me.ObjectsDoImport(FileObj, ImportType_enum.NonUGMaster)
                    Call Me.FileItem_DPNE_MoveToArchiv(FileItem_DPNE)
                Next
            Else
                MyScriptOutput_frm.InfoSysProtocol.Print("No Files to process:")
            End If

            iText = String.Format("Step: Import: SiteDef_Obj:{0} Import P.EndeTime:[{2}]", _
                SiteDef_Obj.SiteInfoWith_SiteId_and_pName, _
                SiteDef_Obj.ImportItemLastModifyDateBegin, _
                now())
            LogF_AddLine(LogF_Protocol_DPNE, iText, True, True, True)


        End Sub


        '-----------------------------------------------------------------------------------------------------------------
        ''' <summary>
        ''' DataSync Modul neu erstellt 26.01.2011 J.Fes
        ''' </summary>
        Private Sub DataSync(ByVal SyncSegDateTimeStartFrom As DateTime, _
            ByVal SyncSegDateTimeEnd As DateTime)

            Dim I As Integer

            Dim SyncSegBegin As DateTime
            Dim SyncSegEnde As DateTIme
            Dim SyncSegRangeMinutes As Integer

            Dim Datasets_and_Irs_RevObj As New JF.PlmJobManager.JobServer.Datasets_and_Irs_cls


            Dim Datasets_and_Irs_ObjLi As New List(Of JF.PlmJobManager.JobServer.Datasets_and_Irs_cls)
            Dim Datasets_and_Irs_ObjLi_ToDelete As New List(Of JF.PlmJobManager.JobServer.Datasets_and_Irs_cls)
            Dim Datasets_and_Irs_ObjLi_EcrtSet As New List(Of JF.PlmJobManager.JobServer.Datasets_and_Irs_cls)

            '-- 18.06.2012 angepasst J.Fes
            '-- Dim ObjectCliName_Parse_Obj As JF.PlmJobManager.JobServer.ObjectCliName_cls '.ObjectCliName_cls '.Parse_cls("")
            Dim MqlOiQ_IFile_Obj As New JF.Tools.JF_ToolsFile.JF_FileProcessing_cls("")
            Dim MqlOiQ_OFile_Obj As New JF.Tools.JF_ToolsFile.JF_FileProcessing_cls("")
            Dim MqlOiQ_Process As New System.Diagnostics.Process


            Dim iCur As Integer = 0
            Dim iSum As Integer = 0

            '-- Legt die Anzahl der Objekte fest die je Lauf verarbeitet werden sollen (MQL QUICKINFO..)
            Dim PaketSizeN As Integer = 250

            Dim PacketNum As Integer = 0
            Dim DeleteObjectsN As Integer = 0
            Dim DataReaderIsReading As Boolean = False
            Dim ActionToDo As String

            Dim FileLineItems As String()
            Dim ECTRflag As Boolean
            Dim Object_UpdateDo_ReasonLastModeDateDiffs As Boolean

            Dim GetDSResult_Obj As New JF.Tools.JF_Return_cls

            '-- Headline Info schreiben
            iText = String.Format("Info: f�r Site[{0}] DataSync ausf�hren f�r den Zeitraum von:[{1}] bis:[{2}]", _
                SiteDef_Obj.SiteInfoWith_SiteId_and_pName, _
                SyncSegDateTimeStartFrom, _
                SyncSegDateTimeEnd)
            LogF_AddLine(LogF_Protocol_DPNE, iText, , , True)


            '-- SyncSegEnde muss zur initaliesierung gesetzt werden
            SyncSegEnde = SyncSegDateTimeStartFrom
            ImportBeginDataTimeNew = SyncSegEnde
            Dim SyncSegCount As Integer = 0

            Do '-- ZeitSegment Loop

                System.Windows.Forms.Application.DoEvents()

                SyncSegBegin = SyncSegEnde
                SyncSegCount += 1

                '   lesen der Daten im Zeitsegment beginend:[SyncSegBegin] ende:[SyncSegBegin + SyncSegRangeMinutes]
                SyncSegRangeMinutes = 12 * 60 ' = 12 Std
                SyncSegRangeMinutes = 24 * 60 * 7 ' = 7 Tage
                SyncSegEnde = SyncSegBegin.AddMinutes(SyncSegRangeMinutes)
                iText = String.Format("Process SyncSegCount:[{0:00#}] SyncSegBegin:[{1}] SyncSegEnde:[{2}]", _
                    SyncSegCount, _
                    SyncSegBegin, _
                    SyncSegEnde)
                LogF_AddLine(LogF_Protocol_DPNE, iText, True, , True)
                LogF_AddLine(LogF_EntireData_DPNE, "------------- " + iText + " -------------")

                Datasets_and_Irs_ObjLi_ToDelete.Clear()
                Datasets_and_Irs_ObjLi_EcrtSet.Clear()

                '-- Datareader erstellen (angepasst 16.2.2011 J.Fes)
                Dim IrsJs_Sql_DbDataReader As System.Data.Common.DbDataReader
                IrsJs_Sql_DbDataReader = MyCls_DataSource_Obj.Objects_tbl_DataReaderGet( _
                    SiteDef_Obj, _
                    JF.PlmJobManager.JobServer.ObjectClass_enum.DS, _
                    SyncSegBegin, _
                    SyncSegEnde)
                iCur = 0

                Do '-- DataReader Loop

                    DataReaderIsReading = IrsJs_Sql_DbDataReader.Read
                    Dim Datasets_and_Irs_ObjCur As New Datasets_and_Irs_cls


                    If DataReaderIsReading Then
                        iCur += 1
                        iSum += 1
                        ' 11.10.2011 Version angepasst auf JS V2.864
                        Call MyCls_DataSource_Obj.Objects_tbl_DataReader_TransData_To_Datasets_and_Irs_Obj( _
                        IrsJs_Sql_DbDataReader, Datasets_and_Irs_ObjCur, ObjectClass_enum.DS, True)

                        '-- hinzufuegen der Datasets_and_Irs_ObjCur zu Datasets_and_Irs_ObjLi
                        Datasets_and_Irs_ObjLi.Add(Datasets_and_Irs_ObjCur)

                        '-- schreiben aller Datens�tze in den LogEntireData File !!!
                        iText = String.Format("iSum:[{0}];ObjectCLiName:[{1}];LastModDate:[{2}]", _
                            iSum, _
                            Datasets_and_Irs_ObjCur.ObjectCliName, _
                            Datasets_and_Irs_ObjCur.ObjectLastModDate)
                        LogF_AddLine(LogF_EntireData_DPNE, iText, False, DebugTestAktive)

                        '-- Last Begin Update Time festhalten
                        If Datasets_and_Irs_ObjCur.ObjectLastModDate > ImportBeginDataTimeNew Then
                            ImportBeginDataTimeNew = Datasets_and_Irs_ObjCur.ObjectLastModDate
                        End If
                    End If


                    If JF.Tools.JF_Tools.EveryTimeDoEvaluate(iCur, PaketSizeN, 0) Or (DataReaderIsReading = False And iCur > 0) Then
                        '-- Step: Die Daten eines Packetes zusammenstellen und verarbeiten
                        PacketNum += 1
                        MqlOiQ_IFile_Obj.ResetToDefaultVaule()
                        MqlOiQ_IFile_Obj.FileDef.File_DPNE = JF.Tools.JF_ToolsString.StringEnvironValuesGet(path.Combine("%temp%", "OiQ_List_" + PacketNum.ToString("000") + ".txt"))
                        MqlOiQ_OFile_Obj.FileDef.File_DPNE = JF.Tools.JF_ToolsFile.ParsePath_DPN(MqlOiQ_IFile_Obj.FileDef.File_DPNE) + "_mx_ObjectInfoQuick.csv"

                        '-- Step: alle Objecte als Paket verarbeiten
                        For Each Datasets_and_Irs_ObjLi_Item As Datasets_and_Irs_cls In Datasets_and_Irs_ObjLi
                            '-- Parsen des ObjectNames aus der JobManager DB
                            ' #Doc: Stand bis 18.06.2012: siehe \\G11004965\JobManagerV2\90-DATA\GB_SettingsGlobal\40-JobServerScripts\GrozBeckert_MxData_Import-2012-06-18.vb
                            MqlOiQ_IFile_Obj.ListOfString_AddString(Datasets_and_Irs_ObjLi_Item.ObjectName)
                        Next
                        '-- ##Debug: Nummern fuer suche der Objekte: ug0001246314;ug0001624385;ug0001546063;
                        'MqlOiQ_IFile_Obj.ListOfString_AddString("ug0001246314") 'ug0001246314;ug0001246314;25.3.2010:14:13:50;25.03.2010:14:13;TRUE  hat EctrFlag
                        'MqlOiQ_IFile_Obj.ListOfString_AddString("ug0001246315")
                        'MqlOiQ_IFile_Obj.ListOfString_AddString("ug0001624385") 'ug0001624385;ug0001624385;1.1.1900:00:00:00;1.1.1900:00:00:00;NotExist
                        'MqlOiQ_IFile_Obj.ListOfString_AddString("ug0001624384") 'ug0001624385;ug0001624385;1.1.1900:00:00:00;1.1.1900:00:00:00;NotExist
                        'MqlOiQ_IFile_Obj.ListOfString_AddString("ug0001546063") 'ug0001546063;ug0001624885;12.11.2010:08:44:48;12.11.2010:08:44;FALSE

                        '-- Step: MqlProcess MqlInput File schreiben
                        MqlOiQ_IFile_Obj.FileWriteAllText(False)

                        '-- Step: Daten aus eMatix via Mql abfragen
                        ImportRun_Return = MqlExecute(String.Format("Paket:[{0}]", PacketNum), _
                            String.Format("exec prog SYS_RefilePart OBJECTINFOQUICK -i {0}", MqlOiQ_IFile_Obj.FileDef.File_DPNE), True)

                        '-----------------------------------------------------------------------------------
                        '-- Step: MqlOiQ_OFile_Obj.FileDef.File_DPNE verarbeiten
                        MqlOiQ_OFile_Obj.ResetToDefaultVaule()
                        MqlOiQ_OFile_Obj.FileReadAllText()

                        iText = String.Format("MqL FileLines N: [{0}]", MqlOiQ_OFile_Obj.ListOfString_LinesWithOutEmpty_TextLines.Count)
                        LogF_AddLine(LogF_Protocol_DPNE, iText)

                        ' Aufbau MQL ReturnDataFile:
                        ' UgFileName-0 Modell-1     LastModDate-2       CheckInDate-3    ECTRflag-4 (wenn ECTR=FALSE dann do refile else NO refile)
                        ' ug0001596020;ug0001603582;18.11.2010:12:06:30;18.11.2010:12:08;FALSE
                        ' ug0001591833;ug0001604660;18.11.2010:12:06:33;18.11.2010:12:08;FALSE
                        ' ug0001595301;ug0001608962;18.11.2010:12:06:36;18.11.2010:12:08;FALSE
                        ' ug0001608974NixDa;ug0001608974NixDa;NotExist

                        For Each FileLine As String In MqlOiQ_OFile_Obj.ListOfString_LinesWithOutEmpty_TextLines

                            iText = "MqL FileLine:" + FileLine
                            LogF_AddLine(LogF_EntireData_DPNE, iText)

                            FileLineItems = FileLine.Split(";"c)
                            Dim Datasets_and_Irs_Obj As New JF.PlmJobManager.JobServer.Datasets_and_Irs_cls

                            If FileLineItems.Length >= 4 Then
                                '-- ersetzungen durchfuehren
                                For I = 0 To FileLineItems.Length - 1
                                    ' #Chr(59)# -> ersetzen zu ;
                                    FileLineItems(I) = FileLineItems(I).Replace("#Chr(59)#", chr(59))
                                Next
                                Object_UpdateDo_ReasonLastModeDateDiffs = False

                                '-- Werte auf Datasets_and_Irs_Obj uebertragen
                                With Datasets_and_Irs_Obj
                                    .ResetToDefaultValue()

                                    .ItemName = FileLineItems(0)
                                    .IrRev = "0"

                                    '-- UgFileName
                                    .ObjectName = FileLineItems(1)
                                    '-- Last ModDate wird genommen aus CheckInDate-3
                                    .ObjectClass = JF.PlmJobManager.JobServer.ObjectClass_enum.DS
                                    .ObjectFromSiteId = SiteIDCurr
                                    .ObjectLastModDate = ConvertDateTime(FileLineItems(3))
                                    ActionToDo = FileLineItems(4).ToUpper

                                    '-- lesen der Datasets_and_Irs_Obj Daten aus JobMgr Db
                                    GetDSResult_Obj = MyCls_DataSource_Obj.Objects_tbl_GetDS(Datasets_and_Irs_Obj)


                                    '-- Aktionen auf Objekt fetlegen
                                    Select Case ActionToDo

                                        Case "FALSE"  'ECTRflag-4 = FALSE dann Object belassen wie es ist
                                            ECTRflag = False
                                            iText = String.Format("ObjectCli:[{0}];(ECTRflag=False);Aktion:[Nothing to DO]", Datasets_and_Irs_Obj.ObjectCliName)

                                        Case "TRUE"   'ECTRflag-4 = FALSE dann eXclude all P.Status
                                            ECTRflag = True
                                            Datasets_and_Irs_ObjLi_EcrtSet.Add(Datasets_and_Irs_Obj)
                                            iText = String.Format("ObjectCli:[{0}];(ECTRflag=True);Aktion:[Set ProcessCol01..10=X and ECTR]", Datasets_and_Irs_Obj.ObjectCliName)
                                            LogF_AddLine(LogF_ActionEctr_DPNE, iText, , True)
                                            LogF_AddLine(LogF_Protocol_DPNE, iText)

                                        Case "NOTEXIST"
                                            ' object auf die loeschen Liste legen
                                            DeleteObjectsN += 1
                                            Datasets_and_Irs_ObjLi_ToDelete.Add(Datasets_and_Irs_Obj)
                                            iText = (String.Format(FileLine + " Object:[{0}] (NotExist in gbmx) Aktion:[Delete Object in JS DB]", Datasets_and_Irs_Obj.ObjectName))
                                            LogF_AddLine(LogF_ActionDeleteData_DPNE, FileLine + " " + iText)
                                            LogF_AddLine(LogF_Protocol_DPNE, iText)
                                    End Select
                                End With

                                ' Referenz Object suchen
                                ' Datasets_and_Irs_RevObj = Datasets_and_Irs_ObjLi.Contains()
                                '-- wer muss upgedatet werden if Datasets_and_Irs_Obj.ObjectLastModDate >
                            End If
                        Next

                        '-- clear Datasets_and_Irs_ObjLi da jetzt wieder ein neues Paket erstellt wird
                        Datasets_and_Irs_ObjLi.Clear()
                    End If

                Loop Until DataReaderIsReading = False '-- DataReader Loop
                IrsJs_Sql_DbDataReader.Close()

                '-- Alle Objekte loeschen die geloescht werden muessen. Info kann erst nach dem durchfuehren des Datareaders gemacht werden
                For Each DsIr_toDel As JF.PlmJobManager.JobServer.Datasets_and_Irs_cls In Datasets_and_Irs_ObjLi_ToDelete
                    GetDSResult_Obj.ResetToDefaultValues()
                    GetDSResult_Obj = MyCls_DataSource_Obj.Objects_tbl_DeleteData( _
                        JF.PlmJobManager.JobServer.ObjectDeleteMethod_enum.M3_DSS, DsIr_toDel)
                    Call ImportRun_DebugPrint(String.Format("Object:[{0}] delete from JS DB", _
                    DsIr_toDel.ObjectCliNameForOutput) + " Result:[" + GetDSResult_Obj.ResultMsgEvaluate + "]")
                Next

                '-- Alle Objecte auf ECTR setzen die auf ECTR gesetzt werden m�ssen
                Call MyScriptOutput_frm.InfoSysProtocol.StatusBarProgressBarStart("ECTR Update")
                For Each DsIr_toEcrtSet As JF.PlmJobManager.JobServer.Datasets_and_Irs_cls In Datasets_and_Irs_ObjLi_EcrtSet
                    GetDSResult_Obj = DsIr_toEcrt(DsIr_toEcrtSet)
                Next

            Loop Until SyncSegEnde > SyncSegDateTimeEnd '-- ZeitSegment Loop

            Call MyScriptOutput_frm.InfoSysProtocol.StatusBarProgressBarSetIdle()

        End Sub

        '-----------------------------------------------------------------------------------------------------------------
        Private Function DsIr_toEcrt(ByVal DsIr_toEcrtSet As JF.PlmJobManager.JobServer.Datasets_and_Irs_cls) As JF.Tools.JF_Return_cls

            Dim GetDSResult_Obj As New JF.Tools.JF_Return_cls

            '-- alle ProcessStats auf Excludet setzen (21)
            DsIr_toEcrtSet.ImportObjectNewProcStateMask = ""
            For I As Integer = 1 To 21
                'DsIr_toEcrtSet.ImportObjectNewProcStateMask += "X234567890"
                DsIr_toEcrtSet.ImportObjectNewProcStateMask += "X         "
            Next

            DsIr_toEcrtSet.ImportObjectUpdProcStateMask = DsIr_toEcrtSet.ImportObjectNewProcStateMask


            '-- 28.1.2011 diese funktion muss gepueft werden !!
            '-- Step:  Alle ProcessCol auf X setzen ProcessCol01..10
            For i As Integer = 1 To 20
                GetDSResult_Obj = MyCls_DataSource_Obj.Objects_tbl_UpdateColumeValue_by_ID(DsIr_toEcrtSet.ID.ToString, "ProcStateCol" + i.ToString("0#"), "X")
            Next
            '-- Step:  Alle ProcessCol auf X setzen ProcessColRf
            GetDSResult_Obj = MyCls_DataSource_Obj.Objects_tbl_UpdateColumeValue_by_ID(DsIr_toEcrtSet.ID.ToString, "ProcStateColRf", "X")
            '-- Step:  ObjectSelectByMarker = ECTR
            GetDSResult_Obj = MyCls_DataSource_Obj.Objects_tbl_UpdateColumeValue_by_ID(DsIr_toEcrtSet.ID.ToString, "ObjectSelectByMarker", "ECTR")
            Return GetDSResult_Obj
        End Function




        '-----------------------------------------------------------------------------------------------------------------
        ''' <summary>
        ''' Temp Sub fur das ausgeben der debug meldungen
        ''' </summary>
        Private Sub ImportRun_DebugPrint(ByVal MsgText_p As String)
            If DebugAktive Then
                ImportRun_Return.ResultMsgAdd("##debug: " + MsgText_p)
                Me.MyScriptOutput_frm.InfoSysProtocol.Print(ImportRun_Return.ResultMsgLast)
            End If
        End Sub

        '-----------------------------------------------------------------------------------------------------------------
        ''' <summary>
        ''' Konvertiert  "1.2.2007:18:02:56" --> "1.2.2007 18:02:56"
        ''' </summary>
        ''' <returns></returns>
        Private Function ConvertDateTime(ByRef DateRead_p As String) As DateTime
            'dim DateRead As string ="1.2.2007:18:02:56"
            Dim DateReadItems As String()
            Dim DateReadReturn As String = DateRead_p
            DateReadItems = DateRead_p.Split(CChar(":"))

            If DateReadItems.Length = 4 Then
                DateReadReturn = DateReadItems(0) + " " + DateReadItems(1) + ":" + DateReadItems(2) + ":" + DateReadItems(3)
            End If

            Return JF.Tools.CTypeTryDefault(Of DateTime)(DateReadReturn, now())
            ' Return JF.Tools.JF_Convert.JF_CDate(DateReadReturn,now())
        End Function


        ''' <summary>
        ''' Konvertiert  "1.2.2007 18:02:56" --> "1.2.2007:18:02:56"
        ''' </summary>
        ''' <returns></returns>
        Private Function ConvertDateTimeFor_eMatrix(ByRef DateTime_p As DateTime) As String
            With DateTime_p
                Return .Day.ToString("0#") + "." + .Month.ToString("0#") + "." + .Year.ToString("0#") + _
                ":" + .Hour.ToString("0#") + ":" + .Minute.ToString("0#") + ":00"
            End With

        End Function

        '-------------------------------------------------------------------------------------------
        ''' <summary>
        ''' Executes MQL command
        ''' </summary>
        ''' <returns></returns>
        Private Function MqlExecute(ByVal infoTextIn As String, _
            ByVal MqlArguments As String, ShowMqlWindow As Boolean) As JF.Tools.JF_Return_cls

            Dim MyReturn As New JF.Tools.JF_Return_cls

            Dim MqlOiQ_Process As New System.Diagnostics.Process
            MqlOiQ_Process.StartInfo.FileName = JF.Tools.JF_ToolsString.StringEnvironValuesGet("%MXBINPATH%\mql.exe")
            MqlOiQ_Process.StartInfo.Arguments = "-b " + MatrixSiteId + " -t -v -c "
            If ShowMqlWindow Or DebugTestAktive Or DebugAktive Then
                MqlOiQ_Process.StartInfo.Arguments = MqlOiQ_Process.StartInfo.Arguments.Replace("-t", "")
            End If
            MqlOiQ_Process.StartInfo.Arguments += chr(34) + MqlArguments + chr(34)


            If MqlOiQ_Process.StartInfo.FileName.Contains("%MXHOME%") Then
                iText = String.Format("ERROR: Umgebungsvariable %MXHOME% nicht gesetzt DataSync abbruch!!")
                LogF_AddLine(LogF_Protocol_DPNE, iText)
                MyReturn.ErrMsg = iText
                Return MyReturn
            End If

            Try

                iText = String.Format("MQL:{0}/Start:[{1}] [{2} {3}]", infoTextIn, Now(), MqlOiQ_Process.StartInfo.FileName, MqlOiQ_Process.StartInfo.Arguments)
                LogF_AddLine(LogF_Protocol_DPNE, iText)

                Call MyScriptOutput_frm.InfoSysProtocol.StatusBarProgressBarStart("MqL", iText)
                MqlOiQ_Process.Start()
                While Not MqlOiQ_Process.HasExited
                    system.windows.Forms.Application.DoEvents()
                    system.Threading.Thread.Sleep(200)
                End While
                MqlOiQ_Process.Close()
                iText = String.Format("MQL:{0} /Ende.:[{1}]", infoTextIn, now())
                LogF_AddLine(LogF_Protocol_DPNE, iText)
                ' Call MyScriptOutput_frm.InfoSysProtocol.StatusBarProgressBarSetIdle()

            Catch ex As Exception
                MyReturn.Ex = ex
            End Try


            Return MyReturn

        End Function


        '-----------------------------------------------------------------------------------------------------------------
        ''' <summary>
        ''' erstellt einen LogFile Namen (New 18.2.2011)
        ''' </summary>
        ''' <returns></returns>
        Private Function LogFileGet_DPNE(ByRef LogFile_Enum_p As LogFile_Enum) As String
            Dim LogFile_DP As String
            Dim LogFile_NE As String
            Dim LogFile_DPNE As String
            LogFile_DP = Archiv_DP_GET(Me.JS_ScriptingInterface.ServerSettings.Dir_DataRoot_DP_30DataBase_22ItemInfoLists)
            LogFile_NE = JF.Tools.JF_ToolsFile.ParsePath_NExtendAtEnd("DatSync", String.Format("_{0}_{1}.txt", CInt(LogFile_Enum_p).toString, LogFile_Enum_p.toString))
            LogFile_NE = JF.Tools.JF_ToolsFile.ParsePath_NExtendWithDateAndTime(LogFile_NE, now(), JF.Tools.JF_ToolsFile.DateTimeFormat_enum.Format_YYMMDDHM)
            LogFile_DPNE = path.Combine(LogFile_DP, LogFile_NE)
            Return LogFile_DPNE
        End Function

        ''' <summary>
        ''' definiert die Verschiedenen LogFile Typen
        ''' </summary>
        Enum LogFile_Enum
            Protocol = 1
            Entire = 2
            InsertData = 3
            UpdateRequired = 4
            DeleteData = 5
            Ectr = 6
        End Enum

        ''' <summary>
        ''' fuegt dem LogFile eine Zeile hinzu
        ''' </summary>
		Private Sub LogF_AddLine(ByRef LogFile_DPNE_p As String, _
			ByVal FileLine_p As String, _
			Optional ByVal HeaderAdd_p As Boolean = False, _
			Optional ByVal ProtoColAdd_p As Boolean = False, _
			Optional ByVal ResMsgForResultColAdd_p As Boolean = False)

            Try
                Call System.IO.File.AppendAllText(LogFile_DPNE_p, FileLine_p + vbCrLf, System.Text.Encoding.GetEncoding(1252))
                If LogFile_DPNE_p = LogF_Protocol_DPNE Then
                    ProtoColAdd_p = True
                End If
                If HeaderAdd_p Then
                    Me.MyScriptOutput_frm.InfoSysHeader.Print(FileLine_p)
                End If
                If ProtoColAdd_p Then
                    Me.MyScriptOutput_frm.InfoSysProtocol.Print(FileLine_p)
                End If

                If ResMsgForResultColAdd_p Then
                    Me.Headline_Return.ResultMsgAdd(FileLine_p)
                End If

            Catch ex As Exception
                'ImportRun_DebugPrint(ex.Message)
                Me.MyScriptOutput_frm.InfoSysProtocol.Print(String.Format("Exception happend on writing to LogFile:[{0}]" + vbCrLf + "{1}", LogFile_DPNE_p, FileLine_p, ex.Message))
            End Try
        End Sub

        '-----------------------------------------------------------------------------------------------------------------
        ''' <summary>
        ''' fuehrt den Import der Daten in die JobManager DB durch
        ''' </summary>
        ''' <param name="FileObj"></param>
        ''' <param name="ImportType">wenn False </param>
        Public Sub ObjectsDoImport(FileObj As JF.Tools.JF_ToolsFile.JF_FileProcessing_cls, ImportType As ImportType_enum)


            Dim I As Integer
            Dim SQLTxt As String

            Dim Text_str As String = ""
            Dim FileLine As String
            Dim FileLineItems As String()
            ' #Doc: Update 20.10.2014 after use O.Attr.1
            Const FileLineNColsMin As Integer = 16
            Dim isUgType As String = ""
            Dim NLinesProcessed As Long
            Dim NLinesImportDone As Long = 0
            Dim EctrFlag As Boolean
            Dim DoImportLine As Boolean

            Call FileObj.FileReadAllText()
            Text_str = "Step: Import :" + FileObj.FileDef.File_NE & " NLines:" + FileObj.nLines.ToString + " [ImportType:" + ImportType.ToString + "]"
            Me.MyScriptOutput_frm.InfoSysProtocol.StatusBarProgressBarStart("")
            Me.MyScriptOutput_frm.InfoSysProtocol.Print_and_StatusBarSetCurrActionStatusInfo_Panel3(Text_str)

            NLinesProcessed = -1
            For Each FileLine In FileObj.ListOfString_LinesWithOutEmpty_TextLines

                NLinesProcessed += 1
                FileLineItems = FileLine.Split(";"c)
                If NLinesProcessed = 0 Then
                    ' erste Zeile ist normalerweise kommentar Zeile
                    DoImportLine = False
                    If FileLineItems.Length > 0 Then
                        If FileLine.Substring(0, 31) <> "UGMaster;ObjectName;ObjectName2" Then
                            DoImportLine = True
                        End If
                    End If
                Else
                    DoImportLine = True
                End If

                If FileLineItems(0).StartsWith("#") Then
                    DoImportLine = False
                End If


                '-- DO..=Aeussere Control Schleife
                Do
                    '-- Zeile nicht importieren
                    If Not DoImportLine Then
                        Exit Do
                    End If

                    '-- nur Zeile verarbeiten wenn Anzahl der Eintr�ge stimmen
                    If FileLineItems.Length < FileLineNColsMin - 1 Then
                        iText = String.Format("ERR: falsches Foramt in Zeile:[{0}] es fehlen Spalten:[Soll:{1}/Ist:{2}]" + vbcrlf + " |-> [{3}]", NLinesProcessed + 1, FileLineNColsMin + 1, FileLineItems.Length, FileLine)
                        LogF_AddLine(LogF_Protocol_DPNE, iText)
                        Exit Do
                    End If



                    '-- Auswerten ob derzeit nur "UGMASTER" Objekte importiert werden sollen
                    isUgType = FileLineItems(3)
                    If ImportType = ImportType_enum.UGMaster And isUgType <> "UGMASTER" Then
                        ' Ausstieg da das Objekt kein "UGMASTER" ist
                        'me.MyScriptOutput_frm.InfoSysProtocol.Print("-> NO Import")
                        Exit Do
                    End If

                    '-- Auswerten ob derzeit nur NICHT "UGMASTER" Objekte importiert werden sollen
                    If ImportType <> ImportType_enum.UGMaster And isUgType = "UGMASTER" Then
                        ' Ausstieg da das Objekt ein "UGMASTER" ist
                        'me.MyScriptOutput_frm.InfoSysProtocol.Print("-> NO Import")
                        Exit Do
                    End If

                    '-- ersetzungen durchfuehren
                    For I = 0 To FileLineItems.Length - 1
                        ' #Chr(59)# -> ersetzen zu ;
                        FileLineItems(I) = FileLineItems(I).Replace("#Chr(59)#", chr(59))
                        FileLineItems(I) = FileLineItems(I).Replace("#chr(59)#", chr(59))
                        FileLineItems(I) = FileLineItems(I).Replace("#CHR(59)#", chr(59))
                        If I = 0 Then
                            ' .prt entfernen
                            FileLineItems(I) = FileLineItems(I).Replace(".prt", "")
                        End If
                        'if DebugAktive Then
                        '	me.MyScriptOutput_frm.InfoSysProtocol.Print(string.Format("FileLineItems:{0:0#}=[{1}]",I,FileLineItems(I)))
                        'End If
                    Next

                    ' -- Docu : Schnittstellen vereinbarung Herr Kotz / J.Fes (Stand 24.02.2011)
                    ' UGMaster;ObjectName;ObjectName2;ObjectType;ObjectUgMaster_Type;ObjectUgMaster_APLevels;ObjectUgMaster_CompCount;ObjectGroup;ObjectLastModDate;ObjectUgMaster_PartFamMemName;ImportError
                    '  0- UGMaster
                    '  1- ObjectName                    .. TEST-JF-001 ug0000212030
                    '  2- ObjectName2                   .. TEST-JF-001 TEST-JF-001
                    '  3- ObjectType                    .. UGPART .. UGMASTER
                    '  4- ObjectUgMaster_Type           .. SP .. AP .. DP
                    '  5- ObjectUgMaster_APLevels       .. 1 BG hat 1 Ebene
                    '  6- ObjectUgMaster_CompCount      .. 5 BG hat 5 Componenten
                    '  7- ObjectGroup                   .. E
                    '  8- ObjectLastModDate             .. 23.2.2011:16:43:38
                    '  9- ObjectUgMaster_PartFamMemName .. ID des PartFamTemplates
                    ' 10- ImportError                   .. z.B. wenn mehere UGMaster Objekte vorhanden
                    ' 11 -Location (neu 21.10.09)       .. Groz-Beckert_Ebingen,Schmeing_Raesfeld,Grob_CH,AKRA_Budweis
                    ' 12- MxType                        ..
                    ' 13- PartName                      .. [00000/01.263-09.1-03 (KON ZE 1)
                    ' 14- CheckInDate                   .. 23.02.2011:16:42
                    ' 15- ECTR Flag O.Attr1(ECTR)       .. True / False
                    ' 16- O.Attr2(Darstellung)          .. Values: detailliert UNIGRAPHICS..  // #New: 20.10.2014

                    ' Eigenschaften uebergeben
                    Import_Obj.ResultReturn.ResetToDefaultValues()
                    Import_Obj.ResetToDefaultValue()

                    Import_Obj.ItemName = FileLineItems(0)
                    Import_Obj.IrRev = "0"

                    Import_Obj.ObjectName = FileLineItems(1)
                    ' PartName in ObjectDescription uebernehmen (21.10.09 J.Fes)
                    Import_Obj.ObjectDescription = FileLineItems(13)
                    ' IrDescripton leeren (21.10.09 J.Fes)
                    Import_Obj.IrDescription = "" ' FileLineItems(13)
                    ' in den
                    Import_Obj.ObjectNote = FileLineItems(12).Replace("Baugruppe", "Bg").Replace("Einzelteil", "Et")

                    ' #Doc Angepasst 18.06.2012 J.Fes
                    Import_Obj.ObjectType("") = JF.PlmJobManager.JobServer.NameMapping.UGDataSetTypes_MapTcCliName(FileLineItems(3), JF.PlmJobManager.JobServer.NameMapping.UGDataSetTypes_MapTcCli_Enum.Cli_To_Tc)
                    'JF.PlmJobManager.JobServer.MyAppl_Shared.UGDataSetTypes_MapTcCli_Enum.Cli_To_Tc)
                    Import_Obj.ObjectUgMaster_Type = FileLineItems(4)
                    Import_Obj.ObjectUgMaster_APLevels = JF.Tools.CTypeTryDefault(Of Integer)(FileLineItems(5), -999)
                    Import_Obj.ObjectUgMaster_CompCount = JF.Tools.CTypeTryDefault(Of Integer)(FileLineItems(6), -999)

                    Import_Obj.ObjectGroup = FileLineItems(7)
                    Import_Obj.IrLastModDate = ConvertDateTime(FileLineItems(8))
                    Import_Obj.IrCreateDate = Import_Obj.IrLastModDate
                    Import_Obj.ObjectCreateDate = Import_Obj.IrLastModDate
                    Import_Obj.ObjectLastModDate = Import_Obj.IrLastModDate
                    Import_Obj.ObjectClass = JF.PlmJobManager.JobServer.ObjectClass_enum.DS
                    Import_Obj.ObjectUgMaster_PartFamMemName = FileLineItems(9)

                    '-- Info ImportObjectErr kommt vor wenn eine Zeichnung mehr als einen "Master" hat wird in MQL ermittelt
                    Import_Obj.ImportObjectErr = FileLineItems(10)
                    '-- Update 12.02.2014/J.Fes Update Import_Obj.IrFromSiteID = SiteIDCurr
                    Import_Obj.ObjectFromSiteID = SiteIDCurr
                    Import_Obj.IrOwningSiteID = FileLineItems(11)

                    '-- ECTR Flag auswerten neu 23.02.2011 / J.Fes
                    If FileLineItems(15).ToUpper = "TRUE" Then
                        ECTRflag = True
                        Import_Obj.ObjectAttr01.Value = "ECTR"
                    Else
                        ECTRflag = False
                        Import_Obj.ObjectAttr01.Value = ""
                    End If

                    '-- #Doc: New 20.10.14 / J.Fes Import ObjectAttr01(Darstellung)
                    Import_Obj.ObjectAttr02.Value = FileLineItems(16)

                    '-- Mappen der Standort Verteilungs Namen WICHTIG "Groz-Beckert_Ebingen" muss durch "mxgb" ersetzt werden da sonst die RemotePart beziehung nicht stimmen
                    Import_Obj.IrOwningSiteID = Import_Obj.IrOwningSiteID.Replace("Groz-Beckert_Ebingen", "mxgb")
                    Import_Obj.IrOwningSiteID = Import_Obj.IrOwningSiteID.Replace("Schmeing_Raesfeld", "SCM")
                    Import_Obj.IrOwningSiteID = Import_Obj.IrOwningSiteID.Replace("Grob_CH", "GROB")
                    Import_Obj.IrOwningSiteID = Import_Obj.IrOwningSiteID.Replace("AKRA_Budweis", "GBCZ")

                    '' #Doc: ACHTUNG: 'mxgb,'
                    '             --> 'mxgb'
                    If Import_Obj.IrOwningSiteID = "mxgb," Then
                        Import_Obj.IrOwningSiteID = "mxgb"
                    End If

                    '-- #Doc: Owning SideID auch auf die Objekte uebergeben
                    Import_Obj.ObjectOwningSiteID = Import_Obj.IrOwningSiteID

                    '-- wenn ein NonUgMaster verarbeitet wird dann
                    '   sind die Referenz Daten vom UGMaster aus der Datenbank zu holen
                    If ImportType = ImportType_enum.NonUGMaster Then

                        ' #toDo: 28.01.2015/J.Fes
                        ' Pr�fen ob Object bereits in DB vorhanden Pr�fung anhand des O.Name Example: ug0000212030
                        ' wenn in DB gefunden dann
                        ' Pr�fen ob ItemName(gefunden) = ItemName(liste)
                        ' wenn ja dann weiter
                        ' wenn nein dann referenz aus DB holen und zuweisen

                        '-- suche ob Dataset bereits in DB vorhanden
                        Me.DSnonMaster_Obj.MyObjectData_ReadFromDB(Import_Obj.ObjectFromSiteID, _
                                                                   Import_Obj.ObjectName, _
                                                                    ObjectClass_enum.DS)

						'-- Abfrage ausfuehren
                        '-- #Doc: Die Daten des UGMASTER holen
                        '--       Damit das UGMaster Object gefunden wird muss fuer den
						'--       ObjectNamen = Import_Obj.ItemName verwendet werden da der UGMASTER ObjectName = dem ItemNamen ist
						Me.DSmaster_Obj.MyObjectData_ReadFromDB(Import_Obj.ObjectFromSiteID, _
                                                                Import_Obj.ItemName, _
                                                                ObjectClass_enum.DS)

                        ' Daten vom UGMaster_Obj auf das Import_Obj uebertragen
                        If DSmaster_Obj.ObjectUgMaster_Type <> "" Then
                            Import_Obj.ObjectUgMaster_APLevels = DSmaster_Obj.ObjectUgMaster_APLevels
                            Import_Obj.ObjectUgMaster_CompCount = DSmaster_Obj.ObjectUgMaster_CompCount
                            Import_Obj.ObjectUgMaster_Type = DSmaster_Obj.ObjectUgMaster_Type
                        End If

                        '-- #Step: bereinigen der MASTER - MODEL relation
                        If Me.DSnonMaster_Obj.ResultReturn.ResultIsEverythingOk And _
                            Me.DSmaster_Obj.ResultReturn.ResultIsEverythingOk And _
                            Me.DSnonMaster_Obj.ItemName <> "" And _
                            (Me.DSnonMaster_Obj.ItemName <> Import_Obj.ItemName) Then

                            'If System.Diagnostics.Debugger.IsAttached Then
                            '    System.Diagnostics.Debugger.Break()
                            'End If


                            '-- #Doc: die Master - Relation hat sich ge�ndert
                            iText = String.Format(" |-> Update Master-Model releation from:{1} to:{2}", _
                                                  Me.Import_Obj.ObjectCliNameForOutput, _
                                                  Me.DSnonMaster_Obj.ItemName, _
                                                  Me.Import_Obj.ItemName)

                            '-- #Doc: read IR data of Dataset
                            Me.DSnonMasterIr_Obj.MyObjectData_ReadFromDB(Import_Obj.ObjectFromSiteID, _
                                                                         Me.DSnonMaster_Obj.IrNameRev.Value.ToString, _
                                                                         ObjectClass_enum.IR)

                            Me.DSmasterIr_Obj.MyObjectData_ReadFromDB(Import_Obj.ObjectFromSiteID, _
                                                                      Me.DSmaster_Obj.IrNameRev.Value.ToString, _
                                                                      ObjectClass_enum.IR)

                            If Me.DSnonMasterIr_Obj.ResultReturn.ResultIsEverythingOk And _
                                Me.DSmasterIr_Obj.ResultReturn.ResultIsEverythingOk Then

                                Dim Return_Obj As New JF.Tools.JF_Return_cls
                                iText += String.Format(" |-> Ir map from:[{0}] -> to:[{1}]", Me.DSnonMasterIr_Obj.IrNameRev, Me.DSmasterIr_Obj.IrNameRev)

                                SQLTxt = String.Format("UPDATE Objects_Ir_Rel_tbl SET [IrId]='{0}' where [ObjectId]='{1}'", _
                                                                      Me.DSmasterIr_Obj.ID.ToString, _
                                                                      Me.DSnonMaster_Obj.ID.ToString)
                                Return_Obj = MyCls_DataSource_Obj.DataBase_SqlExecute(SQLTxt)
                                iText += vbCrLf + String.Format(" |-> {0} n:{1} changed", Return_Obj.ResultMsgEvaluate, Return_Obj.ReturnLong)

                                '-- #Step: CliNamen Updaten -------------------------------------------------
                                With Import_Obj
                                    .ObjectCliName = ObjectCliName_cls.ObjectCliName_gen(.ItemName, .IrRev, .ObjectName, .ObjectType(""))
                                End With
                                iText += String.Format(" |-> Cli Map from:[{0}] -> to:[{1}]", Me.DSnonMaster_Obj.ObjectCliName, Me.Import_Obj.ObjectCliName)
                                SQLTxt = String.Format("UPDATE Objects_tbl SET [ObjectCliName]='{0}' where [Id]='{1}'", _
                                                                      Me.Import_Obj.ObjectCliName, _
                                                                      Me.DSnonMaster_Obj.ID.ToString)
                                Return_Obj = MyCls_DataSource_Obj.DataBase_SqlExecute(SQLTxt)
                                iText += vbCrLf + String.Format(" |-> {0} n:{1} changed", Return_Obj.ResultMsgEvaluate, Return_Obj.ReturnLong)


                                '-- #Step: CleanUp Unused IR -------------------------------------------------
                                '-- #Doc.: finden ob noch referenzen auf IR in Objects_Ir_Rel_tbl zeigen
                                SQLTxt = String.Format("select ID from Objects_Ir_Rel_tbl where [IrId]='{0}'", _
                                                                      Me.DSnonMasterIr_Obj.ID.ToString)
                                Dim DataTbl As DataTable = Nothing
                                If MyCls_DataSource_Obj.cmdFillDataTable(SQLTxt, DataTbl) Then
                                    If DataTbl.Rows.Count = 0 Then
                                        '-- delete IR
                                        iText += String.Format(" |-> Ir remove [{0}]", Me.DSnonMasterIr_Obj.ObjectCliName)
										SQLTxt = String.Format("Delete from Objects_tbl where [Id]='{0}'", Me.DSnonMasterIr_Obj.ID.ToString)
										Return_Obj = MyCls_DataSource_Obj.DataBase_SqlExecute(SQLTxt)
                                        iText += vbCrLf + String.Format(" |-> {0} n:{1} changed", Return_Obj.ResultMsgEvaluate, Return_Obj.ReturnLong)
                                    End If
                                End If
                            Else
                                iText = vbCrLf + Me.DSnonMasterIr_Obj.ResultReturn.ResultMsgEvaluate
                                iText = vbCrLf + Me.DSmasterIr_Obj.ResultReturn.ResultMsgEvaluate

                            End If
                            LogF_AddLine(LogF_Protocol_DPNE, iText)

                        End If
                    End If

                    ' Sonderregel: 'DP' sind eigentlich 'SP' 2.1210;02.02.2015;J.Fes
                    If Import_Obj.ObjectUgMaster_Type = "DP" Then
                        Import_Obj.ObjectUgMaster_Type = "SP"
                    End If


                    '-- Step: Daten in die JobManager DB uebertragen
                    ' #Update 12.02.2014/J.Fes angepasst von Import_Obj.IrFromSiteID auf Import_Obj.ObjectFromSiteID
                    Import_Obj.AddOrUpdate_CurIrObjectData_ToDatabase(Import_Obj.ObjectFromSiteID)


                    If Not Import_Obj.ResultReturn.ResultIsEverythingOk Then
                        Me.ResultReturn.ResultMsgAdd(Import_Obj.ResultReturn.ResultMsgEvaluate)
                        iText = String.Format("Import:ERR:{0} {1}", FileLine, Import_Obj.ResultReturn.ResultMsgEvaluate)
                    Else
                        iText = String.Format("Import:OK.:{0}", FileLine)
                        NLinesImportDone += 1
                    End If
                    LogF_AddLine(LogF_Protocol_DPNE, iText)
                    LogF_AddLine(LogF_ActionInsertData_DPNE, iText)
                    LogF_AddLine(LogF_EntireData_DPNE, iText)

                    '-- Step: EctrFlag
                    If EctrFlag Then
                        ' Daten jetzt aus DB lesen da hierdurch die ID's gesucht werden
                        Call Import_Obj.MyObjectData_ReadFromDB()
                        Call DsIr_toEcrt(Import_Obj)
                    End If

                    ' Ausgabe der Aktivitaeten
                    If JF.Tools.JF_Tools.EveryTimeDoEvaluate(NLinesProcessed, SiteDef_Obj.ImportMsgAfterNImports, 1) Then
                        'me.MyScriptOutput_frm.InfoSysProtocol.Print("Import:" + FileLine)
                        Me.MyScriptOutput_frm.InfoSysProtocol.StatusBarSetCurrActionInfo_Panel1("Done:" & NLinesProcessed.ToString & "/" & FileObj.nLines.ToString & "=" & (NLinesProcessed / FileObj.nLines - 1).ToString("0.0%") & " nImport Done:" & NLinesImportDone.ToString)
                    End If
                    ' !! Ausstieg aus Do Schleife

                    '-- ImportBeginDataTimeNew mit erhoehen
                    If Import_Obj.ObjectLastModDate > SiteDef_Obj.ImportItemLastModifyDateBegin Then
                        ImportBeginDataTimeNew = Import_Obj.ObjectLastModDate
                    End If

                    Exit Do
                Loop While True

            Next

        End Sub


		'---------------------------------------------------------------------------------------------------------------------
		''' <summary>
		''' Moves File to Logfile Archiv (LogRoot_DP\Archv-YYYY-MM-DD\..)
		''' </summary>
		''' <param name="File_DPNE"></param>
		''' <returns></returns>
		Function FileItem_DPNE_MoveToArchiv(ByVal File_DPNE As string) As string
			Dim Archiv_DP As String
			Dim Archiv_DPNE As String
			'Archiv_DP = JF.Tools.JF_ToolsFile.ParsePath_DP(File_DPNE)
			Archiv_DPNE = JF.Tools.JF_ToolsFile.ParsePath_PInsertTP(File_DPNE,JF.Tools.JF_ToolsFile.ParsePath_NExtendWithDateAndTime("Archiv",now(), JF.Tools.JF_ToolsFile.DateTimeFormat_enum.Format_YYMMDD))
			Archiv_DPNE = JF.Tools.JF_ToolsFile.ParsePath_NExtendWithDateAndTime(Archiv_DPNE,now(), JF.Tools.JF_ToolsFile.DateTimeFormat_enum.Format_YYMMDDHM)
			Archiv_DP = JF.Tools.JF_ToolsFile.ParsePath_DP(Archiv_DPNE)
			Call Me.MyScriptOutput_frm.InfoSysProtocol.Print("Archiv_DP..:[" + Archiv_DP + "]")
			Call Me.MyScriptOutput_frm.InfoSysProtocol.Print("Archiv_DPNE:[" + Archiv_DPNE + "]")
			If JF.Tools.JF_ToolsFile.DirCreate(Archiv_DP).ReturnBol Then
				My.Computer.FileSystem.MoveFile(File_DPNE,Archiv_DPNE, True)
				Me.MyScriptOutput_frm.InfoSysProtocol.Print_and_StatusBarSetCurrActionStatusInfo_Panel3( _
					"Aktion: schiebe InputFile:" + vbcrlf + _
					"von   :" + File_DPNE & vbcrlf  + _
					"nach  :" + Archiv_DPNE	)
			End If
			Return Archiv_DPNE
		End Function

		''' <summary>
		''' stellt Archiv Verzeichniss bereit
		''' </summary>
		''' <param name="Root_DP"></param>
		''' <returns></returns>
		Function Archiv_DP_GET(ByVal Root_DP As string) As String
			Dim Archiv_DP As String
			Archiv_DP = path.Combine (Root_DP,JF.Tools.JF_ToolsFile.ParsePath_NExtendWithDateAndTime("Archiv",now(), JF.Tools.JF_ToolsFile.DateTimeFormat_enum.Format_YYMMDD))
			Call JF.Tools.JF_ToolsFile.DirCreate(Archiv_DP)
			return  Archiv_DP
		End Function


		'--------------------------------------------------------------------------------------------------------
		''' <summary>
		''' Temporaer Sub Sync ECTR
		''' </summary>
		Private Sub DataSyncFixECTR
			Dim DatSyncFile_Obj As New JF.Tools.JF_ToolsFile.JF_FileProcessing_cls("")
			Dim FileLineItems As String()

			Dim GetDSResult_Obj As New JF.Tools.JF_Return_cls
			Dim Datasets_and_Irs_Obj As new JF.PlmJobManager.JobServer.Datasets_and_Irs_cls

			DatSyncFile_Obj.FileDef.File_DPNE = "D:\JobManagerV2\90-DATA\GB_WorkInst_PROD\20-DataBase\22-ItemInfoLists\DatSync_2011-02-18_17-40_3_Ectr_temp.txt"
			DatSyncFile_Obj.FileReadAllText

			for each FileLine As string in DatSyncFile_Obj.ListOfString_LinesWithOutEmpty_TextLines
				iText = "MqL FileLine:[" + FileLine + "]"
				LogF_AddLine(LogF_EntireData_DPNE,iText,,true)
                FileLineItems = FileLine.Split(";"c)
				if FileLineItems.Length >= 4 then
					'-- werte auf Datasets_and_Irs_Obj uebertragen
					with Datasets_and_Irs_Obj
						.ResetToDefaultValue

						.ItemName  = FileLineItems(0)
						.IrRev = "0"

						'-- UgFileName
						.ObjectName = FileLineItems(1)
						'-- Last ModDate wird genommen aus CheckInDate-3
						.ObjectClass = JF.PlmJobManager.JobServer.ObjectClass_enum.DS
						.ObjectFromSiteId = SiteIDCurr
						.ObjectLastModDate = ConvertDateTime(FileLineItems(3))
						GetDSResult_Obj = MyCls_DataSource_Obj.Objects_tbl_GetDS(Datasets_and_Irs_Obj)
						iText = string.format("Set Ectr for:[{0}]", .ObjectCliNameForOutput)
						LogF_AddLine(LogF_Protocol_DPNE,iText,,True)
						LogF_AddLine(LogF_ActionEctr_DPNE,iText,,True)
					end with
					GetDSResult_Obj = DsIr_toEcrt(Datasets_and_Irs_Obj)
				end if
			Next
		End Sub



	End Class
End Namespace

