Imports System.Net.Mail
Imports System.IO
Imports System.Data.SqlClient
Imports ClosedXML.Excel
Imports DocumentFormat
Imports System.Net
Imports DAKOSY_Worker

Module Mail
    Dim sPath As String = System.AppDomain.CurrentDomain.BaseDirectory
    Dim options As String = sPath & "OPTIONS.txt" '" & Now.ToString("ddMMyyyyHHmmss") & ".csv"
    Dim last_sent As String = sPath & "last_sent.txt" '" & Now.ToString("ddMMyyyyHHmmss") & ".csv"
    Dim betragOpTr = 1000
    Dim supportPWD = "$up0Rt2809!"
    Sub Main()
        Try
            VERAG_PROG_ALLGEMEIN.cAllgemein.ERR_OP_GLOBAL = VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL
            VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
            Dim PARAM = ""
            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

            System.Console.WriteLine("MailSender gestartet ...")
            ' If IO.File.Exists(options) Then

            'If Not IO.File.Exists(last_sent) Then
            'IO.File.Create(last_sent)
            '  End If

            ' Dim o As String = getOption()



            'Dim _erg = VERAG_PROG_ALLGEMEIN.cNCTS_Helper.getXLS_FremdBRG("ATILLA/VERAG", "TOBB - 15TR0004000020917 / 12TR0004000004665 / 17TR0004000032349 / 17TR0004000029518 ", " '12TR0004000004665','15TR0004000020917','17TR0004000032349','17TR0004000029518 '", CDate("01.08.2021 00:00:00"), CDate("12.08.2021 23:59:59"), True)
            'Dim _list As New List(Of String) : _list.Add(_erg)
            'VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("al@verag.ag", "TOBB " & "ATILLA/VERAG", "*Automatic generated e-mail*",,,, "", "al@verag.ag", _list)

            '_erg = VERAG_PROG_ALLGEMEIN.cNCTS_Helper.getXLS_FremdBRG("IMEX", "TOBB - 15TR0004000020917 / 12TR0004000004665 / 17TR0004000032349 / 17TR0004000029518 ", " '12TR0004000004665','15TR0004000020917','17TR0004000032349','17TR0004000029518 '", CDate("01.08.2021 00:00:00"), CDate("12.08.2021 23:59:59"), True)
            '_list.Clear() : _list.Add(_erg)
            'VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("al@verag.ag", "TOBB " & "IMEX", "*Automatic generated e-mail*",,,, "", "al@verag.ag", _list)

            'Dim _erg = VERAG_PROG_ALLGEMEIN.cNCTS_Helper.getXLS_FremdBRG("UNISPED", "TOBB - 15TR0004000020917 / 12TR0004000004665 / 17TR0004000032349 / 17TR0004000029518 ", " '12TR0004000004665','15TR0004000020917','17TR0004000032349','17TR0004000029518 '", CDate("01.08.2021 00:00:00"), CDate("12.08.2021 23:59:59"), True)
            'Dim _list As New List(Of String) : _list.Add(_erg)
            ''   VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("al@verag.ag", "TOBB " & "UNISPED", "*Automatic generated e-mail*",,,, "", "al@verag.ag", _list)
            'VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("eysan.sans@tobbund.com.tr;kerem.gozutok@tobbund.com.tr", "TOBB " & "UNISPED", "*Automatic generated e-mail*",,,, "Katharina.Haas@unisped.at;Sabine.Muehlboeck@unisped.at;Ernst.Stolzlechner@unisped.at", "al@verag.ag", _list)
            'Exit Sub





            'SendEmail_QS_Auswertung("01.01.2021", "31.01.2021")
            'SendEmail_QS_Auswertung("01.02.2021", "28.02.2021")
            'SendEmail_QS_Auswertung("01.03.2021", "31.03.2021")
            'SendEmail_QS_Auswertung("01.04.2021", "30.04.2021")
            'SendEmail_QS_Auswertung("01.05.2021", "31.05.2021")
            'SendEmail_QS_Auswertung("01.06.2021", "30.06.2021")
            'SendEmail_QS_Auswertung("01.07.2021", "31.07.2021")

            'Threading.Thread.Sleep(165000)



            'Exit Sub

            'PARAM = "THYSSENKRUPP_AUSWERTUNG"
            'PARAM = "JAHRESABRECHNUNG AG-ZS"
            'PARAM = "ZF"

            '------------------------------------------------------------------------------------
            '   PARAM = "NCTSLIST_TOBB"
            '   PARAM = "NCTSLIST_TOBB"
            '------------------------------------------------------------------------------------
            '   PARAM = "KD_OP_Kreditlimit"


            'Dim _erg = VERAG_PROG_ALLGEMEIN.cNCTS_Helper.getXLS_FremdBRG("VERAG/ATILLA", "TOBB - 15TR0004000020917 / 12TR0004000004665 / 17TR0004000032349 / 17TR0004000029518 ", " '12TR0004000004665','15TR0004000020917','17TR0004000032349','17TR0004000029518 '", CDate("07.06.2021 00:00:00"), CDate("07.06.2021 23:59:59"), True)
            'Dim _list As New List(Of String) : _list.Add(_erg)
            'VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("al@verag.ag", "TOBB " & "VERAG/ATILLA test", "*Automatic generated e-mail*",,,,  ,  , _list)
            'Exit Sub


            ' sendTOBB("VERAG/ATILLA", Now.AddDays(-6), Now.AddDays(-1))

            If PARAM = "" Then
                System.Console.WriteLine("OPTION nicht erkannt!")
                Exit Sub
            End If
            Dim cnt = 0
            '  MsgBox(DoesProcessExists("MailSender"))
            'While DoesProcessExists("MailSender") Or cnt > 20
            '    System.Console.WriteLine("MailSender wurde nicht beendet, warten ...")
            '    Threading.Thread.Sleep(1000)
            '    cnt += 1
            'End While
            If cnt >= 20 Then
                System.Console.WriteLine("MailSender konnte nicht gestartet werden, da eine Instanz noch läuft...")
            Else

                'Select Case firma
                '    Case "ATILLA"
                '        Msg.Subject = "Kunden TR - Offene Rechnungen - ATILLA"
                '        ' Msg.To.Add("mestan@verag.ag")

                '        Msg.To.Add("verimex@verimex360.com")
                '        Msg.Bcc.Add("al@verag.ag")
                '    Case "IMEX"
                '        Msg.Subject = "Kunden TR - Offene Rechnungen - IMEX"
                '        Msg.Bcc.Add("al@verag.ag")
                '        Msg.To.Add("mario.hoefer@imex-group.at")
                '        Msg.CC.Add("viktoria.leirich@imex-group.at")
                '        Msg.CC.Add("verimex@verimex360.com")
                '    Case "VERAG"
                '        Msg.Subject = "Kunden TR - Offene Rechnungen"
                '        Msg.To.Add("mestan@verag.ag")
                '        Msg.CC.Add("verimex@verimex360.com")
                '        Msg.Bcc.Add("al@verag.ag")

                '  End Select
                Select Case PARAM
                    Case "KD_OP5000"
                        System.Console.WriteLine("OPTION erkannt: KD_TR_OP5000 _ Erstellt eine Liste türkischer Kunden und versendet diese AL.")
                        If SendEmail_OP5000("VERAG", "", {"al@verag.ag"}, {}, {}, "VERAG - Offene Posten") Then
                            System.Console.WriteLine("Vorgang erfolgreich abgeschlossen ...")
                        End If
                    Case "KD_TR_OP5000"
                        System.Console.WriteLine("OPTION erkannt: KD_TR_OP5000 _ Erstellt eine Liste türkischer Kunden und versendet diese an Mestan und Bahadir.")
                        If SendEmail_OP5000("VERAG", "'TR'", {"mestan@verag.ag", "as@verag.ag"}, {"finans@verimextransit.com"}, {"al@verag.ag"}, "Kunden TR - Offene Rechnungen") Then
                            System.Console.WriteLine("Vorgang erfolgreich abgeschlossen ...")
                        End If
                    Case "KD_TR_OP5000_ATILLA"
                        System.Console.WriteLine("OPTION erkannt: KD_TR_OP5000_ATILLA _ Erstellt eine Liste türkischer Kunden von ATILLA.")
                        If SendEmail_OP5000("ATILLA", "'TR'", {"finans@verimextransit.com"}, {}, {"al@verag.ag"}, "Kunden TR - Offene Rechnungen - ATILLA") Then
                            System.Console.WriteLine("Vorgang erfolgreich abgeschlossen ...")
                        End If
                    Case "KD_TR_OP5000_IMEX"
                        System.Console.WriteLine("OPTION erkannt: KD_TR_OP5000_IMEX _ Erstellt eine Liste türkischer Kunden von IMEX.")
                        If SendEmail_OP5000("IMEX", "'TR'", {"mario.hoefer@imex-group.at"}, {"viktoria.leirich@imex-group.at", "finans@verimextransit.com"}, {"al@verag.ag"}, "Kunden TR - Offene Rechnungen - IMEX") Then
                            System.Console.WriteLine("Vorgang erfolgreich abgeschlossen ...")
                        End If
                    Case "KD_OP_Kreditlimit"
                        System.Console.WriteLine("OPTION erkannt: KD_OP_Kreditlimit _ Erstellt eine OP Liste von Kunden mit Kreditlimit oder VK-Kunden.")
                        If SendEmail_OPKreditlimit({"as@verag.ag"}, {}, {"al@verag.ag"}, "Kunden - Offene Rechnungen - ACHTUNG: nur mit erfasstem Kreditlimit") Then
                            System.Console.WriteLine("Vorgang erfolgreich abgeschlossen ...")
                        End If
                    Case "NCTSLIST_TOBB"
                        System.Console.WriteLine("OPTION erkannt: NCTSLIST_TOBB _ Erstellt eine Liste der Versandscheine mit TOBB Bürgschaft.")

                        sendTOBB("VERAG/ATILLA", Now.AddDays(-1), Now.AddDays(-1))
                        'sendTOBB("IMEX", Now.AddDays(-1), Now.AddDays(-1))
                        sendTOBB("UNISPED", Now.AddDays(-1), Now.AddDays(-1))

                    Case "BRG_AUSWERTUNG_STANDARD"
                        System.Console.WriteLine("OPTION erkannt: BRG_AUSWERTUNG_STANDARD _ Erstellt die Auswertung der Bürgschaften.")
                        System.Console.WriteLine("Einlesen der Bürgschaftsdaten aus ATLAS und E-ZOLL...")
                        einlesenBRG()
                        System.Console.WriteLine("Einlesen abgeschlossen...")
                        System.Console.WriteLine("Auswertung gestartet...")
                        If SendEmail_BRG_Auswertung(IIf(Now.DayOfWeek = 1, True, False)) Then
                            System.Console.WriteLine("Vorgang erfolgreich abgeschlossen ...")
                        End If
                    Case "BRG_AUSWERTUNG_DETAILS"
                        System.Console.WriteLine("OPTION erkannt: BRG_AUSWERTUNG_DETAILS _ Erstellt die Auswertung der Bürgschaften mit Details.")
                        System.Console.WriteLine("Einlesen der Bürgschaftsdaten aus ATLAS und E-ZOLL...")
                        einlesenBRG()
                        System.Console.WriteLine("Einlesen abgeschlossen...")
                        System.Console.WriteLine("Auswertung Details gestartet...")
                        If SendEmail_BRG_Auswertung(IIf(Now.DayOfWeek = 1, True, False), True) Then 'für Andreas Details
                            System.Console.WriteLine("Vorgang erfolgreich abgeschlossen ...")
                        End If
                    Case "WOELFL"
                        System.Console.WriteLine("OPTION erkannt: WOELFL ")
                        System.Console.WriteLine("Starte Wölfl-Mail...")
                        If SendEmail_WOELFL() Then
                            Try
                                Dim outFile As IO.StreamWriter = Nothing
                                outFile = My.Computer.FileSystem.OpenTextFileWriter(last_sent, False)
                                outFile.Write(Now.AddDays(-1).ToShortDateString)
                                outFile.Close()
                                System.Console.WriteLine("Vorgang erfolgreich abgeschlossen ...")
                            Catch ex As Exception
                                MsgBox(ex.Message)
                            End Try
                        End If
                    Case "THYSSENKRUPP_AUSWERTUNG"
                        Dim von = CDate("01." & Now.AddMonths(-1).Month & "." & Now.AddMonths(-1).Year)
                        Dim bis = CDate("01." & Now.Month & "." & Now.Year).AddDays(-1)

                        Dim EORI As String = "DE2841711"
                        System.Console.WriteLine("OPTION erkannt: THYSSENKRUPP_AUSWERTUNG _ Erstellt eine monaltiche Auswertung der DAKSOY-Abfertigungen für THYSSENKRUPP.")
                        System.Console.WriteLine("Auswertung Details gestartet...")
                        If SendEmail_THYSSENKRUPP_AUSWERTUNG("al@verag.ag", EORI, von, bis) Then 'für Andreas Details
                            System.Console.WriteLine("Vorgang erfolgreich abgeschlossen ...")
                        End If
                    Case "RED_BULL"
                        Dim von = CDate("01." & Now.AddMonths(-1).Month & "." & Now.AddMonths(-1).Year)
                        Dim bis = CDate("01." & Now.Month & "." & Now.Year).AddDays(-1)

                        Dim KdNr As String = "756313"
                        System.Console.WriteLine("OPTION erkannt: RED_BULL _ Erstellt eine monaltiche Auswertung der DAKSOY-Abfertigungen für RED_BULL/Alpha Tauri.")
                        System.Console.WriteLine("Auswertung Details gestartet...")
                        If SendEmail_RED_BULL("customs.documents.ata@redbull.com", KdNr, von, bis) Then 'für Andreas Details
                            System.Console.WriteLine("Vorgang erfolgreich abgeschlossen ...")
                        End If

                    Case "JAHRESABRECHNUNG AG-ZS"

                        Dim von = CDate("01.02." & Now.AddYears(-1).Year)
                        Dim bis = CDate("31.01." & Now.Year)
                        Dim Filialen = "'4803', '5003', '5303'"
                        Dim abfertigungsart = "38"
                        System.Console.WriteLine("OPTION erkannt: JAHRESAUSWERTUNG AG-ZS_ Erstellt eine jährliche Auswertung der Abfertigungen für die BH.")
                        System.Console.WriteLine("Auswertung Details gestartet...")

                        If SendEmail_Jahresauwsertung_AG_ZF("as.verag.ag", Filialen, abfertigungsart, von, bis) Then
                            System.Console.WriteLine("Vorgang erfolgreich abgeschlossen ...")
                        End If


                    Case "ZF"
                        Dim von = CDate("01." & Now.AddMonths(-1).Month & "." & Now.AddMonths(-1).Year)
                        Dim bis = CDate("01." & Now.Month & "." & Now.Year).AddDays(-1)

                        Dim KdNr As String = "714869"
                        System.Console.WriteLine("OPTION erkannt: ZF _ Erstellt eine monaltiche Auswertung der DAKSOY-Abfertigungen für ZF.")
                        System.Console.WriteLine("Auswertung Details gestartet...")
                        If SendEmail_ZF("robert.buchbauer@zf.com; christina.eggerl@zf.com; teresa.elster@zf.com", KdNr, von, bis) Then
                            System.Console.WriteLine("Vorgang erfolgreich abgeschlossen ...")
                        End If
                    Case "QS_AUFTEILUNG"
                        System.Console.WriteLine("OPTION erkannt: QS_AUFTEILUNG _ Erstellt die Auswertung der QS-AUFTEILUNG.")
                        System.Console.WriteLine("Auswertung gestartet...")

                        Dim von = CDate("01." & Now.AddMonths(-1).Month & "." & Now.AddMonths(-1).Year)
                        Dim bis = CDate("01." & Now.Month & "." & Now.Year).AddDays(-1)

                        If SendEmail_QS_Auswertung(von, bis) Then 'für Andreas Details
                            System.Console.WriteLine("Vorgang erfolgreich abgeschlossen ...")
                        End If
                    Case "CS_AUFTEILUNG"
                        System.Console.WriteLine("OPTION erkannt: CS_AUFTEILUNG _ Erstellt die Auswertung der FISKAL-AUFTEILUNG.")
                        System.Console.WriteLine("Auswertung gestartet...")
                        If SendEmail_CS_Auswertung() Then 'für Andreas Details
                            System.Console.WriteLine("Vorgang erfolgreich abgeschlossen ...")
                        End If
                    Case "MDM_Zollbuero_Verguetung"
                        System.Console.WriteLine("OPTION erkannt: MDM_Zollbuero_Verguetung _ Erstellt die Auswertung der durchgeführten MWST-Auszahlungen und MD-Kartenausgabe.")
                        System.Console.WriteLine("Auswertung gestartet...")
                        Dim Jahr = -1
                        If (parameter.Count - 1) >= 2 Then
                            Jahr = parameter(2)
                            System.Console.WriteLine("Parameter 'Jahr' erkannt: " & Jahr)
                        End If
                        If MDM_Zollbuero_Verguetung(Jahr) Then 'für Andreas Details
                            System.Console.WriteLine("Vorgang erfolgreich abgeschlossen ...")
                        End If
                    Case "Kassenbuch_Zufall"
                        System.Console.WriteLine("OPTION erkannt: Kassenbuch_Zufall - Zufallsziehung zur Kassenkontrolle.")
                        System.Console.WriteLine("Vorgang gestartet...")
                        If SendEmail_Kassenbuch_Zufall() Then 'für Andreas Details
                            System.Console.WriteLine("Vorgang erfolgreich abgeschlossen ...")
                        End If
                    Case "DEPOT_Kunden_Auswertung"
                        System.Console.WriteLine("OPTION erkannt: DEPOT_Kunden_Auswertung")
                        System.Console.WriteLine("Vorgang gestartet...")
                        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
                        Dim dt As DataTable = SQL.loadDgvBySql("SELECT  KundenNrZentrale FROM  [tblKundenErweitert] INNER JOIN Kunden on kundennr= kde_KundenNr where Depot_Kunde = 1", "FMZOLL")
                        If dt IsNot Nothing Then
                            For Each r In dt.Rows
                                DEPOT_Kunden_Auswertung(r("KundenNrZentrale"))
                            Next
                        End If
                        System.Console.WriteLine("Vorgang erfolgreich abgeschlossen ...")

                    Case Else
                        System.Console.WriteLine("OPTION nicht erkannt!")



                End Select

            End If
            '  Else
            '  System.Console.WriteLine("OPTIONS-Datei nicht gefunden!  " & options)
            '  End If

            Threading.Thread.Sleep(1000)
            '  System.Console.WriteLine("Programm beendet in 5")
            ' Threading.Thread.Sleep(1000)
            ' System.Console.WriteLine("Programm beendet in 4")
            '  Threading.Thread.Sleep(1000)
            System.Console.WriteLine("Programm beendet in 3")
            Threading.Thread.Sleep(1000)
            System.Console.WriteLine("Programm beendet in 2")
            Threading.Thread.Sleep(1000)
            System.Console.WriteLine("Programm beendet in 1")
            Threading.Thread.Sleep(1000)

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

    Sub sendTOBB(FirmaTmp, datVon, datBis)
        Dim _erg = VERAG_PROG_ALLGEMEIN.cNCTS_Helper.getXLS_FremdBRG(FirmaTmp, "TOBB - " & VERAG_PROG_ALLGEMEIN.cNCTS_GUARANTEES.getSlashList(VERAG_PROG_ALLGEMEIN.cNCTS_GUARANTEES.TOBB), VERAG_PROG_ALLGEMEIN.cNCTS_GUARANTEES.getSQLList(VERAG_PROG_ALLGEMEIN.cNCTS_GUARANTEES.TOBB), datVon, datBis, True)
        Dim _list As New List(Of String)
        Dim addbetreff = ""
        Select Case _erg
            Case "NO_RESULT"
                System.Console.WriteLine("Keine Einträge gefunden.")
                addbetreff = " - NO DATA"
            Case ""
            Case Else
                _list.Add(_erg)
        End Select

        Dim bool_sent = False
        Select Case FirmaTmp
           ' Case "VERAG/ATILLA" : bool_sent = VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("al@verag.ag", "TOBB " & FirmaTmp & addbetreff, "*Automatic generated e-mail*",,,, "", "al@verag.ag", _list)
            Case "VERAG/ATILLA" : bool_sent = VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("eysan.sans@tobbund.com.tr;kerem.gozutok@tobbund.com.tr;amine.akan@tobbund.com.tr", "TOBB " & FirmaTmp & addbetreff, "*Automatic generated e-mail*",,,, "atilla@verag.ag", "al@verag.ag", _list)
            Case "IMEX" : bool_sent = VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("eysan.sans@tobbund.com.tr;kerem.gozutok@tobbund.com.tr;amine.akan@tobbund.com.tr", "TOBB " & FirmaTmp & addbetreff, "*Automatic generated e-mail*",,,, "info@imex-group.at;Mario.Hoefer@imex-group.at", "al@verag.ag", _list)
            Case "UNISPED" : bool_sent = VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("eysan.sans@tobbund.com.tr;kerem.gozutok@tobbund.com.tr;amine.akan@tobbund.com.tr", "TOBB " & FirmaTmp & addbetreff, "*Automatic generated e-mail*",,,, "Katharina.Haas@unisped.at;Sabine.Muehlboeck@unisped.at;Ernst.Stolzlechner@unisped.at", "al@verag.ag", _list)
        End Select

        If bool_sent Then
            System.Console.WriteLine("Vorgang erfolgreich abgeschlossen (" & FirmaTmp & ") ...")
        Else
            System.Console.WriteLine("Fehler beim Senden der Mail (" & FirmaTmp & ") ...")
        End If
    End Sub

    Function getOption() As String
        Try
            Dim instr = New StreamReader(options)
            Dim d = instr.ReadLine
            instr.Close()
            Return d
        Catch ex As Exception
            Return ""
        End Try
    End Function
    Private Function DoesProcessExists(ByVal PName As String) As Boolean
        Dim cnt = 0
        For Each p As Process In System.Diagnostics.Process.GetProcessesByName(PName)
            'MsgBox("found" & p.StartInfo.UserName)
            'If p.StartInfo.UserName = Environment.UserName Then
            cnt += 1
            'End If
        Next
        If cnt > 1 Then Return True
        Return False
    End Function


    Private Function SendEmail_Kassenbuch_Zufall() As Boolean
        Dim Msg As New MailMessage
        Dim myCredentials As New System.Net.NetworkCredential
        myCredentials.UserName = "support@verag.ag"
        myCredentials.Password = supportPWD


        ' myCredentials.UserName = "testmail@verag.ag"
        '  myCredentials.Password = "testmail"
        Msg.IsBodyHtml = False
        Dim mySmtpsvr As New SmtpClient()
        '  mySmtpsvr.Host = "192.168.0.107" 'bei web.de
        ' mySmtpsvr.Port = 25 '587 '25
        mySmtpsvr.Host = "owa.verag.ag"
        mySmtpsvr.Port = 587 '25 '587 '25
        mySmtpsvr.UseDefaultCredentials = False
        mySmtpsvr.Credentials = myCredentials
        System.Console.WriteLine("E-Mail Daten initialisiert...")
        Try
            Dim datum As String = Now.AddDays(-1).ToShortDateString

            System.Console.WriteLine("Sende E-Mail...")
            Msg.From = New MailAddress("support@verag.ag")

            Msg.IsBodyHtml = True
            Msg.To.Add("al@verag.ag")
            '   Msg.CC.Add("al@verag.ag")

            Msg.Subject = "Kassenprüfung - Zufallsziehung"

            Msg.Body &= "<span style=""font-family:Arial"">"
            Msg.Body = "Folgende Kasse ist zu kontrollieren und ein Kassensturz durchzuführen:"
            Msg.Body &= "<br><br>"
            Msg.Body &= "Per Zufallsgenerator gezogene Kasse: <b>" & (New VERAG_PROG_ALLGEMEIN.SQL).getValueTxtBySql("Select TOP 1 [Name] + ',  KB-Nr.: ' + cast([KassenbuchNr] as varchar) FROM [VERAG].[dbo].[Personal]  where Mandant='VERA'  AND  [Status]='A' AND BLC='R' AND SBSichtbar=1 and KassenbuchNr is not null   ORDER BY NEWID()", "FMZOLL") & "</b>"
            Msg.Body &= "<br><br><br>"
            Msg.Body &= "Automatisch generiertes E-Mail."
            Msg.Body &= "</span>"

            mySmtpsvr.Send(Msg)

            System.Console.WriteLine("E-Mail gesendet.")
            System.Console.WriteLine("Erfolgreich!")
            Return True

        Catch ex As Exception
            Try
                mySmtpsvr.Port = 25
                mySmtpsvr.Send(Msg)

            Catch ex2 As Exception
                Try
                    mySmtpsvr.Host = "192.168.0.107"
                    mySmtpsvr.Port = 25
                    mySmtpsvr.Send(Msg)

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


        End Try
        Return False
    End Function





    Private Function DEPOT_Kunden_Auswertung(KundenNr) As Boolean
        '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = True
        '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        Dim Msg As New MailMessage
        Dim myCredentials As New System.Net.NetworkCredential
        myCredentials.UserName = "support@verag.ag"
        myCredentials.Password = supportPWD


        ' myCredentials.UserName = "testmail@verag.ag"
        '  myCredentials.Password = "testmail"
        Msg.IsBodyHtml = True
        Dim mySmtpsvr As New SmtpClient()
        '  mySmtpsvr.Host = "192.168.0.107" 'bei web.de
        ' mySmtpsvr.Port = 25 '587 '25
        mySmtpsvr.Host = "owa.verag.ag"
        mySmtpsvr.Port = 587 '25 '587 '25
        mySmtpsvr.UseDefaultCredentials = False
        mySmtpsvr.Credentials = myCredentials
        System.Console.WriteLine("E-Mail Daten initialisiert...")
        Try
            System.Console.WriteLine("Erstelle EXCEL...")
            Dim excel As String = genEXCEL_DEPOT(KundenNr)
            MsgBox(excel)
            System.Console.WriteLine("EXCEL erstellt...")
            If excel <> "" And Not excel.StartsWith("ERROR: ") Then

                System.Console.WriteLine("Sende E-Mail...")
                Msg.From = New MailAddress("al@verag.ag")

                Msg.To.Add("al@verag.ag") 'Detailierter Bericht nur an al@verag.ag


                Msg.Subject = "Auswertung DEPOT"
                Msg.Body = "<p style='12pt Arial'>"
                Msg.Body &= "Anbei befinden sich die Auswertung Ihres Depot-Kontos<br><br>Erstellt am: " & Now.ToShortDateString & ", um " & Now.ToShortTimeString
                Msg.Body &= "<br><br><br>Automatisch generiertes E-Mail."
                Msg.Body &= "</p>"

                Dim attachment1 As Attachment = New Attachment(File.OpenRead(excel), "Auswertung.xlsx")
                Msg.Attachments.Add(attachment1)



                mySmtpsvr.Send(Msg)

                System.Console.WriteLine("E-Mail gesendet.")
                System.Console.WriteLine("Erfolgreich!")
                Return True
            Else
                System.Console.WriteLine(excel)
            End If
        Catch ex As Exception
            Try
                mySmtpsvr.Port = 25
                mySmtpsvr.Send(Msg)

            Catch ex2 As Exception
                Try
                    mySmtpsvr.Host = "192.168.0.107"
                    mySmtpsvr.Port = 25
                    mySmtpsvr.Send(Msg)

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


        End Try
        Return False
    End Function

    Private Function SendEmail_THYSSENKRUPP_AUSWERTUNG(Mailto As String, EORI As String, von As Date, bis As Date) As Boolean
        Try
            Dim excel As String = genEXCEL_THYSSENKRUPP(EORI, von, bis)
            System.Console.WriteLine("EXCEL erstellt...")
            If excel <> "" And Not excel.StartsWith("ERROR: ") Then

                System.Console.WriteLine("Sende E-Mail...")

                Dim Subject = "Auswertungen Zollanmeldungen EORI " & EORI
                Dim Body = "Anbei befinden sich die Auswertungen Zollanmeldungen von " & von.ToShortDateString & " bis " & bis.ToShortDateString & "." &
                     "<br><br>Erstellt am: " & Now.ToShortDateString & ", um " & Now.ToShortTimeString &
                     "<br><br><br>Automatisch generiertes E-Mail. Bitte Antworten Sie nicht an dieses E-Mail." &
                     "<br><br>VERAG SPEDITION AG"


                Dim anhenge As New List(Of String)
                anhenge.Add(excel)
                If VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(Mailto, Subject, Body,,, False,, "al@verag.ag", anhenge) Then
                    System.Console.WriteLine("E-Mail gesendet.")
                    System.Console.WriteLine("Erfolgreich!")
                Else
                    System.Console.WriteLine("ERROR BEIM SENDEN DER MAIL!")

                End If

                Return True
            Else
                System.Console.WriteLine(excel)
            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)
            System.Console.WriteLine(ex.Message & ex.StackTrace)
            Return False
        End Try
    End Function

    Private Function SendEmail_RED_BULL(Mailto As String, KdNr As String, von As Date, bis As Date) As Boolean
        Try
            Dim excel As String = genEXCEL_RED_BULL(KdNr, von, bis)
            System.Console.WriteLine("EXCEL erstellt...")
            If excel <> "" And Not excel.StartsWith("ERROR: ") Then

                System.Console.WriteLine("Sende E-Mail...")

                Dim Subject = "Auswertungen Zollanmeldungen Aplha Tauri "
                Dim Body = "Anbei befinden sich die Auswertungen Zollanmeldungen von " & von.ToShortDateString & " bis " & bis.ToShortDateString & "." &
                     "<br><br>Erstellt am: " & Now.ToShortDateString & ", um " & Now.ToShortTimeString &
                     "<br><br><br>Automatisch generiertes E-Mail. Bitte Antworten Sie nicht an dieses E-Mail." &
                     "<br><br>VERAG SPEDITION AG"


                Dim anhenge As New List(Of String)
                anhenge.Add(excel)
                If VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(Mailto, Subject, Body,,, False,, "d.breimaier@verag.ag;schulung@verag.ag", anhenge) Then
                    System.Console.WriteLine("E-Mail gesendet.")
                    System.Console.WriteLine("Erfolgreich!")
                Else
                    System.Console.WriteLine("ERROR BEIM SENDEN DER MAIL!")

                End If

                Return True
            Else
                System.Console.WriteLine(excel)
            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)
            System.Console.WriteLine(ex.Message & ex.StackTrace)
            Return False
        End Try
    End Function

    Private Function SendEmail_Jahresauwsertung_AG_ZF(Mailto As String, abfertigungsart As Integer, Filialnr As String, von As Date, bis As Date) As Boolean
        Try
            Dim excel As String = genEXCEL_ANNA(Filialnr, abfertigungsart, von, bis)
            System.Console.WriteLine("EXCEL erstellt...")
            If excel <> "" And Not excel.StartsWith("ERROR: ") Then

                System.Console.WriteLine("Sende E-Mail...")

                Dim Subject = "Auswertungen Jahresauswertung A-ZF "
                Dim Body = "Anbei befinden sich die Auswertungen Zollanmeldungen von " & von.ToShortDateString & " bis " & bis.ToShortDateString & "." &
                     "<br><br>Erstellt am: " & Now.ToShortDateString & ", um " & Now.ToShortTimeString &
                     "<br><br><br>Automatisch generiertes E-Mail. Bitte Antworten Sie nicht an dieses E-Mail." &
                     "<br><br>VERAG SPEDITION AG"


                Dim anhenge As New List(Of String)
                anhenge.Add(excel)
                If VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(Mailto, Subject, Body,,, False,, "d.breimaier@verag.ag", anhenge) Then
                    System.Console.WriteLine("E-Mail gesendet.")
                    System.Console.WriteLine("Erfolgreich!")
                Else
                    System.Console.WriteLine("ERROR BEIM SENDEN DER MAIL!")

                End If

                Return True
            Else
                System.Console.WriteLine(excel)
            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)
            System.Console.WriteLine(ex.Message & ex.StackTrace)
            Return False
        End Try
    End Function

    Private Function SendEmail_ZF(Mailto As String, KdNr As String, von As Date, bis As Date) As Boolean
        Try
            Dim excel As String = genEXCEL_ZF(KdNr, von, bis)
            System.Console.WriteLine("EXCEL erstellt...")
            If excel <> "" And Not excel.StartsWith("ERROR: ") Then

                System.Console.WriteLine("Sende E-Mail...")

                Dim Subject = "Auswertungen Zollanmeldungen ZF Friedrichshafen AG "
                Dim Body = "Anbei befinden sich die Auswertungen Zollanmeldungen von " & von.ToShortDateString & " bis " & bis.ToShortDateString & "." &
                     "<br><br>Erstellt am: " & Now.ToShortDateString & ", um " & Now.ToShortTimeString &
                     "<br><br><br>Automatisch generiertes E-Mail. Bitte Antworten Sie nicht an dieses E-Mail." &
                     "<br><br>VERAG SPEDITION AG"


                Dim anhenge As New List(Of String)
                anhenge.Add(excel)
                If VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(Mailto, Subject, Body,,, False,, "d.breimaier@verag.ag;ra@verag.ag", anhenge) Then
                    System.Console.WriteLine("E-Mail gesendet.")
                    System.Console.WriteLine("Erfolgreich!")
                Else
                    System.Console.WriteLine("ERROR BEIM SENDEN DER MAIL!")

                End If

                Return True
            Else
                System.Console.WriteLine(excel)
            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)
            System.Console.WriteLine(ex.Message & ex.StackTrace)
            Return False
        End Try
    End Function


    Private Function SendEmail_BRG_Auswertung(Optional wochenAuswertung As Boolean = False, Optional details As Boolean = False) As Boolean
        Dim Msg As New MailMessage
        Dim myCredentials As New System.Net.NetworkCredential
        myCredentials.UserName = "al@verag.ag"
        myCredentials.Password = "verag#2"

        ' myCredentials.UserName = "testmail@verag.ag"
        '  myCredentials.Password = "testmail"
        Msg.IsBodyHtml = False
        Dim mySmtpsvr As New SmtpClient()
        '  mySmtpsvr.Host = "192.168.0.107" 'bei web.de
        ' mySmtpsvr.Port = 25 '587 '25
        mySmtpsvr.Host = "owa.verag.ag"
        mySmtpsvr.Port = 587 '25 '587 '25
        mySmtpsvr.UseDefaultCredentials = False
        mySmtpsvr.Credentials = myCredentials
        System.Console.WriteLine("E-Mail Daten initialisiert...")
        Try
            Dim datum As String = Now.AddDays(-1).ToShortDateString
            System.Console.WriteLine("Erstelle EXCEL...")
            Dim excel As String = genEXCEL_BRG(details)
            Dim excelKW As String = IIf(wochenAuswertung, genEXCEL_BRGKW(), "")
            System.Console.WriteLine("EXCEL erstellt...")
            If excel <> "" And Not excel.StartsWith("ERROR: ") And Not excelKW.StartsWith("ERROR: ") Then

                System.Console.WriteLine("Sende E-Mail...")
                Msg.From = New MailAddress("al@verag.ag")

                If details Then
                    Msg.To.Add("al@verag.ag") 'Detailierter Bericht nur an al@verag.ag
                Else
                    Msg.To.Add("jl@verag.ag") 'Standardberichte an jl@verag.ag; al@verag.ag
                    Msg.CC.Add("al@verag.ag")
                End If

                Msg.Subject = IIf(wochenAuswertung, "Auswertungen der Bürgschaften", "Auswertung der Bürgschaften") & IIf(details, " - Details", "")
                Msg.Body = IIf(wochenAuswertung, "Anbei befinden sich die Auswertungen der Bürgschaften", "Anbei befindet sich die Auswertung der Bürgschaften") &
                    "." & vbNewLine & vbNewLine & "Erstellt am: " & Now.ToShortDateString & ", um " & Now.ToShortTimeString &
                    vbNewLine & vbNewLine & vbNewLine & "Automatisch generiertes E-Mail."

                Dim attachment1 As Attachment = New Attachment(File.OpenRead(excel), "Auswertung.xlsx")
                Msg.Attachments.Add(attachment1)

                If wochenAuswertung Then
                    Dim attachment2 As Attachment = New Attachment(File.OpenRead(excelKW), "Auswertung_Atilla_Durmaz.xlsx")
                    Msg.Attachments.Add(attachment2)
                End If

                mySmtpsvr.Send(Msg)

                System.Console.WriteLine("E-Mail gesendet.")
                System.Console.WriteLine("Erfolgreich!")
                Return True
            Else
                System.Console.WriteLine(excel)
                System.Console.WriteLine(excelKW)
            End If
        Catch ex As Exception
            Try
                mySmtpsvr.Port = 25
                mySmtpsvr.Send(Msg)

            Catch ex2 As Exception
                Try
                    mySmtpsvr.Host = "192.168.0.107"
                    mySmtpsvr.Port = 25
                    mySmtpsvr.Send(Msg)

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


        End Try
        Return False
    End Function

    Private Function SendEmail_QS_Auswertung(von, bis) As Boolean
        Dim Msg As New MailMessage
        Dim myCredentials As New System.Net.NetworkCredential
        myCredentials.UserName = "al@verag.ag"
        myCredentials.Password = "verag#2"

        ' myCredentials.UserName = "testmail@verag.ag"
        '  myCredentials.Password = "testmail"
        Msg.IsBodyHtml = False
        Dim mySmtpsvr As New SmtpClient()
        '  mySmtpsvr.Host = "192.168.0.107" 'bei web.de
        ' mySmtpsvr.Port = 25 '587 '25
        mySmtpsvr.Host = "owa.verag.ag"
        mySmtpsvr.Port = 587 '25 '587 '25
        mySmtpsvr.UseDefaultCredentials = False
        mySmtpsvr.Credentials = myCredentials
        System.Console.WriteLine("E-Mail Daten initialisiert...")
        Try
            Dim datum As String = Now.AddDays(-1).ToShortDateString
            System.Console.WriteLine("Erstelle EXCEL...")
            Dim excel As String = genEXCEL_QS(von, bis)
            System.Console.WriteLine("EXCEL erstellt..." & excel)
            If excel <> "" And Not excel.StartsWith("ERROR: ") Then

                System.Console.WriteLine("Sende E-Mail...")
                Msg.From = New MailAddress("al@verag.ag")


                Msg.To.Add("al@verag.ag")
                Msg.Bcc.Add("al@verag.ag")
                ' Msg.Bcc.Add("ga@verag.ag")

                Msg.Subject = "Auswertung QS-Aufteilung"
                Msg.Body = "Anbei befindet sich die Auswertung der QS-Aufteilung" &
                "." & vbNewLine & vbNewLine & "Erstellt am: " & Now.ToShortDateString & ", um " & Now.ToShortTimeString &
                vbNewLine & vbNewLine & vbNewLine & "Automatisch generiertes E-Mail."

                Dim attachment1 As Attachment = New Attachment(File.OpenRead(excel), "Auswertung.xlsx")
                Msg.Attachments.Add(attachment1)

                mySmtpsvr.Send(Msg)

                System.Console.WriteLine("E-Mail gesendet.")
                System.Console.WriteLine("Erfolgreich!")
                Return True
            Else
                System.Console.WriteLine(excel)
            End If
        Catch ex As Exception
            Try
                mySmtpsvr.Port = 25
                mySmtpsvr.Send(Msg)

            Catch ex2 As Exception
                Try
                    mySmtpsvr.Host = "192.168.0.107"
                    mySmtpsvr.Port = 25
                    mySmtpsvr.Send(Msg)

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


        End Try
        Return False
    End Function

    Private Function SendEmail_CS_Auswertung() As Boolean
        Dim Msg As New MailMessage
        Dim myCredentials As New System.Net.NetworkCredential
        myCredentials.UserName = "al@verag.ag"
        myCredentials.Password = "verag#2"

        Msg.IsBodyHtml = False
        Dim mySmtpsvr As New SmtpClient()
        mySmtpsvr.Host = "owa.verag.ag"
        mySmtpsvr.Port = 587 '25 '587 '25
        mySmtpsvr.UseDefaultCredentials = False
        mySmtpsvr.Credentials = myCredentials
        System.Console.WriteLine("E-Mail Daten initialisiert...")
        Try
            Dim datum As String = Now.AddDays(-1).ToShortDateString
            System.Console.WriteLine("Erstelle EXCEL...")
            Dim excel As String = genEXCEL_CS()
            System.Console.WriteLine("EXCEL erstellt...")
            If excel <> "" And Not excel.StartsWith("ERROR: ") Then

                System.Console.WriteLine("Sende E-Mail...")
                Msg.From = New MailAddress("al@verag.ag")


                Msg.To.Add("jl@verag.ag")
                Msg.Bcc.Add("al@verag.ag")
                Msg.Bcc.Add("cw@verag.ag")


                Msg.Subject = "Auswertung FISKAL-Aufteilung (Customs Service GmbH)"
                Msg.Body = "Anbei befindet sich die Auswertung der FISKAL-Aufteilung (Customs Service GmbH)" &
                "." & vbNewLine & vbNewLine & "Erstellt am: " & Now.ToShortDateString & ", um " & Now.ToShortTimeString &
                vbNewLine & vbNewLine & vbNewLine & "Automatisch generiertes E-Mail."

                Dim attachment1 As Attachment = New Attachment(File.OpenRead(excel), "Auswertung.xlsx")
                Msg.Attachments.Add(attachment1)

                mySmtpsvr.Send(Msg)

                System.Console.WriteLine("E-Mail gesendet.")
                System.Console.WriteLine("Erfolgreich!")
                Return True
            Else
                System.Console.WriteLine(excel)
            End If
        Catch ex As Exception
            Try
                mySmtpsvr.Port = 25
                mySmtpsvr.Send(Msg)

            Catch ex2 As Exception
                Try
                    mySmtpsvr.Host = "192.168.0.107"
                    mySmtpsvr.Port = 25
                    mySmtpsvr.Send(Msg)

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


        End Try
        Return False
    End Function

    Private Function MDM_Zollbuero_Verguetung(Jahr) As Boolean
        Dim Msg As New MailMessage
        Dim myCredentials As New System.Net.NetworkCredential
        myCredentials.UserName = "al@verag.ag"
        myCredentials.Password = "verag#2"

        Msg.IsBodyHtml = False
        Dim mySmtpsvr As New SmtpClient()
        mySmtpsvr.Host = "owa.verag.ag"
        mySmtpsvr.Port = 587 '25 '587 '25
        mySmtpsvr.UseDefaultCredentials = False
        mySmtpsvr.Credentials = myCredentials
        System.Console.WriteLine("E-Mail Daten initialisiert...")
        Try
            Dim datum As String = Now.AddDays(-1).ToShortDateString
            System.Console.WriteLine("Erstelle EXCEL...")
            Dim excel As String = genEXCEL_MDM_ZOLL(Jahr)
            System.Console.WriteLine("EXCEL erstellt...")
            If excel <> "" And Not excel.StartsWith("ERROR: ") Then

                System.Console.WriteLine("Sende E-Mail...")
                Msg.From = New MailAddress("al@verag.ag")


                ' Msg.To.Add("Viktoria.Leirich@imex-group.at")
                Msg.To.Add("as@verag.ag")
                Msg.To.Add("sales@verag.ag")
                '  Msg.To.Add("jl@verag.ag")
                '  Msg.Bcc.Add("al@verag.ag")
                Msg.CC.Add("jl@verag.ag")
                Msg.CC.Add("al@verag.ag")


                Msg.Subject = "Auswertung MDM-ZOLL Vergütung"
                Msg.Body = "Anbei befindet sich die Auswertung der MDM-ZOLL Vergütung" &
                "." & vbNewLine & vbNewLine & "Erstellt am: " & Now.ToShortDateString & ", um " & Now.ToShortTimeString &
                vbNewLine & vbNewLine & vbNewLine & "Automatisch generiertes E-Mail."

                Dim attachment1 As Attachment = New Attachment(File.OpenRead(excel), "Auswertung.xlsx")
                Msg.Attachments.Add(attachment1)

                mySmtpsvr.Send(Msg)

                System.Console.WriteLine("E-Mail gesendet.")
                System.Console.WriteLine("Erfolgreich!")
                Return True
            Else
                System.Console.WriteLine(excel)
            End If
        Catch ex As Exception
            Try
                mySmtpsvr.Port = 25
                mySmtpsvr.Send(Msg)

            Catch ex2 As Exception
                Try
                    mySmtpsvr.Host = "192.168.0.107"
                    mySmtpsvr.Port = 25
                    mySmtpsvr.Send(Msg)

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


        End Try
        Return False
    End Function


    Private Function SendEmail_OP5000(firma As String, LandEinschr As String, Mail_to() As String, Mail_cc() As String, Mail_bcc() As String, Mail_Subject As String) As Boolean
        '  send()
        '   Exit Function
        Dim Msg As New MailMessage
        Dim myCredentials As New System.Net.NetworkCredential
        'myCredentials.UserName = "al@verag.ag"
        'myCredentials.Password = "Luxandreas#2"

        '   myCredentials.UserName = "al@verag.ag"
        '    myCredentials.Password = "verag#2"

        'myCredentials.UserName = "al@verag.ag"
        'myCredentials.Password = "verag#2"
        myCredentials.UserName = "support@verag.ag"
        myCredentials.Password = supportPWD


        ' myCredentials.UserName = "testmail@verag.ag"
        '  myCredentials.Password = "testmail"
        Msg.IsBodyHtml = False
        Dim mySmtpsvr As New SmtpClient()
        '  mySmtpsvr.Host = "192.168.0.107" 'bei web.de
        ' mySmtpsvr.Port = 25 '587 '25
        mySmtpsvr.Host = "owa.verag.ag"
        mySmtpsvr.Port = 587 '25 '587 '25

        mySmtpsvr.UseDefaultCredentials = False
        mySmtpsvr.Credentials = myCredentials
        System.Console.WriteLine("E-Mail Daten initialisiert...")
        Try
            Dim datum As String = Now.AddDays(-1).ToShortDateString
            System.Console.WriteLine("Erstelle EXCEL...")
            Dim excel As String = ""
            Select Case firma
                Case "ATILLA"
                    excel = genEXCEL_TR_ATILLA(LandEinschr)
                Case "IMEX"
                    excel = genEXCEL_TR_IMEX(LandEinschr)
                Case "VERAG"
                    excel = genEXCEL_TR(LandEinschr)
            End Select



            System.Console.WriteLine("EXCEL erstellt...")
            If excel <> "" And Not excel.StartsWith("ERROR: ") Then

                System.Console.WriteLine("Sende E-Mail...")
                Msg.From = New MailAddress("support@verag.ag")


                For Each m In Mail_to : Msg.To.Add(m) : Next
                For Each m In Mail_cc : Msg.CC.Add(m) : Next
                For Each m In Mail_bcc : Msg.Bcc.Add(m) : Next
                Msg.Subject = Mail_Subject




                '  Msg.To.Add("al@verag.ag")
                Msg.Body = "Anbei befindet sich die Liste der türkischen Kunden mit einem offenen Rechnungsbetrag von über 1.000,- EUR." & vbNewLine & vbNewLine & "Stand: " & Now.ToShortDateString & " " & Now.ToShortTimeString & vbNewLine & vbNewLine & vbNewLine & "Automatisch generiertes E-Mail."

                Dim attachment As Attachment = New Attachment(File.OpenRead(excel), "Kundenliste.xlsx")

                Msg.Attachments.Add(attachment)

                Try
                    mySmtpsvr.Send(Msg)
                Catch ex As Exception
                    Try
                        mySmtpsvr.Port = 25
                        mySmtpsvr.Send(Msg)
                    Catch ex2 As Exception
                        Try
                            mySmtpsvr.Host = "192.168.0.107"
                            mySmtpsvr.Port = 25
                            mySmtpsvr.Send(Msg)

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



                System.Console.WriteLine("E-Mail gesendet.")
                '       MsgBox("E-Mail gesendet.", MsgBoxStyle.Information, Title:="Information")
                System.Console.WriteLine("Erfolgreich!")
                Return True
            Else
                System.Console.WriteLine(excel)
            End If

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

    Private Function SendEmail_OPKreditlimit(Mail_to() As String, Mail_cc() As String, Mail_bcc() As String, Mail_Subject As String) As Boolean
        '  send()
        '   Exit Function
        Dim Msg As New MailMessage
        Dim myCredentials As New System.Net.NetworkCredential
        'myCredentials.UserName = "al@verag.ag"
        'myCredentials.Password = "Luxandreas#2"

        '   myCredentials.UserName = "al@verag.ag"
        '    myCredentials.Password = "verag#2"

        'myCredentials.UserName = "al@verag.ag"
        'myCredentials.Password = "verag#2"
        myCredentials.UserName = "support@verag.ag"
        myCredentials.Password = supportPWD


        ' myCredentials.UserName = "testmail@verag.ag"
        '  myCredentials.Password = "testmail"
        Msg.IsBodyHtml = False
        Dim mySmtpsvr As New SmtpClient()
        '  mySmtpsvr.Host = "192.168.0.107" 'bei web.de
        ' mySmtpsvr.Port = 25 '587 '25
        mySmtpsvr.Host = "owa.verag.ag"
        mySmtpsvr.Port = 587 '25 '587 '25

        mySmtpsvr.UseDefaultCredentials = False
        mySmtpsvr.Credentials = myCredentials
        System.Console.WriteLine("E-Mail Daten initialisiert...")
        Try
            Dim datum As String = Now.AddDays(-1).ToShortDateString
            System.Console.WriteLine("Erstelle EXCEL...")
            Dim excel As String = genEXCEL_OPKreditlimit()


            System.Console.WriteLine("EXCEL erstellt...")
            If excel <> "" And Not excel.StartsWith("ERROR: ") Then

                System.Console.WriteLine("Sende E-Mail...")
                Msg.From = New MailAddress("support@verag.ag")


                For Each m In Mail_to : Msg.To.Add(m) : Next
                For Each m In Mail_cc : Msg.CC.Add(m) : Next
                For Each m In Mail_bcc : Msg.Bcc.Add(m) : Next
                Msg.Subject = Mail_Subject




                '  Msg.To.Add("al@verag.ag")
                Msg.Body = "Anbei befindet sich die Liste der Kunden mit einem offenen Rechnungsbetrag über dem eingegebenen Kreditlimit " & vbNewLine & vbNewLine & "ACHTUNG: Kunden ohne hinterlegten Kreditlimit sind nciht in der Liste beinhaltet." & vbNewLine & vbNewLine & "Stand: " & Now.ToShortDateString & " " & Now.ToShortTimeString & vbNewLine & vbNewLine & vbNewLine & "Automatisch generiertes E-Mail."

                Dim attachment As Attachment = New Attachment(File.OpenRead(excel), "Kundenliste.xlsx")

                Msg.Attachments.Add(attachment)

                Try
                    mySmtpsvr.Send(Msg)
                Catch ex As Exception
                    Try
                        mySmtpsvr.Port = 25
                        mySmtpsvr.Send(Msg)
                    Catch ex2 As Exception
                        Try
                            mySmtpsvr.Host = "192.168.0.107"
                            mySmtpsvr.Port = 25
                            mySmtpsvr.Send(Msg)

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



                System.Console.WriteLine("E-Mail gesendet.")
                '       MsgBox("E-Mail gesendet.", MsgBoxStyle.Information, Title:="Information")
                System.Console.WriteLine("Erfolgreich!")
                Return True
            Else
                System.Console.WriteLine(excel)
            End If

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



    Private Sub send()
        Dim message As New MailMessage("al@verag.ag", "al@verag.ag", "Test", "Testmail")

        Dim client As New SmtpClient("http://192.168.0.107/")
        client.Credentials = New NetworkCredential("al@verag.ag", "verag#2")
        client.Send(message)
    End Sub



    Private Function SendEmail_WOELFL() As Boolean
        Dim Msg As New MailMessage
        Dim myCredentials As New System.Net.NetworkCredential
        myCredentials.UserName = "support@verag.ag"
        myCredentials.Password = supportPWD


        ' myCredentials.UserName = "testmail@verag.ag"
        '  myCredentials.Password = "testmail"
        Msg.IsBodyHtml = False
        Dim mySmtpsvr As New SmtpClient()
        '  mySmtpsvr.Host = "192.168.0.107" 'bei web.de
        ' mySmtpsvr.Port = 25 '587 '25
        mySmtpsvr.Host = "owa.verag.ag"
        mySmtpsvr.Port = 587 '25 '587 '25
        mySmtpsvr.UseDefaultCredentials = False
        mySmtpsvr.Credentials = myCredentials
        System.Console.WriteLine("E-Mail Daten initialisiert...")
        Try
            Dim datum As String = Now.AddDays(-1).ToShortDateString
            Dim von = getDateFromFile()
            If von = "" Then von = datum
            Dim bis = datum
            System.Console.WriteLine("Erstelle CSV...")
            Dim csv As String = genCSV(von, bis)
            System.Console.WriteLine("CSV erstellt...")
            If csv <> "" And Not csv.StartsWith("ERROR: ") Then
                System.Console.WriteLine("Sende E-Mail...")
                Msg.From = New MailAddress("support@verag.ag")
                Msg.To.Add("al@verag.ag")
                Msg.Subject = "VERAG: Gutschriften/Rechnungen " & von & "-" & bis
                Msg.Body = "Sehr geehrte Damen und Herren," & vbNewLine & vbNewLine & "anbei erhalten Sie die Gutschriften/Rechnungen im Zeitraum: " & von & "-" & bis & ". " & vbNewLine & vbNewLine & "Mit frendlichen Grüßen " & vbNewLine & "Ihr VERAG MDM-TEAM" & vbNewLine & vbNewLine & vbNewLine & "Automatisch generiertes E-Mail."

                Dim attachment As Attachment = New Attachment(File.OpenRead(csv), "WOELFL_" & von & "-" & bis & ".csv")
                Msg.Attachments.Add(attachment)

                mySmtpsvr.Send(Msg)

                System.Console.WriteLine("E-Mail gesendet.")
                '       MsgBox("E-Mail gesendet.", MsgBoxStyle.Information, Title:="Information")
                System.Console.WriteLine("Erfolgreich!")
                Return True
            Else
                System.Console.WriteLine(csv)

            End If
        Catch ex As Exception
            Try
                mySmtpsvr.Port = 25
                mySmtpsvr.Send(Msg)

            Catch ex2 As Exception
                Try
                    mySmtpsvr.Host = "192.168.0.107"
                    mySmtpsvr.Port = 25
                    mySmtpsvr.Send(Msg)

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


        End Try
        Return False
    End Function


    Function getDateFromFile() As String
        Try
            Dim instr = New StreamReader(last_sent)
            Dim d As Date = CDate(instr.ReadLine).AddDays(1)
            instr.Close()
            Return d
        Catch ex As Exception
            Return ""
        End Try
    End Function

    Sub genExcel(dt As DataTable)
        Dim wb As New XLWorkbook()

        '   Dim wb As New ClosedXML.Excel.XLWorkbook
        wb.Worksheets.Add(dt, "Kundenliste")
        wb.SaveAs(sPath & "TMP.xlsx")

    End Sub
    Public Function genCSV(von, bis) As String
        Try


            Dim sqlstr = " SELECT CASE [BelegartenNr]	WHEN 71     THEN 'GS' " &
                                 " WHEN 70		THEN 'RG' " &
                                    " END AS [BelegArt] " &
                            " ,[RechnungsNr] " &
                            " ,CONVERT(VARCHAR(10), [RechnungsDatum], 104) as [RechnungsDatum] " &
                            "  ,[FilialenNr],[AbfertigungsNr],[UnterNr] " &
                            " ,CONVERT(VARCHAR(10), [Abfertigungsdatum], 104) as [Abfertigungsdatum] " &
                            " ,isnull(Adressen.WölflKundenNr,'') as WölflKundenNr " &
                            " ,CASE  WHEN [EmpfängerStraße] IS NULL      THEN [EmpfängerName 1] " &
                                    " ELSE		 [EmpfängerName 1] + ' ' +[EmpfängerName 2]  " &
                                    " END AS [Empfänger] " &
                            " ,CASE WHEN [EmpfängerStraße] IS NULL       THEN [EmpfängerName 2] " &
                                    " ELSE		[EmpfängerStraße] " &
                                    " END AS [EmpfängerAdresse 1] " &
                            " ,[EmpfängerOrt] as [EmpfängerAdresse 2] " &
                            " ,[Packstücke und Warenbezeichnung] as Beschreibung,[LeistungsNr],[LeistungsBez],[Steuersatz %] ,[SteuerpflichtigerGesamtbetrag] as [SteuerpflichtigerGesamtbetrag Netto] " &
                            " ,[SteuerfreierGesamtbetrag],[SteuerpflichtigerBetrag] as [SteuerpflichtigerBetrag Netto] ,[SteuerfreierBetrag] " &
                    " FROM [VERAG].[dbo].[Rechnungsausgang] inner join [VERAG].[dbo].[RechnungsausgangPositionen] on Rechnungsausgang.[RK_ID]=RechnungsausgangPositionen.[RK_ID] " &
                            " inner join [VERAG].[dbo].Adressen on Rechnungsausgang.EmpfängerKundenNr=Adressen.AdressenNr " &
                    " WHERE RechnungsKundenNr = 150000 " &
                            " and RechnungsDatum between '" & von & "' and '" & bis & "'"
            ' MsgBox(sqlstr)
            '  Dim SQL As New System.Data.Sql
            Dim dt As DataTable = loadDgvBySqlFMZOLL(sqlstr)


            Dim fn As String = sPath & "WOELFL.csv" '" & Now.ToString("ddMMyyyyHHmmss") & ".csv"
            Dim outFile As IO.StreamWriter = Nothing
            Try
                outFile = My.Computer.FileSystem.OpenTextFileWriter(fn, False)
            Catch ex As Exception
                MsgBox(ex.Message)
                Return "ERROR: Schreibfehler"
            End Try

            System.Console.WriteLine("Vorhandene Datensätze: " & dt.Rows.Count)

            If dt.Rows.Count = 0 Then
                Return "ERROR: KEINE DATEN"
            End If

            Dim clmns As String = ""
            For i = 0 To dt.Columns.Count - 1
                clmns &= dt.Columns(i).ColumnName.ToString().Replace(";", ",") & ";"
            Next

            outFile.WriteLine(clmns)
            For i = 0 To dt.Rows.Count - 1
                clmns = ""
                For j = 0 To dt.Columns.Count - 1
                    Dim o As Object = dt.Rows(i).Item(j).ToString
                    clmns &= dt.Rows(i).Item(j).ToString() & ";"
                Next
                outFile.WriteLine(clmns)
            Next
            outFile.Close()
            Return fn

        Catch ex As Exception
            ' MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message)
            Return "ERROR: " & ex.Message
        End Try
    End Function

    Public Function genEXCEL_BRG(Optional details As Boolean = False) As String
        Try

            Dim cProgramFunctions As New ADMIN.cProgramFunctions
            ' cProgramFunctions.EINLESEN(Now.AddDays(-8).ToShortDateString, Now.ToShortDateString)

            Dim tage As Integer = 7
            Dim startdate As Date = Now.AddDays(-1)
            '  Dim sPath As String = Environment.GetFolderPath(Environment.SpecialFolder.Personal) & "\VERAG\Bürgschaften\" ' My.Computer.FileSystem.GetTempFileName
            'If Not My.Computer.FileSystem.DirectoryExists(sPath) Then
            'My.Computer.FileSystem.CreateDirectory(sPath)
            'End If

            Return cProgramFunctions.genEXCEL_Auswertungen(sPath, tage, startdate, details, details, False)



        Catch ex As Exception
            '  MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message)
            Return "ERROR 03: " & ex.Message & vbNewLine & ex.StackTrace
        End Try
    End Function

    Public Function genEXCEL_QS(von As Date, bis As Date) As String
        Try

            Dim sqlstr As String = ""

            'sqlstr &= " SELECT Aviso.[Grenzstelle], SUM(Speditionsbuch.Abfertigungsanzahl) as Anzahl  FROM Speditionsbuch INNER JOIN [SQLGUIDE01.verag.ost.dmn].AVISO.dbo.AVISO on Aviso.avisoid=Speditionsbuch.AvisoID  "
            'sqlstr &= " WHERE  PersonalnummerQS is not null "
            'sqlstr &= " and FilialenNr NOT IN ( 4801,4806,5501 ) "
            'sqlstr &= " and Abfertigungsdatum between '" & von.ToShortDateString & "' and '" & bis.ToShortDateString & "' " &
            '                                        " GROUP BY Aviso.[Grenzstelle]" &
            '                                        " ORDER BY Anzahl DESC"

            sqlstr &= " SELECT Speditionsbuch.[Grenzstelle], SUM(Speditionsbuch.Abfertigungsanzahl) as Anzahl  FROM Speditionsbuch  inner join Filialen on filialen.FilialenNr=Speditionsbuch.FilialenNr "
            sqlstr &= " WHERE  FilialenNrAbklaerung ='4803' " 'QS SUB
            ' sqlstr &= " WHERE  Filiale  "
            sqlstr &= " and Filialen.Firma='VERAG' "

            sqlstr &= " and Abfertigungsdatum between '" & von.ToShortDateString & "' and '" & bis.ToShortDateString & "' " &
                                                    " GROUP BY Speditionsbuch.[Grenzstelle]" &
                                                    " ORDER BY Anzahl DESC"

            Dim dt As DataTable = loadDgvBySqlFMZOLL(sqlstr)

            Dim exclApp As Object 'as Application
            Dim Datei As Object 'as WorkBook
            Dim Blatt As Object 'as WorkSheet
            exclApp = CreateObject("Excel.Application")

            With exclApp
                .Visible = False
                Dim filepath = sPath & "QS_Auswertung.xlsx"
                While IO.File.Exists(filepath)
                    filepath = sPath & "QS_Auswertung_" & Now.ToString("ddMMyyy_HHmmss_fff") & ".xlsx"
                End While
                Try
                    My.Computer.FileSystem.WriteAllBytes(filepath, My.Resources.QS_Aufteilung, False)
                Catch ex As System.Exception
                    '  MsgBox(ex.Message)
                    Return "ERROR 01: " & ex.Message & vbNewLine & ex.StackTrace
                End Try

                Datei = .Workbooks.Open(filepath) 'Anpassen
                Blatt = Datei.Worksheets("QS") 'Anpassen

                Dim cnt = 0
                For Each r In dt.Rows
                    Blatt.Range("A" & (4 + cnt)).Value = r("Grenzstelle")
                    Blatt.Range("B" & (4 + cnt)).Value = r("Anzahl")
                    cnt += 1
                Next
                Blatt.Range("D1").Value = von.ToShortDateString
                Blatt.Range("F1").Value = bis.ToShortDateString

                Datei.Save()
                Try : Datei.close() : Catch ex As System.Exception
                    Return "ERROR 03: " & ex.Message & vbNewLine & ex.StackTrace
                End Try
                .DisplayAlerts = False
                .quit()
                releaseObject(exclApp)
                releaseObject(Datei)


                Return filepath
            End With
        Catch ex As System.Exception
            '  MsgBox(ex.Message)
            Return "ERROR 02: " & ex.Message & vbNewLine & ex.StackTrace
        End Try

    End Function


    Public Function genEXCEL_THYSSENKRUPP(EORI As String, von As Date, bis As Date) As String
        Try

            Dim sqlstr As String = ""

            sqlstr &= "   SELECT /*eza_id, eza_dyaAnmID,*/cast(eza_Trans_DatumZeit as date) as Datum,eza_ANR as Registriernummer, "

            sqlstr &= " (SELECT [tblDakosy_EZA_Adressen].ezaAd_NameFirma1 FROM [tblDakosy_EZA_Adressen]   WHERE eza_id=ezaAd_EZAId  and ezaAd_AdressTyp='CZ') Absender , "
            sqlstr &= " (SELECT [tblDakosy_EZA_Adressen].ezaAd_LandCode FROM [tblDakosy_EZA_Adressen]   WHERE eza_id=ezaAd_EZAId   and ezaAd_AdressTyp='CZ') AbsenderLand, "
            sqlstr &= " ezaWP_UrsprungslandCode Ursprungsland, "

            sqlstr &= " ezaWP_PositionsNummer as PositionsNummer, "
            sqlstr &= " tblDakosy_EZA_Warenposition.ezaWP_WarennummerEZT TarifnummerEZT, "
            sqlstr &= " tblDakosy_EZA_Warenposition.ezaWP_Artikelpreis Artikelpreis,  "
            sqlstr &= " CASE WHEN ezaWP_PositionsNummer=1 then  SUM(CASE WHEN [ezaAfb_AbgabeArt] = 'B0000' THEN [ezaAfb_Abgabenbetrag] ELSE 0 END) ELSE '' END  EUST, "
            sqlstr &= " CASE WHEN ezaWP_PositionsNummer=1 then  SUM(CASE WHEN [ezaAfb_AbgabeArt] = 'B0000' THEN 0 ELSE [ezaAfb_Abgabenbetrag] END) ELSE '' END  ZOLL, "
            sqlstr &= " ezaWP_PackstueckAnzahl PackstueckAnzahl, "
            sqlstr &= "  sum(tblDakosy_EZA_Warenposition.ezaWP_Eigenmasse) Eigenmasse,/* sum(tblDakosy_EZA_Warenposition.ezaWP_Rohmasse) Rohmasse, */ "

            sqlstr &= " max(tblDakosy_EZA_Warenposition.ezaWP_Warenbezeichnung )Warenbezeichnung "

            sqlstr &= " FROM [VERAG].[dbo].[tblDakosy_EZA] inner join tblDakosy_EZA_Warenposition on ezaWP_EzaId=eza_Id "
            sqlstr &= " inner join tblDakosy_EZA_Aufschub on [ezaAfb_EZAId]=eza_Id "
            sqlstr &= " where (SELECT count(*) FROM [tblDakosy_EZA_Adressen]  WHERE eza_id=ezaAd_EZAId AND  ezaAd_TeilnehmerEORI = '" & EORI & "' and ezaAd_AdressTyp='CN')>0 "

            sqlstr &= " and eza_Trans_DatumZeit between '" & von.ToShortDateString & "' and '" & bis.ToShortDateString & "' "
            sqlstr &= " and eza_status BETWEEN 60 and 60  "
            sqlstr &= " group by eza_id,eza_dyaAnmID,eza_ANR,ezaWP_PositionsNummer,eza_Trans_DatumZeit,ezaWP_UrsprungslandCode ,ezaWP_WarennummerEZT,ezaWP_Artikelpreis,ezaWP_ArtikelpreisWaehrung,ezaWP_PackstueckAnzahl "



            Dim dt As DataTable = loadDgvBySqlFMZOLL(sqlstr)


            Dim filepath = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dt, {"H:I"},,,, False, "Zollanmeldungen_" & EORI & "_" & von.ToShortDateString & "-" & bis.ToShortDateString)
            If filepath = "" Then Return "ERROR 01: Fehler beim Erzeugen des XLS."

            Return filepath
        Catch ex As System.Exception
            '  MsgBox(ex.Message)
            Return "ERROR 02: " & ex.Message & vbNewLine & ex.StackTrace
        End Try

    End Function

    Public Function genEXCEL_RED_BULL(KdNr As String, von As Date, bis As Date) As String
        Try
            Dim KUNDENADR = New VERAG_PROG_ALLGEMEIN.cAdressen(KdNr)
            Dim sqlstr As String = ""

            sqlstr &= "SELECT  cast([Abfertigungsdatum] as date) [Abfertigungsdatum], [BelegNr] [CNR/MRN] ,Abfertigungsbezeichnung,case when [AtlasBezNrEZA] <> '' Then [AtlasBezNrEZA] ELSE [AtlasBezNrNCTS] END as BezugsNr,[LKW Kennzeichen] , case when [AtlasBezNrEZA] <> '' Then EZA.eza_VersendungsLandCode else NCTS.ncts_VersendungsLandCode End as VersendungsLand  , case when [AtlasBezNrEZA] <> '' Then EZA.eza_Bestimmungsland else NCTS.ncts_BestimmungslandCode End as Bestimmungsland,[Absender],[Empfänger],[Packstücke] ,[Rohmasse] , case when [AtlasBezNrEZA] <> '' Then "
            sqlstr &= "(SELECT ezaWP_WarennummerEZT+ ', '  FROM [tblDakosy_EZA_Warenposition] As T2 WHERE T2.ezaWP_EzaId = EZA.eza_id ORDER BY ezaWP_WarennummerEZT FOR XML PATH (''), TYPE) else (SELECT nctsWP_Warennummer + ', '  FROM [tblDakosy_NCTSOut_Warenposition] As T2 WHERE T2.nctsWP_NctsId = NCTS.ncts_Id ORDER BY nctsWP_Warennummer FOR XML PATH (''), TYPE) End as CustomsTariffNr"
            sqlstr &= ", case when [AtlasBezNrEZA] <> '' Then (SELECT ezaWP_AnmeldeVErfahren + ', '  FROM [tblDakosy_EZA_Warenposition] As T2 WHERE T2.ezaWP_EzaId = EZA.eza_id ORDER BY ezaWP_AnmeldeVErfahren FOR XML PATH (''), TYPE) else NCTS.ncts_ArtAnmeldung End as CodeOfCostumsProcedure"
            sqlstr &= " From [VERAG].[dbo].[Speditionsbuch] as SPB"
            sqlstr &= " left join tblDakosy_NCTSOut as NCTS on NCTS.ncts_ObjectName = SPB.AtlasBezNrNCTS"
            sqlstr &= " left join tblDakosy_EZA as EZA on EZA.eza_ObjectName = SPB.AtlasBezNrEZA"
            sqlstr &= " left join Abfertigungsarten as ABF on ABF.[Abfertigungsart] = SPB.[Abfertigungsart]"
            sqlstr &= "  where (VermittlerKundenNr='" & KdNr & "' OR EmpfängerKundenNr='" & KdNr & "')"
            sqlstr &= "  and Abfertigungsdatum between '" & von.ToShortDateString & "' and '" & bis.ToShortDateString & "'"

            Dim dt As DataTable = loadDgvBySqlFMZOLL(sqlstr)


            Dim filepath = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dt,,,,, False, "Report Data_" & KUNDENADR.FullName & "_" & von.ToShortDateString & "-" & bis.ToShortDateString)
            If filepath = "" Then Return "ERROR 01: Fehler beim Erzeugen des XLS."

            Return filepath
        Catch ex As System.Exception
            '  MsgBox(ex.Message)
            Return "ERROR 02: " & ex.Message & vbNewLine & ex.StackTrace
        End Try

    End Function


    Public Function genEXCEL_ANNA(FilialenNr As String, abfertigungsart As Integer, von As Date, bis As Date) As String
        Try

            Dim sqlstr As String = ""

            sqlstr &= "SELECT count(*) as Anzahl,FilialenNr,case when KE.Veranlagungskunde = 1 Then adr.[Name 1] else adre.[Name 1] ENd as Kunde "
            sqlstr &= "FROM [VERAG].[dbo].[Speditionsbuch] as SP "
            sqlstr &= "left join [tblKundenErweitert] as KE on KE.kde_KundenNr = SP.EmpfängerKundenNr "
            sqlstr &= "left join adressen as adr on adr.AdressenNr = SP.EmpfängerKundenNr "
            sqlstr &= "left join [tblKundenErweitert] as KA on KA.kde_KundenNr = SP.VermittlerKundenNr "
            sqlstr &= "left join adressen as adre on adre.AdressenNr = SP.VermittlerKundenNr "
            sqlstr &= "where Abfertigungsart = " & abfertigungsart & "  and Abfertigungsdatum between '" & von.ToShortDateString & "' and '" & bis.ToShortDateString & "' and FilialenNr in (" & FilialenNr & ") and (Ke.Veranlagungskunde = 1 or KA.Veranlagungskunde = 1) "
            sqlstr &= "group by case when KE.Veranlagungskunde = 1 Then adr.[Name 1] else adre.[Name 1] ENd, FilialenNr order by Kunde"


            Dim dt As DataTable = loadDgvBySqlFMZOLL(sqlstr)


            Dim filepath = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dt,,,,, False, "Report Data_" & von.ToShortDateString & "-" & bis.ToShortDateString)
            If filepath = "" Then Return "ERROR 01: Fehler beim Erzeugen des XLS."

            Return filepath
        Catch ex As System.Exception
            '  MsgBox(ex.Message)
            Return "ERROR 02: " & ex.Message & vbNewLine & ex.StackTrace
        End Try

    End Function


    Public Function genEXCEL_ZF(KdNr As String, von As Date, bis As Date) As String
        Try

            Dim KUNDENADR = New VERAG_PROG_ALLGEMEIN.cAdressen(KdNr)
            Dim sqlstr As String = ""

            sqlstr &= "SELECT   CAST([FilialenNr] as varchar) + '/' + CAST([AbfertigungsNr] as varchar) Abfertigungsnummer,cast([Abfertigungsdatum] as date)Abfertigungsdatum,Absender,Rechnungsbetrag Betrag ,BelegNr,[FilialenNr],[AbfertigungsNr],Speditionsbuch.Abfertigungsart,Abfertigungsbezeichnung"
            sqlstr &= " FROM Speditionsbuch INNER JOIN [Abfertigungsarten] ON Speditionsbuch.Abfertigungsart=Abfertigungsarten.Abfertigungsart"
            sqlstr &= " where EmpfängerKundenNr IN (" & KdNr & ") and Abfertigungsdatum BETWEEN '" & von.ToShortDateString & "' AND '" & bis.ToShortDateString & "' And Speditionsbuch.Abfertigungsart IN (1,29)"

            Dim dt As DataTable = loadDgvBySqlFMZOLL(sqlstr)


            Dim sPath As String = Environment.GetFolderPath(Environment.SpecialFolder.Personal) & "\VERAG\SR\"
            If Not My.Computer.FileSystem.DirectoryExists(sPath) Then
                My.Computer.FileSystem.CreateDirectory(sPath)
            End If

            Dim Path = ""
            Dim exclApp As Object 'as Application
            Dim Datei As Object 'as WorkBook
            Dim Blatt As Object 'Microsoft.Office.Interop.Excel.Worksheet 'As Object 'as Worksheet
            exclApp = CreateObject("Excel.Application")

            With exclApp
                .Visible = False

                Try
                    Path = sPath & "ZF_" & von.ToShortDateString & "-" & bis.ToShortDateString & "" & " .xlsx"
                    While System.IO.File.Exists(Path)
                        Path = sPath & "ZF_" & von.ToShortDateString & "-" & bis.ToShortDateString & "_" & Now.ToString("ddMMyyyyHHmmss") & ".xlsx"
                    End While
                    My.Computer.FileSystem.WriteAllBytes(Path, My.Resources.RG_ZF, False)
                Catch ex As System.Exception
                    '  MsgBox(ex.Message)
                    MsgBox("ERROR 01: " & ex.Message & vbNewLine & ex.StackTrace)


                    Return ""
                End Try

                Datei = .Workbooks.Open(Path) 'Anpassen
                Blatt = Datei.Worksheets(1) 'Anpassen

                Blatt.Range("I1").Value = von.ToShortDateString & "-" & bis.ToShortDateString

                Dim cnt = 3
                For Each r In dt.Rows
                    Blatt.Range("A" & cnt).Value = cnt - 2
                    Blatt.Range("B" & cnt).Value = r("Abfertigungsnummer")
                    '   Blatt.Range("C" & cnt).Value = r("RechnungsNr")
                    Blatt.Range("C" & cnt).Value = r("Abfertigungsdatum")
                    Blatt.Range("D" & cnt).Value = r("Abfertigungsbezeichnung")
                    Blatt.Range("E" & cnt).Value = r("Absender")
                    Blatt.Range("F" & cnt).Value = "" 'r("Betrag")
                    Blatt.Range("H" & cnt).Value = r("BelegNr")

                    VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "VERAG"

                    Dim ZOLLANMELDUNG As New cZollsysteme_Aktenbeschriftung
                    If ZOLLANMELDUNG.getDataByBezugsnummer(r("FilialenNr") & "/" & r("AbfertigungsNr"), r("Abfertigungsart"), "", False) Then
                        Blatt.Range("F" & cnt).Value = ZOLLANMELDUNG.Rechnungspreis
                        Blatt.Range("G" & cnt).Value = ZOLLANMELDUNG.Handelsrechnung.Replace(", ", "," & vbNewLine)
                        Blatt.Range("I" & cnt).Value = ZOLLANMELDUNG.ABGABEN_ZOLL
                        Blatt.Range("J" & cnt).Value = ZOLLANMELDUNG.ANZ_POS
                    End If

                    cnt += 1

                Next

                Datei.Save()
                .DisplayAlerts = False
                .quit()
                Try : Datei.close(True) : Catch : End Try
            End With


            'Dim filepath = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dt,,,,, False, "Report Data_" & KUNDENADR.FullName & "_" & von.ToShortDateString & "-" & bis.ToShortDateString)
            Dim filepath = Path
            If filepath = "" Then Return "ERROR 01: Fehler beim Erzeugen des XLS."

            Return filepath
        Catch ex As System.Exception
            '  MsgBox(ex.Message)
            Return "ERROR 02: " & ex.Message & vbNewLine & ex.StackTrace
        End Try

    End Function

    Private Sub releaseObject(ByVal obj As Object)
        Try
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
            obj = Nothing
        Catch ex As Exception
            obj = Nothing
        Finally
            GC.Collect()
        End Try
    End Sub

    Public Function genEXCEL_CS() As String
        Try

            Dim sqlstr As String = ""

            Dim von = CDate("01." & Now.AddMonths(-1).Month & "." & Now.AddMonths(-1).Year)
            Dim bis = CDate("01." & Now.Month & "." & Now.Year).AddDays(-1)

            'sqlstr &= " SELECT Aviso.[Grenzstelle], SUM(Speditionsbuch.Abfertigungsanzahl) as Anzahl FROM Speditionsbuch INNER JOIN [SQLGUIDE01.verag.ost.dmn].AVISO.dbo.AVISO on Aviso.avisoid=Speditionsbuch.AvisoID WHERE Abfertigungsart IN (26,28) "
            'sqlstr &= " AND Aviso.[Grenzstelle] <> 'SFD' and FilialenNr NOT IN ( 4801,4806 ) "
            'sqlstr &= " and Abfertigungsdatum between '" & von.ToShortDateString & "' and '" & bis.ToShortDateString & "' " &
            '                                        " GROUP BY Aviso.[Grenzstelle]" &
            '                                        " ORDER BY Anzahl DESC"


            sqlstr &= " SELECT [Grenzstelle], SUM(Speditionsbuch.Abfertigungsanzahl) as Anzahl FROM Speditionsbuch WHERE Abfertigungsart IN (26,28) "
            sqlstr &= " AND [Grenzstelle] <> 'SFD' and FilialenNr NOT IN ( 4801,4802,4806 ) "
            sqlstr &= " and Abfertigungsdatum between '" & von.ToShortDateString & "' and '" & bis.ToShortDateString & "' " &
                                                    " GROUP BY [Grenzstelle]" &
                                                    " ORDER BY Anzahl DESC"
            Dim dt As DataTable = loadDgvBySqlFMZOLL(sqlstr)

            Dim exclApp As Object 'as Application
            Dim Datei As Object 'as WorkBook
            Dim Blatt As Object 'as WorkSheet
            exclApp = CreateObject("Excel.Application")

            With exclApp
                .Visible = False
                Dim filepath = sPath & "CS_Auswertung.xlsx"
                Try
                    My.Computer.FileSystem.WriteAllBytes(filepath, My.Resources.CS_Aufteilung, False)
                Catch ex As System.Exception
                    '  MsgBox(ex.Message)
                    Return "ERROR 01: " & ex.Message & vbNewLine & ex.StackTrace
                End Try

                Datei = .Workbooks.Open(filepath) 'Anpassen
                Blatt = Datei.Worksheets("CS") 'Anpassen

                Dim cnt = 0
                For Each r In dt.Rows
                    Blatt.Range("A" & (4 + cnt)).Value = r("Grenzstelle")
                    Blatt.Range("B" & (4 + cnt)).Value = r("Anzahl")
                    cnt += 1
                Next
                Blatt.Range("D1").Value = von.ToShortDateString
                Blatt.Range("F1").Value = bis.ToShortDateString

                Datei.Save()
                .DisplayAlerts = False
                .quit()
                Try : Datei.close(True) : Catch : End Try

                Return filepath
            End With
        Catch ex As System.Exception
            '  MsgBox(ex.Message)
            Return "ERROR 02: " & ex.Message & vbNewLine & ex.StackTrace
        End Try

    End Function



    Public Function genEXCEL_MDM_ZOLL(Jahr) As String
        Try


            Dim exclApp As Object 'as Application
            Dim Datei As Object 'as WorkBook
            Dim Blatt As Object 'as WorkSheet
            exclApp = CreateObject("Excel.Application")

            With exclApp
                .Visible = False
                Dim filepath = sPath & "MDM_ZOLL_Verguetung.xlsx"
                Try
                    My.Computer.FileSystem.WriteAllBytes(filepath, My.Resources.MDM_ZOLL_Verguetung, False)
                Catch ex As System.Exception
                    '  MsgBox(ex.Message)
                    Return "ERROR 01: " & ex.Message & vbNewLine & ex.StackTrace
                End Try

                Datei = .Workbooks.Open(filepath) 'Anpassen
                Blatt = Datei.Worksheets("CS") 'Anpassen

                Blatt.Range("F1").Value = If(Jahr > 0, Jahr, Now.AddMonths(-1).Year)


                ' Dim von = CDate("01." & Now.AddMonths(-1) & "." & Now.AddMonths(-1).Year)

                For i = 1 To 12 'Now.AddMonths(-1).Month
                    Dim year = If(Jahr > 0, Jahr, Now.AddMonths(-1).Year)
                    Dim sqlstr As String = ""

                    '  Dim bis = von.AddMonths(1).AddDays(-1)

                    Dim von = CDate("01." & i & "." & year)
                    Dim bis = CDate("01." & i & "." & year).AddMonths(1).AddDays(-1)

                    sqlstr &= "  SELECT  count(*)"
                    sqlstr &= "  FROM tblEABelegnummer as EAB  inner join tblEABelegposition as POS on  EAB.Mandant=POS.Mandant and EAB.[Niederlassung]=POS.[Niederlassung] and EAB.[Benutzer]=POS.[Benutzer] and EAB.[BelegDat]=POS.[BelegDat] and EAB.[BelegNr]=POS.[BelegNr]"
                    sqlstr &= "  where LeistungsNr=480	and [EAB].BelegDat between '" & von.ToShortDateString & "' and '" & bis.ToShortDateString & "' and gebucht=1 and storniert=0  and EAB.Mandant='VERA' AND EAB.Niederlassung='SUA' "
                    ' sqlstr &= "  where LeistungsNr=480	and [EAB].BelegDat between '" & von.ToShortDateString & "' and '" & bis.ToShortDateString & "' and gebucht=1 and storniert=0  and EAB.Mandant='IMEX' "

                    Dim anzahl = 0

                    Dim dt As DataTable = loadDgvBySqlFMZOLL(sqlstr)
                    If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
                        anzahl = dt.Rows(0)(0)
                    End If
                    Blatt.Range("D" & (7 + i)).Value = anzahl



                    sqlstr = "  SELECT COUNT(*)  FROM [tblSDLAbholung]  where sdlAb_Storniert=0 and sdlAb_FahrerAbholAuftrag=1 and sdlAb_Abholung between '" & von.ToShortDateString & "' and '" & bis.ToShortDateString & "'AND sdlAb_Abholung>='01.09.2021 00:00:00'  "
                    anzahl = 0

                    Dim dt2 = loadDgvBySqlSDL(sqlstr)
                    If dt2 IsNot Nothing AndAlso dt2.Rows.Count > 0 Then
                        anzahl = dt2.Rows(0)(0)
                    End If


                    Blatt.Range("B" & (7 + i)).Value = anzahl

                Next




                Datei.Save()
                .DisplayAlerts = False
                .quit()
                Try : Datei.close(True) : Catch : End Try

                Return filepath
            End With
        Catch ex As System.Exception
            '  MsgBox(ex.Message)
            Return "ERROR 02: " & ex.Message & vbNewLine & ex.StackTrace
        End Try

    End Function



    Public Function genEXCEL_DEPOT(KundenNr) As String
        Try

            Dim sqlstr As String = ""



            sqlstr &= "    Select   [Belegnummer] As [Rechnungsnummer/BelegNr], CONVERT(Date,[Belegdatum] ,4) As Belegdatum "
            sqlstr &= " ,[Gesamtausstand] as Betrag,[Buchungstext],Rechnungsausgang.Abfertigungsdatum "
            sqlstr &= " , (SELECT  TOP 1 Abfertigungsbezeichnung FROM Speditionsbuch INNER JOIN Abfertigungsarten ON Abfertigungsarten.Abfertigungsart= Speditionsbuch.Abfertigungsart WHERE Speditionsbuch.AbfertigungsNr=[Rechnungsausgang].AbfertigungsNr And Speditionsbuch.FilialenNr=[Rechnungsausgang].FilialenNr) as Abfertigungsart "
            sqlstr &= " ,Rechnungsausgang.[Packstücke und Warenbezeichnung] "
            sqlstr &= "   FROM  [Offene Posten] "
            sqlstr &= " Left Join [Rechnungsausgang] on [Rechnungsausgang].RechnungsNr=(case WHEN isnumeric(Belegnummer)=1 THEN Belegnummer ELSE -1 END  ) "
            sqlstr &= "  where Kontonummer = 716257 And [Offene Posten].Firma_ID=1 "
            sqlstr &= " order by Belegdatum, op_id "

            '  sqlstr &= " SELECT *  FROM  [Offene Posten] where Kontonummer= " & KundenNr
            '  sqlstr &= " ORDER BY  SSMA_TimeStamp"
            Dim dt As DataTable = loadDgvBySqlFMZOLL(sqlstr)

            Dim exclApp As Object 'as Application
            Dim Datei As Object 'as WorkBook
            Dim Blatt As Object 'as WorkSheet
            exclApp = CreateObject("Excel.Application")

            With exclApp
                .Visible = False
                Dim filepath = sPath & "\Depot.xlsx"
                Try
                    My.Computer.FileSystem.WriteAllBytes(filepath, My.Resources.Depot, False)
                Catch ex As System.Exception
                    '  MsgBox(ex.Message)
                    Return "ERROR 01: " & ex.Message & vbNewLine & ex.StackTrace
                End Try
                MsgBox(filepath)
                Datei = .Workbooks.Open(filepath) 'Anpassen
                Blatt = Datei.Worksheets(1) 'Anpassen

                Dim cnt = 0
                For Each r In dt.Rows
                    Blatt.Range("A" & (4 + cnt)).Value = r("Belegdatum")
                    Blatt.Range("B" & (4 + cnt)).Value = r("Belegnummer")
                    Blatt.Range("C" & (4 + cnt)).Value = r("Bruttobetrag")
                    Blatt.Range("D" & (4 + cnt)).Value = r("Waehrung")
                    Blatt.Range("E" & (4 + cnt)).Value = r("Buchungstext")
                    Blatt.Range("F" & (4 + cnt)).Value = r("KumSaldoEUR")
                    Blatt.Range("G" & (4 + cnt)).Value = r("Bemerkung")
                    cnt += 1
                Next
                Blatt.Range("E1").Value = Now.ToShortDateString

                Datei.Save()
                .DisplayAlerts = False
                .quit()
                Try : Datei.close(True) : Catch : End Try

                Return filepath
            End With
        Catch ex As System.Exception
            '  MsgBox(ex.Message)
            Return "ERROR 02: " & ex.Message & vbNewLine & ex.StackTrace
        End Try

    End Function




    Sub einlesenBRG()
        Dim cProgramFunctions As New ADMIN.cProgramFunctions
        cProgramFunctions.EINLESEN(Now.AddDays(-8).ToShortDateString, Now.ToShortDateString)
    End Sub
    Public Function genEXCEL_BRGKW() As String
        Try
            Dim cProgramFunctions As New ADMIN.cProgramFunctions
            '  cProgramFunctions.EINLESEN(Now.AddDays(-8), Now)

            Dim tage As Integer = 7
            Dim startdate As Date = Now.AddDays(-1)
            '    Dim sPath As String = Environment.GetFolderPath(Environment.SpecialFolder.Personal) & "\VERAG\Bürgschaften\" ' My.Computer.FileSystem.GetTempFileName
            'If Not My.Computer.FileSystem.DirectoryExists(sPath) Then
            'My.Computer.FileSystem.CreateDirectory(sPath)
            'End If

            Return cProgramFunctions.genEXCEL_AuswertungenKW(sPath, cProgramFunctions.getKW(Now.AddDays(-7)), Now.AddDays(-7).Year, False)



        Catch ex As Exception
            ' MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message)
            Return "ERROR 03: " & ex.Message & vbNewLine & ex.StackTrace
        End Try
    End Function



    Public Function genEXCEL_TR(LandEinschr) As String
        Try
            If LandEinschr <> "" Then LandEinschr = " AND LandKz IN (" & LandEinschr & ") "

            Dim sqlstr = " SELECT [Kontonummer] as KdNr,cast(SUM([Gesamtausstand]) as decimal(12,2)) as Summe,max([Waehrung]) as Währung ,max(LandKz) as Land, max(Ordnungsbegriff) as Firma,max(Ort) as Ort,max(Straße) as Straße,max([E-Mail]) as [E-Mail],max(Telefon) as Telefon, min([Fälligkeitsdatum]) as [Fälligkeitsdatum] " &
                         "FROM [Offene Posten] INNER JOIN Adressen ON AdressenNr=Kontonummer " &
                            "WHERE 1=1 " & LandEinschr & " AND Firma_ID NOT IN (7,15) " &
                         "GROUP BY [Kontonummer] " &
                         "HAVING SUM([Gesamtausstand]) > " & betragOpTr &
                         "ORDER BY Firma asc"
            ' MsgBox(sqlstr)
            '  Dim SQL As New System.Data.Sql
            Dim dt As DataTable = loadDgvBySqlFMZOLL(sqlstr)
            System.Console.WriteLine("Vorhandene Datensätze: " & dt.Rows.Count)
            genExcel(dt)

            Return sPath & "TMP.xlsx"

        Catch ex As Exception
            '  MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message)
            Return "ERROR: " & ex.Message
        End Try
    End Function



    Public Function genEXCEL_TR_IMEX(LandEinschr) As String
        Try

            If LandEinschr <> "" Then LandEinschr = " AND LandKz IN (" & LandEinschr & ") "

            Dim sqlstr = " SELECT [KundenNr] as KdNr,cast(SUM(Saldo) as decimal(12,2)) as Summe/*,max([Waehrung]) as Währung */,max(LandKz) as Land, max(Ordnungsbegriff) as Firma,max(Ort) as Ort,max(Straße) as Straße,max([E-Mail]) as [E-Mail],max(Telefon) as Telefon  " &
                         " FROM Offene_Posten_DVO INNER JOIN Adressen ON AdressenNr=[KundenNr]  " &
                            "WHERE 1=1  " & LandEinschr &
                         "GROUP BY [KundenNr] " &
                         "HAVING SUM([Saldo]) > " & betragOpTr &
                         "ORDER BY Firma asc"
            ' MsgBox(sqlstr)
            '  Dim SQL As New System.Data.Sql
            Dim dt As DataTable = loadDgvBySqlFMZOLL(sqlstr)
            System.Console.WriteLine("Vorhandene Datensätze: " & dt.Rows.Count)
            genExcel(dt)

            Return sPath & "TMP.xlsx"

        Catch ex As Exception
            '  MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message)
            Return "ERROR: " & ex.Message
        End Try

    End Function

    Public Function genEXCEL_OPKreditlimit() As String
        Try

            'Dim sqlstr = "SELECT  [AdressenNr],Ordnungsbegriff,Kreditlimit,sum([Offene Posten].Bruttobetrag) as OP_Saldo
            '              FROM [VERAG].[dbo].[Adressen]
            '              inner join Kunden on KundenNr=AdressenNr
            '              inner join [Offene Posten] on KundenNrZentrale=[Offene Posten].Kontonummer
            '              where Kreditlimit<>2600 
            '              and (LEN(Adressennr)=6 and AdressenNr not like '40%')
            '              group by [AdressenNr],Ordnungsbegriff,Kreditlimit 
            '                having sum([Offene Posten].Bruttobetrag) >Kreditlimit"

            Dim sqlstr = "	SELECT  [AdressenNr],Ordnungsbegriff, Kreditlimit ,dbo.fn_ConvertNumber(OP_Saldo, 1031, 2) as OP_Saldo, Vorauskasse, dbo.fn_ConvertNumber(OP_Faellig, 1031, 2)OP_Fällig
						      FROM (SELECT  [AdressenNr],Ordnungsbegriff, CASE WHEN kunden.Vorkasse =1 then '' ELSE CONVERT(varchar, CAST(Kreditlimit AS money), 1) END AS Kreditlimit , (sum([Offene Posten].Bruttobetrag)) as OP_Saldo, CASE WHEN kunden.Vorkasse =1 then 'JA' ELSE 'NEIN' END Vorauskasse
                                    , SUM(case when [Offene Posten].Fälligkeitsdatum<=getdate() then [Offene Posten].Bruttobetrag ELSE 0 end)   as OP_Faellig
                              FROM [VERAG].[dbo].[Adressen] 
                                    inner join Kunden on KundenNr=AdressenNr
                                    inner join [Offene Posten] on KundenNrZentrale=[Offene Posten].Kontonummer
                                    inner join Filialen on filialen.filialenNr=Kunden.FilialenNr
                              where ((Kreditlimit<>2600 and  Kreditlimit<>0) OR kunden.Vorkasse =1)
                                    and (LEN(Adressennr)=6 and AdressenNr not like '40%')
						            and filialen.Firma IN ('VERAG','ATILLA') and filialen.filialenNr<>8001 
                              group by [AdressenNr],Ordnungsbegriff,Kreditlimit ,kunden.Vorkasse
                                    having sum([Offene Posten].Bruttobetrag) >Kreditlimit    
								    ) 
							AS T1 
                              WHERE cast (OP_Faellig as float) > 5000
							order by OP_Faellig desc"

            Dim dt As DataTable = loadDgvBySqlFMZOLL(sqlstr)
            System.Console.WriteLine("Vorhandene Datensätze: " & dt.Rows.Count)
            genExcel(dt)

            Return sPath & "TMP.xlsx"

        Catch ex As Exception
            '  MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message)
            Return "ERROR: " & ex.Message
        End Try
    End Function
    Public Function genEXCEL_TR_ATILLA(LandEinschr) As String
        Try

            If LandEinschr <> "" Then LandEinschr = " AND LandKz IN (" & LandEinschr & ") "

            Dim sqlstr = " SELECT [Kontonummer] as KdNr,cast(SUM([Gesamtausstand]) as decimal(12,2)) as Summe,max([Waehrung]) as Währung ,max(LandKz) as Land, max(Ordnungsbegriff) as Firma,max(Ort) as Ort,max(Straße) as Straße,max([E-Mail]) as [E-Mail],max(Telefon) as Telefon " &
                         "FROM [Offene Posten] INNER JOIN Adressen ON AdressenNr=Kontonummer " &
                            "WHERE 1=1 " & LandEinschr & " AND Firma_ID = 7 " &
                         "GROUP BY [Kontonummer] " &
                         "HAVING SUM([Gesamtausstand]) > " & betragOpTr &
                         "ORDER BY Firma asc"
            ' MsgBox(sqlstr)
            '  Dim SQL As New System.Data.Sql
            Dim dt As DataTable = loadDgvBySqlFMZOLL(sqlstr)
            System.Console.WriteLine("Vorhandene Datensätze: " & dt.Rows.Count)
            genExcel(dt)

            Return sPath & "TMP.xlsx"

        Catch ex As Exception
            '  MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message)
            Return "ERROR: " & ex.Message
        End Try
    End Function
    Public Function loadDgvBySqlFMZOLL(ByVal sql As String) As DataTable
        Try
            Dim myTable = New DataTable()
            Dim conn As SqlConnection = VERAG_PROG_ALLGEMEIN.SQL.GetNewOpenConnectionFMZOLL
            'conn.ConnectionString = "Data Source=192.168.0.91\SQLFMZOLL;Initial Catalog=VERAG;Integrated Security=false;User ID=test;Password=BmWr501956;"
            'conn.Open()

            Using cmd As New SqlCommand(sql, conn)
                Dim dr As SqlDataReader = cmd.ExecuteReader()
                myTable.Load(dr)
                dr.Close()
            End Using
            conn.Close()

            Return myTable
        Catch ex As Exception
            MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message)
        End Try

        Return Nothing
    End Function
    Public Function loadDgvBySqlSDL(ByVal sql As String) As DataTable
        Try
            Dim myTable = New DataTable()
            Dim conn As SqlConnection = VERAG_PROG_ALLGEMEIN.SQL.GetNewOpenConnectionSDL
            'conn.ConnectionString = "Data Source=192.168.0.91\SQLFMZOLL;Initial Catalog=SDL;Integrated Security=false;User ID=test;Password=BmWr501956;"
            'conn.Open()

            Using cmd As New SqlCommand(sql, conn)
                Dim dr As SqlDataReader = cmd.ExecuteReader()
                myTable.Load(dr)
                dr.Close()
            End Using
            conn.Close()

            Return myTable
        Catch ex As Exception
            MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message)
        End Try

        Return Nothing
    End Function
End Module
