


' Aufruf des Webservice von FinanzOnline zur prüfung der UID-Nummer
' Aufgrund von verzögerten Bestätigungen wurd diese Funktion deaktiviert!!!

Imports System.IO
Imports System.Net
Imports System.Text
Imports System.Xml
Imports System.Xml.Serialization

Public Class cEORIWebService




    'Public Shared SESSION_ID As String = ""


    'Shared Function Call_Web_Service_MethodUID_Abfrage(ByRef session As String, ByVal txtFirma As String, ByVal txtEORI As String) As String
    '    Try
    '        ' Return CallWebService.uidAbfrage(session, tid, benid, My.Resources.UID_Nr, txtUid.Text, uidAbfrageRequestStufe.Item2, "", "", "", "", "", "", "")
    '        'Dim s() As Object = CallWebService.uidAbfrage(session, tid, benid, My.Resources.UID_Nr, txtUid.Text, uidAbfrageRequestStufe.Item2, "", "", "", "", "", "", "")

    '        Dim EORIvalidation As New eu.europa.ec1.validation


    '        Dim msg As String = ""
    '        Dim name As String = ""
    '        Dim adrz1 As String = ""
    '        Dim adrz2 As String = ""
    '        Dim adrz3 As String = ""
    '        Dim adrz4 As String = ""
    '        Dim adrz5 As String = ""
    '        Dim adrz6 As String = ""


    '        Dim returnInt As eu.europa.ec1.eoriValidationResult = EORIvalidation.validateEORI({txtEORI})


    '        If returnInt.result.Count > 0 Then
    '            MsgBox(returnInt.result)

    '            'Dim firma As String = name & vbNewLine & adrz1
    '            'If adrz2 <> "" Then firma = firma & vbNewLine & adrz2
    '            'If adrz3 <> "" Then firma = firma & vbNewLine & adrz3
    '            'If adrz4 <> "" Then firma = firma & vbNewLine & adrz4
    '            'If adrz5 <> "" Then firma = firma & vbNewLine & adrz5
    '            'If adrz6 <> "" Then firma = firma & vbNewLine & adrz6

    '            '  frmUIDCheck.firmaUIDFinanzOnline = firma
    '            ' frmUIDCheck.firmaUIDProgramm = txtFirma
    '            ' frmUIDCheck.uidnr = txtUid
    '            ' frmUIDCheck.Show()
    '        Else
    '            MsgBox(returnInt)
    '        End If
    '        Return ""
    '    Catch ex As Exception
    '        MsgBox(ex.Message & ex.StackTrace)
    '    End Try
    '    Return "-1"
    'End Function


    'Shared Function genUID_Formular(ByVal txtUid As String, Optional AvisoId As Integer = -1, Optional SendungsId As Integer = -1, Optional ByRef UID_ERG As Integer = -1) As String 'SESSION_ID wir nur zurückgegeben
    '    Try

    '        Dim msgErgebnis = ""
    '        Dim tmp_SESSION_ID = ""
    '        Dim Firma = ""

    '        UID_ERG = 0 'Call_Web_Service_MethodUID_Abfrage_NEU2020(txtUid, Firma, tmp_SESSION_ID, msgErgebnis)

    '        If UID_ERG = 0 Or UID_ERG = 1 Then
    '            Select Case UID_ERG
    '                Case 0 : msgErgebnis = "UID-Nr. GÜLTIG   -   OK"
    '                Case 1 : msgErgebnis = "UID-Nr. UNGÜLTIG"
    '            End Select

    '            Dim PdfTmp = "" 'SDL.FormularManagerNEU.UID_PRUEFUNG(msgErgebnis, Firma, tmp_SESSION_ID, uid, txtUid, tid, AvisoId, SendungsId)
    '            If PdfTmp <> "" Then

    '                Dim fileName = "UID_Prüfung_" & txtUid & ".pdf"
    '                Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER("DOKUMENTE", "UID_PRUEFUNG", VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA, txtUid, Now.ToString("ddMMyy_HHmmss.ffff"), fileName, -1, False) 'Now.ToString("ddMMyy_HHmmss.ffff")
    '                If Not DS.uploadDataToDATENSERVER(PdfTmp) Then MsgBox("Fehler beim Speichern: Datenserver!") : Return False
    '                If DS.da_id <= 0 Then MsgBox("Keine DocId!") : Return False
    '                Dim da_id = DS.da_id
    '                Dim destPath = DS.GET_TOP1_PATH

    '                If AvisoId > 0 And SendungsId > 0 Then
    '                    Dim ANH As New VERAG_PROG_ALLGEMEIN.cAvisoAnhaenge(AvisoId, fileName, DS.da_id, "UID", "PDF", SendungsId)
    '                    If Not ANH.SAVE Then MsgBox("Fehler beim Anhang speichern!") : Return False
    '                    Dim anhId = ANH.anh_id
    '                End If
    '                Return destPath


    '            End If
    '        Else
    '            MsgBox(msgErgebnis)
    '        End If

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

    '    Return ""

    'End Function

    Shared _url = "http://ec.europa.eu/taxation_customs/dds2/eos/validation/services/validation"




    Shared Function genEORI_Formular(ByVal txtEORI As String, Optional AvisoId As Integer = -1, Optional SendungsId As Integer = -1, Optional ByRef EORI_ERGInt As Integer = -1) As String 'SESSION_ID wir nur zurückgegeben
        Try

            Dim msgErgebnis = ""
            Dim tmp_SESSION_ID = ""
            Dim Firma = ""

            Dim EORI_ERG = ValidateEoriNumber(txtEORI)


            If EORI_ERG.Result.Count > 0 Then

                If EORI_ERG.Result(0).Status = 0 Or EORI_ERG.Result(0).Status = 1 Then

                    Firma = EORI_ERG.Result(0).Name & vbNewLine
                    Firma &= EORI_ERG.Result(0).Street & vbNewLine
                    Firma &= EORI_ERG.Result(0).Country & " " & EORI_ERG.Result(0).PostalCode & " " & EORI_ERG.Result(0).City
                    Firma = Firma.Trim

                    EORI_ERGInt = EORI_ERG.Result(0).Status
                    Select Case EORI_ERG.Result(0).Status
                        Case 0 : msgErgebnis = "EORI-Nr. GÜLTIG   -   OK"
                        Case 1 : msgErgebnis = "EORI-Nr. UNGÜLTIG"
                    End Select

                    Dim PdfTmp = SDL.FormularManagerNEU.EORI_PRUEFUNG(msgErgebnis, Firma, tmp_SESSION_ID, txtEORI, AvisoId, SendungsId)
                    If PdfTmp <> "" Then

                        Dim fileName = "EORI_Prüfung_" & txtEORI & ".pdf"
                        Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER("DOKUMENTE", "EORI_PRUEFUNG", VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA, txtEORI, Now.ToString("ddMMyy_HHmmss.ffff"), fileName, -1, False) 'Now.ToString("ddMMyy_HHmmss.ffff")
                        If Not DS.uploadDataToDATENSERVER(PdfTmp) Then MsgBox("Fehler beim Speichern: Datenserver!") : Return False
                        If DS.da_id <= 0 Then MsgBox("Keine DocId!") : Return False
                        Dim da_id = DS.da_id
                        Dim destPath = DS.GET_TOP1_PATH

                        If AvisoId > 0 And SendungsId > 0 Then
                            Dim ANH As New VERAG_PROG_ALLGEMEIN.cAvisoAnhaenge(AvisoId, fileName, DS.da_id, "EORI", "PDF", SendungsId)
                            If Not ANH.SAVE Then MsgBox("Fehler beim Anhang speichern!") : Return False
                            Dim anhId = ANH.anh_id
                        End If
                        Return destPath


                    End If
                Else
                    MsgBox(EORI_ERG.Result(0).StatusDescr)
                End If
            Else
                MsgBox("Fehler bei der Prüfung der EORI-Nummer. WebService evtl. nicht verfügbar.")
            End If
            Return ""

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

        Return ""

    End Function


    Shared Function genEORI_FormularWithoutSaving(ByVal txtEORI As String, Optional AvisoId As Integer = -1, Optional SendungsId As Integer = -1, Optional ByRef EORI_ERGInt As Integer = -1) As String 'SESSION_ID wir nur zurückgegeben
        Try

            Dim msgErgebnis = ""
            Dim tmp_SESSION_ID = ""
            Dim Firma = ""

            Dim EORI_ERG = ValidateEoriNumber(txtEORI)


            If EORI_ERG.Result.Count > 0 Then

                If EORI_ERG.Result(0).Status = 0 Or EORI_ERG.Result(0).Status = 1 Then

                    Firma = EORI_ERG.Result(0).Name & vbNewLine
                    Firma &= EORI_ERG.Result(0).Street & vbNewLine
                    Firma &= EORI_ERG.Result(0).Country & " " & EORI_ERG.Result(0).PostalCode & " " & EORI_ERG.Result(0).City
                    Firma = Firma.Trim

                    EORI_ERGInt = EORI_ERG.Result(0).Status
                    Select Case EORI_ERG.Result(0).Status
                        Case 0 : msgErgebnis = "EORI-Nr. GÜLTIG   -   OK"
                        Case 1 : msgErgebnis = "EORI-Nr. UNGÜLTIG"
                    End Select

                    Dim PdfTmp = SDL.FormularManagerNEU.EORI_PRUEFUNG(msgErgebnis, Firma, tmp_SESSION_ID, txtEORI, AvisoId, SendungsId)

                    Return PdfTmp

                End If
            Else
                MsgBox("Fehler bei der Prüfung der EORI-Nummer. WebService evtl. nicht verfügbar.")
            End If
            Return ""

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

        Return ""

    End Function




    Shared Function ValidateEoriNumber(ByVal number As String) As EoriResponseModel
        If number Is Nothing Then
            Return Nothing
        End If

        Dim soapEnvelopeXml As XmlDocument = CreateSoapEnvelope(number)
        Dim webRequest As HttpWebRequest = CreateWebRequest(_url)
        InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest)
        Dim asyncResult As IAsyncResult = webRequest.BeginGetResponse(Nothing, Nothing)
        asyncResult.AsyncWaitHandle.WaitOne()
        Dim response As String

        Using webResponse As WebResponse = webRequest.EndGetResponse(asyncResult)

            Using rd As StreamReader = New StreamReader(webResponse.GetResponseStream())
                response = rd.ReadToEnd()
            End Using
        End Using

        Dim startPos As Integer = response.IndexOf("<return>")
        Dim lastPos As Integer = response.LastIndexOf("</return>") - startPos + 9
        Dim responseFormatted As String = response.Substring(startPos, lastPos)
        Dim serializer As XmlSerializer = New XmlSerializer(GetType(EoriResponseModel))
        Dim result As EoriResponseModel

        Using reader As TextReader = New StringReader(responseFormatted)
            result = CType(serializer.Deserialize(reader), EoriResponseModel)
        End Using

        Return result
    End Function

    Private Shared Function CreateWebRequest(ByVal url As String) As HttpWebRequest
        Dim webRequest As HttpWebRequest = CType(webRequest.Create(url), HttpWebRequest)
        webRequest.ContentType = "text/xml;charset=""utf-8"""
        webRequest.Accept = "text/xml"
        webRequest.Method = "POST"
        Return webRequest
    End Function

    Private Shared Function CreateSoapEnvelope(ByVal number As String) As XmlDocument
        Dim soapEnvelopeDocument As XmlDocument = New XmlDocument()
        Dim xmlBuilder As StringBuilder = New StringBuilder()
        xmlBuilder.AppendFormat("<soap:Envelope xmlns:soap={0} >", "'http://schemas.xmlsoap.org/soap/envelope/'")
        xmlBuilder.Append("<soap:Body>")
        xmlBuilder.AppendFormat("<ev:validateEORI xmlns:ev={0} >", "'http://eori.ws.eos.dds.s/'")
        xmlBuilder.AppendFormat("<ev:eori>{0}</ev:eori>", number)
        xmlBuilder.Append("</ev:validateEORI>")
        xmlBuilder.Append("</soap:Body> ")
        xmlBuilder.Append("</soap:Envelope> ")
        soapEnvelopeDocument.LoadXml(xmlBuilder.ToString())
        Return soapEnvelopeDocument
    End Function

    Private Shared Sub InsertSoapEnvelopeIntoWebRequest(ByVal soapEnvelopeXml As XmlDocument, ByVal webRequest As HttpWebRequest)
        Using stream As Stream = webRequest.GetRequestStream()
            soapEnvelopeXml.Save(stream)
        End Using
    End Sub
End Class


<XmlRoot(ElementName:="return")>
Public Class EoriResponseModel
    <XmlElement(ElementName:="requestDate")>
    Public Property RequestDate As String
    <XmlElement(ElementName:="result")>
    Public Property Result As List(Of Result)
End Class

<XmlRoot(ElementName:="result")>
Public Class Result
    <XmlElement(ElementName:="eori")>
    Public Property Eori As String
    <XmlElement(ElementName:="status")>
    Public Property Status As String
    <XmlElement(ElementName:="statusDescr")>
    Public Property StatusDescr As String
    <XmlElement(ElementName:="name")>
    Public Property Name As String
    <XmlElement(ElementName:="street")>
    Public Property Street As String
    <XmlElement(ElementName:="postalCode")>
    Public Property PostalCode As String
    <XmlElement(ElementName:="city")>
    Public Property City As String
    <XmlElement(ElementName:="country")>
    Public Property Country As String
End Class
