Option Explicit On

Imports System.Data
Imports System.Net
Imports System.Reflection
Imports System.Runtime.InteropServices
Imports System.Text.RegularExpressions
Imports System.Windows.Forms
Imports AVISO

'Imports System.Windows.Forms.LinkLabel
Imports HtmlAgilityPack
Imports Microsoft.Office.Interop
Imports Microsoft.Office.Tools.Ribbon
Imports VERAG_PROG_ALLGEMEIN

Public Enum cANHANGSART_ADDIN
    'Upload in Datenarchiv
    PDF = 1
    YMAIL = 2
    PDFANDMAIL = 3

    'Upload in Datenarchiv inkl. Zuweisung zu Objekt
    PDFANDMAIL_DATENSERVER = 4
    PDF_DATENSERVER = 5
    MAIL_DATENSERVER = 6

End Enum



Public Class VERAGRibbon
    Dim LOGIN_OK = False
    Public Shared Event bla()
    Private Sub CustomerRibbon_Load(ByVal sender As System.Object, ByVal e As Microsoft.Office.Tools.Ribbon.RibbonUIEventArgs) Handles MyBase.Load

    End Sub
    Private Function CreateRibbonDropDownItem() As RibbonDropDownItem
        Return Me.Factory.CreateRibbonDropDownItem()
    End Function

    Private Function CreateRibbonMenu() As RibbonMenu
        Return Me.Factory.CreateRibbonMenu()
    End Function

    'Private Function CreateRibbonButton() As RibbonButton
    '    Dim button As RibbonButton = Me.Factory.CreateRibbonButton()
    '    ' AddHandler (button.Click), AddressOf Button_Click
    '    Return button
    'End Function

    Private Sub Ribbon1_Load(ByVal sender As System.Object, ByVal e As RibbonUIEventArgs) Handles MyBase.Load

        cAllgemein.TESTSYSTEM = True

        VERAG_PROG_ALLGEMEIN.cAllgemein.SQLGUIDE01_USED = True
        If VERAG_PROG_ALLGEMEIN.cAllgemein.SQLGUIDE01_USED Then
            VERAG.Label = "VERAG - UNLEASHED"
            btnAVISOUnleashed.Visible = True
        Else
            VERAG.Label = "VERAG"
            btnAVISOUnleashed.Visible = False

        End If
        'cAllgemein.TESTSYSTEM = True
        LOGIN_OK = AVISO_Mail_Functions.initFirmaUser()

    End Sub




    Private Sub Button2_Click(sender As Object, e As RibbonControlEventArgs) Handles Button2.Click
        If LOGIN_OK Then AVISO_Mail_Functions.NewAviso_Hauptfenster()
    End Sub

    Private Sub Button4_Click(sender As Object, e As RibbonControlEventArgs) Handles Button4.Click
        Try


            MsgBox("User: " & System.Security.Principal.WindowsIdentity.GetCurrent().Name & vbNewLine & "Version: " & Assembly.GetExecutingAssembly().GetName().Version.ToString & vbNewLine & "System: " & IIf(cAllgemein.TESTSYSTEM, "TEST", "PRODUKTIV"))
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
    End Sub


    Sub Button1_Click_1(sender As Object, e As RibbonControlEventArgs) Handles Button1.Click
        If LOGIN_OK Then AVISO_Mail_Functions.newEKOLMAIL()
    End Sub


    Private Sub Button1_Click(sender As Object, e As RibbonControlEventArgs)
        'MsgBox("HI")
        '   Dim ThisAddIn As New ThisAddIn
        Dim s As String = ""
        'Dim app = ThisAddIn.getapp()
        '  ThisAddIn.PrintAPageFromEmail()
        RaiseEvent bla()

    End Sub
    Sub btnPdfPrint_Click(sender As Object, e As RibbonControlEventArgs) Handles btnPdfPrint.Click
        AVISO_Mail_Functions.printPDFs()
    End Sub


    Sub Button3_Click(sender As Object, e As RibbonControlEventArgs) Handles btnAvisoMail.Click, btnVollmachten.Click, btnGestellungsgarantien.Click, btnVertraege.Click
        If LOGIN_OK Then AVISO_Mail_Functions.addMailToAviso_Hauptfenster(sender)
    End Sub

    Public Function testConnection() As Boolean

        Dim connection = New VERAG_PROG_ALLGEMEIN.SQL
        If connection.getValueTxtBySql("SELECT 1", "FMZOLL") = 1 Then
            Return True
        Else
            MsgBox("ACHTUNG: Server nicht erreichbar!" & vbCrLf & "VERAG Addin wird beendet")
            Return False
        End If


    End Function

    Private Sub Button3_Click_1(sender As Object, e As RibbonControlEventArgs) Handles Button3.Click
        If LOGIN_OK Then AVISO_Mail_Functions.newBarsanMAIL()
    End Sub

    Private Sub btnDFDS_Click(sender As Object, e As RibbonControlEventArgs) Handles btnDFDS.Click
        If LOGIN_OK Then AVISO_Mail_Functions.newDSDFMAIL()
    End Sub
End Class

Public Class AVISO_Mail_Functions

    Shared Sub addMailToAviso_Hauptfenster(sender As Object)
        Try
            Dim explorer As Outlook.Explorer = Globals.ThisAddIn.Application.ActiveExplorer
            Dim selection As Outlook.Selection = explorer.Selection
            If selection.Count > 0 Then
                Dim selectedItem As Object = selection(1)

                Dim result = TryCast(selectedItem, Outlook.MailItem)

                If result IsNot Nothing Then

                    Dim mailItem As Outlook.MailItem = selectedItem
                    mailItem = DirectCast(mailItem, Outlook.MailItem)

                    addMailToAviso(mailItem, sender)
                Else

                    MsgBox("Die markierte Email kann nicht verarbeitet werden!" & vbNewLine & "Bitte andere Email verwenden.")
                End If
            End If

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


    Shared Function getAttachmentStringList(Mail) As List(Of String)

        Dim att As New List(Of String)
        For Each attachment As Outlook.Attachment In Mail.Attachments
            att.Add(attachment.FileName)
        Next
        Return att

    End Function
    Shared Sub addMailToAviso(mailItem As Outlook.MailItem, sender As Object)
        Try
            If mailItem IsNot Nothing Then
                ' Remove special characters from the file name and make sure it is not longer than 100 characters
                Dim strFileName As String = "E-Mail"
                If mailItem.Subject IsNot Nothing AndAlso mailItem.Subject <> "" Then
                    strFileName = Left(Regex.Replace(mailItem.Subject, "[\/\\\:\?!€,&'\*\<\>\|""]", ""), 100).Replace("""", "").Replace(vbTab, "_")
                    strFileName = VERAG_PROG_ALLGEMEIN.cDATENSERVER.replaceInvalidCahr(strFileName)
                    strFileName = strFileName.Replace("?", "")
                    strFileName = strFileName.Replace(".", "")
                    strFileName = strFileName.Replace("�", "")
                    strFileName &= ".msg"
                End If
                'Dim strFileName As String = "Mail.msg"
                Dim pdf_mail As cANHANGSART_ADDIN
                Dim SendungsId = -1
                Dim Art = ""
                Dim kdNr = -1
                Dim enableOverwritting = False
                Dim ATTACHMENTS_LIST As New List(Of String)
                Dim INFO As String = ""
                loadAttachment(mailItem, ATTACHMENTS_LIST)

                If isMail_EKOL(mailItem) Then
                    If vbYes = MsgBox("DFDS-Anhänge laden?", vbYesNoCancel) Then getATT_DFDS(mailItem, ATTACHMENTS_LIST,,, INFO)
                End If

                If isMail_Barsan(mailItem) Then
                    If vbYes = MsgBox("Barsan-Anhänge laden?", vbYesNoCancel) Then getATT_Barsan(mailItem, ATTACHMENTS_LIST, Art)
                End If

                Dim Bezeichnung = strFileName
                Dim AvisoId = Nothing

                AvisoId = getAvisoId(Bezeichnung, pdf_mail, SendungsId, Art, ATTACHMENTS_LIST, kdNr, sender, enableOverwritting, INFO) '

                If AvisoId < 0 Then Exit Sub

                Dim BezAnhang = If(Bezeichnung <> strFileName, Bezeichnung, "") 'Wenn die Bezeichnung geändert wurde --> und wenn nur 1 Anhang, dann wird die Bezeichnung für den Anhang verwendet.


                Select Case pdf_mail
                    Case cANHANGSART_ADDIN.PDF : saveAttachment(ATTACHMENTS_LIST, AvisoId, SendungsId, Art, BezAnhang)
                    Case cANHANGSART_ADDIN.YMAIL : saveMail(mailItem, AvisoId, Bezeichnung,, SendungsId, Art)
                    Case cANHANGSART_ADDIN.PDFANDMAIL : saveMail(mailItem, AvisoId, Bezeichnung,, SendungsId, Art) : saveAttachment(ATTACHMENTS_LIST, AvisoId, SendungsId, Art, BezAnhang)
                    Case cANHANGSART_ADDIN.PDF_DATENSERVER : saveAttachmentOnDatenserver(ATTACHMENTS_LIST, AvisoId, BezAnhang, sender, kdNr, enableOverwritting)
                    Case cANHANGSART_ADDIN.MAIL_DATENSERVER : saveMailOnDatenserver(mailItem, AvisoId, Bezeichnung, sender, , kdNr, enableOverwritting)
                    Case cANHANGSART_ADDIN.PDFANDMAIL_DATENSERVER : saveMailOnDatenserver(mailItem, AvisoId, Bezeichnung, sender, , kdNr) : saveAttachmentOnDatenserver(ATTACHMENTS_LIST, AvisoId, BezAnhang, sender, kdNr)
                    Case Else
                        saveMail(mailItem, AvisoId, Bezeichnung,, SendungsId, Art)
                End Select

                'If pdf_mail = "PDF" Then
                '    saveAttachment(ATTACHMENTS_LIST, AvisoId, SendungsId, Art, BezAnhang)
                'ElseIf pdf_mail = "PDFANDMAIL" Then
                '    saveMail(mailItem, AvisoId, Bezeichnung,, SendungsId, Art)
                '    saveAttachment(ATTACHMENTS_LIST, AvisoId, SendungsId, Art, BezAnhang)
                'ElseIf pdf_mail = "PDFANDMAIL_DATENSERVER" Then
                '    saveMailOnDatenserver(mailItem, AvisoId, Bezeichnung, sender,, kdNr)
                '    saveAttachmentOnDatenserver(ATTACHMENTS_LIST, AvisoId, BezAnhang, sender, kdNr)
                'ElseIf pdf_mail = "ONLYPDF_DATENSERVER" Then
                '    saveAttachmentOnDatenserver(ATTACHMENTS_LIST, AvisoId, BezAnhang, sender, kdNr, enableOverwritting)
                'ElseIf pdf_mail = "ONLYMAIL_DATENSERVER" Then
                '    saveMailOnDatenserver(mailItem, AvisoId, Bezeichnung, sender, , kdNr)
                'Else 'ONLYMAIL
                '    saveMail(mailItem, AvisoId, Bezeichnung,, SendungsId, Art)
                'End If
            End If

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

    Shared Sub printPDFs()
        Dim cntPDFs = countPDFs()

        If cntPDFs > 0 Then
            If vbYes = MsgBox("Möchten Sie alle " & cntPDFs & " PDF-Anhänge drucken?", vbYesNoCancel) Then
                Try
                    Dim explorer As Outlook.Explorer = Globals.ThisAddIn.Application.ActiveExplorer
                    Dim selection As Outlook.Selection = explorer.Selection
                    If selection.Count > 0 Then
                        Dim selectedItem = selection(1)
                        Dim mailItem As Outlook.MailItem = selectedItem
                        If mailItem IsNot Nothing Then
                            Dim attachments As Outlook.Attachments = mailItem.Attachments
                            For Each attachment As Outlook.Attachment In mailItem.Attachments
                                'Dim io As New IO.FileInfo(attachment.PathName)
                                If attachment.FileName.EndsWith(".pdf") Then
                                    Dim TMP_PATH As String = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getTMPPath(attachment.FileName, ".pdf", False, False, "OutlookAttach_Print")
                                    attachment.SaveAsFile(TMP_PATH)

                                    Marshal.ReleaseComObject(attachment)
                                    If IO.File.Exists(TMP_PATH) Then

                                        VERAG_PROG_ALLGEMEIN.cFormularManager.PrintViaSpirePDF({TMP_PATH}) ', cboPrinter.SelectedItem.ToString)
                                        Try : IO.File.Delete(TMP_PATH) : Catch : End Try
                                    End If
                                End If

                            Next
                        End If

                    End If
                Catch ex As Exception
                    VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
                End Try
            End If
        End If
    End Sub
    Shared Sub newEKOLMAIL()
        Try
            Dim explorer As Outlook.Explorer = Globals.ThisAddIn.Application.ActiveExplorer
            Dim selection As Outlook.Selection = explorer.Selection
            If selection.Count > 0 Then
                Dim selectedItem = selection(1)
                Dim mailItem As Outlook.MailItem = selectedItem
                If mailItem IsNot Nothing Then
                    If AVISO_Mail_Functions.isMail_EKOL(mailItem) Then
                        VERAG_PROG_ALLGEMEIN.cFormularManager.PrintViaSpirePDF(AVISO_Mail_Functions.getATT_EKOL(mailItem))
                    End If
                End If
            End If
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
    End Sub


    Shared Sub newDSDFMAIL()
        Try
            Dim explorer As Outlook.Explorer = Globals.ThisAddIn.Application.ActiveExplorer
            Dim selection As Outlook.Selection = explorer.Selection
            If selection.Count > 0 Then
                Dim selectedItem = selection(1)
                Dim mailItem As Outlook.MailItem = selectedItem
                If mailItem IsNot Nothing Then
                    If AVISO_Mail_Functions.isMail_EKOL(mailItem) Then
                        VERAG_PROG_ALLGEMEIN.cFormularManager.PrintViaSpirePDF(AVISO_Mail_Functions.getATT_EKOL(mailItem))
                    End If
                End If
            End If
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
    End Sub

    Shared Sub newBarsanMAIL()
        Try
            Dim explorer As Outlook.Explorer = Globals.ThisAddIn.Application.ActiveExplorer
            Dim selection As Outlook.Selection = explorer.Selection
            If selection.Count > 0 Then
                Dim selectedItem = selection(1)
                Dim mailItem As Outlook.MailItem = selectedItem
                If mailItem IsNot Nothing Then
                    If AVISO_Mail_Functions.isMail_Barsan(mailItem) Then
                        Dim att = getATT_Barsan(mailItem)
                        'Dim result As MsgBoxResult = MsgBox("Wollen Sie die " & att.Count & " Barsan - PDF's ausdrucken?", vbYesNoCancel)
                        'If result = vbYes Then
                        '    VERAG_PROG_ALLGEMEIN.cFormularManager.PrintViaSpirePDF(att)
                        'End If
                    End If
                End If

            End If
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
    End Sub
    Shared Function initFirmaUser() As Boolean
        Dim LOGIN_OK = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "VERAG" 'DEFAULT

        Try
            Dim ADMIN As New cADMIN
            Try
                Dim WI = System.Security.Principal.WindowsIdentity.GetCurrent().Name
                If WI.Contains("\") Then
                    Dim Split() = WI.Split("\")
                    If Split(0).Contains("VERAG-NCTS") Then : VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "ATILLA"
                    ElseIf Split(0).Contains("VERAG") Then : VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "VERAG"
                    ElseIf Split(0).Contains("IMEX") Then : VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "IMEX"
                    ElseIf Split(0).Contains("UNISU") Then : VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "UNISPED"
                    End If

                    Dim UsrId As Integer = ADMIN.getUstId_ByAD(Split(0), Split(1))
                    If UsrId > 0 Then
                        Dim MA_TMP As New VERAG_PROG_ALLGEMEIN.cMitarbeiter(UsrId)
                        VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = If(MA_TMP.mit_firma = "ALL", MA_TMP.mit_FirmaHaupt, MA_TMP.mit_firma)
                        LOGIN_OK = ADMIN.checkLogin(MA_TMP.mit_username, MA_TMP.mit_pwd, VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA)
                    End If
                End If
            Catch ex As Exception
                '  VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
            End Try
            If Not LOGIN_OK Then
                LOGIN_OK = ADMIN.checkLogin("MAIL_USER", "VERAG_MAIL_USER_2017", VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA)
            End If
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
        Return LOGIN_OK
    End Function


    Shared Sub NewAviso_Hauptfenster()
        VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.clearTMPPath("OutlookAttach")

        Try

            Dim explorer As Outlook.Explorer = Globals.ThisAddIn.Application.ActiveExplorer
            Dim selection As Outlook.Selection = explorer.Selection
            If selection.Count > 0 Then
                Dim selectedItem = selection(1)
                Dim mailItem As Outlook.MailItem = selectedItem
                If mailItem IsNot Nothing Then
                    NewAviso(mailItem)
                End If

            End If

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

    Shared Sub MovedMail()
        Try
            Dim explorer As Outlook.Explorer = Globals.ThisAddIn.Application.ActiveExplorer
            Dim selection As Outlook.Selection = explorer.Selection
            If selection.Count > 0 Then
                Dim selectedItem = selection(1)
                Dim mailItem As Outlook.MailItem = selectedItem
                If mailItem IsNot Nothing Then
                    MsgBox("Du bist hier angelangt!")
                End If

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


    Shared Function getFirmaFromToMail(ToMail As String)
        If ToMail.Contains("@verag") Then Return "VERAG"
        If ToMail.Contains("@imex") Then Return "IMEX"
        If ToMail.Contains("@unisped") Then Return "UNISPED"
        If ToMail.Contains("@front-office") Then Return "FRONTOFFICE"
        Return ""
    End Function

    Shared Sub NewAviso(mailItem As Outlook.MailItem)

        Dim ATTACHMENTS_LIST As New List(Of String)
        Dim KundenNr = -1
        Dim EingangsDatum As Date = CDate("01.01.1990")
        Dim INFO As String = ""

        If mailItem IsNot Nothing Then

            Try

                'MsgBox(mailItem.To)
                'MsgBox(mailItem.)
                'MsgBox(getFirmaFromToMail(mailItem.To))
                Dim art = ""

                EingangsDatum = mailItem.ReceivedTime
                Dim senderMail = ""
                If mailItem.SenderEmailType = "EX" Then
                    senderMail = (mailItem.Sender.GetExchangeUser.PrimarySmtpAddress)
                Else
                    senderMail = (mailItem.SenderEmailAddress)
                End If


                KundenNr = cKundenKontakte.getKdNrFromMailAdress(senderMail, False) ' false, wenn mehrere Niederlassungen von Frimen im KdStamm vorhanden... falsche KdNr...

                If isMail_EKOL(mailItem) Then
                    If vbYes = MsgBox("DFDS-Anhänge laden?", vbYesNoCancel) Then getATT_DFDS(mailItem, ATTACHMENTS_LIST,,, INFO)
                End If
                'End If

                If isMail_Barsan(mailItem) Then
                    If vbYes = MsgBox("Barsan-Anhänge laden?", vbYesNoCancel) Then getATT_Barsan(mailItem, ATTACHMENTS_LIST, art)
                End If


                loadAttachment(mailItem, ATTACHMENTS_LIST)


                cGlobal.Aktive_ID = 0
                Dim mainForm As New AVISO.frmEintragAviso(INFO)
                mainForm.ATT = ATTACHMENTS_LIST
                If KundenNr > 0 Then
                    AddHandler mainForm.Shown, Sub()
                                                   mainForm.kdAvisierer.KdNr = KundenNr
                                               End Sub
                End If
                If EingangsDatum > CDate("01.01.1990") Then
                    mainForm.EingangsDatum = EingangsDatum
                End If

                If INFO <> "" Then
                    If mainForm.txtÄnderungen.Text <> "" Then
                        mainForm.txtÄnderungen.Text &= vbNewLine & INFO
                    Else
                        mainForm.txtÄnderungen.Text = INFO
                    End If
                End If

                mainForm.lblAnhaenge.Text &= ATTACHMENTS_LIST.Count

                mainForm.TopMost = True
                mainForm.StartFromOUTLOOK = True
                mainForm.ShowDialog()
                ATTACHMENTS_LIST = mainForm.ATT




                If cGlobal.Aktive_ID > 0 Then

                    saveAttachment(ATTACHMENTS_LIST, cGlobal.Aktive_ID, -1, art, "")
                    saveMail(mailItem, cGlobal.Aktive_ID,, False)

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

                    'If attachments IsNot Nothing Then
                    '    Marshal.ReleaseComObject(attachments)
                    'End If
                    If mailItem IsNot Nothing Then
                        Marshal.ReleaseComObject(mailItem)
                    End If
                    'If currInspector IsNot Nothing Then
                    '    Marshal.ReleaseComObject(currInspector)
                    'End If

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

        End If
    End Sub


    Shared Sub saveAttachment(ByRef ATTACHMENTS_LIST As List(Of String), AvisoId As Integer, SendungsId As Integer, Art As String, BezeichnungAnh As String)
        Try
            If AvisoId > 0 Then
                If ATTACHMENTS_LIST.Count > 1 Then BezeichnungAnh = "" ' nur wenn 1 Anhang wird die Bezeichnung übernommen.
                For Each ATT In ATTACHMENTS_LIST
                    Dim fi As New IO.FileInfo(ATT)
                    Dim Bezeichnung = BezeichnungAnh
                    If Bezeichnung = "" Then Bezeichnung = fi.Name
                    Dim typ = ""
                    If AVISO.frmSendungAnhangImport.getFileTypeValid(fi.Extension, typ) Then
                        AVISO.frmSendungAnhangImport.saveToDS(AvisoId, Bezeichnung, ATT, Art, typ, ,,, If(SendungsId > 0, SendungsId, Nothing))
                    End If
                Next
            End If
        Catch ex As Exception
            MsgBox(System.Reflection.MethodInfo.GetCurrentMethod.Name & ex.Message & ex.StackTrace)
        End Try
    End Sub

    Shared Sub saveAttachmentOnDatenserver(ByRef ATTACHMENTS_LIST As List(Of String), AvisoId As Integer, BezeichnungAnh As String, Optional sender As Object = Nothing, Optional kdNr As Integer = -1, Optional enableOverwritting As Boolean = False)
        Try
            If AvisoId > 0 Then
                Dim multifiles As Boolean = False
                If ATTACHMENTS_LIST.Count > 1 Then BezeichnungAnh = "" : multifiles = True ' nur wenn 1 Anhang wird die Bezeichnung übernommen.
                For Each ATT In ATTACHMENTS_LIST
                    Dim fi As New IO.FileInfo(ATT)
                    Dim Bezeichnung = BezeichnungAnh
                    If Bezeichnung = "" Then Bezeichnung = fi.Name

                    uploadAttachments(sender, AvisoId, fi.FullName, Bezeichnung, kdNr, enableOverwritting, multifiles)

                Next
            End If
        Catch ex As Exception
            MsgBox(System.Reflection.MethodInfo.GetCurrentMethod.Name & ex.Message & ex.StackTrace)
        End Try

    End Sub


    Shared Sub loadAttachment(ByRef mail As Outlook.MailItem, ByRef ATTACHMENTS_LIST As List(Of String))

        Dim attachments As Outlook.Attachments = Nothing

        Try
            attachments = mail.Attachments
            For Each attachment As Outlook.Attachment In mail.Attachments
                If Not isEmbedded(attachment) Then

                    'Next
                    'For i As Integer = 1 To attachments.Count
                    '    Dim attachment As Outlook.Attachment = attachments.Item(i)
                    ' MsgBox(attachment.FileName)
                    Dim specialFolder = "OutlookAttach\Outlook_" & Now.ToString("ddMMyy_HHmmss.ffff")
                    While IO.Directory.Exists(VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.TMP_PATH & specialFolder)
                        specialFolder = "OutlookAttach\Outlook_" & Now.ToString("ddMMyy_HHmmss.ffff")
                    End While
                    'Dim iof As New IO.FileInfo(attachment.PathName)
                    Dim fileName As String = attachment.FileName
                    fileName = Right(Regex.Replace(fileName, "[\/\\\:\?!€,&'\*\<\>\|""]", ""), 100).Replace("""", "").Replace(vbTab, "_")
                    fileName = fileName.Replace("""", "")
                    fileName = fileName.Replace("“", "")
                    fileName = fileName.Replace("”", "")
                    Dim TMP_PATH As String = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getTMPPath(fileName, "", False, False, specialFolder)
                    attachment.SaveAsFile(TMP_PATH)
                    Dim iof As New IO.FileInfo(TMP_PATH)

                    ' If iof.Length > 5000 Then ' > 5 KB
                    ATTACHMENTS_LIST.Add(TMP_PATH)
                    ' End If 
                End If
                Marshal.ReleaseComObject(attachment)
            Next
        Catch ex As Exception
            MsgBox(ex.Message, ex.StackTrace)
        Finally
            If attachments IsNot Nothing Then
                Marshal.ReleaseComObject(attachments)
            End If
            If mail IsNot Nothing Then
                '   Marshal.ReleaseComObject(mail)
            End If
            'If currInspector IsNot Nothing Then
            '    Marshal.ReleaseComObject(currInspector)
            'End If
        End Try
    End Sub

    Shared Function isEmbedded(attachment As Outlook.Attachment) As Boolean
        If attachment.Type <> Outlook.OlAttachmentType.olByValue Then
            Return True
        End If
        Dim iTmp As Integer = attachment.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x37050003")
        If iTmp = 6 Then
            Return True
        End If
        iTmp = attachment.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x37140003")
        If iTmp = 4 Then
            Return True
        End If

        Return False
    End Function

    Shared Function countPDFs() As Integer
        countPDFs = 0
        Try
            Dim explorer As Outlook.Explorer = Globals.ThisAddIn.Application.ActiveExplorer
            Dim selection As Outlook.Selection = explorer.Selection
            If selection.Count > 0 Then
                Dim selectedItem = selection(1)
                Dim mailItem As Outlook.MailItem = selectedItem
                If mailItem IsNot Nothing Then
                    Dim attachments As Outlook.Attachments = mailItem.Attachments
                    For Each attachment As Outlook.Attachment In mailItem.Attachments
                        'Dim io As New IO.FileInfo(attachment.PathName)
                        If attachment.FileName.EndsWith(".pdf") Then
                            countPDFs += 1
                        End If
                        'O.File.Delete(TMP_PATH)
                    Next
                End If

            End If
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
    End Function
    Public Shared Function GetTempFilePathWithExtension(ByVal extension As String) As String
        Dim path = IO.Path.GetTempPath()
        Dim fileName = Guid.NewGuid().ToString() & extension
        Return IO.Path.Combine(path, fileName)
    End Function


    Shared Function isMail_EKOL(mailItem As Outlook.MailItem) As Boolean
        Try
            If mailItem IsNot Nothing Then
                Dim srch As String = "<a href=""https://web01.ekoltransport.com.tr/dfdsdocumentservice/download/"
                'Dim srch As String = "<a href=""https://web01.ekol.com/documentservice/download/"
                Return mailItem.HTMLBody.ToString.Contains(srch)
            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

    Shared Function isMail_Barsan(mailItem As Outlook.MailItem) As Boolean
        '--------------------- WIRD NICHT MEHR GENUTZT
        Return False
        '--------------------- WIRD NICHT MEHR GENUTZT
        Try
            If mailItem IsNot Nothing Then
                Dim srch As String = "<a href=""https://portal.barsan.com/Dokuman/DokumanGoster.aspx"
                Return mailItem.HTMLBody.ToString.Contains(srch)
            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


    Shared Function getATT_EKOL(mailItem As Outlook.MailItem, Optional ByRef ATT As List(Of String) = Nothing, Optional ByRef LKW_Nr As String = "", Optional ByRef RefNr As String = "", Optional ByRef INFO As String = "") As List(Of String)
        If ATT Is Nothing Then ATT = New List(Of String)
        Try
            If mailItem Is Nothing Then Return ATT

            Dim html = mailItem.HTMLBody
            Dim srch As String = "<a href=""https://web01.ekoltransport.com.tr/dfdsdocumentservice/download/"
            ' Dim srch As String = "<a href=""https://web01.ekol.com/documentservice/download/"
            If html.ToString.Contains(srch) Then

                Dim myDelims As String() = New String() {srch}
                Dim sp = html.Split(myDelims, StringSplitOptions.None)

                ' Dim sp = html.ToString.Split(srch.ToString)
                Dim cnt = 0
                For Each l In sp
                    If cnt > 0 AndAlso l.Contains(""">") Then ' ENDE
                        Dim link = ("https://web01.ekoltransport.com.tr/dfdsdocumentservice/download/" & l.ToString.Substring(0, l.ToString.IndexOf(""">")))
                        'Dim link = ("https://web01.ekol.com/documentservice/download/" & l.ToString.Substring(0, l.ToString.IndexOf(""">")))

                        'Ansonten stüzt der Webservice-Aufruf ab! ABER -> For .NET 4.7 or later, the System.Net.ServicePointManager.SecurityProtocol should not be set manualy!
                        System.Net.ServicePointManager.SecurityProtocol = System.Net.ServicePointManager.SecurityProtocol Or SecurityProtocolType.Tls11 Or SecurityProtocolType.Tls12

                        Dim TMP_PATH = GetTempFilePathWithExtension(".pdf")
                        Try
                            My.Computer.Network.DownloadFile(link, TMP_PATH)
                            If IO.File.Exists(TMP_PATH) AndAlso TMP_PATH.Contains(".pdf") Then
                                ATT.Add(TMP_PATH)
                            End If
                        Catch ex As Exception

                        End Try

                    End If
                    cnt += 1
                Next
            End If
            LKW_Nr = getEKOL_Var(html, "Position :")
            RefNr = getEKOL_Var(html, "Truck :")
            INFO = getEKOL_Var(html, "Route :")

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


    Shared Function getATT_DFDS(mailItem As Outlook.MailItem, Optional ByRef ATT As List(Of String) = Nothing, Optional ByRef LKW_Nr As String = "", Optional ByRef RefNr As String = "", Optional ByRef INFO As String = "") As DataTable
        Try

            If ATT Is Nothing Then ATT = New List(Of String)

            Dim dt As New DataTable()
            dt.Columns.AddRange({
    New DataColumn("Record"),
    New DataColumn("Consignee"),
    New DataColumn("Quantity"),
    New DataColumn("GrossWeight"),
    New DataColumn("OrderCustoms"),
    New DataColumn("Address"),
    New DataColumn("Code"),
    New DataColumn("OperationType"),
    New DataColumn("Links") ' store ALL links (doc + cmr)
})

            Dim doc As New HtmlAgilityPack.HtmlDocument()
            doc.LoadHtml(mailItem.HTMLBody)

            Dim rows = doc.DocumentNode.SelectNodes("//tr")

            If rows Is Nothing Then Return dt

            For Each row In rows

                Dim cells = row.SelectNodes("td")
                If cells Is Nothing Then Continue For

                Dim recordText As String = Clean(cells(0).InnerText)

                If Not IsNumeric(recordText) Then Continue For

                Dim linkNodes = row.SelectNodes(".//a")
                Dim links As New List(Of String)

                If linkNodes IsNot Nothing Then
                    For Each ln In linkNodes
                        Dim href = ln.GetAttributeValue("href", "")
                        If href <> "" Then links.Add(href)
                    Next
                End If

                Dim GetCell = Function(index As Integer) As String
                                  If cells.Count > index Then
                                      Return Clean(cells(index).InnerText)
                                  End If
                                  Return ""
                              End Function

                dt.Rows.Add(recordText, GetCell(1), GetCell(2), GetCell(3), GetCell(4), GetCell(5), GetCell(6), GetCell(7), String.Join("|", links))

            Next


            Dim counter As Integer = 1
            Dim sendungsNrOld As String = ""
            Dim missingDocuments As String = ""

            For Each r As DataRow In dt.Rows

                Dim links = r("Links").ToString().Split("|"c)

                For Each linkRaw In links

                    If String.IsNullOrWhiteSpace(linkRaw) Then Continue For

                    If linkRaw.Contains("dfdsdocumentservice/download") Or linkRaw.Contains("quadronet.dfds.com/link") Then

                        Dim link As String = linkRaw.Trim()

                        If link.EndsWith("%20") Then
                            link = link.Substring(0, link.Length - 3)
                        End If

                        Dim sendungsNr As String = r("Record").ToString()
                        Dim descr As String = r("Consignee").ToString()

                        If descr <> "" Then
                            descr = descr.Replace(";", "_").Replace(".", "_").Replace(" ", "_")

                            descr = VERAG_PROG_ALLGEMEIN.cDATENSERVER.replaceInvalidCahr(descr)
                        End If

                        If sendungsNrOld <> "" AndAlso sendungsNrOld <> sendungsNr Then
                            counter = 1
                        End If

                        Dim filename As String = sendungsNr & "_" & counter &
                                    If(descr <> "", "_" & descr, "")

                        Dim file = VERAG_PROG_ALLGEMEIN.cFormularManager.getFile_FromURLStream_NEW(link, filename,, False)

                        If IO.File.Exists(file) Then
                            ATT.Add(file)
                        Else
                            If missingDocuments <> "" Then
                                missingDocuments &= vbNewLine & filename
                            Else
                                missingDocuments = "fehlende Dokumente:" & vbNewLine & filename
                            End If
                        End If

                        counter += 1
                        sendungsNrOld = sendungsNr

                    End If

                Next

            Next

            If missingDocuments <> "" Then
                INFO = missingDocuments
            End If

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

    End Function

    Private Shared Function Clean(input As String) As String
        If String.IsNullOrWhiteSpace(input) Then Return ""
        Return HtmlEntity.DeEntitize(input).
           Replace("o:p", "").
           Replace(vbCr, "").
           Replace(vbLf, "").
           Trim()
    End Function


    Shared Function getATT_Barsan(mailItem As Outlook.MailItem, Optional ByRef ATT As List(Of String) = Nothing, Optional ByRef art As String = "") As List(Of String)

        If ATT Is Nothing Then ATT = New List(Of String)
        Try

            If mailItem Is Nothing Then Return ATT

            Dim html = mailItem.HTMLBody
            html = html.Replace("<b>•</B>", "<b>•</b>")
            html = html.Replace("<B>•</B>", "<b>•</b>")
            html = html.Replace("<B>•</b>", "<b>•</b>")

            Dim srch As String = "<b>•</b>"
            If html.ToString.Contains(srch) Then

                Dim myDelims As String() = New String() {srch}
                Dim sp = html.Split(myDelims, StringSplitOptions.None)

                ' Dim sp = html.ToString.Split(srch.ToString)
                Dim cnt = 0

                Dim pdfNameWithCounter As String = ""
                Dim counter As Integer = 1
                Dim lastPdfName As String = ""
                Dim linkinHTML = "<a href=""https://portal.barsan.com/Dokuman/DokumanGoster.aspx"
                For Each l In sp
                    If cnt > 0 AndAlso l.Contains(""">") Then ' ENDE

                        Dim lastIndexLink = l.ToString.IndexOf(linkinHTML) + linkinHTML.Length
                        Dim link = ("https://portal.barsan.com/Dokuman/DokumanGoster.aspx" & l.ToString.Substring(lastIndexLink, l.ToString.IndexOf(""">") - lastIndexLink))


                        'Ansonten stüzt der Webservice-Aufruf ab! ABER -> For .NET 4.7 or later, the System.Net.ServicePointManager.SecurityProtocol should not be set manualy!
                        System.Net.ServicePointManager.SecurityProtocol = System.Net.ServicePointManager.SecurityProtocol Or SecurityProtocolType.Tls11 Or SecurityProtocolType.Tls12
                        If l.ToString.ToLower().Contains(".pdf") Then

                            Dim pdfNameOrigin As String = ""
                            Dim pdfStringName = l.ToString.ToLower().Substring(0, l.ToString.IndexOf(linkinHTML) - 1).Trim()
                            Dim pdfNamefromFile = l.ToString.ToLower().Substring(l.ToString.IndexOf(""">") + 2, l.ToString.IndexOf(".pdf") - l.ToString.IndexOf(""">") + 2).Trim()
                            pdfNamefromFile = pdfNamefromFile.Replace(".pdf", "")
                            Dim numName As Boolean = False



                            For Each x As Char In pdfStringName
                                If Char.IsDigit(x) Then
                                    pdfNameOrigin &= x
                                    numName = True
                                Else
                                    Exit For
                                End If
                            Next
                            If lastPdfName <> "" AndAlso lastPdfName = pdfNameOrigin Then
                                pdfNameWithCounter = pdfNameOrigin & "_" & counter
                                counter = counter + 1
                            Else
                                If pdfNameWithCounter <> "" Then
                                    counter = 1
                                    pdfNameWithCounter = ""
                                End If
                            End If

                            Dim pdf = VERAG_PROG_ALLGEMEIN.cFormularManager.getPDFViaSpirePDF_FromURLStream(link, IIf(pdfNameWithCounter <> "", pdfNameWithCounter, IIf(numName = False, pdfNamefromFile, pdfNameOrigin)),, False)
                            If pdfNameOrigin <> "" Then lastPdfName = pdfNameOrigin
                            If IO.File.Exists(pdf) Then
                                ATT.Add(pdf)
                            End If
                            If pdfNamefromFile.ToLower.Contains("bordro") Then art = "Bordro"
                        End If

                    End If
                    cnt += 1
                Next
            End If
            'LKW_Nr = getEKOL_Var(html, "Position :")
            'RefNr = getEKOL_Var(html, "Truck :")
            'INFO = getEKOL_Var(html, "Route :")

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


    Shared Function getEKOL_Var(html, varName, Optional splitTo = "<br>")
        If html.contains(varName) Then
            Dim split = html.split(varName)
            If split(1).ToString.Contains(splitTo) Then
                Dim split2 = html.split(splitTo)
                Return split2(0).ToString.Trim
            End If
        End If
        Return ""
    End Function

    Shared Sub saveMail(mailItem As Outlook.MailItem, AvisoId As Integer, Optional bezeichnung As String = "", Optional saveAttachments As Boolean = True, Optional SendungsId As Integer = -1, Optional Art As String = "")
        '  Dim mailItem As Outlook.MailItem = mailItemTMP.Copy
        Try
            If AvisoId > 0 Then
                ' The full path will place the email in the user's temporary folder 
                If bezeichnung = "" Then bezeichnung = Left(Regex.Replace(mailItem.Subject, "[\/\\\:\?\*\<\>\|""]", ""), 100).Replace("""", "").Replace(vbTab, " ") & ".msg"

                bezeichnung = VERAG_PROG_ALLGEMEIN.cDATENSERVER.replaceInvalidCahr(bezeichnung)

                Dim strTmpPath As String = System.IO.Path.GetTempPath() & bezeichnung & If(bezeichnung.EndsWith(".msg"), "", ".msg")
                ' Save the email to the user's temp folder and convert it to a .MSG
                'Dim cnt = 0
                'If Not saveAttachments Then
                '    While mailItem.Attachments.Count > 0 And cnt < 100
                '        mailItem.Attachments.Remove(1) : cnt += 1 '  Remove(1)  stimmt
                '    End While
                'End If

                mailItem.SaveAs(strTmpPath, Outlook.OlSaveAsType.olMSG)


                '     UploadDocument("http://testURL/sites/testing", "Documents", strFileName, btSaveFile)
                If AVISO.frmSendungAnhangImport.saveToDS(AvisoId, bezeichnung, strTmpPath, Art, "MSG",,,, If(SendungsId, SendungsId, Nothing)) Then
                    '  MsgBox("Anhang wurde hinzugefügt!")
                End If
                ' Clean up the temporary .MSG file from the user's temporary folder
                System.IO.File.Delete(strTmpPath)
            End If

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        Finally
            If mailItem IsNot Nothing Then
                Marshal.ReleaseComObject(mailItem)
            End If
        End Try
    End Sub

    Shared Sub saveMailOnDatenserver(mailItem As Outlook.MailItem, AvisoId As Integer, Optional bezeichnung As String = "", Optional sender As Object = Nothing, Optional saveAttachments As Boolean = True, Optional kdNr As Integer = -1, Optional enableOverwritting As Boolean = False)
        Try
            If AvisoId > 0 Then

                If bezeichnung = "" Then
                    bezeichnung = Left(Regex.Replace(mailItem.Subject, "[\/\\\:\?\*\<\>\|""]", ""), 100).Replace("""", "").Replace(vbTab, " ") & ".msg"
                End If

                bezeichnung = VERAG_PROG_ALLGEMEIN.cDATENSERVER.replaceInvalidCahr(bezeichnung)

                Dim strTmpPath As String = System.IO.Path.GetTempPath() & bezeichnung & If(bezeichnung.EndsWith(".msg"), "", ".msg")

                mailItem.SaveAs(strTmpPath, Outlook.OlSaveAsType.olMSG)

                uploadAttachments(sender, AvisoId, strTmpPath, bezeichnung, kdNr, enableOverwritting)

                ' Clean up the temporary .MSG file from the user's temporary folder
                System.IO.File.Delete(strTmpPath)
            End If
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        Finally
            If mailItem IsNot Nothing Then
                Marshal.ReleaseComObject(mailItem)
            End If
        End Try
    End Sub


    Shared Function getAvisoId(ByRef Bezeichnung, ByRef pdf_mail, ByRef SendungsId, ByRef Art, ByRef Att, ByRef kdNr, ByVal sender, ByRef enableOverwritting, Optional ByRef INFO = "") As Integer


        Select Case sender.name
            Case "btnAvisoMail", "btnAvisoMail2"
                Dim frmAvisoAnfügen As New frmAvisoAnfuegen(Bezeichnung, Art)
                frmAvisoAnfügen.ATT = Att
                If INFO <> "" Then
                    MsgBox(INFO)
                    frmAvisoAnfügen.INFO = INFO
                End If

                If frmAvisoAnfügen.ShowDialog = DialogResult.OK Then
                    Dim AvisoId = frmAvisoAnfügen.AvisoId
                    SendungsId = frmAvisoAnfügen.SendungsId
                    Bezeichnung = frmAvisoAnfügen.Bezeichnung
                    pdf_mail = frmAvisoAnfügen.PDF_MAIL
                    Art = frmAvisoAnfügen.cboArt._value
                    Att = frmAvisoAnfügen.ATT

                    If INFO <> "" Then
                        Dim VermerkeDAL As New cVermerkeDAL
                        Dim myVermerk As New cVermerk
                        myVermerk.VermerkID = 0
                        myVermerk.AvisoID = frmAvisoAnfügen.AvisoId
                        myVermerk.SendungID = SendungsId
                        myVermerk.Datum = Now
                        myVermerk.Mitarbeiter = cGlobal.AktiverMitarbeiter.Mitarbeiter
                        myVermerk.MitarbeiterId = cGlobal.AktiverMitarbeiter.MitarbeiterID
                        myVermerk.Hinweis_Vermerk = INFO
                        myVermerk.VermerkCodeId = 123
                        VermerkeDAL.SpeichernVermerk(myVermerk)
                    End If

                    Return AvisoId
                    End If

                    Return -1

            Case Else
                Dim frmAvisoFormularAnfuegen As New frmAvisoFormularAnfuegen(Bezeichnung, sender)
                frmAvisoFormularAnfuegen.ATT = Att
                If frmAvisoFormularAnfuegen.ShowDialog = DialogResult.OK Then
                    Dim AvisoId = frmAvisoFormularAnfuegen.AvisoId
                    kdNr = frmAvisoFormularAnfuegen.KdNr
                    Bezeichnung = frmAvisoFormularAnfuegen.Bezeichnung
                    pdf_mail = frmAvisoFormularAnfuegen.PDF_MAIL
                    Att = frmAvisoFormularAnfuegen.ATT
                    enableOverwritting = frmAvisoFormularAnfuegen.enableOverwritting

                    Return AvisoId

                End If

                Return -1

        End Select


    End Function



    Shared Sub uploadAttachments(sender As Object, AvisoId As Integer, strTmpPath As String, Optional bezeichnung As String = "", Optional kdNr As Integer = -1, Optional enableOverweriting As Boolean = False, Optional multifiles As Boolean = False)

        If sender Is Nothing Then
            Exit Sub
        End If


        Dim button = sender

        Select Case button.Name

            Case "btnVollmachten"
                Dim DS = New VERAG_PROG_ALLGEMEIN.cDATENSERVER("DOKUMENTE", "VOLLMACHTEN", "VMID_" & AvisoId, "", "", bezeichnung, kdNr, multifiles)
                Dim path = DS.uploadDataToDATENSERVER(strTmpPath)
                If path Then
                    Dim c As New cKundenVollmachten(AvisoId)
                    If bezeichnung.ToLower.EndsWith(".pdf") Then
                        c.kdvm_datenarchivId = DS.da_id
                    Else
                        c.kdvm_emailId = DS.da_id
                    End If
                    c.SAVE()
                End If

            Case "btnVertraege"

                'Bei Verträge können PDF und MAIL angehängt werden!

                If bezeichnung.ToLower.EndsWith(".pdf") Then
                    Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER("DOKUMENTE", "KD_VERTRÄGE", "", "", "", "KV_" & AvisoId, kdNr, multifiles)
                    Dim path = DS.uploadDataToDATENSERVER(strTmpPath,,,,,, enableOverweriting)
                    If path Then
                        Dim KV As New VERAG_PROG_ALLGEMEIN.cKundenVertraege(AvisoId)
                        KV.kv_datenarchivId = DS.da_id
                        KV.SAVE()
                    End If

                Else
                    Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER("DOKUMENTE", "KD_VERTRÄGE", "", "", "", "KV_Mail_" & AvisoId, kdNr, multifiles)
                    Dim path = DS.uploadDataToDATENSERVER(strTmpPath,,,,,, enableOverweriting)
                    If path Then
                        Dim KV As New VERAG_PROG_ALLGEMEIN.cKundenVertraege(AvisoId)
                        KV.kv_datenarchivId_mail = DS.da_id
                        KV.SAVE()
                    End If

                End If

            Case "btnGestellungsgarantien"

                Dim gg As New VERAG_PROG_ALLGEMEIN.cGestellungsgarantien(AvisoId)
                Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER("DOKUMENTE", "GESTELLUNGS_GARANTIEN", "", "", "", "GG_" & gg.gg_Zollamt, kdNr, multifiles)
                Dim path = DS.uploadDataToDATENSERVER(strTmpPath,,,,,, enableOverweriting)
                If path Then
                    gg.gg_datenarchivId = DS.da_id
                    gg.SAVE()
                End If

        End Select

    End Sub


End Class
