Imports System.IO
Imports System.Xml

Public Class frmTCNachrichtenVerarbeitung
    Dim cntDatenEingelesen As Integer = 0
    Dim dsNichtErkannt As Integer = 0
    Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
    Dim allowClose = False
    '  Dim DY_PFAD = "C:\Users\DEVELOPER1\Desktop\test\TEST\"

    Dim TELOTEC_PFAD = "" '"C:\Users\DEVELOPER1\Desktop\test\TEST\Nachrichtendaten_Einarbeitung\"
    Dim TELOTEC_PFAD_VERAG = "" '"C:\Users\DEVELOPER1\Desktop\test\TEST\Nachrichtendaten_Einarbeitung\"
    Dim VERARBEITUNGS_PFAD = "" '"C:\Users\DEVELOPER1\Desktop\test\TEST\Nachrichtendaten_Einarbeitung\"
    Dim ZIEL_PFAD = "" '"C:\Users\DEVELOPER1\Desktop\test\TEST\Nachrichtendaten_Ablage\"
    Dim ERROR_PFAD = "" '"C:\Users\DEVELOPER1\Desktop\test\TEST\Nachrichtendaten_ERROR\"
    ' Dim BOX_VERSION = "8.8"

    Dim Dateiname = ""

    Sub New()

        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()

        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.

    End Sub
    Sub New(allowClose) 'autostart

        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()
        Me.allowClose = allowClose
        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.

    End Sub

    Sub initPfade()
        Me.TELOTEC_PFAD = TELOTEC_Worker.cTC_Paramter.GET_PARAM_ByName("TELOTEC_PFAD", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM)
        Me.TELOTEC_PFAD_VERAG = TELOTEC_Worker.cTC_Paramter.GET_PARAM_ByName("TELOTEC_PFAD_VERAG", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM)
        Me.VERARBEITUNGS_PFAD = TELOTEC_Worker.cTC_Paramter.GET_PARAM_ByName("VERARBEITUNGS_PFAD", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM)
        'VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\TESTSYSTEM\Nachrichtendaten_Einarbeitung\"
        Me.ZIEL_PFAD = TELOTEC_Worker.cTC_Paramter.GET_PARAM_ByName("ZIEL_PFAD", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM)
        'VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\TESTSYSTEM\Nachrichtendaten_Ablage\"
        Me.ERROR_PFAD = TELOTEC_Worker.cTC_Paramter.GET_PARAM_ByName("ERROR_PFAD", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM)
        'VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\TESTSYSTEM\Nachrichtendaten_ERROR\"
        If Not System.IO.Directory.Exists(VERARBEITUNGS_PFAD) Then System.IO.Directory.CreateDirectory(VERARBEITUNGS_PFAD)
        If Not System.IO.Directory.Exists(ZIEL_PFAD) Then System.IO.Directory.CreateDirectory(ZIEL_PFAD)
        If Not System.IO.Directory.Exists(ERROR_PFAD) Then System.IO.Directory.CreateDirectory(ERROR_PFAD)

        'Me.BOX_VERSION = TELOTEC_Worker.cDY_Paramter.GET_PARAM_ByName("BOX_VERSION", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM)

    End Sub


    Private Sub frmDYNachrichtenVerarbeitung_Load(sender As Object, e As EventArgs) Handles Me.Load
        initPfade()
        For Each d In System.IO.Directory.GetFiles(VERARBEITUNGS_PFAD)
            ListBox3.Items.Add(frmStartOptions.cut_file(d))
            Me.Refresh()
        Next

    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Me.Enabled = False
        Try
            Label9.Visible = True
            Dim cnt = getNachrichtenDatenFromTelotec()
            cnt += getNachrichtenDatenFromTelotec_VERAG()
            Label9.Text = cnt & " Datensätze empfangen."

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
        Me.Enabled = True

    End Sub
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Me.Enabled = False
        Try
            Label5.Visible = True
            DatenEinlesen()
            If dsNichtErkannt > 0 Then

                Label6.Text = dsNichtErkannt & " Datensätze nicht " & vbNewLine & "erkannt."
                Label6.Visible = True
            End If
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
        Me.Enabled = True
        Label5.Text = cntDatenEingelesen & " Datensätze verarbeitet."

    End Sub

    Function getNachrichtenDatenFromTelotec() As Integer
        Dim cnt = 0
        Try
            For Each f In System.IO.Directory.GetFiles(TELOTEC_PFAD)
                Dim FI As New FileInfo(f)
                If Not FI.Name.StartsWith(".") Then
                    'Temp. DownloadPfad
                    Dim destFilenameTMP = VERARBEITUNGS_PFAD + "." & If(System.IO.File.Exists(VERARBEITUNGS_PFAD & "." & FI.Name), Now.ToString("yyMMdd_HHmmss.fff_"), "") & FI.Name

                    'Datei herunterladen
                    System.IO.File.Copy(f, destFilenameTMP)
                    If System.IO.File.Exists(destFilenameTMP) Then System.IO.File.Delete(f) 'Datei nach erfolgreichem Herunterladen vom Server löschen

                    'Gültiger Filename
                    Dim destFilename = VERARBEITUNGS_PFAD & If(System.IO.File.Exists(VERARBEITUNGS_PFAD & FI.Name), Now.ToString("yyMMdd_HHmmss.fff_"), "") & FI.Name
                    System.IO.File.Move(destFilenameTMP, destFilename) 'Datei umbenennen

                    Dim fi_dest As FileInfo = New FileInfo(destFilename)
                    ListBox3.Items.Add(frmStartOptions.cut_file(fi_dest.Name)) 'zur Liste hinzufügen
                    cnt += 1
                End If
            Next
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try

        Return cnt

        'Dim cnt = 0
        'Try
        '    Dim DY_server = ""
        '    Dim DY_name = ""
        '    Dim DY_pwd = ""
        '    Dim DY_port = ""
        '    Dim DY_PFAD_out = ""

        '    DAKOSY_Worker.cDakosyFunftions.getSFTPLoginData(DY_server, DY_name, DY_pwd, DY_port, "", DY_PFAD_out)


        '    Dim ConnectionInfo As New ConnectionInfo(DY_server, DY_port, DY_name, New PasswordAuthenticationMethod(DY_name, DY_pwd))
        '    Using client = New SftpClient(ConnectionInfo)
        '        client.Connect()

        '        For Each f In client.ListDirectory(DY_PFAD_out)
        '            '   MsgBox(f.Name)
        '            If Not f.Name.StartsWith(".") Then
        '                'Temp. DownloadPfad
        '                Dim destFilenameTMP = VERARBEITUNGS_PFAD + "." & If(IO.File.Exists(VERARBEITUNGS_PFAD & "." & f.Name), Now.ToString("yyMMdd_HHmmss.fff_"), "") & f.Name

        '                'Datei herunterladen
        '                Dim downloadFileStream As Stream = File.OpenWrite(destFilenameTMP)
        '                client.DownloadFile(f.FullName, downloadFileStream)
        '                If IO.File.Exists(destFilenameTMP) Then client.DeleteFile(f.FullName) 'Datei nach erfolgreichem Herunterladen vom Server löschen
        '                downloadFileStream.Dispose()

        '                'Gültiger Filename
        '                Dim destFilename = VERARBEITUNGS_PFAD & If(IO.File.Exists(VERARBEITUNGS_PFAD & f.Name), Now.ToString("yyMMdd_HHmmss.fff_"), "") & f.Name
        '                IO.File.Move(destFilenameTMP, destFilename) 'Datei umbenennen

        '                Dim fi As FileInfo = New FileInfo(destFilename)
        '                ListBox3.Items.Add(frmStartOptions.cut_file(fi.Name)) 'zur Liste hinzufügen
        '                cnt += 1
        '            End If
        '        Next
        '        client.Disconnect()
        '    End Using
        'Catch ex As Exception
        '    VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        'End Try

        'Return cnt
    End Function

    Function getNachrichtenDatenFromTelotec_VERAG() As Integer
        Dim cnt = 0
        Try
            For Each f In System.IO.Directory.GetFiles(TELOTEC_PFAD_VERAG)
                Dim FI As New FileInfo(f)
                If Not FI.Name.StartsWith(".") Then
                    'Temp. DownloadPfad
                    Dim destFilenameTMP = VERARBEITUNGS_PFAD + "." & If(System.IO.File.Exists(VERARBEITUNGS_PFAD & "." & FI.Name), Now.ToString("yyMMdd_HHmmss.fff_"), "") & FI.Name

                    'Datei herunterladen
                    System.IO.File.Copy(f, destFilenameTMP)
                    If System.IO.File.Exists(destFilenameTMP) Then System.IO.File.Delete(f) 'Datei nach erfolgreichem Herunterladen vom Server löschen

                    'Gültiger Filename
                    Dim destFilename = VERARBEITUNGS_PFAD & If(System.IO.File.Exists(VERARBEITUNGS_PFAD & FI.Name), Now.ToString("yyMMdd_HHmmss.fff_"), "") & FI.Name
                    System.IO.File.Move(destFilenameTMP, destFilename) 'Datei umbenennen

                    Dim fi_dest As FileInfo = New FileInfo(destFilename)
                    ListBox3.Items.Add(frmStartOptions.cut_file(fi_dest.Name)) 'zur Liste hinzufügen
                    cnt += 1
                End If
            Next
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try

        Return cnt
    End Function



    ' Dim toEncodeAsBytes() As Byte = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode)
    '  string returnValue            = System.Convert.ToBase64String(toEncodeAsBytes)
    Public Function stripNonValidXMLCharacters(ByVal textIn As String) As String
        Dim textOut As System.Text.StringBuilder = New System.Text.StringBuilder()
        Dim current As Char
        If textIn Is Nothing OrElse textIn = String.Empty Then Return String.Empty
        For i As Integer = 0 To textIn.Length - 1
            current = textIn(i)
            If (current = "9" OrElse current = "10" OrElse current = "13") OrElse ((current >= "32") AndAlso (current <= "55295")) OrElse ((current >= "57344") AndAlso (current <= "65533")) OrElse ((current >= "65536") AndAlso (current <= "1114111")) Then
                textOut.Append(current)
            End If
        Next

        Return textOut.ToString()
    End Function

    Public Function SanitizeXmlString(ByVal xml As String) As String
        If xml Is Nothing Then
            Throw New ArgumentNullException("xml")
        End If

        Dim buffer As System.Text.StringBuilder = New System.Text.StringBuilder(xml.Length)
        For Each c As Char In xml
            If IsLegalXmlChar(Asc(c)) Then
                buffer.Append(c)
            End If
        Next

        Return buffer.ToString()
    End Function

    Public Function IsLegalXmlChar(ByVal character As Integer) As Boolean
        Return (character = 9 OrElse character = 10 OrElse character = 13 OrElse (character >= 32 AndAlso character <= 55295) OrElse (character >= 57344 AndAlso character <= 65533) OrElse (character >= 65536 AndAlso character <= 1114111))
    End Function

    Private Function getFilesInOrder() As String()
        Dim myDirectory As New System.IO.DirectoryInfo(VERARBEITUNGS_PFAD)
        'Dim myfiles() As String = myDirectory.GetFiles.OrderBy(Function(x) x.LastWriteTime).Select(Function(x) x.FullName).Take(40).ToArray
        Dim myfiles() As String = myDirectory.GetFiles.OrderBy(Function(x) x.CreationTime).Select(Function(x) x.FullName).ToArray
        ' Dim myfiles As FileInfo() = myDirectory.GetFiles().OrderBy(Function(p) p.CreationTime).Select(Function(x) x.FullName).ToArray
        Return myfiles

    End Function

    Sub DatenEinlesen()

        VERAG_PROG_ALLGEMEIN.cAllgemein.ERR_OP_GLOBAL = VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL

        If ListBox3.Items.Count = 0 Then
            Label6.Text = "Keine Daten zum Einlesen vorhanden."
            Label6.Visible = True
            Exit Sub
        End If
        For i = 1 To 3

            For Each d In getFilesInOrder() 'System.IO.Directory.GetFiles(VERARBEITUNGS_PFAD)

                Try
                    Dateiname = d
                    cWorker_NCTS.Dateiname = d
                    If System.IO.File.Exists(d) Then



                        Dim found = False
                        Dim fi As FileInfo = New FileInfo(d)
                        If Not fi.Name.StartsWith(".") Then

                            Dim alreadyMoved = False
                            Select Case i
                                Case 1
                                    If fi.Extension = ".xml" Then
                                        Dim xmlWriterSettings As XmlWriterSettings = New XmlWriterSettings With {.Encoding = System.Text.Encoding.UTF8, .CheckCharacters = True}

                                        Dim doc As New XmlDocument()
                                        Dim XML_Code = System.IO.File.ReadAllText(d, System.Text.UTF8Encoding.Default)

                                        doc.LoadXml(SanitizeXmlString(XML_Code))
                                        Dim VERSION As String = ""


                                        '------------------------------------------------------------------------------------------------------------------------------
                                        '                                                                  eZOLL
                                        '------------------------------------------------------------------------------------------------------------------------------


                                        '------------------------------------------
                                        '------------------ Anmeldung ------------------
                                        '------------------------------------------
                                        'TC: Versandbestätigung
                                        If Not found And cGetMsgType.isTC_Anmeldung(doc) Then
                                            If readTC_Anmeldung(doc, d) <> "" Then found = True
                                            ' If bezugsNr <> "" Then addDGVEinarbeitung("NCTS: Versandbestätigung", bezugsNr) : found = True
                                        End If
                                    End If
                                Case 2
                                    If fi.Extension = ".pdf" AndAlso fi.Name.Contains("_") Then
                                        Dim split = fi.Name.ToString.Replace(".pdf", "").Split("_")
                                        Dim CRN = ""
                                        Dim tc_id = ""
                                        Dim Anm_id = ""
                                        Dim typeMsg = ""
                                        Dim BezugsNr = ""
                                        Dim dec_ProzessArt = ""

                                        If split.Length > 0 Then CRN = split(0)
                                        If split.Length > 1 Then Anm_id = split(1)
                                        If split.Length > 2 Then typeMsg = split(2)

                                        Dim DS As VERAG_PROG_ALLGEMEIN.cDATENSERVER = Nothing

                                        tc_id = SQL.DLookup("[telanm_id]", "tblTelotec_Anmeldung", "telanm_CRN='" & CRN & "'", "FMZOLL")
                                        BezugsNr = SQL.DLookup("Refs_LRN", "tblTelotec_Anmeldung", "telanm_CRN='" & CRN & "' AND [telnam_aktuellsteNachricht]=1", "FMZOLL")
                                        dec_ProzessArt = SQL.DLookup("dec_ProzessArt", "tblTelotec_Anmeldung", "telanm_CRN='" & CRN & "' AND [telnam_aktuellsteNachricht]=1", "FMZOLL")

                                        If BezugsNr <> String.Empty Then


                                            Select Case typeMsg
                                                Case "EZ923" 'STB

                                                    Select Case dec_ProzessArt
                                                        Case "EX" 'ABD
                                                            DS = New VERAG_PROG_ALLGEMEIN.cDATENSERVER("ZOLLDATEN", "ABD", tc_id, "", "", BezugsNr.ToString.Replace("/", "-").Replace(",", "-").Replace("\", "-").Replace(":", "."), 0, False)
                                                            DS.da_vorlage = False

                                                            Dim ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "TELOTEC\ECHTSYSTEM\ZOLLDATEN\ABD\NOT_IDENTIFIED\"
                                                            If IsNumeric(tc_id) AndAlso tc_id > 0 Then ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "TELOTEC\ECHTSYSTEM\ZOLLDATEN\ABD\" & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\"
                                                            If Not System.IO.Directory.Exists(ZIEL_PFAD) Then System.IO.Directory.CreateDirectory(ZIEL_PFAD)

                                                            Dim destFull = ""
                                                            frmStartOptions.moveFile(d, ZIEL_PFAD, destFull)

                                                            If DS.insertDataToDATENSERVER(destFull) Then
                                                                If IsNumeric(tc_id) AndAlso tc_id > 0 Then
                                                                    '    SQL.doSQL("UPDATE [tblTelotec_Anmeldung] SET [telanm_Steuerbescheid_dsId]='" & DS.da_id & "' where telanm_CRN='" & CRN & "'", "FMZOLL")
                                                                    SQL.doSQL("UPDATE Speditionsbuch SET DokumentId_ABD='" & DS.da_id & "' where AtlasBezNrAES='" & BezugsNr.ToString.Trim & "' AND DokumentId_ABD is null", "FMZOLL") 'Falls Spedbuch schon zuvor generiert wurde!
                                                                    If DateDiff(DateInterval.Hour, fi.CreationTime, Now) < 24 Then frmStartOptions.doMailZollbeleg(DS.GET_TOP1_PATH, "ABD", tc_id)
                                                                End If
                                                            End If
                                                            found = True
                                                            addDGVEinarbeitung("PDF: AusfuhrBegleitDokument ", BezugsNr)

                                                        Case Else
                                                            DS = New VERAG_PROG_ALLGEMEIN.cDATENSERVER("ZOLLDATEN", "STEUERBESCHEID", tc_id, "", "", BezugsNr.ToString.Replace("/", "-").Replace(",", "-").Replace("\", "-").Replace(":", "."), 0, False)
                                                            DS.da_vorlage = False

                                                            Dim ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "TELOTEC\ECHTSYSTEM\ZOLLDATEN\STEUERBESCHEID\NOT_IDENTIFIED\"
                                                            If IsNumeric(tc_id) AndAlso tc_id > 0 Then ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "TELOTEC\ECHTSYSTEM\ZOLLDATEN\STEUERBESCHEID\" & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\"
                                                            If Not System.IO.Directory.Exists(ZIEL_PFAD) Then System.IO.Directory.CreateDirectory(ZIEL_PFAD)

                                                            Dim destFull = ""
                                                            frmStartOptions.moveFile(d, ZIEL_PFAD, destFull)

                                                            If DS.insertDataToDATENSERVER(destFull) Then
                                                                If IsNumeric(tc_id) AndAlso tc_id > 0 Then
                                                                    SQL.doSQL("UPDATE [tblTelotec_Anmeldung] SET [telanm_Steuerbescheid_dsId]='" & DS.da_id & "' where telanm_CRN='" & CRN & "'", "FMZOLL")
                                                                    SQL.doSQL("UPDATE Speditionsbuch SET DokumentId_Steuerbeleg='" & DS.da_id & "' where AtlasBezNrEZA='" & BezugsNr.ToString.Trim & "' AND DokumentId_Steuerbeleg is null", "FMZOLL") 'Falls Spedbuch schon zuvor generiert wurde!
                                                                    If DateDiff(DateInterval.Hour, fi.CreationTime, Now) < 24 Then frmStartOptions.doMailZollbeleg(DS.GET_TOP1_PATH, "STEUERBESCHEID", tc_id)
                                                                End If
                                                            End If
                                                            found = True
                                                            addDGVEinarbeitung("PDF: STEUERBESCHEID ", BezugsNr)

                                                    End Select
                                                Case "EZ922" 'STB Mitteilung

                                                    DS = New VERAG_PROG_ALLGEMEIN.cDATENSERVER("ZOLLDATEN", "STEUERBESCHEID_MITT", tc_id, "", "", BezugsNr.ToString.Replace("/", "-").Replace(",", "-").Replace("\", "-").Replace(":", "."), 0, False)
                                                    DS.da_vorlage = False

                                                    Dim ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "TELOTEC\ECHTSYSTEM\ZOLLDATEN\STEUERBESCHEID\NOT_IDENTIFIED\"
                                                    If IsNumeric(tc_id) AndAlso tc_id > 0 Then ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "TELOTEC\ECHTSYSTEM\ZOLLDATEN\STEUERBESCHEID\" & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\"
                                                    If Not System.IO.Directory.Exists(ZIEL_PFAD) Then System.IO.Directory.CreateDirectory(ZIEL_PFAD)

                                                    Dim destFull = ""
                                                    frmStartOptions.moveFile(d, ZIEL_PFAD, destFull)

                                                    If DS.insertDataToDATENSERVER(destFull) Then
                                                        If IsNumeric(tc_id) AndAlso tc_id > 0 Then
                                                            SQL.doSQL("UPDATE [tblTelotec_Anmeldung] SET [telanm_Mitteilung_dsId]='" & DS.da_id & "' where telanm_CRN='" & CRN & "'", "FMZOLL")
                                                            SQL.doSQL("UPDATE Speditionsbuch SET DokumentId_Mitteilung='" & DS.da_id & "' where AtlasBezNrEZA='" & BezugsNr.ToString.Trim & "' AND DokumentId_Mitteilung is null", "FMZOLL") 'Falls Spedbuch schon zuvor generiert wurde!
                                                            If DateDiff(DateInterval.Hour, fi.CreationTime, Now) < 24 Then frmStartOptions.doMailZollbeleg(DS.GET_TOP1_PATH, "STEUERBESCHEID", tc_id)
                                                        End If
                                                    End If
                                                    found = True
                                                    addDGVEinarbeitung("PDF: STEUERBESCHEID (Mittlg.) ", BezugsNr)

                                                Case "TR109" 'VBD

                                                    DS = New VERAG_PROG_ALLGEMEIN.cDATENSERVER("ZOLLDATEN", "VBD", tc_id, "", "", BezugsNr.ToString.Replace("/", "-").Replace(",", "-").Replace("\", "-").Replace(":", "."), 0, False)
                                                    DS.da_vorlage = False

                                                    Dim ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "TELOTEC\ECHTSYSTEM\ZOLLDATEN\VBD\NOT_IDENTIFIED\"
                                                    If IsNumeric(tc_id) AndAlso tc_id > 0 Then ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "TELOTEC\ECHTSYSTEM\ZOLLDATEN\VBD\" & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\"
                                                    If Not System.IO.Directory.Exists(ZIEL_PFAD) Then System.IO.Directory.CreateDirectory(ZIEL_PFAD)

                                                    Dim destFull = ""
                                                    frmStartOptions.moveFile(d, ZIEL_PFAD, destFull)

                                                    If DS.insertDataToDATENSERVER(destFull) Then
                                                        If IsNumeric(tc_id) AndAlso tc_id > 0 Then
                                                            SQL.doSQL("UPDATE [tblTelotec_Anmeldung] SET [telanm_VBD_dsId]='" & DS.da_id & "' where telanm_CRN='" & CRN & "'", "FMZOLL")
                                                            SQL.doSQL("UPDATE Speditionsbuch SET DokumentId_VBD='" & DS.da_id & "' where AtlasBezNrNCTS='" & BezugsNr.ToString.Trim & "' AND DokumentId_VBD is null", "FMZOLL") 'Falls Spedbuch schon zuvor generiert wurde!
                                                            If DateDiff(DateInterval.Hour, fi.CreationTime, Now) < 24 Then frmStartOptions.doMailZollbeleg(DS.GET_TOP1_PATH, "VBD", tc_id)
                                                        End If
                                                    End If
                                                    found = True
                                                    addDGVEinarbeitung("PDF: VBD ", BezugsNr)

                                                Case "EX431" 'AVMEX431
                                                    DS = New VERAG_PROG_ALLGEMEIN.cDATENSERVER("ZOLLDATEN", "AVM", tc_id, "", "", BezugsNr.ToString.Replace("/", "-").Replace(",", "-").Replace("\", "-").Replace(":", "."), 0, False)
                                                    DS.da_vorlage = False

                                                    Dim ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "TELOTEC\ECHTSYSTEM\ZOLLDATEN\AVM\NOT_IDENTIFIED\"
                                                    If IsNumeric(tc_id) AndAlso tc_id > 0 Then ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "TELOTEC\ECHTSYSTEM\ZOLLDATEN\AVM\" & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\"
                                                    If Not System.IO.Directory.Exists(ZIEL_PFAD) Then System.IO.Directory.CreateDirectory(ZIEL_PFAD)

                                                    Dim destFull = ""
                                                    frmStartOptions.moveFile(d, ZIEL_PFAD, destFull)

                                                    If DS.insertDataToDATENSERVER(destFull) Then
                                                        If IsNumeric(tc_id) AndAlso tc_id > 0 Then
                                                            ' SQL.doSQL("UPDATE [tblTelotec_Anmeldung] SET [telanm_Steuerbescheid_dsId]='" & DS.da_id & "' where telanm_CRN='" & CRN & "'", "FMZOLL")
                                                            SQL.doSQL("UPDATE Speditionsbuch SET DokumentId_AVM='" & DS.da_id & "' where AtlasBezNrAES='" & BezugsNr.ToString.Trim & "' AND DokumentId_AVM is null", "FMZOLL") 'Falls Spedbuch schon zuvor generiert wurde!
                                                            If DateDiff(DateInterval.Hour, fi.CreationTime, Now) < 24 Then frmStartOptions.doMailZollbeleg(DS.GET_TOP1_PATH, "AVM", tc_id)
                                                        End If
                                                    End If
                                                    found = True
                                                    addDGVEinarbeitung("PDF: AusgangsVermerk ", BezugsNr)

                                            End Select
                                        End If
                                    End If
                                Case 3  'NOT FOUND 

                                    If fi.Extension = ".pdf" Then ' -> PDFs dürfen länger leben.. (XML kommen oft später..)
                                        If DateDiff(DateInterval.Hour, fi.CreationTime, Now) > 2 Then ' .. aber nur wenn max. 2 h alt..
                                            frmStartOptions.moveFile(d, ERROR_PFAD)
                                            dsNichtErkannt += 1
                                        End If
                                    Else
                                        frmStartOptions.moveFile(d, ERROR_PFAD) ' ..sonst weg damit!
                                        dsNichtErkannt += 1
                                    End If
                                    Me.Refresh()
                            End Select


                            If True Then
                                If Not alreadyMoved Then
                                    If found Then
                                        If Not System.IO.Directory.Exists(ZIEL_PFAD & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\") Then System.IO.Directory.CreateDirectory(ZIEL_PFAD & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\")
                                        frmStartOptions.moveFile(d, ZIEL_PFAD & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\")
                                        cntDatenEingelesen += 1
                                        Me.Refresh()
                                    Else
                                        '--wir oben im SELECT CASE GEREGELT -- > zusätzlicher Durchgang

                                    End If
                                End If

                            End If


                        End If
                    End If
                Catch ex As Exception
                    VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
                End Try
            Next
        Next
    End Sub



    Function getString(doc As XmlDocument) As Boolean
        If doc.HasChildNodes Then
            '  If doc.GetElementsByTagName("DakosyMessageInternal").Count > 0 Then
            Dim sw = New StringWriter()
            Dim xw = New XmlTextWriter(sw)
            doc.WriteTo(xw)
            Dim XmlString = sw.ToString()
            MsgBox(XmlString)
        End If
        Return False
    End Function



    Private Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click
        Me.Close()
    End Sub

    Private Sub btn_Click(sender As Object, e As EventArgs) Handles btn.Click
        Me.Close()
    End Sub




    Sub Savetelanm_FirmaNL(ByRef TC_TMP As TELOTEC_Worker.cTelotec_Anmeldung, division As String)
        TC_TMP.telanm_firma = "IMEX"
        TC_TMP.telanm_niederlassung = "SUB"
        '            
        'If division <> "" Then
        '    If (TC_TMP.telanm_firma Is Nothing OrElse TC_TMP.telanm_firma = "") Or (TC_TMP.telanm_niederlassung Is Nothing OrElse TC_TMP.telanm_niederlassung = "") Then
        '        Select Case division
        '            Case "SUW"
        '                TC_TMP.telanm_firma = "ATILLA"
        '                TC_TMP.telanm_niederlassung = "SUB"
        '            Case "SUB"
        '                TC_TMP.telanm_firma = "VERAG"
        '                TC_TMP.telanm_niederlassung = "SUB"
        '            Case "DUR"
        '                TC_TMP.telanm_firma = "DURMAZ"
        '                TC_TMP.telanm_niederlassung = "SBG"
        '            Case "NKD"
        '                TC_TMP.telanm_firma = "VERAG"
        '                TC_TMP.telanm_niederlassung = "NKD"
        '            Case "WAI"
        '                TC_TMP.telanm_firma = "VERAG"
        '                TC_TMP.telanm_niederlassung = "WAI"
        '            Case "SBG"
        '                TC_TMP.telanm_firma = "VERAG"
        '                TC_TMP.telanm_niederlassung = "SBG"
        '            Case "NEU"
        '                TC_TMP.telanm_firma = "VERAG"
        '                TC_TMP.telanm_niederlassung = "NEU"
        '            Case "GLO"
        '                TC_TMP.telanm_firma = "IMEX"
        '                TC_TMP.telanm_niederlassung = "GLO"
        '            Case "AMB"
        '                TC_TMP.telanm_firma = "AMBAR"
        '                TC_TMP.telanm_niederlassung = "AMBAR"
        '            Case "IME"
        '                TC_TMP.telanm_firma = "IMEX"
        '                TC_TMP.telanm_niederlassung = "IMEX"
        '        End Select
        '        TC_TMP.SAVE()
        '    End If

        'End If
    End Sub




    Sub addDGVEinarbeitung(art, BezugsNr)
        dgvEinarbeitung.Rows.Add(art, BezugsNr)
        Try
            dgvEinarbeitung.FirstDisplayedScrollingRowIndex = dgvEinarbeitung.RowCount - 1
        Catch ex As Exception
        End Try
    End Sub


    Function getVerahrensartFromBezugsNr(bezugsNr) As String
        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
        If SQL.getValueTxtBySql("SELECT TOP 1 COUNT(*) FROM tblDakosy_NCTSOut WHERE ncts_ObjectName='" & bezugsNr & "'", "FMZOLL") > 0 Then Return "NCTS"
        If SQL.getValueTxtBySql("SELECT TOP 1 COUNT(*) FROM tblDakosy_EZA WHERE eza_ObjectName='" & bezugsNr & "'", "FMZOLL") > 0 Then Return "EZA"
        Return ""
    End Function

    Function getStatusCheckTransID(transId As String, transDate As Date) As DAKOSY_Worker.cDakosy_Statusmeldungen
        getStatusCheckTransID = DAKOSY_Worker.cDakosy_Statusmeldungen.LOADByDakosyTransaktionsID(transId)
        If getStatusCheckTransID Is Nothing Then
            getStatusCheckTransID = New DAKOSY_Worker.cDakosy_Statusmeldungen
        End If
        getStatusCheckTransID.dySt_DakosyTransaktionsDatum = transDate
        getStatusCheckTransID.dySt_DakosyTransaktionsID = transId
    End Function

    Function saveDY_ZA(STATUS As DAKOSY_Worker.cDakosy_Statusmeldungen, transID As String, ergtransDate As Date, art As String) As DAKOSY_Worker.cDakosy_Zollanmeldungen
        Dim DY_TMP As DAKOSY_Worker.cDakosy_Zollanmeldungen = Nothing
        DY_TMP = DAKOSY_Worker.cDakosy_Zollanmeldungen.LOADByBezugsNr(STATUS.dySt_BezugsNr.ToString)
        If DY_TMP Is Nothing Then
            DY_TMP = New DAKOSY_Worker.cDakosy_Zollanmeldungen
            DY_TMP.dy_BezugsNr = STATUS.dySt_BezugsNr
            DY_TMP.dy_ART = art
            If DAKOSY_Worker.cDakosy_Statusmeldungen.isNewestTransaktion(STATUS.dySt_BezugsNr, transID, ergtransDate) Then
                DY_TMP.dy_Status = STATUS.dySt_status
            End If
            DY_TMP.SAVE()
            'Eintragen
        Else
            'Update  NCTS.Transaktion.IOReferenz, NCTS.Transaktion.IODatumZeit
            If DAKOSY_Worker.cDakosy_Statusmeldungen.isNewestTransaktion(STATUS.dySt_BezugsNr, transID, ergtransDate) Then
                DY_TMP.UPDATE_Status(STATUS.dySt_status)
            End If

        End If


        'Status wir dnur upgedatet, wenn nicht schon ein neuerer Datensatz verarbeitet wurde!:






        'If DY_TMP.dy_AvisoId Is Nothing Or DY_TMP.dy_SendungsId Is Nothing Then
        'If getAVSIOFromBezugsNr(STATUS.dySt_BezugsNr, DY_TMP.dy_AvisoId, DY_TMP.dy_SendungsId) Then ' Lädt AVSIO
        'DY_TMP.SAVE() ' AVISOID/SendungsID speichern
        ' End If
        ' End If

        saveDY_ZA = DY_TMP
    End Function
    Function saveDY_ZA(dySt_BezugsNr As String, art As String) As DAKOSY_Worker.cDakosy_Zollanmeldungen
        Dim DY_TMP As DAKOSY_Worker.cDakosy_Zollanmeldungen = Nothing
        DY_TMP = DAKOSY_Worker.cDakosy_Zollanmeldungen.LOADByBezugsNr(dySt_BezugsNr)
        If DY_TMP Is Nothing Then
            DY_TMP = New DAKOSY_Worker.cDakosy_Zollanmeldungen
            DY_TMP.dy_BezugsNr = dySt_BezugsNr
            DY_TMP.dy_ART = art
            ' DY_TMP.dy_Status = STATUS.dySt_status
            DY_TMP.SAVE()
            'Eintragen
        Else
            'Update
            ' DY_TMP.UPDATE_Status(STATUS.dySt_status)
        End If
        saveDY_ZA = DY_TMP
    End Function



    Function saveDY_EZA(STATUS As DAKOSY_Worker.cDakosy_Statusmeldungen, DY_TMP As DAKOSY_Worker.cDakosy_Zollanmeldungen, transID As String, transDate As Date, Optional ANR As String = "", Optional MRN As String = "") As DAKOSY_Worker.cDakosyEZA
        'EINTRAG IN tblDakosyNCTSOut
        Dim EZA_TMP As DAKOSY_Worker.cDakosyEZA = Nothing
        EZA_TMP = DAKOSY_Worker.cDakosyEZA.LOADByBezugsNr(STATUS.dySt_BezugsNr.ToString, False)
        If EZA_TMP Is Nothing Then
            EZA_TMP = New DAKOSY_Worker.cDakosyEZA
            EZA_TMP.eza_ObjectName = STATUS.dySt_BezugsNr
            If EZA_TMP IsNot Nothing Then EZA_TMP.eza_dyaAnmID = DY_TMP.dy_Id

            If DAKOSY_Worker.cDakosy_Statusmeldungen.isNewestTransaktion(STATUS.dySt_BezugsNr, transID, transDate) Then
                EZA_TMP.eza_Status = DY_TMP.dy_Status 'weil der Status bereit überprüft wurde --> neuste TransaktionsID
                EZA_TMP.eza_Status_KEWILL_Equivalent = DY_TMP.dy_Status 'weil der Status bereit überprüft wurde --> neuste TransaktionsID
            End If
            'EZA_TMP.ncts_Status_KEWILL_Equivalent = STATUS.dySt_status

            If ANR <> "" Then EZA_TMP.eza_ANR = ANR
            If MRN <> "" Then EZA_TMP.eza_MRN = MRN
            EZA_TMP.SAVE()
            'Eintragen

        Else

            'Update     
            EZA_TMP.UPDATE_Status(DY_TMP.dy_Status) 'weil der Status bereit überprüft wurde --> neuste TransaktionsID

            If ANR <> "" Then EZA_TMP.eza_ANR = ANR : EZA_TMP.SAVE()
            If MRN <> "" Then EZA_TMP.eza_MRN = MRN : EZA_TMP.SAVE()

        End If
        saveDY_EZA = EZA_TMP
    End Function




    Function readTC_Anmeldung(doc As XmlDocument, d As String) As String
        Try
            readTC_Anmeldung = ""
            'Dim sw = New StringWriter()
            'Dim xw = New XmlTextWriter(sw)
            'doc.WriteTo(xw)
            'Dim XmlString = sw.ToString()
            'MsgBox("0")
            'If XmlString.Contains("<vifDec>") Then
            '    MsgBox("1")
            '    Dim xmlvifDec = XmlString.Substring(XmlString.IndexOf("<vifDec>"), XmlString.IndexOf("</vifDec>") + 9 - XmlString.IndexOf("<vifDec>"))
            '    '  MsgBox(xmlDEXPDD)
            '    Dim p = Path.GetTempFileName
            '    MsgBox(p)
            '    Using outputFile As New StreamWriter(p) ', False, System.Text.Encoding.Default)
            '        MsgBox("1,1")
            '        outputFile.Write(xmlvifDec)
            '        outputFile.Close()


            Dim id = TELOTEC_Worker.vifDec.InterfaceDataType.LoadFromFile(d)
            Dim vifDEC As TELOTEC_Worker.vifDec.vifDec = id.vifDec(0)
            '  Dim AES As New DAKOSY_Worker.cDakosyAES

            Dim MsgType = ""

            If vifDEC IsNot Nothing And vifDEC.Refs_LRN IsNot Nothing Then
                readTC_Anmeldung = vifDEC.Refs_LRN
                MsgType = vifDEC.MsgType
            Else
                Return "" 'Keine Bezugsnummer
            End If

            '    Dim DY_TMP As TELOTEC_Worker.cTELOTEC_Zollanmeldungen = saveDY_ZA(readTC_Anmeldung, "AES")

            Dim TC As TELOTEC_Worker.cTelotec_Anmeldung = TELOTEC_Worker.cTelotec_Anmeldung.LOADByBezugsNr(readTC_Anmeldung, MsgType) ' Falls schon ein DS mit dieser Bezugsnummer vorhanden ist.
            If TC Is Nothing Then TC = New TELOTEC_Worker.cTelotec_Anmeldung
            '  If DY_TMP IsNot Nothing Then TC.TC_dyaAnmID = DY_TMP.dy_Id

            TC.telanm_BezugsNr = vifDEC.Refs_LRN
            If TC.telanm_AvisoId Is Nothing Then
                TC.tryFindAviso()
            End If


            If vifDEC IsNot Nothing Then
                'TC.telanm_BezugsNr = vifDEC.Refs_LRN

                TC.Mandant_ID = vifDEC.Mandant_ID
                TC.Bereich_ID = vifDEC.Bereich_ID
                TC.Referenz_ID = vifDEC.Referenz_ID
                TC.ComIndicator = vifDEC.ComIndicator

                TC.Hea_DecTy = vifDEC.Hea_DecTy
                'Art der Anmeldung
                Select Case TC.Hea_DecTy
                    Case "T1", "T2", "T2L" : TC.telanm_ART = TC.Hea_DecTy
                    Case "EUA" : TC.telanm_ART = TC.Hea_DecTy 'EZA
                    Case Else : TC.telanm_ART = TC.Hea_DecTy '^^
                End Select

                TC.MsgType = vifDEC.MsgType
                Select Case TC.MsgType
                    Case "TT906", "TT109" 'Eröffnung des Versandscheins
                        TC.telanm_Status = TELOTEC_Worker.cTC_Statusliste.S_50
                        TC.telanm_Status_KEWILL_Equivalent = TELOTEC_Worker.cTC_Statusliste.S_50
                    Case "TT132" 'Anrechnung des Referenzbetrages 
                        TC.telanm_Status = TELOTEC_Worker.cTC_Statusliste.S_53
                        TC.telanm_Status_KEWILL_Equivalent = TELOTEC_Worker.cTC_Statusliste.S_53
                    Case "TT131" 'Erledigungsmeldung 
                        TC.telanm_Status = TELOTEC_Worker.cTC_Statusliste.S_60
                        TC.telanm_Status_KEWILL_Equivalent = TELOTEC_Worker.cTC_Statusliste.S_60

                    Case "TT922" 'EZA / Mitteilung Zollschuld  --> Abgabenbescheid
                        TC.telanm_Status = TELOTEC_Worker.cTC_Statusliste.S_60
                        TC.telanm_Status_KEWILL_Equivalent = TELOTEC_Worker.cTC_Statusliste.S_60

                    Case "TT923" '  Freigabe IMPORT + EXPORT 
                        TC.telanm_Status = TELOTEC_Worker.cTC_Statusliste.S_60
                        TC.telanm_Status_KEWILL_Equivalent = TELOTEC_Worker.cTC_Statusliste.S_60
                    Case Else
                        Return "" 'Nicht erkannt
                End Select

                'Derzeit nur IMEX
                TC.telanm_firma = vifDEC.Mandant_ID.ToUpper '"IMEX"
                If TC.telanm_BezugsNr.ToString.StartsWith("5501") Then
                    TC.telanm_firma = "IMEX" 'VERAG WO
                End If
                If TC.telanm_BezugsNr.ToString.StartsWith("4801") Or TC.telanm_BezugsNr.ToString.StartsWith("4802") Then
                    TC.telanm_firma = "IMEX" 'VERAG WO
                End If
                TC.telanm_niederlassung = "SUB"

                TC.telanm_Erstellung = Now
                TC.telanm_LetzteBearbeitung = Now

                TC.Mandant_ID = vifDEC.Mandant_ID
                TC.Bereich_ID = vifDEC.Bereich_ID
                TC.Referenz_ID = vifDEC.Referenz_ID
                TC.ComIndicator = vifDEC.ComIndicator
                TC.dec_ProzessArt = vifDEC.dec_ProzessArt
                TC.TransferStatus = vifDEC.TransferStatus

                TC.dec_Anmelde_ID = vifDEC.dec_Anmelde_ID
                TC.dec_Template_ID = vifDEC.dec_Template_ID
                TC.dec_Lager_ID = vifDEC.dec_Lager_ID
                TC.dec_Lag_IND = vifDEC.dec_Lag_IND
                TC.dec_CreateDate = vifDEC.dec_CreateDate
                TC.dec_CreatePersonalID = vifDEC.dec_CreatePersonalID
                TC.dec_PreDec_IND = vifDEC.dec_PreDec_IND
                TC.dec_TotNet = vifDEC.dec_TotNet
                TC.dec_TotNetSplit_IND = vifDEC.dec_TotNetSplit_IND
                TC.dec_FillPackList_IND = vifDEC.dec_FillPackList_IND
                TC.dec_Memo = vifDEC.dec_Memo
                TC.Refs_LRN = vifDEC.Refs_LRN
                TC.Refs_CRN = vifDEC.Refs_CRN
                TC.telanm_CRN = vifDEC.Refs_CRN
                TC.Refs_CSRN = vifDEC.Refs_CSRN
                TC.Refs_ERN = vifDEC.Refs_ERN
                TC.Refs_FRN = vifDEC.Refs_FRN
                TC.Refs_Stat = vifDEC.Refs_Stat

                TC.Hea_DecTy = vifDEC.Hea_DecTy
                TC.Hea_TotItem = vifDEC.Hea_TotItem
                TC.Hea_TotPack = vifDEC.Hea_TotPack
                TC.Hea_TotGross = vifDEC.Hea_TotGross
                TC.Hea_DepLNG = vifDEC.Hea_DepLNG
                TC.Hea_DestLNG = vifDEC.Hea_DestLNG
                TC.Hea_PayTy = vifDEC.Hea_PayTy
                TC.Hea_DefPayRef = vifDEC.Hea_DefPayRef
                TC.Hea_PerPayRef = vifDEC.Hea_PerPayRef
                TC.Hea_PayMet = vifDEC.Hea_PayMet
                TC.Hea_AExpRef = vifDEC.Hea_AExpRef
                TC.Hea_Fin = vifDEC.Hea_Fin
                TC.Hea_Simp = vifDEC.Hea_Simp
                TC.Hea_IssD = vifDEC.Hea_IssD
                TC.Hea_AuthID = vifDEC.Hea_AuthID
                TC.Hea_TransDat = vifDEC.Hea_TransDat
                TC.Hea_WoffD = vifDEC.Hea_WoffD
                TC.Hea_DecDT = vifDEC.Hea_DecDT
                TC.Hea_DecPlc = vifDEC.Hea_DecPlc
                TC.Hea_AccDT = vifDEC.Hea_AccDT
                TC.Hea_SecInd = vifDEC.Hea_SecInd
                TC.Hea_ComRef = vifDEC.Hea_ComRef
                TC.Hea_ProArrDT = vifDEC.Hea_ProArrDT
                TC.Hea_PlaDepDT = vifDEC.Hea_PlaDepDT

                TC.Locs_TradCtry = vifDEC.Locs_TradCtry
                TC.Locs_Disp = vifDEC.Locs_Disp
                TC.Locs_Dest = vifDEC.Locs_Dest
                TC.Locs_GdsLocCd = vifDEC.Locs_GdsLocCd
                TC.Locs_GdsLoc = vifDEC.Locs_GdsLoc
                TC.Locs_GdsLocAuth = vifDEC.Locs_GdsLocAuth
                TC.Locs_LoadPlcCd = vifDEC.Locs_LoadPlcCd
                TC.Locs_LoadPlc = vifDEC.Locs_LoadPlc
                TC.Locs_CustPlc = vifDEC.Locs_CustPlc
                TC.Locs_ArrLocCd = vifDEC.Locs_ArrLocCd
                TC.Locs_ArrLoc = vifDEC.Locs_ArrLoc
                TC.Locs_ArrLocAuth = vifDEC.Locs_ArrLocAuth
                TC.Locs_WarTy = vifDEC.Locs_WarTy
                TC.Locs_WarCtry = vifDEC.Locs_WarCtry
                TC.Locs_War = vifDEC.Locs_War

                TC.Transp_InMo = vifDEC.Transp_InMo
                TC.Transp_BordMo = vifDEC.Transp_BordMo
                TC.Transp_DepTy = vifDEC.Transp_DepTy
                TC.Transp_DepIdnt = vifDEC.Transp_DepIdnt
                TC.Transp_DepNat = vifDEC.Transp_DepNat
                TC.Transp_CrossTy = vifDEC.Transp_CrossTy
                TC.Transp_CrossIdnt = vifDEC.Transp_CrossIdnt
                TC.Transp_CrossIdntNat = vifDEC.Transp_CrossIdntNat
                TC.Transp_ContInd = vifDEC.Transp_ContInd

                TC.ValData_TermDelCd = vifDEC.ValData_TermDelCd
                TC.ValData_TermDelPlc = vifDEC.ValData_TermDelPlc
                TC.ValData_TermDelSit = vifDEC.ValData_TermDelSit
                TC.ValData_InvCurr = vifDEC.ValData_InvCurr
                TC.ValData_ExRa = vifDEC.ValData_ExRa
                TC.ValData_InvVal = vifDEC.ValData_InvVal
                TC.ValData_TransacCd = vifDEC.ValData_TransacCd

                TC.ConorTra_Na = vifDEC.ConorTra_Na
                TC.ConorTra_Strt = vifDEC.ConorTra_Strt
                TC.ConorTra_Pst = vifDEC.ConorTra_Pst
                TC.ConorTra_Cty = vifDEC.ConorTra_Cty
                TC.ConorTra_Ctry = vifDEC.ConorTra_Ctry
                TC.ConorTra_TIN = vifDEC.ConorTra_TIN
                TC.ConorTra_UIDCtry = vifDEC.ConorTra_UIDCtry
                TC.ConorTra_UID = vifDEC.ConorTra_UID

                TC.ConeeTra_Na = vifDEC.ConeeTra_Na
                TC.ConeeTra_Strt = vifDEC.ConeeTra_Strt
                TC.ConeeTra_Pst = vifDEC.ConeeTra_Pst
                TC.ConeeTra_Cty = vifDEC.ConeeTra_Cty
                TC.ConeeTra_Ctry = vifDEC.ConeeTra_Ctry
                TC.ConeeTra_TIN = vifDEC.ConeeTra_TIN
                TC.ConeeTra_UIDCtry = vifDEC.ConeeTra_UIDCtry
                TC.ConeeTra_UID = vifDEC.ConeeTra_UID

                TC.ExpTra_Na = vifDEC.ExpTra_Na
                TC.ExpTra_Strt = vifDEC.ExpTra_Strt
                TC.ExpTra_Pst = vifDEC.ExpTra_Pst
                TC.ExpTra_Cty = vifDEC.ExpTra_Cty
                TC.ExpTra_Ctry = vifDEC.ExpTra_Ctry
                TC.ExpTra_TIN = vifDEC.ExpTra_TIN
                TC.ExpTra_UIDCtry = vifDEC.ExpTra_UIDCtry
                TC.ExpTra_UID = vifDEC.ExpTra_UID

                TC.Declarant_Na = vifDEC.Declarant_Na
                TC.Declarant_Strt = vifDEC.Declarant_Strt
                TC.Declarant_Pst = vifDEC.Declarant_Pst
                TC.Declarant_Cty = vifDEC.Declarant_Cty
                TC.Declarant_Ctry = vifDEC.Declarant_Ctry
                TC.Declarant_TIN = vifDEC.Declarant_TIN
                TC.Declarant_UIDCtry = vifDEC.Declarant_UIDCtry
                TC.Declarant_UID = vifDEC.Declarant_UID
                TC.Declarant_DecRep = vifDEC.Declarant_DecRep

                TC.Represent_RIN = vifDEC.Represent_RIN
                TC.Represent_Na = vifDEC.Represent_Na

                TC.EntryCO_Ref = vifDEC.EntryCO_Ref
                TC.ExitCO_Ref = vifDEC.ExitCO_Ref
                TC.SurvCO_Ref = vifDEC.SurvCO_Ref
                TC.DestCO_Ref = vifDEC.DestCO_Ref
                TC.PresCO_Ref = vifDEC.PresCO_Ref
                TC.DepCO_Ref = vifDEC.DepCO_Ref

                'TC.CtrlRslt_ResCd = vifDEC.CtrlRslt_ResCd'--> in Schnittstelle nicht vorhanden
                TC.CtrlRslt_DLimit = vifDEC.CtrlRslt_DLimit


                TC.POSITIONSDATEN.Clear() 'Falls DS schon Mal eingearbeitet wurde
                If vifDEC.vifDecItem IsNot Nothing AndAlso vifDEC.vifDecItem.Count > 0 Then
                    For Each vidDescITEM In vifDEC.vifDecItem
                        Dim POS As New TELOTEC_Worker.cTelotec_Positionsdaten

                        POS.Mandant_ID = vidDescITEM.Mandant_ID
                        POS.Bereich_ID = vidDescITEM.Bereich_ID
                        POS.Referenz_ID = vidDescITEM.Referenz_ID
                        POS.ComIndicator = vidDescITEM.ComIndicator
                        POS.Pos_ID = vidDescITEM.Pos_ID
                        POS.Item_Status = vidDescITEM.Item_Status
                        POS.Item_ComCd = vidDescITEM.Item_ComCd
                        POS.Item_GdsDes = vidDescITEM.Item_GdsDes
                        POS.Item_Gross = vidDescITEM.Item_Gross
                        POS.Item_Net = vidDescITEM.Item_Net
                        POS.Item_Orig = vidDescITEM.Item_Orig
                        POS.Item_ProcCd = vidDescITEM.Item_ProcCd
                        POS.Item_ProcAddCd = vidDescITEM.Item_ProcAddCd
                        POS.Item_ItVal = vidDescITEM.Item_ItVal
                        POS.Item_Pref = vidDescITEM.Item_Pref
                        POS.Item_Quota = vidDescITEM.Item_Quota
                        POS.Item_ValMet = vidDescITEM.Item_ValMet
                        POS.Item_VATInd = vidDescITEM.Item_VATInd
                        POS.Item_StatVal = vidDescITEM.Item_StatVal
                        POS.SurvCO_Ref = vidDescITEM.SurvCO_Ref
                        POS.Telo_Artikel_ID = vidDescITEM.Telo_Artikel_ID
                        POS.Telo_Artikelmenge = vidDescITEM.Telo_ArtikelMenge
                        POS.Telo_ArtikelMEH = vidDescITEM.Telo_ArtikelMEH

                        'vidDescITEM.vifDecPack

                        POS.PACKSTUECKE.Clear() 'Falls DS schon Mal eingearbeitet wurde
                        If vidDescITEM.vifDecPack IsNot Nothing AndAlso vidDescITEM.vifDecPack.Count > 0 Then
                            For Each vifDecPack In vidDescITEM.vifDecPack
                                Dim PK As New TELOTEC_Worker.cTelotec_Packstuecke

                                PK.Mandant_ID = vifDecPack.Mandant_ID
                                PK.Bereich_ID = vifDecPack.Bereich_ID
                                PK.Referenz_ID = vifDecPack.Referenz_ID
                                PK.ComIndicator = vifDecPack.ComIndicator
                                PK.Pos_ID = vifDecPack.Pos_ID
                                PK.Pack_ID = vifDecPack.Pack_ID
                                PK.Pack_Mark = vifDecPack.Pack_Mark
                                PK.Pack_Kind = vifDecPack.Pack_Kind
                                PK.Pack_Nr = vifDecPack.Pack_Nr
                                PK.Pack_Piec = vifDecPack.Pack_Piec
                                PK.Telo_Gross = vifDecPack.TELO_Gross

                                POS.PACKSTUECKE.Add(PK)
                            Next
                        End If

                        POS.ABGABEN.Clear() 'Falls DS schon Mal eingearbeitet wurde
                        If vidDescITEM.vifDecDutyCalc IsNot Nothing AndAlso vidDescITEM.vifDecDutyCalc.Count > 0 Then
                            For Each vifDecDutyCalc In vidDescITEM.vifDecDutyCalc
                                Dim ABG As New TELOTEC_Worker.cTelotec_PositionsdatenAbgaben

                                ABG.Mandant_ID = vifDecDutyCalc.Mandant_ID
                                ABG.Bereich_ID = vifDecDutyCalc.Bereich_ID
                                ABG.Referenz_ID = vifDecDutyCalc.Referenz_ID
                                ABG.ComIndicator = vifDecDutyCalc.ComIndicator
                                ABG.Pos_ID = vifDecDutyCalc.Pos_ID
                                ABG.DutyCalc_ID = vifDecDutyCalc.DutyCalc_ID
                                ABG.Ty = vifDecDutyCalc.Ty
                                ABG.BaseD = vifDecDutyCalc.BaseD
                                ABG.Curr = vifDecDutyCalc.Curr
                                ABG.Unit = vifDecDutyCalc.Unit
                                ABG.Base = vifDecDutyCalc.Base
                                ABG.Rate = vifDecDutyCalc.Rate
                                ABG.RateUsed = vifDecDutyCalc.RateUsed
                                ABG.Amnt = vifDecDutyCalc.Amnt
                                ABG.MeaID = vifDecDutyCalc.MeaID
                                ABG.TyInd = vifDecDutyCalc.TyInd

                                POS.ABGABEN.Add(ABG)
                            Next
                        End If

                        POS.DOC_CERTS.Clear() 'Falls DS schon Mal eingearbeitet wurde
                        If vidDescITEM.vifDecDocCerts IsNot Nothing AndAlso vidDescITEM.vifDecDocCerts.Count > 0 Then
                            For Each vifDecDocCerts In vidDescITEM.vifDecDocCerts
                                Dim DOCS As New TELOTEC_Worker.cTelotec_PositionsdatenDokumente

                                DOCS.Mandant_ID = vifDecDocCerts.Mandant_ID
                                DOCS.Bereich_ID = vifDecDocCerts.Bereich_ID
                                DOCS.Referenz_ID = vifDecDocCerts.Referenz_ID
                                DOCS.ComIndicator = vifDecDocCerts.ComIndicator
                                DOCS.Pos_ID = vifDecDocCerts.Pos_ID
                                DOCS.DocCerts_ID = vifDecDocCerts.DocCerts_ID
                                DOCS.DocCerts_DocCd = vifDecDocCerts.DocCerts_DocCd
                                DOCS.DocCerts_DTy = vifDecDocCerts.DocCerts_DTy
                                DOCS.DocCerts_DRef = vifDecDocCerts.DocCerts_DRef
                                DOCS.DocCerts_IssD = vifDecDocCerts.DocCerts_IssD


                                POS.DOC_CERTS.Add(DOCS)
                            Next
                        End If
                        TC.POSITIONSDATEN.Add(POS)
                    Next
                End If

                TC.SICHERHEIT.Clear() 'Falls DS schon Mal eingearbeitet wurde
                If vifDEC.vifDecGrteeRef IsNot Nothing AndAlso vifDEC.vifDecGrteeRef.Count > 0 Then
                    For Each vifDecGrteeRef In vifDEC.vifDecGrteeRef
                        Dim GRT As New TELOTEC_Worker.cTelotec_Sicherheit

                        GRT.Mandant_ID = vifDecGrteeRef.Mandant_ID
                        GRT.Bereich_ID = vifDecGrteeRef.Bereich_ID
                        GRT.Referenz_ID = vifDecGrteeRef.Referenz_ID
                        GRT.ComIndicator = vifDecGrteeRef.ComIndicator
                        GRT.GrteeRef_ID = vifDecGrteeRef.GrteeRef_ID
                        GRT.GrteeRef_GTy = vifDecGrteeRef.Grtee_GTy
                        GRT.GRN = vifDecGrteeRef.GRN
                        GRT.OGR = vifDecGrteeRef.OGR
                        GRT.Acc = vifDecGrteeRef.Acc
                        GRT.GTIN = vifDecGrteeRef.GTIN
                        GRT.GVal = vifDecGrteeRef.GVal
                        GRT.Curr = vifDecGrteeRef.Curr

                        TC.SICHERHEIT.Add(GRT)
                    Next
                End If




                TC.ABGABEN.Clear() 'Falls DS schon Mal eingearbeitet wurde
                If vifDEC.vifDecTotDuties IsNot Nothing AndAlso vifDEC.vifDecTotDuties.Count > 0 Then
                    For Each vifDecTotDuties In vifDEC.vifDecTotDuties
                        Dim ABG As New TELOTEC_Worker.cTelotec_Abgaben

                        ABG.Mandant_ID = vifDecTotDuties.Mandant_ID
                        ABG.Bereich_ID = vifDecTotDuties.Bereich_ID
                        ABG.Referenz_ID = vifDecTotDuties.Referenz_ID
                        ABG.ComIndicator = vifDecTotDuties.ComIndicator
                        ABG.TotDuties_ID = vifDecTotDuties.TotDuties_ID
                        ABG.Ty = vifDecTotDuties.Ty
                        ABG.Amnt = vifDecTotDuties.Amnt
                        ABG.TyInd = vifDecTotDuties.TyInd
                        ABG.Erstelldatum = vifDecTotDuties.Erstelldatum

                        TC.ABGABEN.Add(ABG)
                    Next
                End If


                ''''Aktuellste Nachricht
                If SQL.getValueTxtBySql("Select COUNT(*) FROM [tblTelotec_Anmeldung] WHERE telanm_BezugsNr='" & TC.telanm_BezugsNr & "' and telanm_Status>'" & TC.telanm_Status & "' ", "FMZOLL") > 0 Then
                    TC.telnam_aktuellsteNachricht = 0
                Else
                    TC.telnam_aktuellsteNachricht = 1
                    SQL.doSQL("UPDATE [tblTelotec_Anmeldung] set telnam_aktuellsteNachricht = 0 WHERE telanm_BezugsNr='" & TC.telanm_BezugsNr & "' ", "FMZOLL")     'alle anderen auf 0 setzen
                End If

                If TC.SAVE() Then
                    ' TELOTEC_Worker.cTELOTEC_Statusmeldungen.InsertStatusMeldung(DY_TMP, TELOTEC_Worker.cDY_Statusliste.S_05)
                    If If(TC.telanm_Status, 0) = TELOTEC_Worker.cTC_Statusliste.S_60 Then
                        ' TC.insertIntoSpedBuch()
                        Dim ZOLLIMPORT As New DAKOSY_Worker.cZOLL_IMPORT
                           ZOLLIMPORT.TelotecImport(TC)
                        ZOLLIMPORT.insertAbgabenTELOTEC(TC)

                        '=====IMPORT IN VERAG DATENMODELL==========
                        If TC.Hea_DecTy = "EUA" Then
                            Dim IMP As New DAKOSY_Worker.cImporter_TelotecToVERAG
                            IMP.ImportTelotec(TC, False, True)
                        End If
                        '==================================

                    End If
                    ' BEREITSTELLUNG DER DATEN AN FREMDSYSTEME
                    If TC.telanm_ART = "T1" Or TC.telanm_ART.ToString.Contains("T2") Or TC.telanm_ART.ToString.StartsWith("T-") Then
                        Select Case TC.telanm_Status
                            Case TELOTEC_Worker.cTC_Statusliste.S_50, TELOTEC_Worker.cTC_Statusliste.S_60
                                cVERAG_out_ncts.copyFileFTP_VERAGncts_TC(TC)
                        End Select
                    End If
                End If
            End If


            Try
                '  System.System.IO.File.Delete(p)
            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
            End Try

            addDGVEinarbeitung("TC: Anmeldung " & MsgType, readTC_Anmeldung)

            '    End Using

            'End If

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
            readTC_Anmeldung = ""
        End Try
    End Function


    Private Sub dgvEinarbeitung_SelectionChanged(sender As Object, e As EventArgs) Handles dgvEinarbeitung.SelectionChanged
        dgvEinarbeitung.ClearSelection()

    End Sub





    Public Function tryToInsertProgramm(brgak_datum, brgak_betrag, brgak_brgaktoId, brgak_filename, brgak_atc, brgak_fileline) As Boolean

        Dim sql As String = " begin tran" &
                            " if Not exists (select * from tblBrgAufschub with (updlock,serializable) where brgak_filename = @brgak_filename AND  brgak_fileline=@brgak_fileline) " &
                                   " begin " &
                                   " INSERT INTO tblBrgAufschub " &
                                   " (brgak_datum, brgak_betrag, brgak_brgaktoId, brgak_filename, brgak_atc,brgak_fileline) VALUES " &
                                   " (@brgak_datum, @brgak_betrag, @brgak_brgaktoId, @brgak_filename, @brgak_atc,@brgak_fileline) " &
                                " End " &
                                " commit tran "
        '(brgak_fileline='' OR ... )

        ' " ELSE " &
        '    " begin " &
        '       " UPDATE tblBrgAufschub " &
        '      " SET brgak_datum=@brgak_datum, brgak_betrag=@brgak_betrag, brgak_brgaktoId=@brgak_brgaktoId, brgak_filename=@brgak_filename, brgak_atc=@brgak_atc,brgak_fileline=@brgak_fileline " &
        '     " WHERE brgak_filename = @brgak_filename AND (brgak_fileline='' OR brgak_fileline=@brgak_fileline)" &
        '  " End " &



        Dim cn As New System.Data.SqlClient.SqlConnection()
        cn.ConnectionString = "Data Source=SQLGUIDE01.verag.ost.dmn;Initial Catalog=ADMIN;Integrated Security=false;User ID=AppUser;Password=yp/THDd?xM+pZ$;"
        cn.Open()
        Using cn
            Using cmd As New System.Data.SqlClient.SqlCommand(sql, cn)
                cmd.Parameters.AddWithValue("@brgak_datum", brgak_datum)
                cmd.Parameters.AddWithValue("@brgak_betrag", brgak_betrag)
                cmd.Parameters.AddWithValue("@brgak_brgaktoId", brgak_brgaktoId)
                cmd.Parameters.AddWithValue("@brgak_filename", brgak_filename)
                cmd.Parameters.AddWithValue("@brgak_atc", brgak_atc)
                cmd.Parameters.AddWithValue("@brgak_fileline", brgak_fileline)
                Try
                    cmd.ExecuteNonQuery()

                    ''Lösche File: --> vom ALTEN ATLAS
                    'Try
                    '    System.System.IO.File.Delete(frmRoutineManager.PathATLAS & "\" & brgak_filename)
                    'Catch ex As Exception
                    '    writeLog("ERROR", "Fehler beim Löschen der Aufschub-Datei: " & ex.Message)
                    'End Try
                    Return True
                Catch ex As System.Data.SqlClient.SqlException
                    writeLog("ERROR", "Fehler beim Schreiben in die Datenbank: " & ex.Message)
                End Try
            End Using
        End Using
        cn.Close()
        Return False
    End Function





    Private Sub frmTCNachrichtenVerarbeitung_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        If allowClose Then
            Me.Refresh()

            Button2.PerformClick()
            Button1.PerformClick()

            System.Threading.Thread.Sleep(2000)

            Me.Close()
        End If
    End Sub




End Class

