Imports System.Data.OleDb
Imports System.DirectoryServices.ActiveDirectory
Imports System.IO
Imports System.Net
Imports System.Text
Imports System.Xml

Imports DocumentFormat.OpenXml.Drawing.Diagrams

Imports DocumentFormat.OpenXml.Wordprocessing
Imports iTextSharp.text.pdf.qrcode.Version
Imports Org.BouncyCastle.Asn1.Pkcs
Imports Renci.SshNet
Imports VERAG_PROG_ALLGEMEIN


Public Class frmStartOptions
    Dim WithEvents timer As New Timer

    Private Sub lklAufschubkontenATLASEZOLL_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles lklAufschubkontenATLASEZOLL.LinkClicked, LinkLabel3.LinkClicked
        Dim f As New frmRoutineManager("AUFSCHUB", True, cbxHistory.Checked)
        Me.Visible = False
        f.ShowDialog()
        Me.Visible = True
        Me.BringToFront()
        ' AddHandler f.FormClosed, AddressOf closeMe
    End Sub

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

    Private Sub LinkLabel1_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
        Dim f As New frmRoutineManager("BRG", True, cbxHistory.Checked)
        Me.Visible = False
        f.ShowDialog()
        Me.Visible = True
        Me.BringToFront()
        'AddHandler f.FormClosed, AddressOf closeMe
    End Sub


    Sub closeMe()
        Me.Close()
        Application.Exit()
    End Sub

    Private Sub frmStartOptions_Load(sender As Object, e As EventArgs) Handles Me.Load
        timer.Interval = 2500

        VERAG_PROG_ALLGEMEIN.cAllgemein.PROGNAME = "ROUTINE_MANAGER"
        VERAG_PROG_ALLGEMEIN.cAllgemein.PROGID = 17

        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False

        MyComboBox1.Items.Clear()
        MyComboBox1.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("DAKOSY", "DY"))
        MyComboBox1.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("TELEOTEC", "TC"))
        MyComboBox1.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("DHF", "DHF"))

        MyComboBox2.Items.Clear()
        MyComboBox2.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("DAKOSY", "DY"))
        MyComboBox2.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("TELEOTEC", "TC"))
        MyComboBox2.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("DHF", "DHF"))

        cboBMDUnispedFirma.Items.Clear()
        cboBMDUnispedFirma.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("", ""))
        cboBMDUnispedFirma.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("UNISPED Österreich", "21"))
        cboBMDUnispedFirma.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("UNISPED Deutschland", "22"))
        cboBMDUnispedFirma.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("UNISPED Zollservice (AT)", "23"))
        cboBMDUnispedFirma.changeItem("")

        cboSYSKAFirma.Items.Clear()
        cboSYSKAFirma.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("", ""))
        cboSYSKAFirma.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("VERAG Spedition AG", "1"))
        cboSYSKAFirma.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("VERAG Spedition AG (DE)", "4"))
        cboSYSKAFirma.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("VERAG Customs Service GmbH", "11"))
        cboSYSKAFirma.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("ATILLA Spedition GmbH", "7"))
        cboSYSKAFirma.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("Front-Office Suben eG", "17"))
        cboSYSKAFirma.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("VERAG 360 GmbH", "19"))
        cboSYSKAFirma.changeItem("")

        txtGJ_UNISPED.Text = Now.Year

        txtEZOLLAnhDat._value = Now.ToShortDateString

        Dim PARAM = "" 'INSERT_BENACHRICHTIGUNG_VERMERKE_TEAMS
        Dim parameter() As String = Environment.GetCommandLineArgs().ToArray
        If (parameter.Count - 1) >= 1 Then 'Höher als 1 weil der index 0 der Pfad zum programm ist
            PARAM = parameter(1)
            'For i = 1 To parameter.Count - 1
            ' 'If parameter(i) = "HISTORY" Then PARAM = True
            ' Next
        End If

        'doIDSPlatts()
        'Exit Sub

        'PARAM=""
        'Standart-Errorverhalten ist MAIL
        VERAG_PROG_ALLGEMEIN.cAllgemein.ERR_OP_GLOBAL = VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL
        If PARAM <> "" Then
            'LOG
        End If
        Select Case PARAM
            Case "BRG_AUFSCHUB"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                Dim f As New frmRoutineManager("ALL", True)
                '  Me.Visible = False
                f.Show()
                AddHandler f.FormClosed, AddressOf closeMe
            Case "BRG_AUFSCHUB_HISTORY"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                Dim f As New frmRoutineManager("ALL", True, True)
                ' Me.Visible = False
                f.Show()
                AddHandler f.FormClosed, AddressOf closeMe

            Case "DY_EINARBEITUNG"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = True
                Dim f As New frmDYNachrichtenVerarbeitung(True)
                'Me.Visible = False ' irgend ein Grund
                f.Show()
                AddHandler f.FormClosed, AddressOf closeMe
            Case "DY_EINARBEITUNG_PROD"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                Dim f As New frmDYNachrichtenVerarbeitung(True)
                ' Me.Visible = False ' irgend ein Grund
                f.Show()
                AddHandler f.EV_FINISHED, AddressOf closeMe
                AddHandler f.FormClosed, AddressOf closeMe

            Case "NCTSTR_EINARBEITUNG_TEST"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = True
                Dim f As New frmTRNCTS_NachrichtenVerarbeitung(True)
                '  Me.Visible = False
                f.Show()
                AddHandler f.FormClosed, AddressOf closeMe
            Case "NCTSTR_EINARBEITUNG_PROD"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                Dim f As New frmTRNCTS_NachrichtenVerarbeitung(True)
                ' Me.Visible = False
                f.Show()
                AddHandler f.FormClosed, AddressOf closeMe

            Case "NCTSTR_EINARBEITUNG_OREGON_TEST"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = True
                Dim f As New frmTRNCTS_NachrichtenVerarbeitung_OREGON(True)
                ' Me.Visible = False
                f.Show()
                AddHandler f.FormClosed, AddressOf closeMe
            Case "NCTSTR_EINARBEITUNG_OREGON_PROD"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                Dim f As New frmTRNCTS_NachrichtenVerarbeitung_OREGON(True)
                ' Me.Visible = False
                f.Show()
                AddHandler f.FormClosed, AddressOf closeMe


            Case "NCTSTR_EINARBEITUNG_ATEZ_TEST"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = True
                Dim f As New frmTRNCTS_NachrichtenVerarbeitung_ATEZ(True)
                ' Me.Visible = False
                f.Show()
                AddHandler f.FormClosed, AddressOf closeMe

            Case "NCTSTR_EINARBEITUNG_ATEZ_PROD"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                Dim f As New frmTRNCTS_NachrichtenVerarbeitung_ATEZ(True)
                ' Me.Visible = False
                f.Show()
                AddHandler f.FormClosed, AddressOf closeMe


            Case "UPDATE_SMS"
                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "VERAG"
                UPDATE_SMS()
                closeMe()
            Case "DY_EINARBEITUNG_UNISPED"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "UNISPED"
                Dim f As New frmDYNachrichtenVerarbeitung(True)
                ' Me.Visible = False
                f.Show()
                AddHandler f.EV_FINISHED, AddressOf closeMe
                AddHandler f.FormClosed, AddressOf closeMe

            Case "MDM_EINARBEITUNG"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                Dim f As New frmMDMNachrichtenVerarbeitung(True)
                ' Me.Visible = False
                f.Show()
                AddHandler f.FormClosed, AddressOf closeMe
            Case "TC_EINARBEITUNG"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = True
                Dim f As New frmTCNachrichtenVerarbeitung(True)
                '  Me.Visible = False
                f.Show()
                AddHandler f.FormClosed, AddressOf closeMe
            Case "TC_EINARBEITUNG_PROD"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                Dim f As New frmTCNachrichtenVerarbeitung(True)
                '  Me.Visible = False
                f.Show()
                AddHandler f.FormClosed, AddressOf closeMe

            Case "DY_CODELISTEN" ' TEST & PROD
                Dim f As New frmInfo(PARAM)
                f.Show()
                AddHandler Me.Shown, Sub()
                                         Me.Refresh()
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0008", True)
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0008", False)
                                         Me.Refresh()
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0017", True)
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0017", False)
                                         Me.Refresh()
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0014", True)
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0014", False)
                                         Me.Refresh()
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0141", True)
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0141", False)
                                         Me.Refresh()
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("I0400", True)
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("I0400", False)
                                         Me.Refresh()
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("I0700", True)
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("I0700", False)
                                         Me.Refresh()
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0010", True)
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0010", False)
                                         Me.Refresh()
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0013", True)
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0013", False)
                                         Me.Refresh()
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("A0122", True)
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("A0122", False)
                                         Me.Refresh()
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("A0127", True)
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("A0127", False)
                                         Me.Refresh()
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("I0200", True)
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("I0200", False)
                                         Me.Refresh()
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("I6010", True)
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("I6010", False)
                                         importEZOLLWechselkurse(True)
                                         importEZOLLWechselkurse(False)
                                         Me.Refresh()
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0219", True)
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0219", False)
                                         Me.Refresh()
                                         closeMe()
                                     End Sub
            Case "KD_DATA_DAKOSY"
                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                DAKOSY_Worker.cDakosyFunftions.sendData()
                closeMe()
            Case "EZT_Bundesanzeiger_Importcodenummern"
                Dim f As New frmInfo(PARAM)
                f.Show()
                getETZBundesanzeiger_ImportCodenummern()
                closeMe()
            Case "EZB_Waehrungskurse"
                Dim f As New frmInfo(PARAM)
                f.Show()
                getEZB_Waehrungskurse()
                closeMe()
            Case "EZB_Waehrungskurse90D"
                Dim f As New frmInfo(PARAM)
                f.Show()
                getEZB_Waehrungskurse90D()
                closeMe()
            Case "UID_Pruefung"
                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                getUID_Pruefung(MyTextBox1.Text)
                closeMe()
            Case "WOELFL_USTVAntraege"
                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                sendWOELFL_USTVAntraege("al@verag.ag")
                closeMe()
            Case "SDL_GUELTISBIS"
                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                VERAG_PROG_ALLGEMEIN.SDL_Functions.SDL_GueltigBis_UTA_IDS()
                closeMe()

            Case "zoll_mail_attach"
                Dim f As New frmInfo(PARAM)
                f.Show()
                Dim pfad = ""
                Dim betreff = ""
                Dim von = ""

                If (parameter.Count - 1) >= 3 Then 'Höher als 1 weil der index 0 der Pfad zum programm ist

                    pfad = parameter(2)
                    betreff = parameter(3)
                    If (parameter.Count - 1) >= 5 Then von = parameter(5)

                    VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False

                    If von.Contains("@q8.com") Or betreff.Contains("IDSPRD: Platts Price Report") Then
                        importFileFromIDSMailAnhang(pfad, betreff)
                    ElseIf von.Contains("@miccustoms.com") Or betreff.Contains("FORWARDING EMAIL | BEZUGSNUMMER") Or betreff = "Report nctsTransDeclGuarantees generated successfully" Then
                        importFileFromMICMailAnhang(pfad, betreff)
                    Else
                        importFileFromDyMailAnhang(pfad, betreff)
                    End If
                End If
                closeMe()

            Case "MAIL_ATTACH_WORK_FILES"

                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                doIDSPlatts()
                doExcelImportNCTS_FREMD()

                closeMe()

            Case "ezoll_anhaenge"
                Dim f As New frmInfo(PARAM)
                f.Show()

                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                importFileFromEZOLL(Now) 'VERAG


                VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "UNISPED"
                importFileFromEZOLL(Now)

                closeMe()


            Case "ezoll_anhaenge_verag"
                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False

                importFileFromEZOLL(Now)

                closeMe()


            Case "ezoll_anhaenge_unisped"
                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "UNISPED"

                importFileFromEZOLL(Now)

                closeMe()


            Case "INSERT_BENACHRICHTIGUNG_VERMERKE_TEAMS"
                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False

                INSERT_BENACHRICHTIGUNG_VERMERKE_TEAMS()

                closeMe()


            '-----------IMEX---------------
            Case "IMEX_DVO_KUNDEN_BU"
                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                VERAG_PROG_ALLGEMEIN.cDVO_Interface.genStammdatenANSI(False, True, True)
                closeMe()

            Case "SYSKA_DATEN_BU"
                Dim f As New frmInfo(PARAM)
                f.Show()

                'FIBI Daten bereitstellen:
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                VERAG_PROG_ALLGEMEIN.cSyska_Interface.genDatensatz_Stammdaten(1, False)
                VERAG_PROG_ALLGEMEIN.cSyska_Interface.genDatensatz_Buchungen(1, False)

                VERAG_PROG_ALLGEMEIN.cSyska_Interface.genDatensatz_Stammdaten(7, False)
                VERAG_PROG_ALLGEMEIN.cSyska_Interface.genDatensatz_Buchungen(7, False)

                VERAG_PROG_ALLGEMEIN.cSyska_Interface.genDatensatz_Stammdaten(11, False)
                VERAG_PROG_ALLGEMEIN.cSyska_Interface.genDatensatz_Buchungen(11, False)

                VERAG_PROG_ALLGEMEIN.cSyska_Interface.genDatensatz_Stammdaten(17, False)
                VERAG_PROG_ALLGEMEIN.cSyska_Interface.genDatensatz_Buchungen(17, False)

                VERAG_PROG_ALLGEMEIN.cSyska_Interface.genDatensatz_Stammdaten(19, False)
                VERAG_PROG_ALLGEMEIN.cSyska_Interface.genDatensatz_Buchungen(19, False)

                'Offene Posten übernehmen:
                VERAG_PROG_ALLGEMEIN.cSyska_Interface.OP_Einlesen_ALL()

                'Risiko in FiBu eintragen:
                VERAG_PROG_ALLGEMEIN.cSyska_Interface.UPDATE_FIBU_RISIKO()

                closeMe()
            Case "SYSKA_RISIKO"
                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                VERAG_PROG_ALLGEMEIN.cSyska_Interface.UPDATE_FIBU_RISIKO()

                closeMe()

            Case "SYSKA_OP_EINLESEN"
                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                VERAG_PROG_ALLGEMEIN.cSyska_Interface.OP_Einlesen_ALL()

                closeMe()

            Case "UNISPED_BMD"
                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                VERAG_PROG_ALLGEMEIN.cBMD_Interface.genDatensatzCSV_ALL(False, False) 'Kunden noch nicht
                closeMe()
                '------------------------------
            Case "AWOR_LDV_to_BMD"
                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                VERAG_PROG_ALLGEMEIN.cLDV_Interface.copyLDV_BMD()
                closeMe()

                '-----------AMBAR-------------------
            Case "AMBAR_DATEV_DEBITOREN"

                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                VERAG_PROG_ALLGEMEIN.cDatev_Interface.genDatensatzCSV_ALL("AMBAR", False, True, False)
                closeMe()

            Case "AMBAR_DATEV_BUCHUNGEN"

                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                VERAG_PROG_ALLGEMEIN.cDatev_Interface.genDatensatzCSV_ALL("AMBAR", False, False, True)
                closeMe()


            Case "AMBAR_DATEV_ALL"

                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                VERAG_PROG_ALLGEMEIN.cDatev_Interface.genDatensatzCSV_ALL("AMBAR", False, True, True)
                closeMe()

            Case "ASFINAG_EXPORT"
                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                Dim blt = New cAsfinag.Exportist
                Dim autoclose As Boolean = True
                blt.initExportPfade()
                blt.exportiereWhiteList(autoclose)
                blt.exportiereBlackList(autoclose)
                closeMe()

            Case "ASFINAG_IMPORT"
                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                Dim autoclose As Boolean = True
                Dim testFTP As Boolean = VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM
                Dim fmCLF As New frmAsfinag_NachrichtenVerabeitung("CLF", testFTP, autoclose)
                fmCLF.Show()
                AddHandler fmCLF.FormClosed, AddressOf closeMe
                Dim fmTTR As New frmAsfinag_NachrichtenVerabeitung("TTR", testFTP, autoclose)
                fmTTR.Show()
                AddHandler fmTTR.FormClosed, AddressOf closeMe
                closeMe()

            Case "ASFINAG_IMPORT_TEST"
                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = True
                Dim autoclose As Boolean = True
                Dim testFTP As Boolean = VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM
                Dim fmCLF As New frmAsfinag_NachrichtenVerabeitung("CLF", testFTP, autoclose)
                fmCLF.ShowDialog()
                AddHandler fmCLF.FormClosed, AddressOf closeMe
                Dim fmTTR As New frmAsfinag_NachrichtenVerabeitung("TTR", testFTP, autoclose)
                fmTTR.ShowDialog()
                AddHandler fmTTR.FormClosed, AddressOf closeMe
                closeMe()

            Case "ABGLEICH_KUNDENUEMSAETZE"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                Dim lastyears = 2
                If DELETE_Kundenumsaetze(lastyears) Then
                    INSERT_Kundenumsaetze(lastyears)
                End If
                '------------------------------
            Case Else
                'Nur bei manuellem Start wird der fehler ausgegeben
                VERAG_PROG_ALLGEMEIN.cAllgemein.ERR_OP_GLOBAL = VERAG_PROG_ALLGEMEIN.ERROR_OP.SHOW
                Me.WindowState = FormWindowState.Normal
        End Select
    End Sub

    Function INSERT_BENACHRICHTIGUNG_VERMERKE_TEAMS() As Boolean
        Try

            Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL

            Dim DT = SQL.loadDgvBySql("
                                    SELECT * FROM (
                                    SELECT Vermerke.*, CASE WHEN tblSnd_TeamId IS NULL THEN (SELECT TeamId from ADMIN.dbo.tblMitarbeiter WHERE mit_id=MitarbeiterId) ELSE tblSnd_TeamId END as tblSnd_TeamId,Firma
                                      FROM [Aviso] inner join tblSendungen on [Aviso].AvisoID=tblSnd_AvisoID inner join Vermerke on Vermerke.SendungID=tblSnd_SendungID
                                      where Status NOT IN (1,2) and Vermerke.VermerkeCode=13
                                      and VermerkIDAufgehoben is null 
                                      and DATEDIFF(HOUR,Vermerke.Datum,getdate())>24
                                        ) as T1 where tblSnd_TeamId is not null
	                                    and tblSnd_TeamId=1 
            ", "AVISO")
            If DT IsNot Nothing Then
                For Each r In DT.Rows
                    VERAG_PROG_ALLGEMEIN.cAvisoBenachrichtigungen.INSERT_BENACHRICHTIGUNG(r("AvisoId"), r("SendungId"), 5, "T", r("tblSnd_TeamId"), "Reminder: " & r("hinweis_vermerk"), 0,, , r("VermerkID"), r("VermerkeCode"), r("Firma"))
                Next
            End If
            Return True
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)

            Return False

        End Try
    End Function
    Function importFileFromEZOLL(datum As Date) As Boolean
        Try
            Dim db = "EZOLL"
            Select Case VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
                Case "UNISPED" : db = "EZOLL_UNISPED"
            End Select
            Dim sql As New VERAG_PROG_ALLGEMEIN.SQL
            Dim dt As DataTable = sql.loadDgvBySql("SELECT [zzAktivitaet].LizenzNr,[zzAktivitaet].Operatorid,[zzAktivitaet].AnmID,MsgTyp,[zzAktivitaet].ErstelltAm,pfad,LRN,CRN ,[zzAktivitaet].VorgangID   FROM [zzAktivitaet]     INNER JOIN zsAnmRefs On zsAnmrefs.AnmID=zzAktivitaet.AnmID 
                                                where MsgTyp IN ('EZ922','EZ923','TR109', 'EX431') and ErstelltAm>='" & datum.ToShortDateString & " 00:00:00'  and pfad is not null", db, 200)
            If dt IsNot Nothing Then
                For Each row In dt.Rows
                    Dim cDHF_Anhaenge As New VERAG_PROG_ALLGEMEIN.cDHF_Anhaenge(row("AnmID"), row("MsgTyp"), row("LizenzNr"))

                    If Not cDHF_Anhaenge.hasEntry Then 'WENN NEU::

                        cDHF_Anhaenge.AnmID = row("AnmID")
                        cDHF_Anhaenge.LizenzNr = row("LizenzNr")
                        cDHF_Anhaenge.Operatorid = row("Operatorid")
                        cDHF_Anhaenge.AnmID = row("AnmID")
                        cDHF_Anhaenge.MsgTyp = row("MsgTyp")
                        cDHF_Anhaenge.ErstelltAm = row("ErstelltAm")
                        cDHF_Anhaenge.pfad = row("pfad")
                        cDHF_Anhaenge.LRN = If(row("LRN") IsNot DBNull.Value, row("LRN"), "")
                        cDHF_Anhaenge.CRN = If(row("CRN") IsNot DBNull.Value, row("CRN"), "")

                        Dim destFull = ""
                        Dim Bezeichnung = ""
                        Select Case row("MsgTyp")
                            Case "EZ922" : Bezeichnung = "STEUERBESCHEID"
                            Case "EZ923"
                                Select Case row("VorgangID")
                                    Case "AF"
                                        Bezeichnung = "ABD"
                                    Case Else '"EF" 
                                        Bezeichnung = "STEUERBESCHEID_MITT"
                                End Select
                            Case "TR109" : Bezeichnung = "VBD"
                            Case "EX431" : Bezeichnung = "AVM"
                        End Select

                        Try


                            If cDHF_Anhaenge.pfad <> "" Then
                                Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER("ZOLLDATEN", Bezeichnung, cDHF_Anhaenge.AnmID, "", "", "DHF_" & cDHF_Anhaenge.LRN.ToString.Replace("/", "-").Replace(",", "-").Replace("\", "-").Replace(":", "."), 0, False)
                                DS.da_vorlage = False

                                Dim ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "ZOLARIS\ECHTSYSTEM\ZOLLDATEN\" & Bezeichnung & "\" & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\"
                                If Not IO.Directory.Exists(ZIEL_PFAD) Then IO.Directory.CreateDirectory(ZIEL_PFAD)

                                destFull = ""
                                Select Case VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA

                                    Case "UNISPED" : copyFile(cDHF_Anhaenge.pfad.Replace("C:\", "\\SRV04.unisu.at\c$\"), ZIEL_PFAD, destFull)
                                    Case Else : copyFile(cDHF_Anhaenge.pfad.Replace("C:\", "\\Ezoll\c$\"), ZIEL_PFAD, destFull)

                                End Select

                                If destFull <> "" Then
                                    If DS.insertDataToDATENSERVER(destFull) Then
                                        cDHF_Anhaenge.docID = DS.da_id
                                    End If
                                End If
                            End If
                        Catch ex As Exception
                            MsgBox(ex.Message & ex.StackTrace)
                        End Try

                        cDHF_Anhaenge.SAVE()
                        Dim SPEDBUCH_TMP As VERAG_PROG_ALLGEMEIN.cSpeditionsbuch = Nothing
                        If cDHF_Anhaenge.docID > 0 AndAlso cDHF_Anhaenge.LRN <> "" Then
                            Select Case row("MsgTyp")
                                Case "EZ922"
                                    DAKOSY_Worker.cZOLL_IMPORT.EZOLLImport(cDHF_Anhaenge.LRN, "EZA", SPEDBUCH_TMP) 'Versucht den SpedBucheintrag, falls noch nicht vorhanden
                                    sql.doSQL("Update Speditionsbuch SET [DokumentId_Steuerbeleg]='" & cDHF_Anhaenge.docID & "' WHERE AtlasBezNrEZA='" & cDHF_Anhaenge.LRN & "' AND [DokumentId_Steuerbeleg] is null", "FMZOLL")
                                Case "TR109"
                                    DAKOSY_Worker.cZOLL_IMPORT.EZOLLImport(cDHF_Anhaenge.LRN, "NCTS", SPEDBUCH_TMP) 'Versucht den SpedBucheintrag, falls noch nicht vorhanden
                                    sql.doSQL("Update Speditionsbuch SET [DokumentId_VBD]='" & cDHF_Anhaenge.docID & "' WHERE AtlasBezNrEZA='" & cDHF_Anhaenge.LRN & "' AND [DokumentId_VBD] is null", "FMZOLL")
                                    ' BEREITSTELLUNG DER DATEN AN FREMDSYSTEME
                                    cVERAG_out_ncts.copyFileFTP_VERAGncts_EZOLL(cDHF_Anhaenge.AnmID)

                                Case "EZ923" ' STB/ABD
                                    Select Case row("VorgangID")
                                        Case "AF" ' --> AUSFUHR --> ABD
                                            'AES Stuff.... 
                                            DAKOSY_Worker.cZOLL_IMPORT.EZOLLImport(cDHF_Anhaenge.LRN, "AES", SPEDBUCH_TMP) 'Versucht den SpedBucheintrag, falls noch nicht vorhanden
                                            sql.doSQL("Update Speditionsbuch SET [DokumentId_ABD]='" & cDHF_Anhaenge.docID & "' WHERE AtlasBezNrEZA='" & cDHF_Anhaenge.LRN & "' AND DokumentId_ABD is null", "FMZOLL")
                                            'Zeitspanne ? 3 Tage , älter nicht senden..
                                            If destFull <> "" AndAlso SPEDBUCH_TMP IsNot Nothing AndAlso SPEDBUCH_TMP.SendungID IsNot Nothing Then
                                                doMailZollbeleg(destFull, "ABD", SPEDBUCH_TMP.SendungID, cDHF_Anhaenge.LRN)
                                            End If
                                        Case Else '' --> EINFUHR --> 'Ergänzung STB - Mitteilung

                                            DAKOSY_Worker.cZOLL_IMPORT.EZOLLImport(cDHF_Anhaenge.LRN, "EZA", SPEDBUCH_TMP) 'Versucht den SpedBucheintrag, falls noch nicht vorhanden
                                            sql.doSQL("Update Speditionsbuch SET DokumentId_Mitteilung='" & cDHF_Anhaenge.docID & "' WHERE AtlasBezNrEZA='" & cDHF_Anhaenge.LRN & "' AND DokumentId_Mitteilung is null", "FMZOLL")

                                    End Select

                                Case "EX431" 'AVM  --> EZoll Anhänge & Mail senden
                                    'AES Stuff....
                                    DAKOSY_Worker.cZOLL_IMPORT.EZOLLImport(cDHF_Anhaenge.LRN, "AES", SPEDBUCH_TMP) 'Versucht den SpedBucheintrag, falls noch nicht vorhanden
                                    sql.doSQL("Update Speditionsbuch SET [DokumentId_AVM]='" & cDHF_Anhaenge.docID & "' WHERE AtlasBezNrEZA='" & cDHF_Anhaenge.LRN & "' AND DokumentId_AVM is null", "FMZOLL")

                                    If destFull <> "" AndAlso SPEDBUCH_TMP IsNot Nothing AndAlso SPEDBUCH_TMP.SendungID IsNot Nothing Then
                                        doMailZollbeleg(destFull, "AVM", SPEDBUCH_TMP.SendungID, cDHF_Anhaenge.LRN)
                                    End If

                            End Select

                        End If

                    End If
                Next
            End If
            Return True

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)

            Return False

        End Try
    End Function


    Sub doMailZollbeleg(pfad, art, dy_id)
        Try

            Dim DY As New DAKOSY_Worker.cDakosy_Zollanmeldungen(dy_id)
            If DY.dy_SendungsId IsNot Nothing AndAlso CInt(DY.dy_SendungsId) > 0 Then

                doMailZollbeleg(pfad, art, DY.dy_SendungsId, DY.dy_BezugsNr)

            End If

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
        End Try
    End Sub




    Sub doMailZollbeleg(pfad, art, dy_SendungsId, BezugsNr)
        Try

            If dy_SendungsId IsNot Nothing AndAlso CInt(dy_SendungsId) > 0 Then
                Dim SND As New VERAG_PROG_ALLGEMEIN.cSendungen(dy_SendungsId)
                Dim list As New List(Of Integer)

                sendMailZollbeleg(pfad, SND.tblSnd_EmpfaengerKdNr, art, list, BezugsNr, SND, SND.getKdAtrNr("EMPFAENGER"))
                sendMailZollbeleg(pfad, SND.tblSnd_AbsenderKdNr, art, list, BezugsNr, SND, "")
                sendMailZollbeleg(pfad, SND.tblSnd_FrachtfuehrerKdNr, art, list, BezugsNr, SND, SND.getKdAtrNr("FRAECHTER"))
                sendMailZollbeleg(pfad, SND.tblSnd_AvisiererKdNr, art, list, BezugsNr, SND, SND.getKdAtrNr("AVISIERER"))
                sendMailZollbeleg(pfad, SND.tblSnd_AuftraggeberKdNr, art, list, BezugsNr, SND, SND.getKdAtrNr("AUFTRAGGEBER"))
                sendMailZollbelegGESTELLUNGSADRESSE(pfad, SND.NCTS_ngaId, art, list, BezugsNr, SND)
            End If

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)

        End Try
    End Sub




    'Sub doMailZollbelegTC(pfad, art, tc_id)
    '    Try

    '        Dim DY As New TELOTEC_Worker.cTelotec_Anmeldung(tc_id)
    '        If DY.telanm_SendungsId IsNot Nothing AndAlso CInt(DY.telanm_SendungsId) > 0 Then
    '            Dim SND As New VERAG_PROG_ALLGEMEIN.cSendungen(DY.telanm_SendungsId)
    '            Dim list As New List(Of Integer)

    '            sendMailZollbeleg(pfad, SND.tblSnd_EmpfaengerKdNr, art, list, DY, SND)
    '            sendMailZollbeleg(pfad, SND.tblSnd_AbsenderKdNr, art, list, DY, SND)
    '            sendMailZollbeleg(pfad, SND.tblSnd_FrachtfuehrerKdNr, art, list, DY, SND)
    '            sendMailZollbeleg(pfad, SND.tblSnd_AvisiererKdNr, art, list, DY, SND)
    '            sendMailZollbeleg(pfad, SND.tblSnd_AuftraggeberKdNr, art, list, DY, SND)
    '        End If

    '    Catch ex As Exception
    '        VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)

    '    End Try
    'End Sub

    Function getStandortTXT(AVISO) As String
        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
        If AVISO IsNot Nothing Then

            If AVISO.Grenzstelle.Replace("???", "") = "" Then
                Return SQL.getValueTxtBySql("SELECT basncd_dstnr +' - ' + [basncd_name]  FROM basncd WHERE basncd_dstnr='" & If(AVISO.Zollstelle, "") & "' ", "ATLAS")
            Else
                Dim GRZ As New VERAG_PROG_ALLGEMEIN.cGrenzstelle(AVISO.Grenzstelle)
                If GRZ IsNot Nothing AndAlso GRZ.hasEntry Then
                    Return If(GRZ.grz_ZollamtDST, "") & " " & If(GRZ.grz_ZollamtBezeichnung, "")
                End If
            End If
        End If
        Return ""
    End Function
    Sub sendMailZollbeleg(pfad As String, KundenNr As Integer, art As String, ByRef list As List(Of Integer), BezugsNr As String, SND As VERAG_PROG_ALLGEMEIN.cSendungen, KdAtrNr As Object)
        Try
            If KundenNr > 0 Then
                If Not list.Exists(Function(x) x = KundenNr) Then 'nicht bereits verarbeitet
                    list.Add(KundenNr)
                    Dim pfadList As New List(Of String)
                    pfadList.Add(pfad)
                    Dim KD As New VERAG_PROG_ALLGEMEIN.cKunde(KundenNr)
                    Dim KD_ERW As New VERAG_PROG_ALLGEMEIN.cKundenErweitert(KundenNr)

                    If KD_ERW IsNot Nothing AndAlso KD IsNot Nothing Then ' AndAlso KD.EmailFreigabe Then


                        Dim AVISO = VERAG_PROG_ALLGEMEIN.cAviso.getAvisoById(SND.tblSnd_AvisoID)
                        'Wenn Freigabe-Mail aktiv und Steuerbescheid oder VBD gewählt, soll bei Fremdgrenzen die BelegMail gesendet werden.
                        Dim sendMailFremdgrenze = False
                        If KD_ERW.EmailFreigabe_Art = "FG" Or KD_ERW.EmailFreigabe_Export_Art = "FG" Then
                            If KD_ERW.EmailFreigabe_SteuerbescheidPDF Or KD_ERW.EmailFreigabe_VBDPDF Then

                                If AVISO IsNot Nothing Then
                                    'Fremdgrenze    
                                    If AVISO.Grenzstelle = "???" Then
                                        sendMailFremdgrenze = True
                                    Else
                                        'Prüfen ob WO oder ZA
                                        Dim GRZ As New VERAG_PROG_ALLGEMEIN.cGrenzstelle(AVISO.Grenzstelle)
                                        If GRZ IsNot Nothing AndAlso GRZ.hasEntry Then
                                            If GRZ.grz_Zollamt Then sendMailFremdgrenze = True  '--> Mail bei Beleg
                                            If GRZ.grz_Warenort Then sendMailFremdgrenze = True   '--> Mail bei Beleg
                                        End If
                                    End If
                                End If
                            End If
                        End If


                        If sendMailFremdgrenze Or KD_ERW.EmailFreigabe_Art = "BLG" Or KD_ERW.EmailFreigabe_Export_Art = "BLG" Or (art = "AVM" And KD_ERW.Email_AVM) Or (art = "ABD" And (KD_ERW.EmailFreigabe_ABDPDF Or KD_ERW.EmailFreigabe_Export_Art = "BLG")) Or art = "ZNV" Then ' Bei AVM ist es immer nach Freigabe, auch ZNV 
                            Dim Standort = "SUB"
                            Select Case SND.FilialenNr
                                Case "5501" : Standort = "IMX"
                                Case "5601" : Standort = "UNI"
                                Case "5701" : Standort = "AMB"
                                Case "5801" : Standort = "FO"
                                Case "4801" : Standort = "ATL"
                                Case "4802" : Standort = "ATL"
                                Case "5003" : Standort = "SBG"
                                Case "5103" : Standort = "WAI"
                                Case "5303" : Standort = "NKD"
                                Case Else
                                    Standort = "SUB"
                            End Select

                            Dim cStandorteDAL As New VERAG_PROG_ALLGEMEIN.cStandorteDAL

                            'Dim gst = ""
                            'Dim AVISO = VERAG_PROG_ALLGEMEIN.cAviso.getAvisoById(DY.dy_AvisoId)
                            'If AVISO IsNot Nothing Then
                            '    gst = AVISO.Grenzstelle.Replace("???", "")
                            'End If

                            Dim cStandort = cStandorteDAL.LesenStandort(-1, "", "SELECT * FROM Standorte WHERE Standort = '" & Standort & "'")
                            Dim FirmaTmp = VERAG_PROG_ALLGEMEIN.cAllgemein.getFirmaFromFiliale2(SND.FilialenNr)



                            Dim betreff = cStandort.eMail_Zollbeleg_Betreff '"Zollbeleg"
                            betreff = betreff.Replace("%LKW%", AVISO.LKW_Nr)
                            betreff = betreff.Replace("%AbfertigungsNr%", SND.FilialenNr & "/" & SND.AbfertigungsNr)
                            betreff = betreff.Replace("%Standort%", "")
                            betreff = betreff.Replace("%Uhrzeit%", "")
                            betreff = betreff.Replace("%KdAuftrNr%", If(KdAtrNr IsNot Nothing AndAlso KdAtrNr.ToString.Trim <> "", "Ihre Auftragsnr: " & KdAtrNr, ""))


                            Dim body = cStandort.eMail_Zollbeleg_Text


                            Dim EMails As String = ""
                            Dim EMails_CC As String = ""
                            Dim EMails_BCC As String = ""

                            Dim Emails_list_sent As New VERAG_PROG_ALLGEMEIN.cEmailBenachrichtigungList

                            Dim Mail_Art = -1
                            Select Case art
                                Case "AVM", "ABD" 'Export
                                    Mail_Art = 4 ' Freigabe Export

                                    'If EMails_BCC = "" Then
                                    '    EMails_BCC = "al@verag.ag"
                                    'Else
                                    '    EMails_BCC &= ";al@verag.ag"
                                    'End If
                                Case Else
                                    Mail_Art = 2
                            End Select
                            Select Case SND.tblSnd_Abfertigungsart_ID
                                Case 6, 7, 33, 34, 37, 40, 43
                                    Mail_Art = 4 ' Freigabe Export
                            End Select




                            VERAG_PROG_ALLGEMEIN.cEmailBenachrichtigung.eMails_einlesen(KundenNr, Mail_Art, EMails, EMails_CC, EMails_BCC, Emails_list_sent)
                            '  body = body.Replace("%Platzhalter%", "E-Mails: " & EMails & " CC: " & EMails_CC & " BCC:" & EMails_BCC)
                            body = body.Replace("%Platzhalter%", "")

                            body = body.Replace("%LKW%", AVISO.LKW_Nr)
                            body = body.Replace("%AbfertigungsNr%", SND.FilialenNr & "/" & SND.AbfertigungsNr)
                            body = body.Replace("%Standort%", getStandortTXT(AVISO))
                            body = body.Replace("%Uhrzeit%", Now.ToShortDateString & " " & Now.ToShortTimeString & " Uhr")
                            body = body.Replace("%KdAuftrNr%", If(KdAtrNr IsNot Nothing AndAlso KdAtrNr.ToString.Trim <> "", "Ihre Auftragsnr: " & KdAtrNr, ""))





                            ''!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                            'VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR("!!!!!!!!!!!!!!!!!!!!!!!!!: " & vbNewLine & EMails & vbNewLine & EMails_CC, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
                            ''!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

                            '!!!!!!!!!!!!!!!!!!!!!!!!!!
                            'EMails = "luxbauer@gmail.com"
                            'EMails_CC = ""
                            'EMails_BCC = ""
                            '!!!!!!!!!!!!!!!!!!!!!!!!!!

                            'If EMails_BCC = "" Then
                            '    EMails_BCC = "al@verag.ag"
                            'Else
                            '    EMails_BCC &= ";al@verag.ag"
                            ''End If
                            ''!!!!!!!!!!!!!!!!!!!!!!!!!!
                            'If KundenNr = 706113 Then
                            '    EMails = "al@verag.ag"
                            '    EMails_CC = ""
                            '    EMails_BCC = ""
                            'End If
                            ''!!!!!!!!!!!!!!!!!!!!!!!!!!


                            Dim API = VERAG_PROG_ALLGEMEIN.cAPI.INSERT_API(VERAG_PROG_ALLGEMEIN.cAPI_INOUT.OUT, VERAG_PROG_ALLGEMEIN.cAPI_Type.MAIL, VERAG_PROG_ALLGEMEIN.cAPI_ART.AVISO_OUT_BELEGMAIL, art,,, KundenNr, SND.tblSnd_AvisoID, SND.tblSnd_SendungID, SND.FilialenNr, SND.AbfertigungsNr)

                            API.api_EMail = EMails
                            API.api_EMailCC = EMails_CC
                            API.api_EMailBCC = EMails_BCC
                            API.api_EMailSubject = betreff
                            API.api_EMailText = body
                            API.api_EMailAttCnt = pfadList.Count

                            betreff = betreff.Replace(vbNewLine, "").Replace(vbCr, "").Replace(vbLf, "").Replace(vbCrLf, "").Replace(System.Environment.NewLine, " ")


                            Select Case art
                                Case "STB"
                                    If KD_ERW.EmailFreigabe_SteuerbescheidPDF Then

                                        betreff = betreff.Replace("%Zollbeleg%", "Abgabenbescheid " & BezugsNr)
                                        If VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(EMails, betreff, body, getAbsenderEmail(FirmaTmp), False, False, EMails_CC, EMails_BCC, pfadList) Then
                                            API.UPDTAE_OK()
                                            insertSendungsVermerk(SND.tblSnd_SendungID, SND.tblSnd_AvisoID, "Zollbeleg '" & art & "' gesendet an: " & EMails, 46)
                                        Else
                                            API.UPDTAE_ERR()
                                        End If
                                    End If
                                Case "VBD"
                                    If (KD_ERW.EmailFreigabe_Export And KD_ERW.EmailFreigabe_Export_Art = "BLG") Or KD_ERW.EmailFreigabe_VBDPDF Then
                                        betreff = betreff.Replace("%Zollbeleg%", "Versandbegleitdokument " & BezugsNr)
                                        If VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(EMails, betreff, body, getAbsenderEmail(FirmaTmp), False, False, EMails_CC, EMails_BCC, pfadList) Then
                                            API.UPDTAE_OK()
                                            insertSendungsVermerk(SND.tblSnd_SendungID, SND.tblSnd_AvisoID, "Zollbeleg '" & art & "' gesendet an: " & EMails, 46)
                                        Else
                                            API.UPDTAE_ERR()
                                        End If
                                    End If
                                Case "ZNV"
                                    If KD_ERW.EmailFreigabe_SteuerbescheidPDF Then
                                        betreff = betreff.Replace("%Zollbeleg%", "Abgabenbescheid ZNV " & BezugsNr)
                                        If VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(EMails, betreff, body, getAbsenderEmail(FirmaTmp), False, False, EMails_CC, EMails_BCC, pfadList) Then
                                            API.UPDTAE_OK()
                                            insertSendungsVermerk(SND.tblSnd_SendungID, SND.tblSnd_AvisoID, "Zollbeleg '" & art & "' gesendet an: " & EMails, 46)
                                        Else
                                            API.UPDTAE_ERR()
                                        End If
                                    End If
                                Case "ABD"
                                    If KD_ERW.EmailFreigabe_Export Or KD_ERW.EmailFreigabe_ABDPDF Then
                                        betreff = betreff.Replace("%Zollbeleg%", "Ausfuhrbegleitdokument " & BezugsNr)
                                        If VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(EMails, betreff, body, getAbsenderEmail(FirmaTmp), False, False, EMails_CC, EMails_BCC, pfadList) Then
                                            API.UPDTAE_OK()
                                            insertSendungsVermerk(SND.tblSnd_SendungID, SND.tblSnd_AvisoID, "Zollbeleg '" & art & "' gesendet an: " & EMails, 46)
                                        Else
                                            API.UPDTAE_ERR()
                                        End If
                                    End If
                                Case "AVM"
                                    If KD_ERW.EmailFreigabe_Export Or KD_ERW.Email_AVM Then
                                        betreff = betreff.Replace("%Zollbeleg%", "Ausgangsvermerk " & BezugsNr)
                                        If VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(EMails, betreff, body, getAbsenderEmail(FirmaTmp), False, False, EMails_CC, EMails_BCC, pfadList) Then
                                            API.UPDTAE_OK()
                                            insertSendungsVermerk(SND.tblSnd_SendungID, SND.tblSnd_AvisoID, "Zollbeleg '" & art & "' gesendet an: " & EMails, 46)
                                        Else
                                            API.UPDTAE_ERR()
                                        End If
                                    End If
                            End Select

                        End If
                    End If
                End If
            End If
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)

        End Try
    End Sub
    Sub sendMailZollbelegGESTELLUNGSADRESSE(pfad As String, nga_id As Object, art As String, ByRef list As List(Of Integer), BezugsNr As String, SND As VERAG_PROG_ALLGEMEIN.cSendungen)
        Try
            If nga_id IsNot Nothing Then
                If nga_id > 0 Then 'Not list.Exists(Function(x) x = KundenNr) Then 'nicht bereits verarbeitet
                    '   list.Add(KundenNr)
                    Dim pfadList As New List(Of String)
                    pfadList.Add(pfad)
                    Dim GST As New VERAG_PROG_ALLGEMEIN.cNCTSGestellungsadressen(nga_id)

                    If GST IsNot Nothing Then ' AndAlso KD.EmailFreigabe Then


                        Dim AVISO = VERAG_PROG_ALLGEMEIN.cAviso.getAvisoById(SND.tblSnd_AvisoID)
                        'Wenn Freigabe-Mail aktiv und Steuerbescheid oder VBD gewählt, soll bei Fremdgrenzen die BelegMail gesendet werden.
                        Dim sendMailFremdgrenze = False
                        'If KD_ERW.EmailFreigabe_Art = "FG" Or KD_ERW.EmailFreigabe_Export_Art = "FG" Then
                        '    If KD_ERW.EmailFreigabe_SteuerbescheidPDF Or KD_ERW.EmailFreigabe_VBDPDF Then

                        '        If AVISO IsNot Nothing Then
                        '            'Fremdgrenze    
                        '            If AVISO.Grenzstelle = "???" Then
                        '                sendMailFremdgrenze = True
                        '            Else
                        '                'Prüfen ob WO oder ZA
                        '                Dim GRZ As New VERAG_PROG_ALLGEMEIN.cGrenzstelle(AVISO.Grenzstelle)
                        '                If GRZ IsNot Nothing AndAlso GRZ.hasEntry Then
                        '                    If GRZ.grz_Zollamt Then sendMailFremdgrenze = True  '--> Mail bei Beleg
                        '                    If GRZ.grz_Warenort Then sendMailFremdgrenze = True   '--> Mail bei Beleg
                        '                End If
                        '            End If
                        '        End If
                        '    End If
                        'End If


                        If True Then ' Bei AVM ist es immer nach Freigabe, auch ZNV 
                            Dim Standort = "SUB"
                            Select Case SND.FilialenNr
                                Case "5501" : Standort = "IMX"
                                Case "5601" : Standort = "UNI"
                                Case "5701" : Standort = "AMB"
                                Case "5801" : Standort = "FO"
                                Case "4801" : Standort = "ATL"
                                Case "4802" : Standort = "ATL"
                                Case "5003" : Standort = "SBG"
                                Case "5103" : Standort = "WAI"
                                Case "5303" : Standort = "NKD"
                                Case Else
                                    Standort = "SUB"
                            End Select

                            Dim cStandorteDAL As New VERAG_PROG_ALLGEMEIN.cStandorteDAL

                            Dim cStandort = cStandorteDAL.LesenStandort(-1, "", "SELECT * FROM Standorte WHERE Standort = '" & Standort & "'")
                            Dim FirmaTmp = VERAG_PROG_ALLGEMEIN.cAllgemein.getFirmaFromFiliale2(SND.FilialenNr)



                            Dim betreff = cStandort.eMail_Zollbeleg_Betreff '"Zollbeleg"
                            betreff = betreff.Replace("%LKW%", AVISO.LKW_Nr)
                            betreff = betreff.Replace("%AbfertigungsNr%", SND.FilialenNr & "/" & SND.AbfertigungsNr)
                            betreff = betreff.Replace("%Standort%", "")
                            betreff = betreff.Replace("%Uhrzeit%", "")
                            betreff = betreff.Replace("%KdAuftrNr%", "")


                            Dim body = cStandort.eMail_Zollbeleg_Text


                            Dim EMails As String = ""
                            Dim EMails_CC As String = ""
                            Dim EMails_BCC As String = ""

                            '   Dim Emails_list_sent As New VERAG_PROG_ALLGEMEIN.cEmailBenachrichtigungList

                            '   VERAG_PROG_ALLGEMEIN.cEmailBenachrichtigung.eMails_einlesen(KundenNr, Mail_Art, EMails, EMails_CC, EMails_BCC, Emails_list_sent)
                            EMails = If(GST.nga_gestellungsMail, "")

                            body = body.Replace("%Platzhalter%", "")

                            body = body.Replace("%LKW%", AVISO.LKW_Nr)
                            body = body.Replace("%AbfertigungsNr%", SND.FilialenNr & "/" & SND.AbfertigungsNr)
                            body = body.Replace("%Standort%", getStandortTXT(AVISO))
                            body = body.Replace("%Uhrzeit%", Now.ToShortDateString & " " & Now.ToShortTimeString & " Uhr")
                            body = body.Replace("%KdAuftrNr%", "")





                            ''!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                            'VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR("!!!!!!!!!!!!!!!!!!!!!!!!!: " & vbNewLine & EMails & vbNewLine & EMails_CC, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
                            ''!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

                            '!!!!!!!!!!!!!!!!!!!!!!!!!!
                            'EMails = "luxbauer@gmail.com"
                            'EMails_CC = ""
                            'EMails_BCC = ""
                            '!!!!!!!!!!!!!!!!!!!!!!!!!!

                            'If EMails_BCC = "" Then
                            '    EMails_BCC = "al@verag.ag"
                            'Else
                            '    EMails_BCC &= ";al@verag.ag"
                            ''End If
                            ''!!!!!!!!!!!!!!!!!!!!!!!!!!
                            'If KundenNr = 706113 Then
                            '    EMails = "al@verag.ag"
                            '    EMails_CC = ""
                            '    EMails_BCC = ""
                            'End If
                            ''!!!!!!!!!!!!!!!!!!!!!!!!!!


                            betreff = betreff.Replace(vbNewLine, "").Replace(vbCr, "").Replace(vbLf, "").Replace(vbCrLf, "").Replace(System.Environment.NewLine, " ")

                            If EMails <> "" Then
                                Select Case art
                                    Case "VBD"
                                        Dim API = VERAG_PROG_ALLGEMEIN.cAPI.INSERT_API(VERAG_PROG_ALLGEMEIN.cAPI_INOUT.OUT, VERAG_PROG_ALLGEMEIN.cAPI_Type.MAIL, VERAG_PROG_ALLGEMEIN.cAPI_ART.AVISO_OUT_GESTELLUNGMAIL, art,,, nga_id, SND.tblSnd_AvisoID, SND.tblSnd_SendungID, SND.FilialenNr, SND.AbfertigungsNr)
                                        API.api_EMail = EMails
                                        API.api_EMailCC = EMails_CC
                                        API.api_EMailBCC = EMails_BCC
                                        API.api_EMailSubject = betreff
                                        API.api_EMailText = body
                                        API.api_EMailAttCnt = pfadList.Count

                                        betreff = betreff.Replace("%Zollbeleg%", "Versandbegleitdokument " & BezugsNr)
                                        If VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(EMails, betreff, body, getAbsenderEmail(FirmaTmp), False, False, EMails_CC, EMails_BCC, pfadList) Then
                                            API.UPDTAE_OK()
                                            insertSendungsVermerk(SND.tblSnd_SendungID, SND.tblSnd_AvisoID, "Zollbeleg '" & art & "' gesendet an: " & EMails, 46)
                                        Else
                                            API.UPDTAE_ERR()
                                        End If

                                End Select

                            End If

                        End If
                    End If
                End If
            End If
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)

        End Try
    End Sub


    Shared Sub insertSendungsVermerk(SendungID As Integer, AvisoID As Integer, Text As String, VermerkCodeId As Integer, Optional Beschreibung As String = "", Optional VorauskasseId As Object = Nothing, Optional addAuto As Boolean = False)
        'Daten zuweisen und speichern
        Dim myVermerk As New VERAG_PROG_ALLGEMEIN.cVermerk
        myVermerk.VermerkID = 0
        myVermerk.AvisoID = AvisoID
        myVermerk.Datum = Now
        myVermerk.Mitarbeiter = "(AUTO)"
        myVermerk.MitarbeiterId = -1
        myVermerk.Hinweis_Vermerk = Text
        myVermerk.VermerkCodeId = VermerkCodeId
        myVermerk.SendungID = SendungID
        If VorauskasseId IsNot Nothing AndAlso VorauskasseId IsNot DBNull.Value Then myVermerk.VorauskasseId = VorauskasseId
        myVermerk.VermerkArt = "S"
        Dim VermerkeDAL As New VERAG_PROG_ALLGEMEIN.cVermerkeDAL

        VermerkeDAL.SpeichernVermerk(myVermerk)

        If myVermerk.VermerkCodeId = 18 Then
            VermerkeDAL.UpdateLKW(myVermerk.AvisoID, False)
        End If

    End Sub

    Public Shared Function getAbsenderEmail(Optional FirmaTmp = "") As String
        Select Case If(FirmaTmp = "", VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA, FirmaTmp)
            Case "IMEX" : Return "noreply@imex-group.at"
            Case "ATILLA" : Return "noreply@verag.ag"
            Case "UNISPED" : Return "No-Reply@unisped.at"
            Case "FRONTOFFICE" : Return "noreply@front-office.eu"
            Case Else : Return "noreply@verag.ag"
        End Select
    End Function
    Sub importFileFromMICMailAnhang(pfad, betreff)

        Try
            Dim sql As New VERAG_PROG_ALLGEMEIN.SQL
            Dim DS As VERAG_PROG_ALLGEMEIN.cDATENSERVER = Nothing

            'moveFile(d, VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\nlc\")

            'IO.Directory.CreateDirectory(VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\ZOLLDATEN\TEST3\" & betreff.ToString.Replace(",", ""))
            'Report nctsTransDeclGuarantees generated successfully
            'If betreff.ToString.Contains("VBD FORWARDING EMAIL | BEZUGSNUMMER = ") Then
            If betreff.ToString.Contains("TAD FORWARDING EMAIL | ") Then
                betreff = betreff.replace("WG: ", "")
                betreff = betreff.replace("FW: ", "")
                betreff = betreff.replace("TAD FORWARDING EMAIL | ", "")
                betreff = betreff.trim


                Dim split = betreff.ToString.Split("|")

                Dim MRN = ""
                Dim LRN = ""
                For Each s In split
                    If s.Trim.StartsWith("MRN") Then
                        MRN = s.Replace("MRN", "").Trim
                    End If
                    If s.Trim.StartsWith("LRN") Then
                        LRN = s.Replace("LRN", "").Trim
                    End If
                Next

                Dim tmp_filialenNr = ""
                Dim tmp_abfertigungsNr = ""

                Dim SPEDBUCH As VERAG_PROG_ALLGEMEIN.cSpeditionsbuch = Nothing
                If LRN.ToString.Length >= 13 And LRN.ToString.Replace("-", "/").Contains("/") Then
                    Dim sp = LRN.ToString.Replace("-", "/").Split("/")
                    If sp(0).Length = 4 And sp(1).Length >= 8 Then
                        tmp_filialenNr = sp(0)
                        tmp_abfertigungsNr = sp(1).Substring(0, 8)
                        If IsNumeric(tmp_filialenNr) And IsNumeric(tmp_abfertigungsNr) Then
                            SPEDBUCH = New VERAG_PROG_ALLGEMEIN.cSpeditionsbuch(tmp_filialenNr, tmp_abfertigungsNr)
                            insertIntoSpedBuch_MIC(tmp_filialenNr, tmp_abfertigungsNr, LRN, "", SPEDBUCH, MRN) 'SPEDBUCH GENEREITERENERENRNERNERNERN!!!!
                        End If
                    End If
                End If

                DS = New VERAG_PROG_ALLGEMEIN.cDATENSERVER("ZOLLDATEN", "VBD", tmp_filialenNr & tmp_abfertigungsNr, "", "", LRN.ToString.Replace("/", "-").Replace(",", "-").Replace("\", "-").Replace(":", "."), 0, False)
                DS.da_vorlage = False

                Dim ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "MIC\ECHTSYSTEM\ZOLLDATEN\VBD\NOT_IDENTIFIED\"
                If SPEDBUCH IsNot Nothing AndAlso SPEDBUCH.hasEntry Then ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "MIC\ECHTSYSTEM\ZOLLDATEN\VBD\" & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\"
                If Not IO.Directory.Exists(ZIEL_PFAD) Then IO.Directory.CreateDirectory(ZIEL_PFAD)

                Dim destFull = ""
                moveFile(pfad, ZIEL_PFAD, destFull)



                If DS.insertDataToDATENSERVER(destFull) Then
                    If SPEDBUCH IsNot Nothing AndAlso SPEDBUCH.hasEntry Then
                        SPEDBUCH.DokumentId_VBD = DS.da_id
                        SPEDBUCH.SAVE()
                        'doMailZollbeleg(DS.GET_TOP1_PATH, "VBD", dy_id)
                    End If
                End If

                ''ABD
            ElseIf betreff.ToString.Contains("EAD FORWARDING EMAIL | ") Then
                betreff = betreff.replace("WG: ", "")
                betreff = betreff.replace("FW: ", "")
                betreff = betreff.replace("EAD FORWARDING EMAIL | ", "")
                betreff = betreff.trim

                Dim split = betreff.ToString.Split("|")

                Dim BEZUGSNUMMER = ""
                For Each s In split
                    If s.Trim.StartsWith("BEZUGSNUMMER ") Then
                        BEZUGSNUMMER = s.Replace("BEZUGSNUMMER ", "").Trim
                    End If

                Next

                Dim tmp_filialenNr = ""
                Dim tmp_abfertigungsNr = ""

                Dim SPEDBUCH As VERAG_PROG_ALLGEMEIN.cSpeditionsbuch = Nothing
                If BEZUGSNUMMER.ToString.Length >= 13 And BEZUGSNUMMER.ToString.Replace("-", "/").Contains("/") Then
                    Dim sp = BEZUGSNUMMER.ToString.Replace("-", "/").Split("/")
                    If sp(0).Length = 4 And sp(1).Length >= 8 Then
                        tmp_filialenNr = sp(0)
                        tmp_abfertigungsNr = sp(1).Substring(0, 8)
                        If IsNumeric(tmp_filialenNr) And IsNumeric(tmp_abfertigungsNr) Then
                            SPEDBUCH = New VERAG_PROG_ALLGEMEIN.cSpeditionsbuch(tmp_filialenNr, tmp_abfertigungsNr)
                            insertIntoSpedBuch_MIC(tmp_filialenNr, tmp_abfertigungsNr, "", BEZUGSNUMMER, SPEDBUCH, "")
                        End If
                    End If
                End If

                DS = New VERAG_PROG_ALLGEMEIN.cDATENSERVER("ZOLLDATEN", "ABD", tmp_filialenNr & tmp_abfertigungsNr, "", "", BEZUGSNUMMER.ToString.Replace("/", "-").Replace(",", "-").Replace("\", "-").Replace(":", "."), 0, False)
                DS.da_vorlage = False

                Dim ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "MIC\ECHTSYSTEM\ZOLLDATEN\ABD\NOT_IDENTIFIED\"
                If SPEDBUCH IsNot Nothing AndAlso SPEDBUCH.hasEntry Then ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "MIC\ECHTSYSTEM\ZOLLDATEN\ABD\" & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\"
                If Not IO.Directory.Exists(ZIEL_PFAD) Then IO.Directory.CreateDirectory(ZIEL_PFAD)

                Dim destFull = ""
                moveFile(pfad, ZIEL_PFAD, destFull)

                If DS.insertDataToDATENSERVER(destFull) Then
                    If SPEDBUCH IsNot Nothing AndAlso SPEDBUCH.hasEntry Then
                        SPEDBUCH.DokumentId_ABD = DS.da_id
                        SPEDBUCH.SAVE()
                        'doMailZollbeleg(DS.GET_TOP1_PATH, "ABD", dy_id)
                    End If
                End If

                'AVM
            ElseIf betreff.ToString.Contains("AVM - Ausgangsvermerk (DE), ") Then
                betreff = betreff.replace("WG: ", "")
                betreff = betreff.replace("FW: ", "")
                betreff = betreff.replace("AVM - Ausgangsvermerk (DE), ", "")
                If betreff.ToString.Contains(",") Then
                    Dim sp = betreff.ToString.Split(",")
                    betreff = sp(0).Trim

                    Dim dy_id As String = ""
                    If betreff.ToString.Length > 15 Then
                        dy_id = sql.getValueTxtBySql("SELECT isnull(aes_dyaAnmID,-1)  FROM [tblDakosy_AES] inner join tblDakosy_Zollanmeldungen on dy_id=aes_dyaAnmID where '" & betreff.ToString.Trim & "' LIKE aes_ObjectName +'%'  and LEN(aes_ObjectName)>=13", "FMZOLL")
                    Else
                        dy_id = sql.getValueTxtBySql("SELECT isnull(aes_dyaAnmID,-1)  FROM [tblDakosy_AES] inner join tblDakosy_Zollanmeldungen on dy_id=aes_dyaAnmID where aes_ObjectName='" & betreff.ToString.Trim & "'", "FMZOLL")
                    End If
                    '  IO.Directory.CreateDirectory(VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\ZOLLDATEN\TEST3\")

                    DS = New VERAG_PROG_ALLGEMEIN.cDATENSERVER("ZOLLDATEN", "AVM", dy_id, "", "", betreff.ToString.Replace("/", "-").Replace(",", "-").Replace("\", "-").Replace(":", "."), 0, False)
                    DS.da_vorlage = False

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

                    Dim destFull = ""
                    moveFile(pfad, ZIEL_PFAD, destFull)

                    If DS.insertDataToDATENSERVER(destFull) Then
                        If IsNumeric(dy_id) AndAlso dy_id > 0 Then
                            sql.doSQL("UPDATE tblDakosy_Zollanmeldungen SET dy_AVM_dsId='" & DS.da_id & "' where dy_id='" & dy_id & "'", "FMZOLL")
                            sql.doSQL("UPDATE Speditionsbuch SET DokumentId_AVM='" & DS.da_id & "' where AtlasBezNrEZA='" & betreff.ToString.Trim & "' AND DokumentId_AVM is null", "FMZOLL") 'Falls Spedbuch schon zuvor generiert wurde!
                            doMailZollbeleg(DS.GET_TOP1_PATH, "AVM", dy_id)
                        End If
                    End If

                End If
            ElseIf betreff = "Report nctsTransDeclGuarantees generated successfully" Then

                ' Dim ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\ZOLLDATEN\NCTS_XLS\" & Now.Year & "\"
                Dim ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\ZOLLDATEN\NCTS_XLS\NEW\"
                If Not IO.Directory.Exists(ZIEL_PFAD) Then IO.Directory.CreateDirectory(ZIEL_PFAD)

                Dim destFull = ""
                moveFile(pfad, ZIEL_PFAD, destFull)




            End If

            ' GENERELLES NOT IDENTIFIED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!




            '""""""""""""
            ' If Not alreadyMoved Then

            ' End If

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
        End Try

    End Sub
    Sub importFileFromIDSMailAnhang(pfad, betreff)

        Try
            Dim sql As New VERAG_PROG_ALLGEMEIN.SQL
            Dim DS As VERAG_PROG_ALLGEMEIN.cDATENSERVER = Nothing

            If betreff.contains("IDSPRD: Platts Price Report") Then

                Dim ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "IDS\IDS_XLS\Platts_Price_Report\NEW\"
                If Not IO.Directory.Exists(ZIEL_PFAD) Then IO.Directory.CreateDirectory(ZIEL_PFAD)

                Dim destFull = ""
                moveFile(pfad, ZIEL_PFAD, destFull)

            End If

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
        End Try

    End Sub
    'Sub importFileFromIDSMailAnhang(pfad, betreff)

    '    Try
    '        Dim sql As New VERAG_PROG_ALLGEMEIN.SQL
    '        Dim DS As VERAG_PROG_ALLGEMEIN.cDATENSERVER = Nothing

    '        If betreff.contains("IDSPRD: Platts Price Report") Then

    '            Dim ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "IDS\IDS_XLS\Platts_Price_Report\" & Now.Year & "\"
    '            If Not IO.Directory.Exists(ZIEL_PFAD) Then IO.Directory.CreateDirectory(ZIEL_PFAD)

    '            Dim destFull = ""
    '            moveFile(pfad, ZIEL_PFAD, destFull)

    '            Dim Excel1 As Object 'New Microsoft.Office.Interop.Excel.Application
    '            Dim Blatt As Object 'Microsoft.Office.Interop.Excel.Worksheet 'As Object 'as Worksheet
    '            Excel1 = CreateObject("Excel.Application")
    '            Dim txt As String
    '            Dim Datei As Object 'as WorkBook
    '            '  VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(destFull, "00", System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)

    '            Dim DT_PLATTS As New DataTable()

    '            DT_PLATTS.Columns.Add("IsoCode")
    '            DT_PLATTS.Columns.Add("Outlet")
    '            DT_PLATTS.Columns.Add("Group Description")
    '            DT_PLATTS.Columns.Add("Product")
    '            DT_PLATTS.Columns.Add("Price Period Start")
    '            DT_PLATTS.Columns.Add("Price Period End")
    '            DT_PLATTS.Columns.Add("Excise")
    '            DT_PLATTS.Columns.Add("Netprice")
    '            DT_PLATTS.Columns.Add("Currency")
    '            Try
    '                destFull = "\\datenarchiv.verag.ost.dmn\DATENARCHIV\IDS\IDS_XLS\Platts_Price_Report\2022\PLATTSPR_707156_0000167908_1_20032022063012.xls"

    '                VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("al@verag.ag", "TEST 1OOO " & destFull, "*AUTO*",,,,,,  )

    '                With Excel1
    '                    VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("al@verag.ag", "TEST 1.1", "*AUTO*",,,,,,  )
    '                    Try

    '                        Datei = .Workbooks.Open(destFull,, True) 'Anpassen
    '                        VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("al@verag.ag", "TEST 1.2", "*AUTO*",,,,,,  )

    '                    Catch ex As Exception
    '                        VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
    '                        MsgBox(ex.Message & ex.StackTrace)
    '                    End Try
    '                    'Try
    '                    '    Datei = .Workbooks.Open(destFull,, True) 'Anpassen
    '                    'Catch ex As Exception
    '                    '    System.Threading.Thread.Sleep(5000) ' 5 Sek. warten --> noch Zugriff vom Erstellen?
    '                    '    Datei = .Workbooks.Open(destFull,, True)
    '                    'End Try

    '                    Blatt = Datei.Worksheets(1) 'Anpassen

    '                    VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("al@verag.ag", "TEST 1.3", "*AUTO*",,,,,,  )
    '                    'Excel1.Workbooks.Open(destFull)
    '                    'Excel1.Visible = True ....wers braucht ?

    '                    Dim zeile = 12
    '                    'txt =""

    '                    VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("al@verag.ag", "TEST 2: " & Blatt.Range("A" & zeile).Value, "*AUTO*",,,,,,  )

    '                    While zeile <= 10000 AndAlso Blatt.Range("A" & zeile) IsNot Nothing AndAlso Blatt.Range("A" & zeile).Value <> ""

    '                        If Blatt.Range("A" & zeile).Value.ToString.Contains("Austria") Then

    '                            DT_PLATTS.Rows.Add({Blatt.Range("A" & zeile).Value, Blatt.Range("B" & zeile).Value, Blatt.Range("C" & zeile).Value, Blatt.Range("D" & zeile).Value, Blatt.Range("E" & zeile).Value, Blatt.Range("F" & zeile).Value, Blatt.Range("H" & zeile).Value, Blatt.Range("I" & zeile).Value, Blatt.Range("J" & zeile).Value})


    '                        End If



    '                        zeile += 1

    '                    End While
    '                    VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("al@verag.ag", "zeile: " & zeile, "*AUTO*",,,,,,  )


    '                End With


    '                'NEUE EXCEL GENEREITER, PREISE ANPASSEN, MAIL SENDEN
    '                If DT_PLATTS.Rows.Count > 0 Then
    '                    Dim XLS_PAth = destFull.Replace(".xls", "_NEW.xls")
    '                    Dim XLS_Tmp = ""
    '                    VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(DT_PLATTS,,,,, False, XLS_Tmp)
    '                    If XLS_Tmp <> "" Then
    '                        IO.File.Move(XLS_Tmp, XLS_PAth) ' Verschiebt die Datei

    '                        VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("al@verag.ag", "IDSPRD: Platts Price Report", "*AUTO*",,,,,, {XLS_PAth})

    '                    End If
    '                End If

    '                Excel1.Workbooks.Close
    '                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Excel1)
    '                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Blatt)
    '                Excel1 = Nothing
    '                Blatt = Nothing
    '                GC.Collect()


    '            Catch ex As Exception
    '                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)

    '                Try
    '                    Excel1.Workbooks.Close
    '                    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Excel1)
    '                    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Blatt)
    '                    Excel1 = Nothing
    '                    Blatt = Nothing
    '                    GC.Collect()

    '                Catch ex2 As Exception
    '                    VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex2.Message, ex2.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
    '                End Try
    '            End Try

    '        End If

    '    Catch ex As Exception
    '        VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
    '    End Try

    'End Sub

    Function getPlattsAufschlag(outletGroug As String) As Double
        If outletGroug.Contains("4473") Then Return 0.032
        If outletGroug.Contains("4474") Then Return 0.032
        If outletGroug.Contains("4486") Then Return 0.042
        Return 0.048
    End Function

    Function getPlattsAufschlag_SONDER(outletGroug As String) As Double
        If outletGroug.Contains("4473") Then Return 0.032
        If outletGroug.Contains("4474") Then Return 0.032
        If outletGroug.Contains("4486") Then Return 0.042
        Return 0.048
    End Function

    Function getPlattsAufschlag_SONDER_Lukenda(outletGroug As String) As Double
        If outletGroug.Contains("4473") Then Return 0.032 - 0.015
        If outletGroug.Contains("4474") Then Return 0.032 - 0.015
        If outletGroug.Contains("4493") Then Return 0.032 - 0.015
        If outletGroug.Contains("4485") Then Return 0.032 - 0.015
        If outletGroug.Contains("4486") Then Return 0.032 - 0.015
        Return 0.048 '-0.015

    End Function
    Sub doIDSPlatts()

        Try
            Dim sql As New VERAG_PROG_ALLGEMEIN.SQL
            Dim DS As VERAG_PROG_ALLGEMEIN.cDATENSERVER = Nothing
            Dim ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "IDS\IDS_XLS\Platts_Price_Report\NEW\"


            If IO.Directory.Exists(ZIEL_PFAD) Then



                For Each IDS_FILE In IO.Directory.GetFiles(ZIEL_PFAD)
                    Dim DT_PLATTS As New DataTable()
                    DT_PLATTS.Columns.Add("IsoCode")
                    DT_PLATTS.Columns.Add("Outlet")
                    DT_PLATTS.Columns.Add("Group Description")
                    DT_PLATTS.Columns.Add("Product")
                    DT_PLATTS.Columns.Add("Price Period Start")
                    DT_PLATTS.Columns.Add("Price Period End")
                    DT_PLATTS.Columns.Add("Excise")
                    DT_PLATTS.Columns.Add("Netprice")
                    DT_PLATTS.Columns.Add("Currency")
                    DT_PLATTS.Columns.Add("NetpriceNEW")

                    Dim DT_PLATTS_SONDER = DT_PLATTS.Clone
                    Dim DT_PLATTS_SONDER_Lukenda = DT_PLATTS.Clone

                    ':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
                    ' EXCEL AUSLESEN:::::::
                    ':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::



                    If Not IO.Directory.Exists(ZIEL_PFAD.Replace("\NEW\", "\" & Now.Year & "\")) Then IO.Directory.CreateDirectory(ZIEL_PFAD.Replace("\NEW\", "\" & Now.Year & "\"))

                    Dim FILE_NEW = IDS_FILE.Replace("\NEW\", "\" & Now.Year & "\").Replace(".xls", "_ORIG.xls")


                    While IO.File.Exists(FILE_NEW)
                        FILE_NEW = IDS_FILE.Replace("\NEW\", "\" & Now.Year & "\").Replace(".xls", Now.ToString("_ddMMyy.HHmmss") & "_ORIG.xls")
                    End While



                    IO.File.Move(IDS_FILE, FILE_NEW)


                    Dim FILE_NEW_Lukenda = FILE_NEW.Replace("_ORIG.xls", "_special_Lukenda_ORIG.xls")
                    IO.File.Copy(FILE_NEW, FILE_NEW_Lukenda)

                    'IDS_FILE = ZIEL_PFAD.Replace("\NEW\", "\" & Now.Year & "\").Replace(".xls", "_ORIG.xls")

                    Dim Excel1 As Object 'New Microsoft.Office.Interop.Excel.Application
                    Dim Blatt As Object 'Microsoft.Office.Interop.Excel.Worksheet 'As Object 'as Worksheet
                    Excel1 = CreateObject("Excel.Application")
                    Dim txt As String
                    Dim Datei As Object 'as WorkBook
                    '  VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(destFull, "00", System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)


                    Try

                        With Excel1
                            Try

                                Datei = .Workbooks.Open(FILE_NEW,, True) 'Anpassen

                            Catch ex As Exception
                                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
                                '  MsgBox(ex.Message & ex.StackTrace)
                            End Try

                            Blatt = Datei.Worksheets(1) 'Anpassen

                            'Excel1.Workbooks.Open(destFull)
                            'Excel1.Visible = True ....wers braucht ?
                            Dim zeile = 12

                            While zeile <= 10000 AndAlso Blatt.Range("A" & zeile) IsNot Nothing AndAlso Blatt.Range("A" & zeile).Value <> ""

                                If Blatt.Range("A" & zeile).Value.ToString.Contains("Austria") Then

                                    'ALLGEMEIN
                                    Dim NetpriceNEW As Double = getPlattsAufschlag(Blatt.Range("B" & zeile).Value)
                                    If NetpriceNEW > 0 Then
                                        NetpriceNEW += CDbl(Blatt.Range("I" & zeile).Value) ' Aufschalg + NETTO
                                        DT_PLATTS.Rows.Add({Blatt.Range("A" & zeile).Value, Blatt.Range("B" & zeile).Value, Blatt.Range("C" & zeile).Value, Blatt.Range("D" & zeile).Value, Blatt.Range("E" & zeile).Value, Blatt.Range("F" & zeile).Value, Blatt.Range("H" & zeile).Value, Blatt.Range("I" & zeile).Value, Blatt.Range("J" & zeile).Value, NetpriceNEW})
                                    End If

                                    'SONDERKONDITION
                                    Dim NetpriceNEW_SOND As Double = getPlattsAufschlag_SONDER(Blatt.Range("B" & zeile).Value)
                                    If NetpriceNEW_SOND > 0 Then
                                        NetpriceNEW_SOND += CDbl(Blatt.Range("I" & zeile).Value) ' Aufschalg + NETTO
                                        DT_PLATTS_SONDER.Rows.Add({Blatt.Range("A" & zeile).Value, Blatt.Range("B" & zeile).Value, Blatt.Range("C" & zeile).Value, Blatt.Range("D" & zeile).Value, Blatt.Range("E" & zeile).Value, Blatt.Range("F" & zeile).Value, Blatt.Range("H" & zeile).Value, Blatt.Range("I" & zeile).Value, Blatt.Range("J" & zeile).Value, NetpriceNEW_SOND})
                                    End If
                                    'SONDERKONDITION Lukenda
                                    NetpriceNEW_SOND = getPlattsAufschlag_SONDER_Lukenda(Blatt.Range("B" & zeile).Value)
                                    If NetpriceNEW_SOND > 0 Then
                                        NetpriceNEW_SOND += CDbl(Blatt.Range("I" & zeile).Value) ' Aufschalg + NETTO
                                        DT_PLATTS_SONDER_Lukenda.Rows.Add({Blatt.Range("A" & zeile).Value, Blatt.Range("B" & zeile).Value, Blatt.Range("C" & zeile).Value, Blatt.Range("D" & zeile).Value, Blatt.Range("E" & zeile).Value, Blatt.Range("F" & zeile).Value, Blatt.Range("H" & zeile).Value, Blatt.Range("I" & zeile).Value, Blatt.Range("J" & zeile).Value, NetpriceNEW_SOND})
                                    End If
                                End If

                                zeile += 1

                            End While


                        End With

                        ''NEUE EXCEL GENEREITER, PREISE ANPASSEN, MAIL SENDEN
                        'If DT_PLATTS.Rows.Count > 0 Then
                        '    'Dim XLS_PAth = IDS_FILE.Replace(".xls", "_NEW.xls")
                        '    Dim FIN_FILE = FILE_NEW.Replace("_ORIG.xls", ".xlsx")


                        '    Dim XLS_Tmp = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(DT_PLATTS,,,,, False)
                        '    If XLS_Tmp <> "" Then
                        '        IO.File.Move(XLS_Tmp, FIN_FILE) ' Verschiebt die Datei

                        '        ' Dim FIN_FILE = IDS_FILE.Replace("_ORIG.xls", ".xls")
                        '        Dim MAIL_attach As New List(Of String)
                        '        MAIL_attach.Add(FIN_FILE)
                        '        VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("al@verag.ag", "IDSPRD: Platts Price Report", "*AUTO*",,,,,, MAIL_attach)

                        '    End If
                        'End If

                        Excel1.Workbooks.Close
                        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Excel1)
                        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Blatt)
                        Excel1 = Nothing
                        Blatt = Nothing
                        GC.Collect()


                    Catch ex As Exception

                        VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)

                        Try
                            Excel1.Workbooks.Close
                            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Excel1)
                            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Blatt)
                            Excel1 = Nothing
                            Blatt = Nothing
                            GC.Collect()

                        Catch ex2 As Exception
                            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex2.Message, ex2.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
                        End Try
                    End Try

                    'ALLGEMEIN
                    genXLS_NewPrice(DT_PLATTS, FILE_NEW, "IDSPRD: Platts Price Report", "z.batinic@verag.ag;n.ljubas@verag.ag;s.vidovic@verag.ag;ma@verag.ag;alex@verag.ag;ft@verag.ag", "sales@verag.ag;al@verag.ag;sb@verag.ag", "") '--> Send XLS Mail

                    'SONDERKONDITION
                    '  genXLS_NewPrice(DT_PLATTS_SONDER, FILE_NEW.Replace("_ORIG.xls", "_special_ORIG.xls")) '--> Send XLS Mail
                    genXLS_NewPrice(DT_PLATTS_SONDER_Lukenda, FILE_NEW_Lukenda, "IDSPRD: Platts Price Report - Lukenda", "Logistik@lukenda-transport.com;ivan.andric@lukenda-transport.hr", "", "sales@verag.ag;al@verag.ag") '--> Send XLS Mail


                Next
            End If

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
        End Try

    End Sub

    Sub genXLS_NewPrice(DT_PLATTS As DataTable, FILE_NEW As String, MAIL_SUBJ As String, MAIL_TO As String, MAIL_CC As String, MAIL_BCC As String)
        ':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
        'NEUES EXCEL ERSTELLEN:::::::
        ':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
        If DT_PLATTS.Rows.Count > 0 Then
            Dim Excel2 As Object 'New Microsoft.Office.Interop.Excel.Application
            Dim Blatt2 As Object 'Microsoft.Office.Interop.Excel.Worksheet 'As Object 'as Worksheet
            Excel2 = CreateObject("Excel.Application")
            Dim Datei2 As Object 'as WorkBook
            '  VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(destFull, "00", System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)

            Try

                With Excel2
                    Try

                        Datei2 = .Workbooks.Open(System.AppDomain.CurrentDomain.BaseDirectory & "\Resources\Muster_IDS_PLATTSPR.xls",, True) 'Anpassen

                    Catch ex As Exception
                        VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
                        MsgBox(ex.Message & ex.StackTrace)
                    End Try

                    Blatt2 = Datei2.Worksheets(1)

                    Dim zeile = 12

                    'Blatt2.Range("G:G").NumberFormat = "0.000"
                    For Each ROW In DT_PLATTS.Rows
                        Blatt2.Range("A" & zeile).Value = ROW("IsoCode")
                        Blatt2.Range("B" & zeile).Value = ROW("Outlet")
                        Blatt2.Range("C" & zeile).Value = ROW("Group Description")
                        Blatt2.Range("D" & zeile).Value = ROW("Product")
                        Blatt2.Range("E" & zeile).Value = ROW("Price Period Start").ToString
                        Blatt2.Range("F" & zeile).Value = ROW("Price Period End").ToString
                        Blatt2.Range("G" & zeile).Value = CDbl(ROW("NetpriceNEW")) '.ToString("N3")
                        Blatt2.Range("H" & zeile).Value = ROW("Currency")

                        zeile += 1
                    Next


                End With

                Dim FIN_FILE = FILE_NEW.Replace("_ORIG.xls", ".xls")
                While IO.File.Exists(FIN_FILE)
                    FIN_FILE = FILE_NEW.Replace("_ORIG.xls", Now.ToString("_ddMMyy.HHmmss") & ".xls")
                End While


                Datei2.SaveAs(FIN_FILE)


                Excel2.Workbooks.Close
                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Excel2)
                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Blatt2)
                Excel2 = Nothing
                Blatt2 = Nothing
                GC.Collect()



                ':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
                'NEUES EXCEL PER MAIL SCHICKEN:::::::
                ':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

                Dim MAIL_attach As New List(Of String)
                MAIL_attach.Add(FIN_FILE)
                VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(MAIL_TO, MAIL_SUBJ, "*AUTO*",,,, MAIL_CC, MAIL_BCC, MAIL_attach)

                ':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)

                Try
                    Excel2.Workbooks.Close
                    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Excel2)
                    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Blatt2)
                    Excel2 = Nothing
                    Blatt2 = Nothing
                    GC.Collect()

                Catch ex2 As Exception
                    VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex2.Message, ex2.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
                End Try
            End Try

        End If


    End Sub
    Public Function FileInUse(ByVal sFile As String) As Boolean
        If System.IO.File.Exists(sFile) Then
            Try
                Dim F As Short = FreeFile()
                FileOpen(F, sFile, OpenMode.Binary, OpenAccess.ReadWrite, OpenShare.LockReadWrite)
                FileClose(F)
            Catch
                Return True
            End Try
        End If
    End Function

    Function doExcelImportNCTS_FREMD() As Boolean
        Dim sql As New VERAG_PROG_ALLGEMEIN.SQL
        Dim DS As VERAG_PROG_ALLGEMEIN.cDATENSERVER = Nothing
        Dim ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\ZOLLDATEN\NCTS_XLS\NEW\"


        If IO.Directory.Exists(ZIEL_PFAD) Then

            For Each MIC_FILE In IO.Directory.GetFiles(ZIEL_PFAD)

                ':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
                ' EXCEL AUSLESEN:::::::
                ':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::


                'Excel2.Workbooks.Open(destFull,, True)
                Dim Excel1 As Object 'New Microsoft.Office.Interop.Excel.Application
                Dim Blatt As Object 'Microsoft.Office.Interop.Excel.Worksheet 'As Object 'as Worksheet
                Excel1 = CreateObject("Excel.Application")
                Dim txt As String
                Dim Datei As Object 'as WorkBook

                Try
                    With Excel1

                        Datei = .Workbooks.Open(MIC_FILE,, True) 'Anpassen
                        'Try
                        '    Datei = .Workbooks.Open(destFull,, True) 'Anpassen
                        'Catch ex As Exception
                        '    System.Threading.Thread.Sleep(5000) ' 5 Sek. warten --> noch Zugriff vom Erstellen?
                        '    Datei = .Workbooks.Open(destFull,, True)
                        'End Try

                        Blatt = Datei.Worksheets(1) 'Anpassen

                        'Excel1.Workbooks.Open(destFull)
                        'Excel1.Visible = True ....wers braucht ?

                        Dim zeile = 2
                        'txt =""
                        While zeile <= 20000 AndAlso Blatt.Range("A" & zeile) IsNot Nothing AndAlso Blatt.Range("A" & zeile).value IsNot Nothing AndAlso Blatt.Range("A" & zeile).value <> "" AndAlso Blatt.Range("F" & zeile) IsNot Nothing AndAlso Blatt.Range("A" & zeile).Value = "GB"
                            ' If zeile < 5 Then VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR("MIC", "AA", System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
                            'asd
                            Dim MRN = Blatt.Range("F" & zeile).Value
                            If MRN <> "" Then
                                'If zeile < 5 Then VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR("MIC", "OO", System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)

                                Dim NCTS_FREMD = VERAG_PROG_ALLGEMEIN.cNCTS_TR.LOADByMRN(MRN, True)
                                If NCTS_FREMD Is Nothing Then NCTS_FREMD = New VERAG_PROG_ALLGEMEIN.cNCTS_TR()

                                Dim StatusTxt = Blatt.Range("G" & zeile).Value

                                NCTS_FREMD.ncts_ObjectName = Blatt.Range("H" & zeile).Value
                                NCTS_FREMD.ncts_MRN = MRN
                                NCTS_FREMD.ncts_Partnersystem = "MIC"
                                NCTS_FREMD.ncts_ArtAnmeldung = Blatt.Range("D" & zeile).Value

                                NCTS_FREMD.ncts_Trans_DatumZeit = Blatt.Range("E" & zeile).Value
                                NCTS_FREMD.ncts_Erstellung = Blatt.Range("E" & zeile).Value
                                NCTS_FREMD.ncts_Eroeffnung = Blatt.Range("E" & zeile).Value
                                NCTS_FREMD.ncts_Ankunft = Blatt.Range("U" & zeile).Value
                                If Blatt.Range("U" & zeile).Value IsNot Nothing AndAlso IsDate(Blatt.Range("U" & zeile).Value) Then
                                    NCTS_FREMD.ncts_Erledigung = Blatt.Range("U" & zeile).Value 'WriteOff ->nicht sicher
                                    NCTS_FREMD.ncts_GestelltAm = Blatt.Range("U" & zeile).Value 'WriteOff ->nicht sicher
                                End If
                                If NCTS_FREMD.ncts_Erledigung IsNot Nothing AndAlso IsDate(NCTS_FREMD.ncts_Erledigung) Then
                                    NCTS_FREMD.ncts_Gestellt = True
                                End If

                                NCTS_FREMD.ncts_AbgangsDienststellennummer = Blatt.Range("M" & zeile).Value
                                NCTS_FREMD.ncts_BestimmungsstelleDienststellennummer = Blatt.Range("N" & zeile).Value
                                NCTS_FREMD.ncts_VersendungsLandCode = Blatt.Range("K" & zeile).Value
                                NCTS_FREMD.ncts_BestimmungslandCode = Blatt.Range("L" & zeile).Value
                                NCTS_FREMD.ncts_Wiedergestellungsdatum = Blatt.Range("T" & zeile).Value 'Frist

                                Dim PLANT = Blatt.Range("B" & zeile).Value 'Plant

                                Select Case PLANT
                                    Case "01" : NCTS_FREMD.ncts_firma = "VERAG" : NCTS_FREMD.ncts_niederlassung = "SUB"
                                    Case "02" : NCTS_FREMD.ncts_firma = "UNISPED" : NCTS_FREMD.ncts_niederlassung = "SUB"
                                    Case "03" : NCTS_FREMD.ncts_firma = "AWOR" : NCTS_FREMD.ncts_niederlassung = "LNZ"
                                End Select

                                Select Case If(StatusTxt, "")
                                    Case "Write-off notification"
                                        NCTS_FREMD.ncts_Status = 60
                                    Case "Declaration sent", "Declaration Positive Acknowledge"
                                        NCTS_FREMD.ncts_Status = 41
                                    Case "Release for transit", "Cancellation request sent"
                                        NCTS_FREMD.ncts_Status = 50
                                    Case "Cancellation request accepted"
                                        NCTS_FREMD.ncts_Status = 90
                                    Case Else
                                        NCTS_FREMD.ncts_Status = 5
                                End Select
                                NCTS_FREMD.ncts_Status_KEWILL_Equivalent = NCTS_FREMD.ncts_Status



                                NCTS_FREMD.ncts_SICHERHEITSANGABEN.Clear()
                                Dim GRN As New VERAG_PROG_ALLGEMEIN.cNCTS_TR_Sicherheitsangaben
                                GRN.nctsSA_GRN = Blatt.Range("P" & zeile).Value
                                GRN.nctsSA_AbgabenBetrag = Blatt.Range("R" & zeile).Value 'GBP?????
                                NCTS_FREMD.ncts_SICHERHEITSANGABEN.Add(GRN)
                                NCTS_FREMD.SAVE_ALL()

                            End If
                            zeile += 1

                        End While
                        If VERAG_PROG_ALLGEMEIN.cAllgemein.ERR_OP_GLOBAL = VERAG_PROG_ALLGEMEIN.ERROR_OP.SHOW Then
                            MsgBox(zeile & " Zeilen eingearbeitet.")
                        End If
                    End With

                    Excel1.Workbooks.Close
                    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Excel1)
                    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Blatt)
                    Excel1 = Nothing
                    Blatt = Nothing
                    GC.Collect()

                    'Return True

                Catch ex As Exception
                    VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)

                    Try
                        Excel1.Workbooks.Close
                        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Excel1)
                        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Blatt)
                        Excel1 = Nothing
                        Blatt = Nothing
                        GC.Collect()

                    Catch ex2 As Exception
                        VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex2.Message, ex2.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
                    End Try
                End Try

                Try
                    If Not IO.Directory.Exists(ZIEL_PFAD.Replace("\NEW\", "\" & Now.Year & "\")) Then IO.Directory.CreateDirectory(ZIEL_PFAD.Replace("\NEW\", "\" & Now.Year & "\"))

                    Dim newFile = MIC_FILE.Replace("\NEW\", "\" & Now.Year & "\")

                    While IO.File.Exists(newFile)
                        newFile = MIC_FILE.Replace("\NEW\", "\" & Now.Year & "\" & Now.ToString("ddMMyy_HHmmss") & "_")
                    End While

                    IO.File.Move(MIC_FILE, newFile)

                Catch ex2 As Exception
                    VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex2.Message, ex2.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
                End Try

            Next
            Return True
        End If
        Return False
    End Function
    Function insertIntoSpedBuch_MIC(FilialenNr As Integer, AbfertigungsNr As Integer, AtlasBezNrNCTS As String, AtlasBezNrEZA As String, ByRef SPEDBUCH As VERAG_PROG_ALLGEMEIN.cSpeditionsbuch, MRN As String) As Boolean
        'Dim SPEDBUCH As New VERAG_PROG_ALLGEMEIN.cSpeditionsbuch

        Dim firmaTmp = VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
        VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = VERAG_PROG_ALLGEMEIN.cAllgemein.getFirmaFromFiliale2(FilialenNr)
        If Not SPEDBUCH.hasEntry Then 'countSpedbuchEntrysFilialeAbf(FilialenNr, AbfertigungsNr) = 0 Then
            '  VERAG_PROG_ALLGEMEIN.cErrorHandler.sendERRORperMail("HEUREKA EZA ", "" & Me.eza_ObjectName, Now.ToString("yyyy.MM.dd HH:mm"), "al@verag.ag", "")
            SPEDBUCH.FilialenNr = FilialenNr
            SPEDBUCH.AbfertigungsNr = AbfertigungsNr
            SPEDBUCH.NewUNTER_NR()

            SPEDBUCH.Abfertigungsanzahl = 1
            SPEDBUCH.Fakturiert = 0
            SPEDBUCH.AtlasBezNrEZA = AtlasBezNrEZA
            SPEDBUCH.AtlasBezNrNCTS = AtlasBezNrNCTS
            SPEDBUCH.Zollsystem = "D"
            SPEDBUCH.Sachbearbeiter = "AUTO"
            SPEDBUCH.BelegNr = MRN

            Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
            SPEDBUCH.AvisoID = SQL.DLookup("tblSnd_AvisoID", "tblSendungen", " FilialenNr='" & FilialenNr & "' and AbfertigungsNr='" & AbfertigungsNr & "' ", "AVISO", 0)
            SPEDBUCH.SendungID = SQL.DLookup("tblSnd_SendungID", "tblSendungen", " FilialenNr='" & FilialenNr & "' and AbfertigungsNr='" & AbfertigungsNr & "' ", "AVISO", 0)

            Dim ZOLL_IMPORT As New DAKOSY_Worker.cZOLL_IMPORT

            Dim notfound = False
            Dim posAnzahl = 0
            Dim filialeBez = ""
            SPEDBUCH = ZOLL_IMPORT.IMPORT(SPEDBUCH, SPEDBUCH.AvisoID, SPEDBUCH.SendungID, "VERA", filialeBez, 2, AtlasBezNrEZA, "", notfound, True)

            If notfound Then Return False
            '   VERAG_PROG_ALLGEMEIN.cErrorHandler.sendERRORperMail("HEUREKA EZA !!", "" & Me.eza_ObjectName, Now.ToString("yyyy.MM.dd HH:mm"), "al@verag.ag", "")

            ' MsgBox(SPEDBUCH.FilialenNr & " - " & SPEDBUCH.AbfertigungsNr)
            VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = firmaTmp

            If SPEDBUCH.SAVE Then
                VERAG_PROG_ALLGEMEIN.cSendungen.SET_SpedbuchEntry(SPEDBUCH.SendungID, True)
                Return True
            Else
                Return False
            End If

        End If
        Return False

    End Function


    'Function countSpedbuchEntrysFilialeAbf(filiale, abfertigungsnummer) As Integer
    '    Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
    '    If If(abfertigungsnummer, "") = "" Then Return 0
    '    Return Sql.getValueTxtBySqlVarList("SELECT isnull(count(*),0) FROM Speditionsbuch WHERE [FilialenNr]='" & filiale & "' AND AbfertigungsNr='" & abfertigungsnummer & "'", "FMZOLL")
    'End Function


    Sub importFileFromDyMailAnhang(pfad, betreff)


        Try
            Dim sql As New VERAG_PROG_ALLGEMEIN.SQL
            Dim DS As VERAG_PROG_ALLGEMEIN.cDATENSERVER = Nothing

            'moveFile(d, VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\nlc\")

            'IO.Directory.CreateDirectory(VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\ZOLLDATEN\TEST3\" & betreff.ToString.Replace(",", ""))

            If betreff.ToString.Contains("VBD - Versandbegleitdokument (DE), ") Then
                Dim found = False
                betreff = betreff.replace("WG: ", "")
                betreff = betreff.replace("FW: ", "")
                betreff = betreff.replace("VBD - Versandbegleitdokument (DE), ", "")

                If betreff.contains(",") Then
                    betreff = betreff.ToString.Split(",")(0).Trim
                End If
                'Dim dy_id As String = sql.getValueTxtBySql("SELECT isnull(ncts_dyaAnmID,-1)  FROM [tblDakosy_NCTSOut] inner join tblDakosy_Zollanmeldungen on dy_id=ncts_dyaAnmID where ncts_ObjectName='" & betreff.ToString.Trim & "' ", "FMZOLL")
                Dim dy_id As String = ""
                If betreff.ToString.Length > 15 Then
                    dy_id = sql.getValueTxtBySql("SELECT isnull(ncts_dyaAnmID,-1)  FROM [tblDakosy_NCTSOut004] inner join tblDakosy_Zollanmeldungen on dy_id=ncts_dyaAnmID where ncts_ObjectName='" & betreff.ToString.Trim & "' ", "FMZOLL")
                    If dy_id = "" Then
                        dy_id = sql.getValueTxtBySql("SELECT isnull(ncts_dyaAnmID,-1)  FROM [tblDakosy_NCTSOut004] inner join tblDakosy_Zollanmeldungen on dy_id=ncts_dyaAnmID where '" & betreff.ToString.Trim & "' LIKE ncts_ObjectName +'%'  and LEN(ncts_ObjectName)>=13 ", "FMZOLL")
                    End If
                Else
                    dy_id = sql.getValueTxtBySql("SELECT isnull(ncts_dyaAnmID,-1)  FROM [tblDakosy_NCTSOut004] inner join tblDakosy_Zollanmeldungen on dy_id=ncts_dyaAnmID where ncts_ObjectName='" & betreff.ToString.Trim & "' ", "FMZOLL")
                End If
                If IsNumeric(dy_id) AndAlso dy_id > 0 Then found = True

                '  IO.Directory.CreateDirectory(VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\ZOLLDATEN\TEST3\")

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

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

                Dim destFull = ""
                moveFile(pfad, ZIEL_PFAD, destFull)


                If DS.insertDataToDATENSERVER(destFull) Then
                    If IsNumeric(dy_id) AndAlso dy_id > 0 Then
                        sql.doSQL("UPDATE tblDakosy_Zollanmeldungen SET dy_VBD_dsId='" & DS.da_id & "' where dy_id='" & dy_id & "'", "FMZOLL")
                        sql.doSQL("UPDATE Speditionsbuch SET DokumentId_VBD='" & DS.da_id & "' where AtlasBezNrNCTS='" & betreff.ToString.Trim & "' AND DokumentId_VBD is null", "FMZOLL") 'Falls Spedbuch schon zuvor generiert wurde!
                        doMailZollbeleg(DS.GET_TOP1_PATH, "VBD", dy_id)
                    End If
                End If


                If Not found Then 'OLD --- NCTS < 004!
                    'Dim dy_id As String = sql.getValueTxtBySql("SELECT isnull(ncts_dyaAnmID,-1)  FROM [tblDakosy_NCTSOut] inner join tblDakosy_Zollanmeldungen on dy_id=ncts_dyaAnmID where ncts_ObjectName='" & betreff.ToString.Trim & "' ", "FMZOLL")
                    dy_id = ""
                    If betreff.ToString.Length > 15 Then
                        dy_id = sql.getValueTxtBySql("SELECT isnull(ncts_dyaAnmID,-1)  FROM [tblDakosy_NCTSOut] inner join tblDakosy_Zollanmeldungen on dy_id=ncts_dyaAnmID where '" & betreff.ToString.Trim & "' LIKE ncts_ObjectName +'%'  and LEN(ncts_ObjectName)>=13 ", "FMZOLL")
                    Else
                        dy_id = sql.getValueTxtBySql("SELECT isnull(ncts_dyaAnmID,-1)  FROM [tblDakosy_NCTSOut] inner join tblDakosy_Zollanmeldungen on dy_id=ncts_dyaAnmID where ncts_ObjectName='" & betreff.ToString.Trim & "' ", "FMZOLL")
                    End If


                    '  IO.Directory.CreateDirectory(VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\ZOLLDATEN\TEST3\")

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

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

                    destFull = ""
                    moveFile(pfad, ZIEL_PFAD, destFull)


                    If DS.insertDataToDATENSERVER(destFull) Then
                        If IsNumeric(dy_id) AndAlso dy_id > 0 Then
                            sql.doSQL("UPDATE tblDakosy_Zollanmeldungen SET dy_VBD_dsId='" & DS.da_id & "' where dy_id='" & dy_id & "'", "FMZOLL")
                            sql.doSQL("UPDATE Speditionsbuch SET DokumentId_VBD='" & DS.da_id & "' where AtlasBezNrNCTS='" & betreff.ToString.Trim & "' AND DokumentId_VBD is null", "FMZOLL") 'Falls Spedbuch schon zuvor generiert wurde!
                            doMailZollbeleg(DS.GET_TOP1_PATH, "VBD", dy_id)
                        End If
                    End If

                End If


                '=====ATEZ BEREITSTELLUNG==========
                cWorker_NCTS.checkATEZ_Bereitstellung_VBD(betreff.ToString.Trim, destFull)

                '==================================


            ElseIf betreff.ToString.Contains("DAKOSY GE - Abgabenbescheid/Befund , Bezugsnr.: ") Then
                betreff = betreff.replace("WG: ", "")
                betreff = betreff.replace("FW: ", "")
                betreff = betreff.replace("DAKOSY GE - Abgabenbescheid/Befund , Bezugsnr.: ", "")
                If betreff.ToString.Contains(",") Then
                    Dim sp = betreff.ToString.Split(",")


                    If betreff.contains("Registriernr.: ATD") Then ' ZNV!!!!
                        betreff = sp(0).Trim
                        Dim SND_ID = sql.getValueTxtBySql("SELECT TOP (1) [tblSnd_SendungID]  FROM [tblSendungen]  where '" & betreff.ToString.Trim & "' LIKE (cast(FilialenNr as varchar(4))+ '/' + cast(AbfertigungsNr as varchar(8))+'%')", "AVISO")
                        If IsNumeric(SND_ID) AndAlso SND_ID > 0 Then
                            DS = New VERAG_PROG_ALLGEMEIN.cDATENSERVER("ZOLLDATEN", "ZNV", "SND_ID_" & SND_ID, "", "", betreff.ToString.Replace("/", "-").Replace(",", "-").Replace("\", "-").Replace(":", "."), 0, False)
                            DS.da_vorlage = False
                            Dim destFull = ""
                            Dim ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\ZOLLDATEN\ZNV\" & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\"
                            If Not IO.Directory.Exists(ZIEL_PFAD) Then IO.Directory.CreateDirectory(ZIEL_PFAD)
                            moveFile(pfad, ZIEL_PFAD, destFull)

                            If DS.insertDataToDATENSERVER(destFull) Then
                                ' sql.doSQL("UPDATE tblDakosy_Zollanmeldungen SET dy_STEUERBESCHEID_dsId='" & DS.da_id & "' where dy_id='" & dy_id & "'", "FMZOLL")
                                sql.doSQL("UPDATE Speditionsbuch SET DokumentId_Steuerbeleg='" & DS.da_id & "' where AtlasBezNrEZA='" & betreff.ToString.Trim & "' AND DokumentId_Steuerbeleg is null", "FMZOLL") 'Falls Spedbuch schon zuvor generiert wurde!
                                doMailZollbeleg(DS.GET_TOP1_PATH, "ZNV", SND_ID, betreff)
                            End If

                        End If


                    Else ' STB !!!!

                        betreff = sp(0).Trim


                        Dim dy_id As String = ""
                        If betreff.ToString.Length > 15 Then
                            dy_id = sql.getValueTxtBySql("SELECT isnull(eza_dyaAnmID,-1)  FROM [tblDakosy_EZA] inner join tblDakosy_Zollanmeldungen on dy_id=eza_dyaAnmID where eza_ObjectName='" & betreff.ToString.Trim & "'", "FMZOLL")
                            If dy_id = "" Then
                                dy_id = sql.getValueTxtBySql("SELECT isnull(eza_dyaAnmID,-1)  FROM [tblDakosy_EZA] inner join tblDakosy_Zollanmeldungen on dy_id=eza_dyaAnmID where '" & betreff.ToString.Trim & "' LIKE eza_ObjectName +'%'  and LEN(eza_ObjectName)>=13", "FMZOLL")
                            End If
                        Else
                            dy_id = sql.getValueTxtBySql("SELECT isnull(eza_dyaAnmID,-1)  FROM [tblDakosy_EZA] inner join tblDakosy_Zollanmeldungen on dy_id=eza_dyaAnmID where eza_ObjectName='" & betreff.ToString.Trim & "'", "FMZOLL")
                        End If
                        '  IO.Directory.CreateDirectory(VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\ZOLLDATEN\TEST3\")

                        DS = New VERAG_PROG_ALLGEMEIN.cDATENSERVER("ZOLLDATEN", "STEUERBESCHEID", dy_id, "", "", betreff.ToString.Replace("/", "-").Replace(",", "-").Replace("\", "-").Replace(":", "."), 0, False)
                        DS.da_vorlage = False

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

                        Dim destFull = ""
                        moveFile(pfad, ZIEL_PFAD, destFull)

                        If DS.insertDataToDATENSERVER(destFull) Then
                            If IsNumeric(dy_id) AndAlso dy_id > 0 Then
                                sql.doSQL("UPDATE tblDakosy_Zollanmeldungen SET dy_STEUERBESCHEID_dsId='" & DS.da_id & "' where dy_id='" & dy_id & "'", "FMZOLL")
                                sql.doSQL("UPDATE Speditionsbuch SET DokumentId_Steuerbeleg='" & DS.da_id & "' where AtlasBezNrEZA='" & betreff.ToString.Trim & "' AND DokumentId_Steuerbeleg is null", "FMZOLL") 'Falls Spedbuch schon zuvor generiert wurde!
                                doMailZollbeleg(DS.GET_TOP1_PATH, "STB", dy_id)
                            End If
                        End If

                    End If
                End If

                'ABD
            ElseIf betreff.ToString.Contains("ABD - Ausfuhrbegleitdokument (DE), ") Then
                betreff = betreff.replace("WG: ", "")
                betreff = betreff.replace("FW: ", "")
                betreff = betreff.replace("ABD - Ausfuhrbegleitdokument (DE), ", "")
                If betreff.ToString.Contains(",") Then
                    Dim sp = betreff.ToString.Split(",")
                    betreff = sp(0).Trim

                    Dim dy_id As String = ""
                    If betreff.ToString.Length > 15 Then
                        dy_id = sql.getValueTxtBySql("SELECT isnull(aes_dyaAnmID,-1)  FROM [tblDakosy_AES] inner join tblDakosy_Zollanmeldungen on dy_id=aes_dyaAnmID where aes_ObjectName='" & betreff.ToString.Trim & "'", "FMZOLL")
                        If dy_id = "" Then
                            dy_id = sql.getValueTxtBySql("SELECT isnull(aes_dyaAnmID,-1)  FROM [tblDakosy_AES] inner join tblDakosy_Zollanmeldungen on dy_id=aes_dyaAnmID where '" & betreff.ToString.Trim & "' LIKE aes_ObjectName +'%'  and LEN(aes_ObjectName)>=13", "FMZOLL")
                        End If
                    Else
                        dy_id = sql.getValueTxtBySql("SELECT isnull(aes_dyaAnmID,-1)  FROM [tblDakosy_AES] inner join tblDakosy_Zollanmeldungen on dy_id=aes_dyaAnmID where aes_ObjectName='" & betreff.ToString.Trim & "'", "FMZOLL")
                    End If
                    '  IO.Directory.CreateDirectory(VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\ZOLLDATEN\TEST3\")

                    DS = New VERAG_PROG_ALLGEMEIN.cDATENSERVER("ZOLLDATEN", "ABD", dy_id, "", "", betreff.ToString.Replace("/", "-").Replace(",", "-").Replace("\", "-").Replace(":", "."), 0, False)
                    DS.da_vorlage = False

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

                    Dim destFull = ""
                    moveFile(pfad, ZIEL_PFAD, destFull)

                    If DS.insertDataToDATENSERVER(destFull) Then
                        If IsNumeric(dy_id) AndAlso dy_id > 0 Then
                            sql.doSQL("UPDATE tblDakosy_Zollanmeldungen SET dy_ABD_dsId='" & DS.da_id & "' where dy_id='" & dy_id & "'", "FMZOLL")
                            sql.doSQL("UPDATE Speditionsbuch SET DokumentId_ABD='" & DS.da_id & "' where AtlasBezNrEZA='" & betreff.ToString.Trim & "' AND DokumentId_ABD is null", "FMZOLL") 'Falls Spedbuch schon zuvor generiert wurde!
                            doMailZollbeleg(DS.GET_TOP1_PATH, "ABD", dy_id)
                        End If
                    End If

                End If

                'AVM
            ElseIf betreff.ToString.Contains("AVM - Ausgangsvermerk (DE), ") Then
                betreff = betreff.replace("WG: ", "")
                betreff = betreff.replace("FW: ", "")
                betreff = betreff.replace("AVM - Ausgangsvermerk (DE), ", "")
                If betreff.ToString.Contains(",") Then
                    Dim sp = betreff.ToString.Split(",")
                    betreff = sp(0).Trim

                    Dim dy_id As String = ""
                    If betreff.ToString.Length > 15 Then
                        dy_id = sql.getValueTxtBySql("SELECT isnull(aes_dyaAnmID,-1)  FROM [tblDakosy_AES] inner join tblDakosy_Zollanmeldungen on dy_id=aes_dyaAnmID where aes_ObjectName='" & betreff.ToString.Trim & "'", "FMZOLL")
                        If dy_id = "" Then
                            dy_id = sql.getValueTxtBySql("SELECT isnull(aes_dyaAnmID,-1)  FROM [tblDakosy_AES] inner join tblDakosy_Zollanmeldungen on dy_id=aes_dyaAnmID where '" & betreff.ToString.Trim & "' LIKE aes_ObjectName +'%'  and LEN(aes_ObjectName)>=13", "FMZOLL")
                        End If
                    Else
                        dy_id = sql.getValueTxtBySql("SELECT isnull(aes_dyaAnmID,-1)  FROM [tblDakosy_AES] inner join tblDakosy_Zollanmeldungen on dy_id=aes_dyaAnmID where aes_ObjectName='" & betreff.ToString.Trim & "'", "FMZOLL")
                    End If
                    '  IO.Directory.CreateDirectory(VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\ZOLLDATEN\TEST3\")

                    DS = New VERAG_PROG_ALLGEMEIN.cDATENSERVER("ZOLLDATEN", "AVM", dy_id, "", "", betreff.ToString.Replace("/", "-").Replace(",", "-").Replace("\", "-").Replace(":", "."), 0, False)
                    DS.da_vorlage = False

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

                    Dim destFull = ""
                    moveFile(pfad, ZIEL_PFAD, destFull)

                    If DS.insertDataToDATENSERVER(destFull) Then
                        If IsNumeric(dy_id) AndAlso dy_id > 0 Then
                            sql.doSQL("UPDATE tblDakosy_Zollanmeldungen SET dy_AVM_dsId='" & DS.da_id & "' where dy_id='" & dy_id & "'", "FMZOLL")
                            sql.doSQL("UPDATE Speditionsbuch SET DokumentId_AVM='" & DS.da_id & "' where AtlasBezNrEZA='" & betreff.ToString.Trim & "' AND DokumentId_AVM is null", "FMZOLL") 'Falls Spedbuch schon zuvor generiert wurde!
                            doMailZollbeleg(DS.GET_TOP1_PATH, "AVM", dy_id)
                        End If
                    End If

                End If
            End If

            ' GENERELLES NOT IDENTIFIED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!




            '""""""""""""
            ' If Not alreadyMoved Then

            ' End If

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
        End Try

    End Sub

    Private Sub LinkLabel4_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel4.LinkClicked
        Me.Cursor = Cursors.WaitCursor
        Try
            DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0008", True) 'TESTSYSTEM
            Dim erg = DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0008", False) 'ECHTSYSTEM
            showPic(erg, picC0008)
        Catch ex As Exception : VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name) : End Try
        Me.Cursor = Cursors.Default
    End Sub


    Sub showPic(ok As Boolean, pic As PictureBox)
        pic.Visible = True
        If ok Then
            pic.BackgroundImage = My.Resources.ok
        Else
            pic.BackgroundImage = My.Resources.del
        End If
        timer.Enabled = True
    End Sub
    Private Sub timer_Tick(sender As Object, e As EventArgs) Handles timer.Tick
        timer.Enabled = False
        picC0008.Visible = False
        PictureBox1.Visible = False
        PictureBox2.Visible = False
        PictureBox3.Visible = False
        PictureBox4.Visible = False
        PictureBox5.Visible = False
        PictureBox6.Visible = False
        PictureBox7.Visible = False
        PictureBox8.Visible = False
        PictureBox9.Visible = False
        PictureBox10.Visible = False
        PictureBox11.Visible = False
        PictureBox12.Visible = False
        PictureBox13.Visible = False
        PictureBox14.Visible = False
        PictureBox18.Visible = False
        PictureBox19.Visible = False
        PictureBox20.Visible = False
        PictureBox21.Visible = False

    End Sub

    Private Sub LinkLabel5_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel5.LinkClicked
        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = True
        Dim f As New frmDYNachrichtenVerarbeitung
        f.ShowDialog()
        Me.Visible = True
    End Sub

    Private Sub LinkLabel6_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel6.LinkClicked
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = True
        If DAKOSY_Worker.cDakosyFunftions.sendData() Then ' Application.StartupPath & "\Dakosy_SEND\")

        End If

        Exit Sub

        Dim dt = DAKOSY_Worker.cDakosyFunftions.getKDData()

        If dt IsNot Nothing Then
            Dim saveFile = ""
            If DAKOSY_Worker.cDakosyFunftions.generateVERAGKdData(dt, Application.StartupPath & "\Dakosy_SEND\", saveFile) Then
                MsgBox(saveFile)
            End If
        End If
    End Sub



    Private Sub LinkLabel7_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel7.LinkClicked
        Me.Cursor = Cursors.WaitCursor
        Try
            DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0017", True) 'TESTSYSTEM
            Dim erg = DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0017", False) 'ECHTSYSTEM
            showPic(erg, PictureBox1)
        Catch ex As Exception : VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name) : End Try
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub LinkLabel8_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel8.LinkClicked
        Me.Cursor = Cursors.WaitCursor
        Try
            DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0014", True) 'TESTSYSTEM
            Dim erg = DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0014", False) 'ECHTSYSTEM
            showPic(erg, PictureBox2)
        Catch ex As Exception : VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name) : End Try
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub LinkLabel2_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel2.LinkClicked

    End Sub

    Private Sub pnl_Paint(sender As Object, e As PaintEventArgs) Handles pnl.Paint

    End Sub

    Private Sub LinkLabel9_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel9.LinkClicked
        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        Dim f As New frmDYNachrichtenVerarbeitung
        f.ShowDialog()
        Me.Visible = True
    End Sub

    Private Sub LinkLabel10_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel10.LinkClicked
        Me.Cursor = Cursors.WaitCursor
        Try
            DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0010", True) 'TESTSYSTEM
            Dim erg = DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0010", False) 'ECHTSYSTEM
            showPic(erg, PictureBox3)
        Catch ex As Exception : VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name) : End Try
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub LinkLabel11_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel11.LinkClicked
        Me.Cursor = Cursors.WaitCursor
        Try
            DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("A0122", True) 'TESTSYSTEM
            Dim erg = DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("A0122", False) 'ECHTSYSTEM
            showPic(erg, PictureBox4)
        Catch ex As Exception : VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name) : End Try
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub LinkLabel12_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel12.LinkClicked
        Me.Cursor = Cursors.WaitCursor
        Try
            DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("A0127", True) 'TESTSYSTEM
            Dim erg = DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("A0127", False) 'ECHTSYSTEM
            showPic(erg, PictureBox5)
        Catch ex As Exception : VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name) : End Try
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub LinkLabel13_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel13.LinkClicked
        Me.Cursor = Cursors.WaitCursor
        Try
            DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("I0400", True) 'TESTSYSTEM
            Dim erg = DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("I0400", False) 'ECHTSYSTEM
            showPic(erg, PictureBox6)
        Catch ex As Exception : VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name) : End Try
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub LinkLabel14_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel14.LinkClicked
        Me.Cursor = Cursors.WaitCursor
        Try
            DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0013", True) 'TESTSYSTEM
            Dim erg = DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0013", False) 'ECHTSYSTEM
            showPic(erg, PictureBox7)
        Catch ex As Exception : VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name) : End Try
        Me.Cursor = Cursors.Default

    End Sub

    Private Sub LinkLabel15_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel15.LinkClicked
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        If DAKOSY_Worker.cDakosyFunftions.sendData() Then ' Application.StartupPath & "\Dakosy_SEND\")

        End If

    End Sub

    Private Sub LinkLabel16_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel16.LinkClicked
        Me.Cursor = Cursors.WaitCursor
        Try
            DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("I0200", True) 'TESTSYSTEM
            Dim erg = DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("I0200", False) 'ECHTSYSTEM
            showPic(erg, PictureBox8)
        Catch ex As Exception : VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name) : End Try
        Me.Cursor = Cursors.Default
    End Sub


    Public Function moveFile(file, toDirectory, Optional ByRef dest = "") ', Optional unlockFile = True)
        Try
            If Not IO.File.Exists(file) Then Return False
            If Not IO.Directory.Exists(toDirectory) Then IO.Directory.CreateDirectory(toDirectory)
            dest = toDirectory & cut_file(file).Replace("lock_", "")
            If IO.File.Exists(dest) Then
                dest = toDirectory & Now.ToString("yyMMdd_HHmmss.fff_") & cut_file(file).Replace("lock_", "")
            End If
            IO.File.Move(file, dest) ' Verschiebt die Datei
            Return True
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & file & vbNewLine & "DestPfad: " & toDirectory, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
        Return False
    End Function
    Public Function lockFile(file) As String
        Try
            If Not IO.File.Exists(file) Then Return file
            If file.ToString.Contains("lock_") Then Return file
            Dim FIO As New FileInfo(file)
            Dim dest = FIO.Directory.FullName & "\lock_" & FIO.Name
            If IO.File.Exists(dest) Then Return file
            IO.File.Move(file, dest) ' Verschiebt die Datei
            Return dest
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & file, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
        Return file
    End Function

    Public Function unlockFile(file) As String
        Try
            Dim dest = file.ToString.Replace("\lock_", "")
            If Not IO.File.Exists(file) Then Return False
            If Not IO.File.Exists(dest) Then Return False

            IO.File.Move(file, dest) ' Verschiebt die Datei
            Return dest
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & file, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
        Return file
    End Function
    Public Function moveFile_DateBack(file, toDirectory, Optional ByRef dest = "")
        If Not IO.File.Exists(file) Then Return False
        If Not IO.Directory.Exists(toDirectory) Then IO.Directory.CreateDirectory(toDirectory)
        dest = toDirectory & cut_file(file)
        Dim fio As IO.FileInfo = New FileInfo(file)
        Dim ext = fio.Extension
        If IO.File.Exists(dest) Then
            dest = toDirectory & cut_file(file).Replace(ext, Now.ToString("_yyMMdd_HHmmss.fff")) & ext
        End If
        IO.File.Move(file, dest) ' Verschiebt die Datei
        Return True
    End Function

    Public Function copyFile_DateBack(file, toDirectory, Optional ByRef dest = "")
        If Not IO.File.Exists(file) Then Return False
        If Not IO.Directory.Exists(toDirectory) Then IO.Directory.CreateDirectory(toDirectory)
        dest = toDirectory & cut_file(file)
        Dim fio As IO.FileInfo = New FileInfo(file)
        Dim ext = fio.Extension
        If IO.File.Exists(dest) Then
            dest = toDirectory & cut_file(file).Replace(ext, Now.ToString("_yyMMdd_HHmmss.fff")) & ext
        End If
        IO.File.Copy(file, dest) ' Verschiebt die Datei
        Return True
    End Function

    'Public Function getFileName_DateBack(file) As String
    '    If Not IO.File.Exists(file) Then Return False

    '    Dim fio As IO.FileInfo = New FileInfo(file)
    '    Dim ext = fio.Extension

    '    Return cut_file(file).Replace(ext, Now.ToString("_yyMMdd_HHmmss.fff")) & ext
    'End Function
    Public Function getFileName(file) As String
        If Not IO.File.Exists(file) Then Return False

        Dim fio As IO.FileInfo = New FileInfo(file)

        Return fio.Name
    End Function


    Public Function copyFile(file, toDirectory, Optional ByRef dest = "")
        If Not IO.File.Exists(file) Then Return False
        If Not IO.Directory.Exists(toDirectory) Then IO.Directory.CreateDirectory(toDirectory)
        dest = toDirectory & ".tmp_" & cut_file(file)
        Dim tmpExt = ""
        While IO.File.Exists(dest) Or IO.File.Exists(dest).ToString.Replace(".tmp_", "") 'wenn mit oder ohen .tmp_ existiert...
            tmpExt = Now.ToString("yyMMdd_HHmmss.fff_")
            dest = toDirectory & ".tmp_" & tmpExt & cut_file(file)
        End While
        IO.File.Copy(file, dest) ' Verschiebt die Datei
        IO.File.Move(dest, dest.ToString.Replace(".tmp_" & tmpExt, "")) ' Umbenennen der Datei --> der "." am Anfang dient dazu, dass die Datei nicht abgegriffen wird, während sie kopiert wird!
        dest = dest.ToString.Replace(".tmp_" & tmpExt, "")
        Return True

    End Function
    Public Function cut_file(ByVal file As String) As String ' Funktion zum Entfernen der Backslashs / Ordner While file.Contains("\") file = file.Remove(0, 1) End While Return file End Function 
        While file.Contains("\")
            file = file.Remove(0, 1)
        End While
        Return file
    End Function

    Private Sub LinkLabel17_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel17.LinkClicked
        getETZBundesanzeiger_ImportCodenummern()
    End Sub
    Sub getETZBundesanzeiger_ImportCodenummern()
        Dim bool = False
        Dim zip = getNachrichtenDatenFromBundesanzeiger()
        If zip <> "" Then
            bool = loadEZTZipToDB(zip)

        End If
        showPic(bool, PictureBox9)
    End Sub

    Function getEZB_Waehrungskurse() As Boolean
        Dim MyData As String = ""
        getEZB_Waehrungskurse = False
        Try
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

            Using WC As New System.Net.WebClient()
                ' C0008_URL()
                WC.Encoding = ASCIIEncoding.UTF8
                Dim URL = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml" 'cDY_Paramter.GET_PARAM_ByName("C0008_URL", TESTSYSTEM)
                If URL = String.Empty Then Return False

                MyData = WC.DownloadString(URL)
                Dim doc As New XmlDocument()
                doc.LoadXml(MyData)
                If doc.HasChildNodes Then

                    If doc.GetElementsByTagName("gesmes:Envelope").Count > 0 Then
                        If doc.GetElementsByTagName("gesmes:Envelope")(0).HasChildNodes AndAlso doc.GetElementsByTagName("gesmes:Envelope")(0).ChildNodes.Count > 2 Then
                            Dim Cube = doc.GetElementsByTagName("gesmes:Envelope")(0).ChildNodes(2)
                            If Cube.HasChildNodes AndAlso Cube.ChildNodes(0).Name = "Cube" And Cube.ChildNodes(0).Attributes.Count > 0 Then
                                Dim Cube2 = Cube.ChildNodes(0)
                                Dim datum As Date = DateTime.ParseExact(Cube2.Attributes(0).Value, "yyyy-MM-dd", Nothing)
                                If Cube2.HasChildNodes Then
                                    For Each Entry As XmlNode In Cube2.ChildNodes

                                        Dim EZB As New VERAG_PROG_ALLGEMEIN.cEZB_Waehrungskurse

                                        '                  Dim Code = ""
                                        'Dim Description = ""
                                        ' Dim StartDate = Nothing
                                        ' Dim EndDate = Nothing
                                        If Entry.Attributes("currency") IsNot Nothing Then EZB.ezb_waehrungscode = Entry.Attributes("currency").Value
                                        If Entry.Attributes("rate") IsNot Nothing Then EZB.ezb_kurs = CDbl(Entry.Attributes("rate").Value.Replace(".", ","))
                                        'If Entry.SelectNodes("Description").Count > 0 Then EZB.ezb_waehrungsschluessel = Entry.SelectNodes("Description")(0).InnerText
                                        EZB.ezb_datum = datum 'CDate(Entry.SelectNodes("StartDate")(0).InnerText)
                                        EZB.SAVE()
                                        '  LC.Add(New VERAG_PROG_ALLGEMEIN.cEZB_Waehrungskurse(Code, Description, StartDate, EndDate))
                                        '   VERAG_PROG_ALLGEMEIN.
                                        getEZB_Waehrungskurse = True

                                        Try
                                            Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
                                            SQL.doSQL("IF NOT EXISTS (SELECT * FROM baskur WHERE baskur_code ='" & EZB.ezb_waehrungscode & "' AND  baskur_gbdat =cast(getdate() as date) ) 
                                                        BEGIN   
                                                            INSERT INTO [baskur] 
                                                               ([baskur_code],[baskur_typ],[baskur_bez],[baskur_faktor],[baskur_kurs],[baskur_gvdat],[baskur_gbdat],[baskur_edat],[baskur_adat],[baskur_sb],[baskur_cdealt],[baskur_wkz]) 
                                                               VALUES ('" & EZB.ezb_waehrungscode & "',1,'-',1," & Entry.Attributes("rate").Value & ",cast(getdate() as date),cast(getdate() as date),getdate(),getdate(),'VRG',000,'EUR')
                                                        END", "ATLAS")

                                        Catch ex As Exception
                                            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)

                                        End Try

                                    Next
                                End If
                                VERAG_PROG_ALLGEMEIN.cEZB_Waehrungskurse.UPDATE_Waehrungstabelle(datum) ' Waehrungstabelle befüllen

                            End If

                        End If
                    End If
                End If
                'If LC.Count > 0 Then
                '    Return LC.INSERT_DB(TESTSYSTEM)
                'End If
            End Using

        Catch ex As Exception
            MsgBox(ex.Message & ex.StackTrace)
            Return False
        End Try


    End Function


    Function getUID_Pruefung(maxAnz As Integer) As Boolean
        getUID_Pruefung(maxAnz, "VERAG", "UID Prüfung VERAG", "as@verag.ag;ih@verag.ag;kb@verag.ag", "al@verag.ag",,, True)
        getUID_Pruefung(maxAnz, "IMEX", "UID Prüfung IMEX", "Viktoria.Leirich@imex-group.at;as@verag.ag;kb@verag.ag", "al@verag.ag",,, True)
        getUID_Pruefung(maxAnz, "AMBAR", "UID Prüfung AMBAR", "as@verag.ag", "al@verag.ag",,, True)
        getUID_Pruefung(maxAnz, "UNISPED", "UID Prüfung UNISPED", "al@verag.ag", "al@verag.ag",,, True)
        'getUID_Pruefung(maxAnz, "VERAG", "UID Prüfung VERAG", "mm@verag.ag;la@verag.ag", "al@verag.ag")

    End Function

    Function sendWOELFL_USTVAntraege(Mail_To, Optional Mail_CC = "", Optional Mail_BCC = "")
        Try
            Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL

            Dim dt = SQL.loadDgvBySql(" 
                            SELECT  [UStVAn_KuNr]VERAGKundenNr
                            ,isnull(WölflKundenNr,'')PartnerKundenNr
                                  --,[UStVAn_LandNr]
                                  ,cast([UStVAn_ReDatVon]as date)ReDatVon
                                  ,cast([UStVAn_ReDatBis]as date)ReDatBis
                                  ,LND.LandKz AntragsLand
	                              ,[UStVAn_Name]Firma
                                  ,isnull([UStVAn_Straße],'')Strasse
                                  ,isnull([UStVAn_LandKz],'')LandKz
                                  ,isnull([UStVAn_PLZ],'')Plz
                                  ,isnull([UStVAn_Ort],'') Ort 
                                  , isnull(cast( cast([UStVAn_AntragEingereichtAm] as date)as varchar),'') AntragEingereichtAm
                                  ,isnull([UStVAn_VZBetrag],'')VZBetrag
                                  , isnull(cast( cast([UStVAn_VZDatum] as date)as varchar),'') VZDatum 
                                  ,isnull([UStVAn_RZBetragVZ],'')RZBetragVZ 
                                  , isnull(cast( cast([UStVAn_RZDatumVZ] as date)as varchar),'') RZDatumVZ 
                                  ,isnull([UStVAn_Währungscode],'')Waehrungscode
                                  ,isnull([UStVAn_USteuerbetrag],'')USteuerbetrag
                                  ,isnull([UStVAn_Erstattungsbetrag],'')Erstattungsbetrag
                                  ,isnull([UStVAn_USteuerbetragEUR],'')USteuerbetragEUR
                                  ,isnull([UStVAn_ErstattungsbetragEUR],'') ErstattungsbetragEUR 
	                                FROM [VERAG].[dbo].[tblUStVAntrag]
                              inner join [Länderverzeichnis für die Außenhandelsstatistik] as LND on LandNr=UStVAn_LandNr
                              inner join Adressen on UStVAn_KuNr=AdressenNr
                                where UStVAn_ReDatVon>= cast(('01.01.' + cast((DATEPART(YEAR,getdate())-1) as varchar)) as date)
                              and (UStVAn_KuNr between 150000 and 159999 OR UStVAn_KuNr between 180000 and 189999 )
                              order by UStVAn_KuNr,[UStVAn_LandNr],UStVAn_ReDatVon
                            ", "FMZOLL")

            If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
                Dim PDF = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genCSVFromDT(dt, False)
                If PDF <> "" Then
                    Dim list As New List(Of String)
                    list.Add(PDF)
                    Dim Body = "Anbei befindet sich die Auflistung der USTV-Anträge.<br>"

                    Body &= "<br><br>Erstellt am: " & Now.ToShortDateString & ", um " & Now.ToShortTimeString
                    Body &= "<br><br>Automatisch generiertes E-Mail."
                    Dim Mail_betreff = "USTV-Anträge"

                    VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(Mail_To, Mail_betreff, Body,,, False, Mail_CC, Mail_BCC, list)

                End If
            End If
            Return True
        Catch ex As Exception
            MsgBox(ex.Message & ex.StackTrace)
            Return False
        End Try
    End Function

    Function getUID_Pruefung(maxAnz As Integer, Mail_FIMRA As String, Mail_betreff As String, Mail_To As String, Optional Mail_CC As String = "", Optional Mail_BCC As String = "", Optional TageZurueck As String = "", Optional setKundenvermerk As Boolean = False) As Boolean
        Dim firmatmp = VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
        Try
            VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = Mail_FIMRA
            Dim dateBack = If(TageZurueck <> "", CDate(Now.AddDays(TageZurueck * -1)), Nothing)
            Dim dt = VERAG_PROG_ALLGEMEIN.cUIDPruefung.doUIDPruefungALL(dateBack, True, False, maxAnz, False)
            If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
                Dim PDF = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dt,,,,, False)
                If PDF <> "" Then
                    Dim list As New List(Of String)
                    list.Add(PDF)
                    Dim Body = "Anbei befinden sich die Auflistung der geprüfen UID-Nummern.<br>Bei UID-Nummer mit dem Prüfungserbnis 'OK' wurde das Prüfdatum in den Kundenstamm eingetragen. "
                    Body &= "<br><b>Ungültige UID-Nummern werden automatisch im Aviso vermerkt!</b>"
                    Body &= "<br><br>Erstellt am: " & Now.ToShortDateString & ", um " & Now.ToShortTimeString
                    Body &= "<br><br>Automatisch generiertes E-Mail."

                    VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(Mail_To, Mail_betreff, Body,,, False, Mail_CC, Mail_BCC, list)
                    '  VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("al@verag.ag", "UID Prüfung", Body,,, False, ,, list)
                End If

                If setKundenvermerk Then

                    For Each r As DataRow In dt.Rows
                        If r("Ergebnis") = "UNGÜLTIG" Then

                            Dim kunde As cKunde = New cKunde(r("kdNr"))
                            Dim KdFirma = VERAG_PROG_ALLGEMEIN.cAllgemein.getFirmaFromFiliale(kunde.FilialenNr)
                            If KdFirma = VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA Then
                                Dim kundeErw As cKundenErweitert = New cKundenErweitert(kunde.KundenNr)
                                Dim textUIDVermerk As String = "UID Nr." & r("UstIdKz") & r("UstIdnr") & " ungültig, zuletzt geprüft wo gültig am " & r("letzte Prüfung") & " lt. monatl. Prüfung!"

                                If kundeErw.kde_BesonderheitenNeu Then

                                    Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
                                    If SQL.doSQL("INSERT INTO tblKundenBesonderheiten (kdb_KundenNr,kdb_kategorie,kdb_text,kdb_mitId,kdb_mitName,kdb_EingetragenAm,kdb_visible,kdb_hervorheben,kdb_history) " &
                                    " VALUES(" & kunde.KundenNr & ",'ALLG' ,'" & textUIDVermerk & "'," & "4" & ",'" & "AUTO" & "','" & Now() & "',1,1,0)", "FMZOLL") Then
                                        setUIDToNull(kunde)

                                    End If

                                Else

                                    If kunde.Besonderheiten <> "" Then kunde.Besonderheiten &= vbNewLine
                                    kunde.Besonderheiten &= textUIDVermerk
                                    kunde.SAVE()
                                    setUIDToNull(kunde)

                                End If
                                changeSteuerschlüssel(kunde)
                            End If

                        End If

                    Next


                End If


            End If
            VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = firmatmp
            Return True
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = firmatmp
            MsgBox(ex.Message & ex.StackTrace)
            Return False
        End Try

    End Function

    Sub setUIDToNull(kunde)

        Dim addressen As cAdressen = New cAdressen(kunde.KundenNr)
        addressen.UstIdKz = DBNull.Value
        addressen.UstIdNr = DBNull.Value
        addressen.UstIdGeprüft = DBNull.Value
        addressen.SAVE()

    End Sub

    Sub changeSteuerschlüssel(kunde As cKunde)

        If kunde.Steuerschlüssel IsNot Nothing Then

            Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
            Dim steuersatz = SQL.DLookup("[Steuersatz %]", "[Steuertabelle]", "[Steuerschlüssel]='" & kunde.Steuerschlüssel & "'", "FMZOLL", -1)


            Dim Filiale As New VERAG_PROG_ALLGEMEIN.cFilialen(kunde.FilialenNr)
            If steuersatz = 0 Then
                Select Case Filiale.LandKz
                    Case "A", "AT"
                        kunde.Steuerschlüssel = 2
                    Case "D", "DE"
                        kunde.Steuerschlüssel = 19
                    Case "GB"
                        kunde.Steuerschlüssel = 20
                End Select
                kunde.SAVE()
            Else
                Exit Sub 'Steuersatz ist hinterlegt, keiner Änderung!
            End If

        End If

    End Sub
    'Function getUID_PruefungVERAG(maxAnz As Integer) As Boolean
    '    Dim firmatmp = VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
    '    Try
    '        VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "VERAG"
    '        Dim dt = VERAG_PROG_ALLGEMEIN.cUIDPruefung.doUIDPruefungALL(CDate(Now.ToString("01.MM.yyyy")).AddMonths(-1), True, False, maxAnz, False)
    '        If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
    '            Dim PDF = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dt,,,,, False)
    '            If PDF <> "" Then
    '                Dim list As New List(Of String)
    '                list.Add(PDF)
    '                Dim Body = "Anbei befinden sich die Auflistung der geprüfen UID-Nummern.<br>Bei UID-Nummer mit dem Prüfungserbnis 'OK' wurde das Prüfdatum in den Kundenstamm eingetragen. "
    '                Body &= "<br><b>Ungültige UID-Nummern bitte manuell bearbeiten!</b>"
    '                Body &= "<br><br>Erstellt am: " & Now.ToShortDateString & ", um " & Now.ToShortTimeString
    '                Body &= "<br><br>Automatisch generiertes E-Mail."

    '                VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("kb@verag.ag", "UID Prüfung VERAG", Body,,, False, "al@verag.ag",, list)
    '                '  VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("al@verag.ag", "UID Prüfung", Body,,, False, ,, list)
    '            End If
    '        End If
    '        VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = firmatmp
    '        Return True
    '    Catch ex As Exception
    '        VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = firmatmp
    '        MsgBox(ex.Message & ex.StackTrace)
    '        Return False
    '    End Try
    'End Function
    'Function getUID_PruefungIMEX(maxAnz As Integer) As Boolean
    '    Dim firmatmp = VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
    '    Try
    '        VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "IMEX"

    '        Dim dt = VERAG_PROG_ALLGEMEIN.cUIDPruefung.doUIDPruefungALL(CDate(Now.ToString("01.MM.yyyy")).AddMonths(-1), True, False, maxAnz, False)
    '        If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
    '            Dim PDF = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dt,,,,, False)
    '            If PDF <> "" Then
    '                Dim list As New List(Of String)
    '                list.Add(PDF)
    '                Dim Body = "Anbei befinden sich die Auflistung der geprüfen UID-Nummern.<br>Bei UID-Nummer mit dem Prüfungserbnis 'OK' wurde das Prüfdatum in den Kundenstamm eingetragen. "
    '                Body &= "<br><b>Ungültige UID-Nummern bitte manuell bearbeiten!</b>"
    '                Body &= "<br><br>Erstellt am: " & Now.ToShortDateString & ", um " & Now.ToShortTimeString
    '                Body &= "<br><br>Automatisch generiertes E-Mail."

    '                VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("Viktoria.Leirich@imex-group.at;kb@verag.ag", "UID Prüfung IMEX", Body,,, False, "al@verag.ag",, list)
    '                '  VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("al@verag.ag", "UID Prüfung", Body,,, False, ,, list)
    '            End If
    '        End If
    '        VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = firmatmp
    '        Return True
    '    Catch ex As Exception
    '        VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = firmatmp
    '        MsgBox(ex.Message & ex.StackTrace)
    '        Return False
    '    End Try
    'End Function
    'Function getUID_PruefungAMBAR(maxAnz As Integer) As Boolean
    '    Dim firmatmp = VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
    '    Try
    '        VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "AMBAR"

    '        Dim dt = VERAG_PROG_ALLGEMEIN.cUIDPruefung.doUIDPruefungALL(CDate(Now.ToString("01.MM.yyyy")).AddMonths(-1), True, False, maxAnz, False)
    '        If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
    '            Dim PDF = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dt,,,,, False)
    '            If PDF <> "" Then
    '                Dim list As New List(Of String)
    '                list.Add(PDF)
    '                Dim Body = "Anbei befinden sich die Auflistung der geprüfen UID-Nummern.<br>Bei UID-Nummer mit dem Prüfungserbnis 'OK' wurde das Prüfdatum in den Kundenstamm eingetragen. "
    '                Body &= "<br><b>Ungültige UID-Nummern bitte manuell bearbeiten!</b>"
    '                Body &= "<br><br>Erstellt am: " & Now.ToShortDateString & ", um " & Now.ToShortTimeString
    '                Body &= "<br><br>Automatisch generiertes E-Mail."

    '                VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("kb@verag.ag", "UID Prüfung AMBAR", Body,,, False, "al@verag.ag",, list)
    '                '  VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("al@verag.ag", "UID Prüfung", Body,,, False, ,, list)
    '            End If
    '        End If
    '        VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = firmatmp
    '        Return True
    '    Catch ex As Exception
    '        VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = firmatmp
    '        MsgBox(ex.Message & ex.StackTrace)
    '        Return False
    '    End Try
    'End Function

    Function getEZB_Waehrungskurse90D() As Boolean
        Dim MyData As String = ""
        getEZB_Waehrungskurse90D = False
        Try
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

            Using WC As New System.Net.WebClient()
                ' C0008_URL()
                WC.Encoding = ASCIIEncoding.UTF8
                Dim URL = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist-90d.xml" 'cDY_Paramter.GET_PARAM_ByName("C0008_URL", TESTSYSTEM)
                If URL = String.Empty Then Return False

                MyData = WC.DownloadString(URL)
                Dim doc As New XmlDocument()
                doc.LoadXml(MyData)
                If doc.HasChildNodes Then

                    If doc.GetElementsByTagName("gesmes:Envelope").Count > 0 Then
                        If doc.GetElementsByTagName("gesmes:Envelope")(0).HasChildNodes AndAlso doc.GetElementsByTagName("gesmes:Envelope")(0).ChildNodes.Count > 2 Then
                            If doc.GetElementsByTagName("gesmes:Envelope")(0).ChildNodes(2).HasChildNodes Then

                                For Each Entry2 As XmlNode In doc.GetElementsByTagName("gesmes:Envelope")(0).ChildNodes(2).ChildNodes

                                    Dim datum As Date = DateTime.ParseExact(Entry2.Attributes(0).Value, "yyyy-MM-dd", Nothing)

                                    If True Then

                                        If Entry2.Name = "Cube" Then
                                            Dim Cube = Entry2

                                            If Cube.HasChildNodes AndAlso Cube.ChildNodes(0).Name = "Cube" And Cube.ChildNodes(0).Attributes.Count > 0 Then

                                                For Each Entry As XmlNode In Cube.ChildNodes

                                                    Dim EZB As New VERAG_PROG_ALLGEMEIN.cEZB_Waehrungskurse

                                                    '                  Dim Code = ""
                                                    'Dim Description = ""
                                                    ' Dim StartDate = Nothing
                                                    ' Dim EndDate = Nothing
                                                    '      MsgBox("as!!!!!o")


                                                    If Entry.Attributes("currency") IsNot Nothing Then EZB.ezb_waehrungscode = Entry.Attributes("currency").Value
                                                    If Entry.Attributes("rate") IsNot Nothing Then EZB.ezb_kurs = CDbl(Entry.Attributes("rate").Value.Replace(".", ","))
                                                    'If Entry.SelectNodes("Description").Count > 0 Then EZB.ezb_waehrungsschluessel = Entry.SelectNodes("Description")(0).InnerText
                                                    EZB.ezb_datum = datum 'CDate(Entry.SelectNodes("StartDate")(0).InnerText)
                                                    EZB.SAVE()
                                                    '  LC.Add(New VERAG_PROG_ALLGEMEIN.cEZB_Waehrungskurse(Code, Description, StartDate, EndDate))
                                                    '   VERAG_PROG_ALLGEMEIN.
                                                    getEZB_Waehrungskurse90D = True


                                                    'MsgBox(datum.ToShortDateString & " - " & Now.ToShortDateString)

                                                    'If datum.ToShortDateString = Now.ToShortDateString Then 'aktuellen TAG sichern.
                                                    '    Try

                                                    '        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
                                                    '        SQL.doSQL("INSERT INTO [baskur] 
                                                    '                   ([baskur_code],[baskur_typ],[baskur_bez],[baskur_faktor],[baskur_kurs],[baskur_gvdat],[baskur_gbdat],[baskur_edat],[baskur_adat],[baskur_sb],[baskur_cdealt],[baskur_wkz]) 
                                                    '                   VALUES ('" & EZB.ezb_waehrungscode & "',1,'-',1," & Entry.Attributes("rate").Value & ",cast(getdate() as date),cast(getdate() as date),getdate(),getdate(),'VRG',000,'EUR')", "ATLAS")

                                                    '    Catch ex As Exception
                                                    '        VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)

                                                    '    End Try
                                                    'End If


                                                Next



                                            End If
                                        End If
                                    End If
                                Next
                            End If




                        End If
                    End If
                End If
                'If LC.Count > 0 Then
                '    Return LC.INSERT_DB(TESTSYSTEM)
                'End If
            End Using

        Catch ex As Exception
            MsgBox(ex.Message)
            Return False
        End Try

    End Function

    Function getNachrichtenDatenFromBundesanzeiger() As String
        Dim cnt = 0
        Try
            Dim DY_server = "ftp://www.awr-portal.de/" '"217.17.30.74"
            Dim DY_name = "SAPverag"
            Dim DY_pwd = "SAPi64c"
            Dim DY_port = "21"
            Dim DY_PFAD_out = "/ASCII(bis4.6B)/Importcodenummern/Deutschland/Initialload.zip"
            Dim VERARBEITUNGS_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\EZT\Importcodenummern\" & Now.Year & "\"
            If Not System.IO.Directory.Exists(VERARBEITUNGS_PFAD) Then System.IO.Directory.CreateDirectory(VERARBEITUNGS_PFAD)

            '  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))
            'Dim ConnectionInfo2 As New ConnectionInfo(DY_server, DY_port, DY_name, New PasswordAuthenticationMethod(DY_name, DY_pwd))

            Dim ftp As System.Net.FtpWebRequest = CType(System.Net.FtpWebRequest.Create(DY_server & DY_PFAD_out), System.Net.FtpWebRequest)


            ftp.Credentials = New System.Net.NetworkCredential(DY_name, DY_pwd)

            'Turn off KeepAlive (will close connection on completion)

            ftp.KeepAlive = False

            'we want a binary

            ftp.UseBinary = True

            'Define the action required (in this case, download a file)

            ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile



            'If we were using a method that uploads data e.g. UploadFile

            'we would open the ftp.GetRequestStream here an send the data



            'Get the response to the Ftp request and the associated stream

            Dim dwlFileName = VERARBEITUNGS_PFAD & Now.ToString("yyyyMMdd_HHmmss_") & "Initialload.zip"
            Using response As System.Net.FtpWebResponse = CType(ftp.GetResponse, System.Net.FtpWebResponse)

                Using responseStream As IO.Stream = response.GetResponseStream

                    'loop to read & write to file
                    Using fs As New IO.FileStream(dwlFileName, IO.FileMode.Create)

                        Dim buffer(2047) As Byte

                        Dim read As Integer = 0

                        Do

                            read = responseStream.Read(buffer, 0, buffer.Length)

                            fs.Write(buffer, 0, read)

                        Loop Until read = 0 'see Note(1)

                        responseStream.Close()

                        fs.Flush()

                        fs.Close()

                    End Using

                    responseStream.Close()

                End Using

                response.Close()

            End Using

            Return dwlFileName


        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try

        Return ""
    End Function


    Function loadEZTZipToDB(pfadZIP As String) As Boolean
        Try
            loadEZTZipToDB = False
            Dim VERARBEITUNGS_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\EZT\Importcodenummern\" & Now.Year & "\Extrakt\"
            If System.IO.Directory.Exists(VERARBEITUNGS_PFAD) Then System.IO.Directory.Delete(VERARBEITUNGS_PFAD, True) 'Zuerst löschen, damit leer ist
            System.IO.Directory.CreateDirectory(VERARBEITUNGS_PFAD)


            System.IO.Compression.ZipFile.ExtractToDirectory(pfadZIP, VERARBEITUNGS_PFAD)
            If System.IO.Directory.GetFiles(VERARBEITUNGS_PFAD).Count > 0 Then
                loadEZTZipToDB = (insertEZTIntoDB(System.IO.Directory.GetFiles(VERARBEITUNGS_PFAD)(0), True) And
                   insertEZTIntoDB(System.IO.Directory.GetFiles(VERARBEITUNGS_PFAD)(0), False))
            End If
            'System.IO.Directory.Delete(VERARBEITUNGS_PFAD,True)

        Catch ex As Exception
            MsgBox(ex.Message & ex.StackTrace)
            Return False
        End Try
    End Function

    Function insertEZTIntoDB(pfad As String, TESTSYSTEM As Boolean) As Boolean
        Dim ts = VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = TESTSYSTEM
        Try
            If Not System.IO.File.Exists(pfad) Then Return False

            Dim reader As StreamReader = My.Computer.FileSystem.OpenTextFileReader(pfad, System.Text.Encoding.Default)
            Dim a As String

            'If Not VERAG_PROG_ALLGEMEIN.cEZT_ImportCodenummern.delWholeDB() Then Return False ' nicht mehr, da upgedatet wird
            Dim cnt = 0
            Do
                a = reader.ReadLine
                '
                ' Code here
                '
                If a IsNot Nothing AndAlso a.Length > 40 Then

                    Dim EZT As New VERAG_PROG_ALLGEMEIN.cEZT_ImportCodenummern
                    Dim pos As String = 0
                    EZT.ezt_Land = a.Substring(pos, 3) : pos += 3
                    EZT.ezt_Codenummer = a.Substring(pos, 11) : pos += 11
                    EZT.ezt_BesMasseinheit = a.Substring(pos, 3) : pos += 3
                    EZT.ezt_BesMasseinheit2 = a.Substring(pos, 3) : pos += 3
                    EZT.ezt_Start = Date.ParseExact(a.Substring(pos, 8), "yyyyMMdd", System.Globalization.DateTimeFormatInfo.CurrentInfo) : pos += 8
                    EZT.ezt_Ende = Date.ParseExact(a.Substring(pos, 8), "yyyyMMdd", System.Globalization.DateTimeFormatInfo.CurrentInfo) : pos += 8
                    EZT.ezt_Sprache = a.Substring(pos, 3) : pos += 3
                    EZT.ezt_Text = a.Substring(pos)
                    EZT.SAVE()
                    cnt += 1
                    ' Sub New(ezt_Land, ezt_Codenummer, ezt_BesMasseinheit, ezt_BesMasseinheit2, ezt_Start, ezt_Ende, ezt_Sprache, ezt_Text)
                    If cnt Mod 10 = 0 Then Application.DoEvents()
                End If
            Loop Until a Is Nothing
            reader.Close()
            VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = ts
            Return True
        Catch ex As Exception
            MsgBox(ex.Message & ex.StackTrace)
            VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = ts
            Return False
        End Try
    End Function

    Private Sub LinkLabel18_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel18.LinkClicked
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        Dim bool = getEZB_Waehrungskurse()
        showPic(bool, PictureBox10)
    End Sub

    Private Sub LinkLabel19_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel19.LinkClicked
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        Dim bool = getEZB_Waehrungskurse90D()
        showPic(bool, PictureBox11)
    End Sub

    Private Sub LinkLabel20_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel20.LinkClicked
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        Dim bool = getUID_Pruefung(MyTextBox1.Text, "VERAG", "UID Prüfung VERAG", "as@verag.ag;ih@verag.ag;kb@verag.ag", "al@verag.ag",, MyTextBox2._value, cbxVermerk.Checked)
        'bool = getUID_Pruefung(MyTextBox1.Text, "VERAG", "UID Prüfung VERAG", "d.breimaier@verag.ag",,, MyTextBox2._value, cbxVermerk.Checked)
        'Dim bool = getUID_PruefungVERAG(MyTextBox1.Text)
        showPic(bool, PictureBox12)
    End Sub

    Private Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        VERAG_PROG_ALLGEMEIN.cDVO_Interface.genStammdatenANSI(False, cbxKd.Checked, cbxBu.Checked)
    End Sub

    Private Sub LinkLabel22_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel22.LinkClicked
        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = True
        Dim f As New frmTCNachrichtenVerarbeitung
        f.ShowDialog()
        Me.Visible = True
    End Sub

    Private Sub LinkLabel21_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel21.LinkClicked
        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        Dim f As New frmTCNachrichtenVerarbeitung
        f.ShowDialog()
        Me.Visible = True
    End Sub

    Private Sub LinkLabel24_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel24.LinkClicked
        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = True
        Dim f As New frmMDMNachrichtenVerarbeitung
        f.ShowDialog()
        Me.Visible = True
    End Sub

    Private Sub LinkLabel23_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel23.LinkClicked
        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        Dim f As New frmMDMNachrichtenVerarbeitung
        f.ShowDialog()
        Me.Visible = True
    End Sub

    Private Sub LinkLabel25_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel25.LinkClicked
        importFileFromEZOLL(If(CheckBox2.Checked, Now.AddDays(-7), If(CheckBox3.Checked, Now.AddMonths(-1), Now)))
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs)
        For Each d In System.IO.Directory.GetDirectories(VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\Nachrichtendaten_Ablage\2019")
            Dim fid As New FileInfo(d)
            If fid.Name >= 20190820 Then


                For Each f In System.IO.Directory.GetFiles(d)
                    Dim fi As New FileInfo(f)
                    If fi.Extension = ".xml" Then

                        Dim XML_Code = System.IO.File.ReadAllText(f, System.Text.UTF8Encoding.Default)

                        If XML_Code.Contains("<FCFCDC>") And XML_Code.Contains("<TaxOffice>9153</TaxOffice>") Then
                            If Not IO.File.Exists(VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\TEST\FISKAL\" & fi.Name) Then
                                IO.File.Copy(f, VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\TEST\FISKAL\" & fi.Name)
                            End If
                        End If


                        '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(f, System.Text.UTF8Encoding.Default)

                        'doc.LoadXml(frmDYNachrichtenVerarbeitung.SanitizeXmlString(XML_Code))

                        'If cGetMsgType.isEZA_FreierVerkehrAktVeredelUmwandlungXML(doc) Then
                        '    MsgBox(f)
                        'End If

                    End If
                Next
            End If

        Next

    End Sub

    Private Sub LinkLabel26_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel26.LinkClicked
        Me.Cursor = Cursors.WaitCursor
        Try
            DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("I0700", True) 'TESTSYSTEM
            Dim erg = DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("I0700", False) 'ECHTSYSTEM
            showPic(erg, PictureBox13)
        Catch ex As Exception : VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name) : End Try
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub TabPage2_Click(sender As Object, e As EventArgs)

    End Sub
    Private Sub form1_KeyUp(ByVal sender As Object, ByVal e As EventArgs) Handles Button11.Click



        Dim rowSplitter As Char() = {vbCr, vbLf}
        Dim columnSplitter As Char() = {vbTab}
        Dim dataInClipboard As IDataObject = Clipboard.GetDataObject()
        Dim stringInClipboard As String = CStr(dataInClipboard.GetData(DataFormats.Text))
        Dim rowsInClipboard As String() = stringInClipboard.Split(rowSplitter, StringSplitOptions.RemoveEmptyEntries)
        Dim r As Integer = 0 'dgvMRN.SelectedRows(0).Index
        Dim c As Integer = 0 'dgvMRN.SelectedRows(0).Cells(0).ColumnIndex

        MsgBox(rowsInClipboard.Length)
        If dgvMRN.Rows.Count < (r + rowsInClipboard.Length) Then
            dgvMRN.Rows.Add(r + rowsInClipboard.Length - dgvMRN.Rows.Count)
        End If

        For iRow As Integer = 0 To rowsInClipboard.Length - 1
            Dim valuesInRow As String() = rowsInClipboard(iRow).Split(columnSplitter)

            For iCol As Integer = 0 To valuesInRow.Length - 1

                If dgvMRN.ColumnCount - 1 >= c + iCol Then
                    dgvMRN.Rows(r + iRow).Cells(c + iCol).Value = valuesInRow(iCol)
                End If
            Next
        Next
    End Sub
    Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
        Dim ftmp As Object = If(IsNumeric(txtVRGOut_FilialenNr.Text.Trim), txtVRGOut_FilialenNr.Text, Nothing)
        Dim atmp As Object = If(IsNumeric(txtVRGOut_AbfertigungsNr.Text.Trim), txtVRGOut_AbfertigungsNr.Text, Nothing)


        'DGV------------------------------------
        If dgvMRN.Rows.Count - 1 > 0 Then
            For Each r As DataGridViewRow In dgvMRN.Rows
                If r.Cells(0) IsNot Nothing Then
                    Dim BezugsNrDgv = ""
                    Dim okDGV = False
                    Dim mrn = r.Cells(0).Value
                    If If(mrn, "") <> String.Empty Then
                        Select Case MyComboBox1._value
                            Case "DY"
                                BezugsNrDgv = cVERAG_out_ncts.getBezugnNr_ByMRN(mrn)
                                okDGV = cVERAG_out_ncts.copyFileFTP_VERAGncts_DY_ByBezugsNr(BezugsNrDgv, getISett, ftmp, atmp)
                            Case "TC"
                                BezugsNrDgv = TELOTEC_Worker.cTelotec_Anmeldung.getBezugnNr_ByMRN(mrn)
                                okDGV = cVERAG_out_ncts.copyFileFTP_VERAGncts_TC_ByBezugsNr(BezugsNrDgv, getISett, ftmp, atmp)
                            Case "DHF"
                                BezugsNrDgv = cVERAG_out_ncts.getLRN_ByCRN(mrn)
                                okDGV = cVERAG_out_ncts.copyFileFTP_VERAGncts_EZOLL_ByBezugsNr(BezugsNrDgv, getISett, ftmp, atmp)
                        End Select
                    End If
                    If okDGV Then
                        r.DefaultCellStyle.BackColor = System.Drawing.Color.LightGreen
                    Else
                        r.DefaultCellStyle.BackColor = System.Drawing.Color.IndianRed
                    End If
                End If
                Me.Refresh()
            Next
            Exit Sub
        End If
        '------------------------------------

        Dim BezugsNr = txtVRGOut_BezugsNr.Text
        If txtVRGOut_BezugsNr.Text.Trim = "" And txtVRGOut_MRN.Text <> "" Then

            Select Case MyComboBox1._value
                Case "DY" : BezugsNr = cVERAG_out_ncts.getBezugnNr_ByMRN(txtVRGOut_MRN.Text)
                Case "TC" : BezugsNr = TELOTEC_Worker.cTelotec_Anmeldung.getBezugnNr_ByMRN(txtVRGOut_MRN.Text)
                Case "DHF" : BezugsNr = cVERAG_out_ncts.getLRN_ByCRN(txtVRGOut_MRN.Text)
            End Select

        End If
        If BezugsNr = "" Then
            MsgBox("Bezugsnummer leer!")
            Exit Sub
        End If

        Dim ok As Boolean = False
        Select Case MyComboBox1._value
            Case "DY" : ok = cVERAG_out_ncts.copyFileFTP_VERAGncts_DY_ByBezugsNr(BezugsNr, getISett, ftmp, atmp)
            Case "TC" : ok = cVERAG_out_ncts.copyFileFTP_VERAGncts_TC_ByBezugsNr(BezugsNr, getISett, ftmp, atmp)
            Case "DHF" : ok = cVERAG_out_ncts.copyFileFTP_VERAGncts_EZOLL_ByBezugsNr(BezugsNr, getISett, ftmp, atmp)
        End Select

        showPic(ok, PictureBox14)

    End Sub


    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim ok As Boolean = False
        Select Case MyComboBox2._value
            Case "DY" : ok = cVERAG_out_eza.copyFileFTP_VERAGEZA_DY_ByBezugsNr(txtVRGOutEZA_BezugsNr.Text, getISettEZA)
                'Case "TC" : ok = cVERAG_out_ncts.copyFileFTP_VERAGncts_TC_ByBezugsNr(txtVRGOut_BezugsNr.Text, getISett)
                'Case "DHF" : ok = cVERAG_out_ncts.copyFileFTP_VERAGncts_EZOLL_ByBezugsNr(txtVRGOut_BezugsNr.Text, getISett)
        End Select

        showPic(ok, PictureBox15)


    End Sub
    Function getISett() As cVERAG_Interface_Settings
        getISett = New cVERAG_Interface_Settings
        getISett.acticeInterface_OREGON = cbxISett_OREGON.Checked
        getISett.acticeInterface_TOBB = cbxISett_TOBB.Checked
        getISett.acticeInterface_EKOL = cbxISett_EKOL.Checked
        getISett.acticeInterface_TEST = cbxISett_TEST.Checked
        getISett.acticeInterface_VERAG = cbxISett_VERAG.Checked
        getISett.acticeInterface_IMEX = cbxISett_IMEX.Checked
    End Function

    Function getISettEZA() As cVERAG_Interface_Settings
        getISettEZA = New cVERAG_Interface_Settings
        getISettEZA.acticeInterface_VERAG = cbxISettEZA_VERAG.Checked
    End Function




    Private Sub LinkLabel28_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel28.LinkClicked
        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "UNISPED"
        Dim f As New frmDYNachrichtenVerarbeitung
        f.ShowDialog()
        Me.Visible = True
    End Sub

    Private Sub LinkLabel30_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel30.LinkClicked
        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = True
        Dim f As New frmTRNCTS_NachrichtenVerarbeitung
        f.ShowDialog()
        Me.Visible = True
    End Sub

    Private Sub LinkLabel31_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel31.LinkClicked
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        ASFINAG_LKW()
    End Sub

    Function ASFINAG_LKW(Optional isFMZoll As Boolean = True) As Boolean
        Try
            Dim SQl As New VERAG_PROG_ALLGEMEIN.SQL

            ' CLF-Einträge aus den bestehenden SDL-Datensätzen entfernen,
            ' damit nach dem Aktualisierungslauf der Istzustand der CLF in der SDL hergestellt wird.
            If Not SQl.doSQL("UPDATE SDL Set  OBUID = NULL, Vertragsabschlussdatum = NULL, Kategorie = NULL, Status = NULL WHERE (SDLNr = 200) AND (NOT Vertragsabschlussdatum IS NULL)", "SDL") Then
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR("ERROR", "Fehler beim Reset SDL-Daten.", System.Reflection.MethodBase.GetCurrentMethod.Name)
                Return False
            End If

            ' Nummer der Speditionsdienstleistung für MautAT einlesen.
            Dim SDLNr = SQl.getValueTxtBySql("SELECT isnull(SDLNr,'') FROM vwSpeditionsdienstleistungen WHERE (Sicht = 'vwMautAT')", "SDL")
            If SDLNr = "" Then
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR("ERROR", "SDL-Nr nicht gefunden.", System.Reflection.MethodBase.GetCurrentMethod.Name)
                Return False
            End If


            If isFMZoll Then

                ' Verbindung zur ASFINAG Datenbank herstellen
                Dim connectionString = ""
                If VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM Then
                    connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\DEVELOPER\f\FMZoll\Mautmanager.adp"
                Else
                    connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\FMZOLL\f\FMZoll\Mautmanager.adp"
                End If
                Dim con As New OleDbConnection(connectionString)
                Dim cmd As New OleDbCommand
                Dim var1 As String
                Dim adapter As OleDbDataAdapter = New OleDbDataAdapter()
                Dim reader As OleDbDataReader = Nothing

                ' Kfz Kennzeichen einlesen.
                Dim SQLQuery = "SELECT CardNumber, ValidTo, OBUID, KfzKennzeichen, Nationalität, DatumVertragsabschluss, Kategorie, Schadstoffklasse, Status FROM vwCLFBody " ' vwCLFBody verwendet immer zuletzt importierte CLF!
                Using Command As New OleDbCommand(SQLQuery, con)
                    Using oRDR As OleDbDataReader = Command.ExecuteReader
                        While (oRDR.Read)
                            Dim KartenNr = oRDR.GetValue("CardNumber")

                            Dim KfzKennzeichen = fktConvert(oRDR.GetValue("KfzKennzeichen"))

                            ' Kundennummer einlesen
                            Dim KdNr As Integer = SQl.getValueTxtBySql("SELECT AdressenNr FROM Kreditkarten WHERE KartenNr='" & KartenNr & "'", "SDL",,, -1)

                            If KdNr > 0 Then

                                Call fktKundenSDLVerwalten(KdNr, SDLNr)
                                Call fktKundenLkwVerwalten(KdNr, oRDR.GetValue("KfzKennzeichen"), oRDR.GetValue("Nationalität"))

                                Dim SDL = New VERAG_PROG_ALLGEMEIN.cSDL(KdNr, oRDR.GetValue("KfzKennzeichen"), SDLNr)
                                If Not SDL.hasentry Then
                                    SDL.KundenNr = KdNr
                                    SDL.KfzKennzeichen = KfzKennzeichen
                                    SDL.SDLNr = SDLNr
                                    SDL.History = 0 'fktLiefereHistorywert(!KundenNr, !SDLNr)
                                    SDL.Erfassungsdatum = Now
                                Else
                                    SDL.Änderungsdatum = Now
                                End If
                                SDL.Sachbearbeiter = "ASFINAG"

                                Dim Validto = SQL.checkNullStr(oRDR.GetValue("DatumVertragsabschluss"))

                                SDL.KartenNr = SQL.checkNullStr(oRDR.GetValue("CardNumber"))
                                If Validto <> "" Then
                                    SDL.GültigBis = DateAdd("d", -1, DateAdd("m", 1, DateSerial("20" & Mid(oRDR.GetValue("CardNumber"), 1, 2), Mid(Validto, 3, 2), 1)))
                                End If

                                SDL.OBUID = SQL.checkNullStr(oRDR.GetValue("OBUID"))
                                SDL.Vertragsabschlussdatum = SQL.checkNullStr(oRDR.GetValue("DatumVertragsabschluss"))
                                SDL.Kategorie = SQL.checkNullStr(oRDR.GetValue("Kategorie"))
                                SDL.Schadstoffklasse = SQL.checkNullStr(oRDR.GetValue("Schadstoffklasse"))
                                SDL.Status = SQL.checkNullStr(oRDR.GetValue("Status"))
                                SDL.SAVE()
                            End If

                        End While
                    End Using
                End Using
                con.Close()
            Else

                ' Kfz Kennzeichen einlesen.

                Dim strSQLASFINAG = "SELECT cardNumber, ValidTo, OBUID, vehicleLicensePlate, nationality, contractDate, vehicleCategory, emissionCategory, status FROM vwCLFBody"

                Dim dtAsfinag As DataTable = SQl.loadDgvBySql_Param(strSQLASFINAG, "ASFINAG")

                ' ????????
                'If dtAsfinag.Rows.Count < 1 Then
                '    Return False
                'End If

                For Each row As DataRow In dtAsfinag.Rows

                    Dim KdNr As Integer = SQl.getValueTxtBySql("SELECT Kreditkarten.AdressenNr FROM Kreditkarten WHERE Kreditkarten.KartenNr='" & row.Item("cardNumber") & "'", "FMZOLL",,, -1)


                    If KdNr > 0 Then

                        Call fktKundenSDLVerwalten(KdNr, SDLNr)
                        Call fktKundenLkwVerwalten(KdNr, row.Item("vehicleLicensePlate"), row.Item("nationality"))

                        ' Die MautAT Tabelle aktualisieren.

                        Dim SDL = New VERAG_PROG_ALLGEMEIN.cSDL(KdNr, row.Item("vehicleLicensePlate"), SDLNr)

                        If Not SDL.hasentry Then
                            SDL.KundenNr = KdNr
                            SDL.KfzKennzeichen = row.Item("vehicleLicensePlate")
                            SDL.SDLNr = SDLNr
                            SDL.History = 0 'fktLiefereHistorywert(!KundenNr, !SDLNr)
                            SDL.Erfassungsdatum = Now
                        Else
                            SDL.Änderungsdatum = Now
                        End If
                        SDL.Sachbearbeiter = "ASFINAG" & IIf(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, "_TEST", "")

                        Dim Validto = SQL.checkNullStr(row.Item("contractDate"))

                        SDL.KartenNr = SQL.checkNullStr(row.Item("cardNumber"))
                        If Validto <> "" Then
                            'MsgBox(Mid(row.Item("ValidTo"), 1, 2) & " " & Mid(row.Item("ValidTo"), 3, 2))
                            SDL.GültigBis = DateAdd("d", -1, DateAdd("m", 1, DateSerial("20" & Mid(row.Item("ValidTo"), 1, 2), Mid(row.Item("ValidTo"), 3, 2), 1))) 'noch im DETAIL checken!
                        End If

                        SDL.OBUID = SQL.checkNullStr(row.Item("OBUID"))
                        SDL.Vertragsabschlussdatum = SQL.checkNullStr(row.Item("contractDate"))
                        SDL.Kategorie = SQL.checkNullStr(row.Item("vehicleCategory"))
                        SDL.Schadstoffklasse = SQL.checkNullStr(row.Item("emissionCategory"))
                        SDL.Status = SQL.checkNullStr(row.Item("status"))
                        SDL.SAVE()
                    End If

                    Dim strOBU = "OBU " & row.Item("OBUID") & " jetzt in " & KdNr & "/" & row.Item("vehicleLicensePlate") & "/" & SDLNr & "/" & 0 & "."

                    ' Mehrfachvorkommen der OBU-ID prüfen.
                    Dim strSQL = "SELECT OBUID, Vermerk  FROM vwSDL WHERE (SDLNr = " & SDLNr & ") And (OBUID = '" & row.Item("OBUID") & "') And ((KundenNr <> " & KdNr & ") Or (KfzKennzeichen <> '" & row.Item("vehicleLicensePlate") & "'))"
                    Dim dtCheckOBUID As DataTable = SQl.loadDgvBySql_Param(strSQL, "SDL")

                    If dtCheckOBUID.Rows.Count > 0 Then

                        For Each rowCheckOBUID As DataRow In dtCheckOBUID.Rows
                            Dim SDL = New VERAG_PROG_ALLGEMEIN.cSDL(KdNr, row.Item("vehicleLicensePlate"), SDLNr)
                            Dim leftString = Trim(strOBU & " " & SDL.Vermerk.Substring(0, 100))
                            SDL.Vermerk = Trim(strOBU & " " & SDL.Vermerk.Substring(0, 100))
                            SDL.OBUID = DBNull.Value
                            SDL.SAVE()

                        Next
                    End If

                Next


            End If

            Return True

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.SHOW)
            Return False
        End Try
    End Function

    Public Function fktConvert(KfzKennzeichen) As String
        fktConvert = ""
        Dim I As Integer

        If KfzKennzeichen Is Nothing OrElse KfzKennzeichen Is DBNull.Value Then
            Return Nothing
        End If

        For I = 1 To Len(KfzKennzeichen)
            Select Case Mid(KfzKennzeichen, I, 1)
                Case "A" To "Z"
                    fktConvert = fktConvert & UCase(Mid(KfzKennzeichen, I, 1))
                Case "0" To "9"
                    fktConvert = fktConvert & Mid(KfzKennzeichen, I, 1)
            End Select
        Next I
    End Function

    Public Function fktKundenLkwVerwalten(ByRef KdNr As Integer, ByRef KfzKennzeichen As String, Nationalitaet As String)
        Dim SDL_LKW As New VERAG_PROG_ALLGEMEIN.cSDL_LKW(KdNr, KfzKennzeichen)

        If Not SDL_LKW.hasEntry Then
            SDL_LKW.Erfassungsdatum = Now
        Else
            SDL_LKW.Änderungsdatum = Now
        End If
        SDL_LKW.Sachbearbeiter = "ASFINAG" & IIf(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, "_TEST", "")
        SDL_LKW.Nationalität = Nationalitaet

        Return SDL_LKW.SAVE
    End Function
    Public Function fktKundenSDLVerwalten(ByRef KdNr As Integer, ByRef SDLNr As Integer) As Boolean
        Dim KUNDEN_SDL As New VERAG_PROG_ALLGEMEIN.cKundenSDL(KdNr, SDLNr)

        If Not KUNDEN_SDL.hasEntry Then
            KUNDEN_SDL.Erfassungsdatum = Now
        Else
            KUNDEN_SDL.Änderungsdatum = Now
        End If
        KUNDEN_SDL.Sachbearbeiter = "ASFINAG" & IIf(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, "_TEST", "")

        Return KUNDEN_SDL.SAVE

    End Function

    Private Sub LinkLabel29_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel29.LinkClicked
        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        Dim f As New frmTRNCTS_NachrichtenVerarbeitung
        f.ShowDialog()
        Me.Visible = True
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = CheckBox5.Checked 'False
        If Not IsNumeric(txtGJ_UNISPED.Text) Then MsgBox("GJ: Falsches Fomat!")

        If cboBMDUnispedFirma._value = "" Then
            VERAG_PROG_ALLGEMEIN.cBMD_Interface.genDatensatzCSV_ALL(CheckBox4.Checked, False,, txtGJ_UNISPED.Text)
        Else
            VERAG_PROG_ALLGEMEIN.cBMD_Interface.genDatensatzCSV_Buchungen(cboBMDUnispedFirma._value, CheckBox4.Checked, txtGJ_UNISPED.Text)
        End If
    End Sub

    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = CheckBox5.Checked 'False
        VERAG_PROG_ALLGEMEIN.cBMD_Interface.genDatensatzCSV_ALL(CheckBox4.Checked,, False)
    End Sub

    Private Sub LinkLabel32_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel32.LinkClicked
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        '  Dim bool = getUID_PruefungIMEX(MyTextBox1.Text)
        Dim bool = getUID_Pruefung(MyTextBox1.Text, "IMEX", "UID Prüfung IMEX", "Viktoria.Leirich@imex-group.at;as@verag.ag;kb@verag.ag", "al@verag.ag",, MyTextBox2._value, cbxVermerk.Checked)
        showPic(bool, PictureBox12)
    End Sub
    Private Sub LinkLabel33_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel33.LinkClicked
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        Dim bool = getUID_Pruefung(MyTextBox1.Text, "AMBAR", "UID Prüfung AMBAR", "io@ambarlog.de", , "al@verag.ag;as@verag.ag", MyTextBox2._value, cbxVermerk.Checked)
        showPic(bool, PictureBox12)
    End Sub

    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
        UPDATE_SMS()
    End Sub

    Function UPDATE_SMS() As Boolean
        Try
            Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
            Dim dt As DataTable = SQL.loadDgvBySql("SELECT * FROM tblSMS where sms_Status not IN(3,4) and (CASE sms_art WHEN 'WHATSAPP' THEN whatsApp_gatewayId ELSE sms_MessageIds END) is not null and isnull(sms_MessageIds,'') not like 'https://api.esendex.com/%' AND sms_Datum>DATEADD(DAY,-2, GETDATE())", "FMZOLL")
            If dt IsNot Nothing Then
                For Each r In dt.Rows
                    Dim cSMS As New VERAG_PROG_ALLGEMEIN.cSMS(r("sms_id"))

                    Select Case cSMS.sms_art
                        Case "WHATSAPP" : cSMS.checkWhatsAppStatus(True)
                        Case "SMS" : cSMS.checkSMSStatus(True)
                    End Select
                Next
            End If
            Return True
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name)
            Return False
        End Try
    End Function

    Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
        If cbxSyskaWdh.Checked And txtSyskaWdhDateiname.Text = "" Then
            MsgBox("Dateiname angeben!") : Exit Sub
        End If

        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = CheckBox6.Checked 'False
        If cboSYSKAFirma._value = "" Then
            VERAG_PROG_ALLGEMEIN.cSyska_Interface.genDatensatz_ALL(CheckBox7.Checked, False, If(cbxSyskaWdh.Checked, txtSyskaWdhDateiname.Text, ""))
        Else
            VERAG_PROG_ALLGEMEIN.cSyska_Interface.genDatensatz_Buchungen(cboSYSKAFirma._value, CheckBox7.Checked, If(cbxSyskaWdh.Checked, txtSyskaWdhDateiname.Text, ""))
        End If
    End Sub

    Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = CheckBox6.Checked 'False
        If cboSYSKAFirma._value = "" Then
            VERAG_PROG_ALLGEMEIN.cSyska_Interface.genDatensatz_ALL(CheckBox7.Checked,, False)
        Else
            VERAG_PROG_ALLGEMEIN.cSyska_Interface.genDatensatz_Stammdaten(cboSYSKAFirma._value, CheckBox7.Checked)
        End If
    End Sub

    Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click
        Dim FO As New VERAG_PROG_ALLGEMEIN.cFinanzOnlineWebService
        VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "VERAG"
        FO.initValues()

        If FO.Call_Web_Service_MethodUID_Login_NEU2020() = 0 Then
            Dim UID_ERG = FO.Call_Web_Service_MethodUID_Abfrage_NEU2020(759181)

            If UID_ERG IsNot Nothing Then

                Select Case UID_ERG.uid_valid
                    Case 1 : MsgBox("UID-Nr. GÜLTIG   -   OK")
                    Case 0 : MsgBox("UID-Nr. UNGÜLTIG")
                End Select
            End If
        End If

        FO.Call_Web_Service_MethodUID_Logout_NEU2020()


        ' VERAG_PROG_ALLGEMEIN.cFinanzOnlineWebService.Call_Web_Service_MethodUID_Abfrage_NEU2020("DE115311033")


        'doExcelImportNCTS_FREMD(InputBox("Eing:",, "F:\mic2.xlsx"))
        'Dim list As New List(Of Integer)
        'Dim DY As New DAKOSY_Worker.cDakosy_Zollanmeldungen(572237)
        'Dim SND As New VERAG_PROG_ALLGEMEIN.cSendungen(DY.dy_SendungsId)

        'sendMailZollbeleg("C:\VeragTMP\USER_4\VERG-SYS_IMP_ZOLL_TAX-IPDC-4803_21061055-ATC400039161120217701-$V8.pdf", 750735, "STB", list, DY.dy_BezugsNr, SND)
    End Sub

    Private Sub lblEZOLLDat_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles lblEZOLLDat.LinkClicked
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        Dim bool = importFileFromEZOLL(txtEZOLLAnhDat._value)
        showPic(bool, piceZollAnh)
    End Sub

    Private Sub CheckBox2_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox2.CheckedChanged

    End Sub

    Private Sub LinkLabel35_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel35.LinkClicked
        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = True
        Dim f As New frmTRNCTS_NachrichtenVerarbeitung_OREGON
        f.ShowDialog()
        Me.Visible = True
    End Sub

    Private Sub LinkLabel34_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel34.LinkClicked
        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        Dim f As New frmTRNCTS_NachrichtenVerarbeitung_OREGON
        f.ShowDialog()
        Me.Visible = True
    End Sub

    Private Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click
        'VERAG_PROG_ALLGEMEIN.cSyska_Interface.genDatensatz_StammdatenTEST(1, True)
    End Sub

    Private Sub Button12_Click(sender As Object, e As EventArgs) Handles Button12.Click
        'VERAG_PROG_ALLGEMEIN.cSyska_Interface.UPDATE_FIBU_RISIKO(401026)
        'VERAG_PROG_ALLGEMEIN.cSyska_Interface.UPDATE_FIBU_RISIKO(401516)
        'VERAG_PROG_ALLGEMEIN.cSyska_Interface.UPDATE_FIBU_RISIKO(203203)
        'VERAG_PROG_ALLGEMEIN.cSyska_Interface.UPDATE_FIBU_RISIKO(202888)
        'VERAG_PROG_ALLGEMEIN.cSyska_Interface.UPDATE_FIBU_RISIKO(101001)
        'VERAG_PROG_ALLGEMEIN.cSyska_Interface.UPDATE_FIBU_RISIKO(402155)
        'VERAG_PROG_ALLGEMEIN.cSyska_Interface.UPDATE_FIBU_RISIKO(402055)
        'VERAG_PROG_ALLGEMEIN.cSyska_Interface.UPDATE_FIBU_RISIKO(300405)
        'VERAG_PROG_ALLGEMEIN.cSyska_Interface.UPDATE_FIBU_RISIKO(202766)
        'VERAG_PROG_ALLGEMEIN.cSyska_Interface.UPDATE_FIBU_RISIKO(203252)
        'VERAG_PROG_ALLGEMEIN.cSyska_Interface.UPDATE_FIBU_RISIKO(401454)
        'VERAG_PROG_ALLGEMEIN.cSyska_Interface.UPDATE_FIBU_RISIKO(202479)
        'VERAG_PROG_ALLGEMEIN.cSyska_Interface.UPDATE_FIBU_RISIKO(402162)
        'VERAG_PROG_ALLGEMEIN.cSyska_Interface.UPDATE_FIBU_RISIKO(401729)
        'VERAG_PROG_ALLGEMEIN.cSyska_Interface.UPDATE_FIBU_RISIKO(202811)

        VERAG_PROG_ALLGEMEIN.cSyska_Interface.UPDATE_FIBU_RISIKO()

    End Sub

    Private Sub Button13_Click(sender As Object, e As EventArgs) Handles Button13.Click
        VERAG_PROG_ALLGEMEIN.cSyska_Interface.OP_Einlesen_ALL()
    End Sub

    Private Sub LinkLabel36_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel36.LinkClicked
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        Dim bool = getUID_Pruefung(MyTextBox1.Text, "UNISPED", "UID Prüfung UNISPED", "al@verag.ag", "al@verag.ag",, MyTextBox2._value, cbxVermerk.Checked)
        showPic(bool, PictureBox12)
    End Sub

    Private Sub Button14_Click(sender As Object, e As EventArgs) Handles Button14.Click
        VERAG_PROG_ALLGEMEIN.cLDV_Interface.copyLDV_BMD()

    End Sub

    Private Sub TabPage1_Click(sender As Object, e As EventArgs) Handles TabPage1.Click

    End Sub

    Private Sub Button15_Click(sender As Object, e As EventArgs) Handles Button15.Click
        doExcelImportNCTS_FREMD()
    End Sub

    Private Sub Button16_Click(sender As Object, e As EventArgs) Handles Button16.Click
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        doIDSPlatts()
        doExcelImportNCTS_FREMD()
    End Sub

    Private Sub LinkLabel37_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel37.LinkClicked
        Me.Cursor = Cursors.WaitCursor
        Try
            DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0141", True) 'TESTSYSTEM
            Dim erg = DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0141", False) 'ECHTSYSTEM
            showPic(erg, PictureBox16)
        Catch ex As Exception : VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name) : End Try
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub LinkLabel38_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel38.LinkClicked
        Me.Cursor = Cursors.WaitCursor
        Try
            DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("I0610", True) 'TESTSYSTEM
            Dim erg = DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("I0610", False) 'ECHTSYSTEM
            showPic(erg, PictureBox17)
        Catch ex As Exception : VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name) : End Try
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub LinkLabel40_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel40.LinkClicked
        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = True
        Dim f As New frmTRNCTS_NachrichtenVerarbeitung_ATEZ
        f.ShowDialog()
        Me.Visible = True
    End Sub

    Private Sub LinkLabel39_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel39.LinkClicked
        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        Dim f As New frmTRNCTS_NachrichtenVerarbeitung_ATEZ
        f.ShowDialog()
        Me.Visible = True
    End Sub

    Private Sub btnDatev_Click(sender As Object, e As EventArgs) Handles btnDatev.Click
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = cbxDatevTest.Checked
        VERAG_PROG_ALLGEMEIN.cDatev_Interface.genDatensatzCSV_ALL("AMBAR", cbxDatevOpen.Checked, cbxDatevDebitoren.Checked, cbxDatevBuchungen.Checked)
    End Sub

    Private Sub LinkLabel44_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel44.LinkClicked
        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = cbxTestsystem.Checked
        If Not checkTestsystemSettings() Then Exit Sub
        Dim f As New frmAsfinag_NachrichtenVerabeitung("TTR", cbxTestFTP.Checked)
        f.ShowDialog()
        Me.Visible = True
    End Sub

    Private Sub LinkLabel43_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel43.LinkClicked
        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = cbxTestsystem.Checked
        If Not checkTestsystemSettings() Then Exit Sub
        Dim f As New frmAsfinag_NachrichtenVerabeitung("CLF", cbxTestFTP.Checked)
        f.ShowDialog()
        Me.Visible = True
        'ASFINAG_LKW(False)
    End Sub

    Private Sub LinkLabel42_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel42.LinkClicked
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = cbxTestsystem.Checked
        If Not checkTestsystemSettings() Then Exit Sub
        Me.Cursor = Cursors.WaitCursor
        Dim blt = New cAsfinag.Exportist
        blt.initExportPfade()
        showPic(blt.exportiereWhiteList, PictureBox18)
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub LinkLabel41_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel41.LinkClicked
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = cbxTestsystem.Checked
        If Not checkTestsystemSettings() Then Exit Sub
        Me.Cursor = Cursors.WaitCursor
        Dim blt = New cAsfinag.Exportist
        blt.initExportPfade()
        showPic(blt.exportiereBlackList, PictureBox19)
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub LinkLabel45_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel45.LinkClicked

        showPic(importEZOLLWechselkurse(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM), PictureBox20)

    End Sub
    Private Sub Button17_Click(sender As Object, e As EventArgs) Handles Button17.Click
        Dim f As New frmDatenarchivarchiv
        f.ShowDialog()
    End Sub

    Private Sub Button18_Click(sender As Object, e As EventArgs) Handles Button18.Click
        doAASVermerke_Schwelle()

    End Sub

    Function doAASVermerke_Schwelle()
        Try
            Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
            Dim dt = SQL.loadDgvBySql("
               SELECT TOP 1000 aviso.AvisoID,Vermerke.[Hinweis_Vermerk]
                ,CASE WHEN Vermerke.SendungID is not null THEN(SELECT FilialenNr from tblSendungen WHERE tblSnd_SendungID=Vermerke.SendungID) ELSE NULL END FilialenNr
                  FROM [Aviso]
                  inner join Vermerke on [Aviso].AvisoID=Vermerke.AvisoID
                  inner join VermerkeCodes on Vermerke.VermerkeCode=VermerkeCodes.VermerkCodeId
                  WHERE  [Aviso].Status NOT IN (1,2)  AND  AAS_Warnsystem=1 and AAS_Warnstufe=0 and DATEDIFF(HOUR,Vermerke.Datum,GETDATE())>AAS_SchwelleStunden and [VermerkIDAufgehoben] is null
                    and (Auftraggeber_KdNr IN (901043,100950,700945) or Frächter_KdNr IN (901043,100950,700945))
                  AND Aviso.Datum > DATEADD( day,-1,GETDATE())
                ", "AVISO")

            If dt IsNot Nothing Then
                For Each r In dt.Rows
                    insertBenachrichtigung_AAS(r("AvisoId"), r("SendungsId"), VERAG_PROG_ALLGEMEIN.cAllgemein.getFirmaFromFiliale2(r("FilialenNr")), VERAG_PROG_ALLGEMEIN.cAvisoBenachrichtigungenCodes.AAE_Benachrichtigung, "REMINDER", "REMINDER: " & r("Hinweis_Vermerk"), 1)
                Next
            End If
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
            Return False
        End Try
        Return True
    End Function
    Function doAASVermerke_24h()
        Try
            Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
            Dim dt = SQL.loadDgvBySql("
               SELECT TOP 1000 aviso.AvisoID, Datum
                  FROM [Aviso]
                  WHERE  [Aviso].Status NOT IN (1,2) 
                  and DATEDIFF(HOUR, (select top 1 Datum from Vermerke where Vermerke.AvisoID=aviso.AvisoID order by Vermerke.Datum desc),GETDATE())>24
                  and DATEDIFF(HOUR, (select top 1 Datum from Aenderungen where Aenderungen.AvisoID=aviso.AvisoID order by Aenderungen.Datum desc),GETDATE())>24
                  AND Datum > DATEADD( day,-2,GETDATE())
                ", "AVISO")

            If dt IsNot Nothing Then
                For Each r In dt.Rows
                    insertBenachrichtigung_AAS(r("AvisoId"), r("SendungsId"), VERAG_PROG_ALLGEMEIN.cAllgemein.getFirmaFromFiliale2(r("FilialenNr")), VERAG_PROG_ALLGEMEIN.cAvisoBenachrichtigungenCodes.AAE_Benachrichtigung, "REMINDER w4h", "REMINDER: " & r("Hinweis_Vermerk"), 0)
                Next
            End If
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
            Return False
        End Try
        Return True
    End Function

    Function doAASVermerke_Ankunft() ' 4 Stunden
        Try
            Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
            Dim dt = SQL.loadDgvBySql("
                 SELECT TOP 1000 aviso.AvisoID, Datum
                  FROM [Aviso]
                  WHERE  [Aviso].Status IN (3) 
                  and DATEDIFF(HOUR, (select top 1 Datum from Vermerke where Vermerke.AvisoID=aviso.AvisoID order by Vermerke.Datum desc),GETDATE())>4
                  and DATEDIFF(HOUR, (select top 1 Datum from Aenderungen where Aenderungen.AvisoID=aviso.AvisoID order by Aenderungen.Datum desc),GETDATE())>4
                  AND Datum > DATEADD( day,-2,GETDATE())
  
                ", "AVISO")

            If dt IsNot Nothing Then
                For Each r In dt.Rows
                    insertBenachrichtigung_AAS(r("AvisoId"), r("SendungsId"), VERAG_PROG_ALLGEMEIN.cAllgemein.getFirmaFromFiliale2(r("FilialenNr")), VERAG_PROG_ALLGEMEIN.cAvisoBenachrichtigungenCodes.AAE_Benachrichtigung, "REMINDER", "REMINDER: " & r("Hinweis_Vermerk"), 0)
                Next
            End If
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
            Return False
        End Try
        Return True
    End Function

    Function insertBenachrichtigung_AAS(AvisoId, SendungsId, firma, code, TXT_AAS_HEAD, TXT_AAS_BODY, prio)
        '
        'Benachrichtigung
        Try
            Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
            Dim sendToID As String = SQL.DLookup("tblSnd_VG_MA", "tblSendungen", "tblSnd_SendungID='" & SendungsId & "'", "AVISO", -1)
            Dim art = "B"

            'Wenn Benutzer vorschreiben nicht online, dann Benutzer der Sendung...
            If sendToID <= 0 OrElse (Not VERAG_PROG_ALLGEMEIN.cSession.IS_ONLINE(sendToID, True)) Then
                sendToID = SQL.DLookup("LetzterMitarbeiterId", "tblSendungen", "tblSnd_SendungID='" & SendungsId & "'", "AVISO", -1)
                art = "B"
            End If

            'Wenn Benutzer der Sendung nicht online, dann Benutzer des LKW ..
            If sendToID <= 0 OrElse (Not VERAG_PROG_ALLGEMEIN.cSession.IS_ONLINE(sendToID, True)) Then
                sendToID = SQL.DLookup("LetzterMitarbeiterId", "Aviso", "AvisoId='" & AvisoId & "'", "AVISO", -1)
                art = "B"
            End If

            'Wenn Benutzer des LKWs nicht online, Team...
            If sendToID <= 0 OrElse (Not VERAG_PROG_ALLGEMEIN.cSession.IS_ONLINE(sendToID, True)) Then
                sendToID = SQL.DLookup("tblSnd_TeamId", "tblSendungen", "tblSnd_SendungID='" & SendungsId & "'", "AVISO", -1)
                art = "T"
            End If

            'Wenn TEAM  nicht gefunden, Firma...
            If sendToID <= 0 Then
                If firma IsNot Nothing AndAlso firma <> "" Then
                    sendToID = firma
                    art = "F"
                End If
            End If

            'Wenn gefunden
            If (art = "F" AndAlso If(sendToID, "") <> "") OrElse sendToID >= 0 Then
                Dim statusAVISO = SQL.DLookup("Status", "Aviso", "AvisoID='" & AvisoId & "'", "AVISO")
                Dim GrenzstelleAVISO = SQL.DLookup("Grenzstelle", "Aviso", "AvisoID='" & AvisoId & "'", "AVISO")
                If GrenzstelleAVISO = "???" Then
                    Select Case statusAVISO
                        Case VERAG_PROG_ALLGEMEIN.cGlobal.Status_NichtEingetroffen, VERAG_PROG_ALLGEMEIN.cGlobal.Status_Freigegeben
                            'Nicht
                        Case Else

                            VERAG_PROG_ALLGEMEIN.cAvisoBenachrichtigungen.INSERT_BENACHRICHTIGUNG(AvisoId, SendungsId, code, art, sendToID, TXT_AAS_HEAD, prio, , TXT_AAS_BODY.Trim,,, firma)
                    End Select
                End If
            End If

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
            Return False
        End Try
        Return True
    End Function

    Private Sub Button19_Click(sender As Object, e As EventArgs) Handles Button19.Click
        doAASVermerke_24h()
    End Sub

    Private Sub Button20_Click(sender As Object, e As EventArgs) Handles Button20.Click
        doAASVermerke_Ankunft()
    End Sub

    Private Sub LinkLabel99_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel46.LinkClicked

        Try
            VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = cbxTestsystem.Checked

            Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
            Dim frm As New Form
            Dim dgv As New DataGridView()
            Dim dt As DataTable = SQL.loadDgvBySql("SELECT dbo.CLFBody.PKHistory,
                                                    dbo.CLFBody.ImportDate,
                                                    dbo.CLFBody.PKFileName,
                                                    dbo.CLFBody.PKLine,
                                                    dbo.CLFBody.RecordType,
                                                    dbo.CLFBody.fileNumber,
                                                    dbo.CLFBody.cardNumber,
                                                    dbo.CLFBody.validTo,	
                                                    dbo.CLFBody.OBUID,
                                                    dbo.CLFBody.vehicleLicensePlate,
                                                    dbo.CLFBody.nationality,
                                                    dbo.CLFBody.vehicleCategory,
                                                    dbo.CLFBody.emissionCategory,
                                                    dbo.CLFBody.status,
                                                    dbo.CLFBody.contractDate,
                                                    dbo.CLFBody.fileVersion,
                                                    dbo.CLFBody.engineCharacteristics,
                                                    dbo.CLFBody.CO2EmissionsClass,
                                                    dbo.CLFBody.contractType FROM dbo.CLF INNER JOIN dbo.CLFBody ON dbo.CLF.PKHistory = dbo.CLFBody.PKHistory AND dbo.CLF.PKFileName = dbo.CLFBody.PKFileName
                                                    ", "ASFINAG")

            dgv.DataSource = dt
            If dgv IsNot Nothing Then
                frm.Size = New Size(1400, 1000)
                dgv.Size = New Size(frm.Size.Width - 50, frm.Size.Height - 50)
                dgv.Dock = DockStyle.Fill
                dgv.Anchor = AnchorStyles.Left
                dgv.Anchor = AnchorStyles.Top
                dgv.ReadOnly = True
                frm.Controls.Add(dgv)
                frm.StartPosition = FormStartPosition.CenterScreen
                frm.ShowDialog()
            End If


        Catch ex As Exception

            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try

    End Sub

    Private Function importEZOLLWechselkurse(isTestsystem As Boolean) As Boolean

        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = isTestsystem

        Dim MyData As String = ""
        Dim SQL = New SQL
        Dim erg = True

        Dim firstDaycurrentMonth = DateTime.Now.AddMonths(0)
        firstDaycurrentMonth = New DateTime(firstDaycurrentMonth.Year, firstDaycurrentMonth.Month, 1)

        Dim lastDaycurrentMonth = DateTime.Now.AddMonths(1)
        lastDaycurrentMonth = New DateTime(lastDaycurrentMonth.Year, lastDaycurrentMonth.Month, 1).AddDays(-1)

        Dim kursart = "1" 'notirete Währung
        Dim startdatum_tag2 = firstDaycurrentMonth.Day
        Dim startdatum_monat2 = firstDaycurrentMonth.Month
        Dim startdatum_jahr2 = firstDaycurrentMonth.Year
        Dim enddatum_tag2 = lastDaycurrentMonth.Day
        Dim enddatum_monat2 = lastDaycurrentMonth.Month
        Dim enddatum_jahr2 = lastDaycurrentMonth.Year

        Try
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

            Using WC As New System.Net.WebClient()
                ' C0008_URL()
                WC.Encoding = ASCIIEncoding.UTF8
                Dim URL = "https://www.zoll.de/SiteGlobals/Functions/Kurse/KursExport.xml?view=xmlexportkursesearchresultZOLLWeb&kursart=" & kursart &
                    "&startdatum_tag2=" & startdatum_tag2 &
                    "&startdatum_monat2=" & startdatum_monat2 &
                    "&startdatum_jahr2=" & startdatum_jahr2 &
                    "&enddatum_tag2=" & enddatum_tag2 &
                    "&enddatum_monat2=" & enddatum_monat2 &
                    "&enddatum_jahr2=" & enddatum_jahr2 &
                    "&sort=asc&spalte=gueltigkeit"
                If URL = String.Empty Then Return False

                MyData = WC.DownloadString(URL)
                Dim doc As New XmlDocument()
                doc.LoadXml(MyData)
                If doc.HasChildNodes Then

                    If doc.GetElementsByTagName("kurs").Count > 0 Then
                        Dim endDatum, startDatum
                        Dim count As Integer = 1
                        For Each node As XmlElement In doc.GetElementsByTagName("kurs")
                            Dim wk As New cFremdwaehrungskurse()
                            If node.Attributes("id") IsNot Nothing Then wk.fw_id = node.Attributes("id").Value
                            If node.HasChildNodes Then
                                For Each element As XmlElement In node.ChildNodes
                                    If element.Name = "land" AndAlso element.InnerText <> "" Then wk.fw_land = element.InnerText
                                    If element.Name = "iso2" AndAlso element.InnerText <> "" Then wk.fw_iso2 = element.InnerText
                                    If element.Name = "iso3" AndAlso element.InnerText <> "" Then wk.fw_iso3 = element.InnerText
                                    If element.Name = "kurswert" AndAlso element.InnerText <> "" Then
                                        wk.fw_kurswert = element.InnerText
                                    End If
                                    If element.Name = "startdatum" AndAlso element.InnerText <> "" Then
                                        wk.fw_startdatum = element.InnerText
                                        startDatum = wk.fw_startdatum
                                    End If
                                    If element.Name = "enddatum" AndAlso element.InnerText <> "" Then
                                        wk.fw_enddatum = element.InnerText
                                        endDatum = wk.fw_enddatum
                                    End If
                                Next
                                count = count + 1
                                wk.SAVE()
                            End If
                        Next
                        Dim wk_euro As New cFremdwaehrungskurse()
                        wk_euro.fw_id = 0
                        wk_euro.fw_land = "Europa"
                        wk_euro.fw_kurswert = 1
                        wk_euro.fw_iso3 = "EUR"
                        wk_euro.fw_iso2 = "EU"
                        wk_euro.fw_startdatum = firstDaycurrentMonth.ToShortDateString()
                        wk_euro.fw_enddatum = lastDaycurrentMonth.ToShortDateString()
                        wk_euro.SAVE()

                        'Dim sqlCount = SQL.getValueTxtBySqlVarList("SELECT isnull(count(*),0) FROM tblZOLL_Wechselkurse WHERE [fw_startdatum]='" & startDatum & "' AND fw_enddatum='" & endDatum & "'", "FMZOLL")
                        'If count <> sqlCount Then
                        '    'MsgBox("Anzahl der Importierten Datensätze:" & sqlCount & vbNewLine & "Anzahl Datensätze in Datei: " & count)
                        '    'erg = False
                        'End If

                    End If
                End If

            End Using

            Return erg

        Catch ex As Exception
            MsgBox(ex.Message & ex.StackTrace)
        End Try
    End Function

    Private Sub LinkLabel47_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel47.LinkClicked
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = cbxTestsystem.Checked
        showPic(ASFINAG_LKW(False), PictureBox21)
    End Sub

    Private Sub LinkLabel46_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel99.LinkClicked, LinkLabel46.LinkClicked
        Me.Cursor = Cursors.WaitCursor
        Try
            DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0219", True) 'TESTSYSTEM
            Dim erg = DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0219", False) 'ECHTSYSTEM
            showPic(erg, PictureBox99)
        Catch ex As Exception : VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name) : End Try
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub LinkLabel48_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel48.LinkClicked
        Dim f = VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
        VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "UNISPED"
        importFileFromEZOLL(If(CheckBox2.Checked, Now.AddDays(-7), If(CheckBox3.Checked, Now.AddMonths(-1), Now)))
        VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = f
    End Sub

    Private Function checkTestsystemSettings() As Boolean
        Dim check As Boolean = False
        If cbxTestFTP.Checked And Not cbxTestsystem.Checked Then
            MsgBox("Testdaten von/auf TEST-FTP in/von Prod-Umgebung importieren/exportieren?" & vbNewLine & " Keine gute Idee!")
        Else
            check = True
        End If
        Return check

    End Function

    Private Sub tbcntr_SelectedIndexChanged(sender As Object, e As EventArgs) Handles tbcntr.SelectedIndexChanged
        If tbcntr.SelectedIndex = 3 Then

            checkTBLandTWLNr()

        End If

    End Sub

    Private Sub checkTBLandTWLNr()

        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = cbxTestsystem.Checked
        Dim dt = SQL.loadDgvBySql("SELECT filename, fileVersion from [dbo].[FileINfo]", "ASFINAG")

        If dt IsNot Nothing Then
            For Each r In dt.Rows
                If r("filename") = "TBL" Then txtTBLNr.Text = r("fileVersion")
                If r("filename") = "TWL" Then txtTWLNr.Text = r("fileVersion")

            Next


        End If

    End Sub

    Private Sub cbxTestsystem_CheckedChanged(sender As Object, e As EventArgs) Handles cbxTestsystem.CheckedChanged
        If tbcntr.SelectedIndex = 3 Then
            checkTBLandTWLNr()
        End If
    End Sub

    Private Sub LinkLabel49_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel49.LinkClicked
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = cbxTestsystem.Checked
        If Not checkTestsystemSettings() Then Exit Sub
        Me.Cursor = Cursors.WaitCursor
        Dim blt = New cAsfinag.Exportist
        blt.initExportPfade()
        showPic(blt.exportiereWhiteList, PictureBox18)
        showPic(blt.exportiereBlackList, PictureBox19)
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub LinkLabel50_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel50.LinkClicked
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        sendWOELFL_USTVAntraege("al@verag.ag")
    End Sub

    Function INSERT_Kundenumsaetze(insertLastYears As Integer) As Boolean
        Try

            Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL

            Dim sqltext = "INSERT INTO tblKundenumsatz ( KundenNr, Firma_ID, Jahr, steuerpflichtig, steuerfrei, Nettoumsatz, MwSt, Bruttoumsatz, Währung, Rechnungen, Gutschriften, Datum, Nummer )
                            SELECT RechnungsKundenNr AS KundenNr, 
                            Firma_ID, 
                            Year([Rechnungsdatum]) AS Jahr, 
                            Sum(SteuerpflichtigerBetragLokal) AS steuerpflichtig, 
                            Sum(SteuerfreierBetragLokal) AS steuerfrei,
                            Sum(SteuerfreierBetragLokal) AS Nettoumsatz, 
                            Sum(SteuerbetragLokal) AS MwSt, 
                            Sum(RechnungsbetragLokal) AS Bruttoumsatz, 
                            WährungLokal AS Währung, 
                            sum(Case when [BelegartenNr]=70 Then 1 else 0 End) as Rechnungen,
                            sum(Case when [BelegartenNr]=71 Then 1 else 0 End) as Gutschriften,
                            Max(Rechnungsdatum) AS Datum, 
                            Max(Rechnungsnummer) AS Nummer
                            FROM [VERAG].[dbo].[tblTrdinInvoice]
                            where Year([Rechnungsdatum]) > (year(getdate()) - " & insertLastYears & ")
                            GROUP BY RechnungsKundenNr, Firma_ID, Year([Rechnungsdatum]), WährungLokal
                            ORDER BY RechnungsKundenNr, Firma_ID, Year([Rechnungsdatum]) DESC , WährungLokal"

            Return SQL.doSQL(sqltext, "FMZOLL")
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)

            Return False

        End Try
    End Function

    Function DELETE_Kundenumsaetze(deleteLastYears As Integer) As Boolean
        Try

            Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
            Return SQL.doSQL("DELETE from tblKundenumsatz where Jahr > (year(getdate()) -" & deleteLastYears & ")", "FMZOLL")

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)

            Return False

        End Try
    End Function

    Private Sub Button22_Click(sender As Object, e As EventArgs) Handles Button22.Click
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        Dim lastyears = 2
        Dim ok = False
        If DELETE_Kundenumsaetze(lastyears) Then
            ok = INSERT_Kundenumsaetze(lastyears)
        End If
        showPic(ok, PictureBox22)
    End Sub

    Private Sub LinkLabel51_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel51.LinkClicked

        Dim CHAT As New cMessenger.cMessenger_Chat

        showPic(CHAT.setOldChatsInactiv(MyTextBox3.Text), PictureBox23)

    End Sub
End Class