Modules/Modules.Interfaces/ZUGFeRDInterface.vb
Jonathan Jenne d33624c66c jj firebird
2018-12-18 13:22:32 +01:00

97 lines
3.1 KiB
VB.net

Imports System.Xml
Imports System.Xml.Serialization
Imports System.Xml.XPath
Imports System.Xml.Xsl
Imports DigitalData.Modules.Interfaces.Exceptions
Imports DigitalData.Modules.Logging
Public Class ZUGFeRDInterface
Private _logConfig As LogConfig
Private _logger As Logger
Private Const ZUGFERD_CONVERTER_EXE = "pdf_zugferd_test.exe"
Private Const ZUGFERD_CONVERTER_SUCCESS_MESSAGE = "Document contains ZUGFeRD data."
Public Enum ErrorType
NoValidFile
ExtractionFailed
End Enum
Public Sub New(LogConfig As LogConfig)
_logConfig = LogConfig
_logger = _logConfig.GetLogger()
End Sub
''' <summary>
''' Validates a ZUGFeRD File and extracts the XML Document from it
''' </summary>
''' <param name="Path"></param>
''' <exception cref="ZUGFeRDExecption"></exception>
''' <returns></returns>
Public Function ExtractZUGFeRDFile(Path As String) As CrossIndustryDocumentType
Dim oException As New Exception
Dim oXmlDocument = ValidateZUGFeRDFile(Path)
If IsNothing(oXmlDocument) Then
Throw New ZUGFeRDExecption(ErrorType.ExtractionFailed, "Datei ist kein gültiges ZUGFeRD Format.")
End If
Return SerializeZUGFeRDDocument(oXmlDocument)
End Function
Public Function ValidateZUGFeRDFile(Path As String) As XPathDocument
Dim oProcessOutput, oProcessError As String
Dim oXmlDocument As XPathDocument
Dim oTempFile = IO.Path.GetTempFileName()
Dim oProcess As New Process() With {
.StartInfo = New ProcessStartInfo() With {
.FileName = ZUGFERD_CONVERTER_EXE,
.RedirectStandardError = True,
.RedirectStandardOutput = True,
.UseShellExecute = False,
.Arguments = $"-i ""{Path}"" -o ""{oTempFile}"""
}
}
Try
oProcess.Start()
oProcessOutput = oProcess.StandardOutput.ReadToEnd()
oProcessError = oProcess.StandardError.ReadToEnd()
oProcess.WaitForExit()
Catch ex As Exception
_logger.Error(ex)
Throw ex
End Try
If Not oProcessOutput.Contains(ZUGFERD_CONVERTER_SUCCESS_MESSAGE) Then
_logger.Warn("File {0} is not a valid ZUGFeRD File!", Path)
Throw New ZUGFeRDExecption(ErrorType.NoValidFile, "Datei ist kein gültiges ZUGFeRD Format.")
End If
Try
oXmlDocument = New XPathDocument(oTempFile)
Catch ex As Exception
_logger.Error(ex)
Throw ex
End Try
Return oXmlDocument
End Function
Public Function SerializeZUGFeRDDocument(Document As XPathDocument) As CrossIndustryDocumentType
Try
Dim oNavigator As XPathNavigator = Document.CreateNavigator()
Dim oReader = oNavigator.ReadSubtree()
Dim oSerializer As New XmlSerializer(GetType(CrossIndustryDocumentType))
Return oSerializer.Deserialize(oReader)
Catch ex As Exception
_logger.Error(ex)
Throw ex
End Try
End Function
End Class