Change Name to MultiTool

This commit is contained in:
Jonathan Jenne
2021-10-29 10:37:04 +02:00
parent f00e332737
commit 1035a0fb1f
121 changed files with 186 additions and 185 deletions

View File

@@ -0,0 +1,7 @@
''' <summary>
''' Class for loading column/field config from database
''' </summary>
Public Class Configuration
End Class

View File

@@ -0,0 +1,580 @@
Imports DigitalData.Modules.Logging
Imports DigitalData.Modules.Language
Imports DigitalData.Modules.Database
Imports MultiTool.Shared
Imports System.Text.RegularExpressions
Namespace Winline
Public Class Data
Inherits BaseClass
Private ReadOnly Database As MSSQLServer
Private ReadOnly Config As Config
Public Accounts As New List(Of Account)
Public Mandators As New List(Of Mandator)
Public DocumentKinds As New List(Of DocumentKind)
Public Years As List(Of Integer)
Public TemplateConfiguration As New List(Of TemplateColumn)
'Public XmlConfigHead As List(Of TemplateColumn)
'Public XmlConfigPositions As List(Of TemplateColumn)
Public Const ALL_MESOCOMP = "mesocomp"
Public Const V21_ARTICLENUMBER = "c011"
Public Const V21_REPLACEMENTARTICLENUMBER = "c123"
Public Const V50_ACCOUNTNUMBER = "c002"
Public Const V50_ACCOUNTNAME = "c003"
Public Const V50_STREETNAME = "c050"
Public Const V50_ZIPCODE = "c051"
Public Const V50_CITYNAME = "c052"
Public Const T45_KEY = "c000"
Public Const T45_NAME = "c001"
Public Const T45_CONTACTNUMBER = "c063"
Public Const V05_ACCOUNTID = "c002"
Public Const V05_ACCOUNTNAME = "c003"
Public Const T357_KINDID = "c030"
Public Const T357_KINDNAME = "c001"
Public Const T01_DATABASEINFO = "c004"
Public Const T01_MANDATORID = "c000"
Public Const T01_MANDATORNAME = "c003"
Public Sub New(pLogConfig As LogConfig, pDatabase As MSSQLServer, pConfig As Config)
MyBase.New(pLogConfig, pLogConfig.GetLogger())
Database = pDatabase
Config = pConfig
End Sub
<DebuggerStepThrough>
Public Function GetWinLineYear(pYear As Integer)
Return (pYear - 1900) * 12
End Function
<DebuggerStepThrough>
Public Function GetWinLineYear()
Return GetWinLineYear(Config.GetYear)
End Function
Public Sub LoadAccounts(pMandator As Mandator)
Logger.Info("Loading Accounts for Mandator [{0}]", pMandator)
Dim oYear = GetWinLineYear()
Try
Dim oSQL = $"
SELECT DISTINCT
[c002], -- Kundennummer
[c003], -- Kundenname
[c050], -- Straße
[c052], -- Ort
[c051] -- PLZ
FROM [{pMandator.Server}].[{pMandator.Database}].[dbo].[v050]
WHERE
c139 IS NULL
AND mesocomp = '{pMandator.Id}'
AND mesoyear = {oYear}"
Dim oTable = Database.GetDatatable(oSQL)
Dim oAccounts As New List(Of Account)
For Each oRow As DataRow In oTable.Rows
Dim oAccountNumber As String = Utils.NotNull(oRow.Item(V50_ACCOUNTNUMBER), String.Empty)
Dim oAccountName As String = Utils.NotNull(oRow.Item(V50_ACCOUNTNAME), String.Empty)
Dim oStreetName As String = Utils.NotNull(oRow.Item(V50_STREETNAME), String.Empty)
Dim oZipCode As String = Utils.NotNull(oRow.Item(V50_ZIPCODE), String.Empty)
Dim oCityName As String = Utils.NotNull(oRow.Item(V50_CITYNAME), String.Empty)
oAccounts.Add(New Account With {
.Id = oAccountNumber,
.Name = oAccountName,
.StreetName = oStreetName,
.ZipCode = oZipCode,
.CityName = oCityName,
.Mandator = pMandator.Id
})
Next
Accounts.AddRange(oAccounts)
Logger.Info("[{0}] Accounts loaded for Mandator [{1}]", oAccounts.Count, pMandator)
Catch ex As Exception
Logger.Warn("Could not load Accounts for Mandator [{0}]", pMandator)
Logger.Error(ex)
End Try
End Sub
Public Sub LoadMandators()
Try
Dim oSQL = "SELECT [c000], [c003], [c004] FROM [cwlsystem].[dbo].[T001SRV] (NOLOCK)"
Dim oTable = Database.GetDatatable(oSQL)
Mandators.Clear()
For Each oRow As DataRow In oTable.Rows
Dim oDbInfo = SplitConnectionInfo(oRow)
Dim oMandator = New Mandator With {
.Id = oRow.Item(T01_MANDATORID),
.Name = oRow.Item(T01_MANDATORNAME),
.Database = oDbInfo.Item1,
.Server = oDbInfo.Item2
}
Dim oMandatorConfig As Config.MandatorConfig = Config.Mandators.
Where(Function(m) oMandator.Id = m.Name).
SingleOrDefault()
If oMandatorConfig IsNot Nothing Then
oMandator.IsWhitelisted = True
oMandator.Regex = oMandatorConfig.ArticleRegex
oMandator.Order = oMandatorConfig.Order
End If
Mandators.Add(oMandator)
Next
Logger.Info("[{0}] Mandators loaded", Mandators.Count)
Catch ex As Exception
Logger.Warn("Could not load Mandators")
Logger.Error(ex)
End Try
End Sub
Public Sub LoadEconomicYears()
Dim oCurrentYear = Now.Year
Dim oRange As IEnumerable(Of Integer) = Enumerable.Range(oCurrentYear - 10, 12).ToList()
Years = oRange
End Sub
Public Sub LoadDocumentKinds(pMandators As List(Of Mandator))
Dim oDocumentKinds As New List(Of DocumentKind)
Dim oMandatorString = String.Join(",", pMandators.Select(Function(m) $"'{m.Id}'").ToArray)
Dim oYear As Integer = GetWinLineYear()
DocumentKinds.Clear()
For Each oMandator As Mandator In pMandators
Try
Dim oSQL = $"
SELECT
[c030],
[c001],
[mesocomp]
FROM [{oMandator.Database}].[dbo].[t357] (NOLOCK)
WHERE (
[c001] LIKE 'Werk%(VK)' OR
[c001] LIKE 'Werk%(WK)'
)
AND [mesocomp] = '{oMandator.Id}' AND [mesoyear] = {oYear}"
Dim oTable As DataTable = Database.GetDatatable(oSQL)
If oTable.Rows.Count = 0 Then
Logger.Warn("No DocumentKinds found for Mandator [{0}]", oMandator.Id)
Continue For
End If
For Each oRow As DataRow In oTable.Rows
oDocumentKinds.Add(New DocumentKind With {
.Id = oRow.Item(T357_KINDID),
.Name = oRow.Item(T357_KINDNAME),
.Mandator = oRow.Item(ALL_MESOCOMP)
})
Next
Catch ex As Exception
Logger.Warn("Could not load DocumentKinds")
Logger.Error(ex)
End Try
Next
DocumentKinds = oDocumentKinds.ToList()
End Sub
Public Function TryGetAccount(pGLN As String, pMandator As Mandator) As Account
Try
If pGLN Is Nothing OrElse pGLN = String.Empty Then
Return Nothing
End If
Dim oYear As Integer = GetWinLineYear()
Dim oSQL = $"
SELECT
[c002], -- Kundennummer
[c003], -- Kundenname
[c050], -- Straße
[c052], -- Ort
[c051] -- PLZ
FROM [{pMandator.Database}].[dbo].[v050]
WHERE [c004] = 2 -- KontoTyp
AND [c260] = '{pGLN}'
AND [mesocomp] = '{pMandator.Id}' and [mesoyear] = {oYear}"
Dim oTable As DataTable = Database.GetDatatable(oSQL)
' GLN not found in this Mandator, continue to next one
If oTable.Rows.Count = 0 Then
Logger.Debug("GLN [{0}] was not found in Mandator: [{1}]", pGLN, pMandator.Id)
Return Nothing
End If
' Duplicate GLN, exit and do nothing about this number
If oTable.Rows.Count > 1 Then
Logger.Warn("GLN [{0}] was found more than once in Mandator: [{1}]", pGLN, pMandator.Id)
Return Nothing
End If
Dim oRow As DataRow = oTable.Rows.Item(0)
Dim oAccountNumber As String = Utils.NotNull(oRow.Item(V50_ACCOUNTNUMBER), String.Empty)
Dim oAccountName As String = Utils.NotNull(oRow.Item(V50_ACCOUNTNAME), String.Empty)
Dim oStreetName As String = Utils.NotNull(oRow.Item(V50_STREETNAME), String.Empty)
Dim oZipCode As String = Utils.NotNull(oRow.Item(V50_ZIPCODE), String.Empty)
Dim oCityName As String = Utils.NotNull(oRow.Item(V50_CITYNAME), String.Empty)
Return New Account With {
.Id = oAccountNumber,
.Name = oAccountName,
.StreetName = oStreetName,
.CityName = oCityName,
.ZipCode = oZipCode,
.Mandator = pMandator.Id
}
Catch ex As Exception
Logger.Warn("Error while trying to get account for GLN [{0}]", pGLN)
Logger.Error(ex)
Return Nothing
End Try
End Function
Public Function TryGetArticleNumber(pEAN As String, pMandator As Mandator) As String
Try
Dim oYear As Integer = GetWinLineYear()
Dim oSQL As String = $"
SELECT
[c011], -- Artikelnummer
[c003], -- Artikelbezeichnung
[c075], -- EAN-Nummer
[c123] -- Ersatzartikelnummer
FROM [{pMandator.Database}].[dbo].[v021]
WHERE [c075] = '{pEAN}'
AND [mesocomp] = '{pMandator.Id}' AND [mesoyear] = {oYear}"
Dim oTable As DataTable = Database.GetDatatable(oSQL)
' EAN not found in this Mandator, continue to next one
If oTable.Rows.Count = 0 Then
Logger.Debug("EAN [{0}] was not found in Mandator: [{1}]", pEAN, pMandator.Id)
Return Nothing
End If
' Duplicate EAN, exit and do nothing about this number
If oTable.Rows.Count > 1 Then
Logger.Warn("EAN [{0}] was found more than once", pEAN)
Return Nothing
End If
Dim oRow As DataRow = oTable.Rows.Item(0)
Dim oArticleNumber As String = Utils.NotNull(oRow.Item(V21_ARTICLENUMBER), String.Empty)
Return oArticleNumber
Catch ex As Exception
Logger.Error(ex)
Return Nothing
End Try
End Function
Public Function GetContacts(pAccountNumber As String, pMandator As Mandator) As List(Of Contact)
Try
Dim oContacts As New List(Of Contact)
Dim oYear As Integer = GetWinLineYear()
Dim oSQL As String = $"
SELECT
[c000], -- Key
[c001], -- Name
[c063] -- Kontaktnummer
FROM [{pMandator.Database}].[dbo].[t045]
WHERE [c063] LIKE '{pAccountNumber}-%'
AND [mesocomp] = '{pMandator.Id}' AND [mesoyear] = {oYear}"
Dim oTable As DataTable = Database.GetDatatable(oSQL)
' Contact not found in this Mandator, continue to next one
If oTable.Rows.Count = 0 Then
Logger.Debug("Contact for Account [{0}] was not found in Mandator: [{1}]", pAccountNumber, pMandator.Id)
Return Nothing
End If
For Each oRow In oTable.Rows
oContacts.Add(New Contact With {
.Id = Utils.NotNull(oRow.Item(T45_KEY), Nothing),
.Name = Utils.NotNull(oRow.Item(T45_NAME), Nothing),
.Number = Utils.NotNull(oRow.Item(T45_CONTACTNUMBER), Nothing)
})
Next
Return oContacts
Catch ex As Exception
Logger.Error(ex)
Return Nothing
End Try
End Function
Public Function GetReplacementArticleNumber(pArticleNumber As String, pMandator As Mandator)
Try
Dim oYear As Integer = GetWinLineYear()
Dim oSQL As String = $"
SELECT
[c011], -- Artikelnummer
[c003], -- Artikelbezeichnung
[c075], -- EAN-Nummer
[c123] -- Ersatzartikelnummer
FROM [{pMandator.Database}].[dbo].[v021]
WHERE [c011] = '{pArticleNumber}'
AND [mesocomp] = '{pMandator.Id}' AND [mesoyear] = {oYear}"
Dim oTable As DataTable = Database.GetDatatable(oSQL)
' ArticleNumber not found in this Mandator, continue to next one
If oTable.Rows.Count = 0 Then
Logger.Debug("ArticleNumber [{0}] was not found in Mandator: [{1}]", pArticleNumber, pMandator.Id)
Return Nothing
End If
' Duplicate EAN, exit and do nothing about this number
If oTable.Rows.Count > 1 Then
Logger.Warn("ArticleNumber [{0}] was found more than once", pArticleNumber)
Return Nothing
End If
Dim oRow As DataRow = oTable.Rows.Item(0)
Dim oReplacementArticleNumber = Utils.NotNull(oRow.Item(V21_REPLACEMENTARTICLENUMBER), Nothing)
If oReplacementArticleNumber Is Nothing Then
Return pArticleNumber
End If
Return GetReplacementArticleNumber(oReplacementArticleNumber, pMandator)
Catch ex As Exception
Logger.Error(ex)
Return Nothing
End Try
End Function
Public Function FindMatchingMandatorFromOrder(pData As Documents.Document) As Mandator
Dim oPositions = pData.Rows.
Where(Function(r) r.Name.ToUpper.EndsWith("T026")).
ToList()
Dim oEANNumbers = oPositions.
Select(Function(p) p.Fields.Item("Artikelnummer").Original).
Distinct().
ToList()
'Dim oPositions As List(Of Schemas.Orders.Input.MESOWebServiceEXIMVRG_ordersT026) = pData.Items.
' Where(Function(i) TypeOf i Is Schemas.Orders.Input.MESOWebServiceEXIMVRG_ordersT026).
' Select(Of Schemas.Orders.Input.MESOWebServiceEXIMVRG_ordersT026)(Function(i) i).
' ToList()
Dim oYear = GetWinLineYear()
Dim oMandatorId As String = String.Empty
Dim oWhitelistedMandators = Mandators.
Where(Function(m) m.IsWhitelisted = True).
ToList()
For Each oEANNumber In oEANNumbers
For Each oMandator In oWhitelistedMandators
Dim oSQL As String = $"
SELECT
[c011], -- Artikelnummer
[c003], -- Artikelbezeichnung
[c075], -- EAN-Nummer
[c123] -- Ersatzartikelnummer
FROM [{oMandator.Database}].[dbo].[v021]
WHERE [c075] = '{oEANNumber}'
AND [mesocomp] = '{oMandator.Id}' AND [mesoyear] = {oYear}"
Dim oTable As DataTable = Database.GetDatatable(oSQL)
' EAN not found in this Mandator, continue to next one
If oTable.Rows.Count = 0 Then
Logger.Debug("EAN [{0}] was not found in Mandator: [{1}]", oEANNumber, oMandator.Id)
Continue For
End If
' Duplicate EAN, exit and do nothing about this manda
If oTable.Rows.Count > 1 Then
Logger.Warn("EAN [{0}] was found more than once. Skipping Mandator [{1}]", oEANNumber, oMandator.Id)
Exit For
End If
Dim oRow As DataRow = oTable.Rows.Item(0)
Dim oArticleNumber As String = Utils.NotNull(oRow.Item(V21_ARTICLENUMBER), String.Empty)
' EAN was found, now we need to check it against the Regex of the current Mandantor, if one exists
If oMandator.Regex <> String.Empty Then
Try
Dim oRegex As New Regex(oMandator.Regex)
Dim oMatch = oRegex.Match(oArticleNumber)
' If ArticleNumber matches the regex, we assign it and exit
If oMatch.Success Then
oMandatorId = oMandator.Id
Exit For
Else
' If it does not match, continue to the next mandator
End If
Catch ex As Exception
Logger.Error(ex)
Logger.Warn("Regex [{0}] could not be parsed. Skipping.", oMandator.Regex)
End Try
Else
' If no regex was found, we assume the number matches
oMandatorId = oMandator.Id
End If
Next
Next
If oMandatorId = String.Empty Then
Return Nothing
Else
Return oWhitelistedMandators.
Where(Function(m) m.Id = oMandatorId).
Take(1).
SingleOrDefault()
End If
End Function
'Public Function FindMatchingMandatorFromOrder(pData As Schemas.Orders.Input.MESOWebService) As Mandator
' Dim oPositions As List(Of Schemas.Orders.Input.MESOWebServiceEXIMVRG_ordersT026) = pData.Items.
' Where(Function(i) TypeOf i Is Schemas.Orders.Input.MESOWebServiceEXIMVRG_ordersT026).
' Select(Of Schemas.Orders.Input.MESOWebServiceEXIMVRG_ordersT026)(Function(i) i).
' ToList()
' Dim oYear = GetWinLineYear()
' Dim oMandatorId As String = String.Empty
' Dim oWhitelistedMandators = Mandators.
' Where(Function(m) m.IsWhitelisted = True).
' ToList()
' For Each oPos In oPositions
' For Each oMandator In oWhitelistedMandators
' Dim oSQL As String = $"
' SELECT
' [c011], -- Artikelnummer
' [c003], -- Artikelbezeichnung
' [c075], -- EAN-Nummer
' [c123] -- Ersatzartikelnummer
' FROM [{oMandator.Database}].[dbo].[v021]
' WHERE [c075] = '{oPos.Artikelnummer}'
' AND [mesocomp] = '{oMandator.Id}' AND [mesoyear] = {oYear}"
' Dim oTable As DataTable = Database.GetDatatable(oSQL)
' ' EAN not found in this Mandator, continue to next one
' If oTable.Rows.Count = 0 Then
' Logger.Debug("EAN [{0}] was not found in Mandator: [{1}]", oPos.Artikelnummer, oMandator.Id)
' Continue For
' End If
' ' Duplicate EAN, exit and do nothing about this manda
' If oTable.Rows.Count > 1 Then
' Logger.Warn("EAN [{0}] was found more than once. Skipping Mandator [{1}]", oPos.Artikelnummer, oMandator.Id)
' Exit For
' End If
' Dim oRow As DataRow = oTable.Rows.Item(0)
' Dim oArticleNumber As String = Utils.NotNull(oRow.Item(V21_ARTICLENUMBER), String.Empty)
' ' EAN was found, now we need to check it against the Regex of the current Mandantor, if one exists
' If oMandator.Regex <> String.Empty Then
' Try
' Dim oRegex As New Regex(oMandator.Regex)
' Dim oMatch = oRegex.Match(oArticleNumber)
' ' If ArticleNumber matches the regex, we assign it and exit
' If oMatch.Success Then
' oMandatorId = oMandator.Id
' Exit For
' Else
' ' If it does not match, continue to the next mandator
' End If
' Catch ex As Exception
' Logger.Error(ex)
' Logger.Warn("Regex [{0}] could not be parsed. Skipping.", oMandator.Regex)
' End Try
' Else
' ' If no regex was found, we assume the number matches
' oMandatorId = oMandator.Id
' End If
' Next
' Next
' If oMandatorId = String.Empty Then
' Return Nothing
' Else
' Return oWhitelistedMandators.
' Where(Function(m) m.Id = oMandatorId).
' Take(1).
' SingleOrDefault()
' End If
'End Function
Public Function LoadTemplateConfiguration() As Boolean
Try
Dim oSql = $"SELECT * FROM [DD_ECM].[dbo].[VWEDI_XML_ITEMS]"
Dim oTable As DataTable = Database.GetDatatable(oSql)
Dim oItems As New List(Of TemplateColumn)
For Each oRow As DataRow In oTable.Rows
Dim oColumn As New TemplateColumn With {
.Name = oRow.Item("XML_NAME"),
.Root = oRow.Item("XML_ROOT"),
.Type = oRow.Item("XML_TYPE"),
.Template = oRow.Item("TEMPLATE_NAME"),
.[Function] = oRow.Item("FUNCTION_ID"),
.[ReadOnly] = oRow.Item("IS_READ_ONLY"),
.[Visible] = oRow.Item("IS_VISIBLE")
}
oItems.Add(oColumn)
Next
TemplateConfiguration = oItems
Return True
Catch ex As Exception
Logger.Error(ex)
Return False
End Try
End Function
''' <summary>
''' Turns a database info like "SQLCWLDATEN on SERVER\INSTANCE" into a Tuple of two strings
''' </summary>
''' <param name="pRow"></param>
''' <returns></returns>
Private Function SplitConnectionInfo(pRow As DataRow) As Tuple(Of String, String)
Dim oDbInfo = pRow.Item(T01_DATABASEINFO).ToString()
Dim oSplittedInfo = SplitAtString(oDbInfo.ToUpper, "ON")
Dim oServer = oSplittedInfo.Item(1).Trim()
Dim oDatabase = oSplittedInfo.Item(0).Trim()
If oDatabase.StartsWith("SQL") Then
oDatabase = oDatabase.Remove(0, 3)
End If
Return New Tuple(Of String, String)(oDatabase, oServer)
End Function
Private Function SplitAtString(pStringToSplit As String, pDelimiter As String) As List(Of String)
Dim oDelimiter As String() = New String(0) {pDelimiter}
Return pStringToSplit.
Split(oDelimiter, StringSplitOptions.None).
ToList()
End Function
End Class
End Namespace

View File

@@ -0,0 +1,24 @@
Namespace Winline
Public Class Account
Public Property Id As String
Public Property Name As String
Public Property StreetName As String
Public Property CityName As String
Public Property ZipCode As String
Public Property Mandator As String
Public Overrides Function GetHashCode() As Integer
Return Id.GetHashCode()
End Function
Public Overrides Function Equals(obj As Object) As Boolean
Return DirectCast(obj, Account).Id = Id
End Function
Public Overrides Function ToString() As String
Return $"{Name} ({Id})"
End Function
End Class
End Namespace

View File

@@ -0,0 +1,12 @@
Namespace Winline
Public Class Contact
Public Property Id As Integer
Public Property Number As String
Public Property Name As String
Public Overrides Function ToString() As String
Return Name
End Function
End Class
End Namespace

View File

@@ -0,0 +1,19 @@
Namespace Winline
Public Class DocumentKind
Public Id As Integer
Public Name As String
Public Mandator As String
Public Overrides Function GetHashCode() As Integer
Return Id.GetHashCode()
End Function
Public Overrides Function Equals(obj As Object) As Boolean
Return DirectCast(obj, DocumentKind).Id = Id
End Function
Public Overrides Function ToString() As String
Return $"{Name} ({Id})"
End Function
End Class
End Namespace

View File

@@ -0,0 +1,23 @@
Namespace Winline
Public Class Mandator
Public Property Id As String
Public Property Name As String
Public Property Database As String
Public Property Server As String
Public Property Regex As String
Public Property Order As Integer
Public Property IsWhitelisted As Boolean
Public Overrides Function GetHashCode() As Integer
Return Id.GetHashCode()
End Function
Public Overrides Function Equals(obj As Object) As Boolean
Return DirectCast(obj, Mandator).Id = Id
End Function
Public Overrides Function ToString() As String
Return $"{Name} ({Id})"
End Function
End Class
End Namespace

View File

@@ -0,0 +1,13 @@
Namespace Winline
Public Class TemplateColumn
Public Name As String
Public Root As String
Public Type As String
Public IsHead As Boolean
Public Template As String
Public [ReadOnly] As Boolean
Public Visible As Boolean
Public [Function] As Constants.XmlFunction
End Class
End Namespace

View File

@@ -0,0 +1,259 @@
Imports System.Xml
Imports System.Net
Imports System.Net.Http
Imports System.Globalization
Imports AutoMapper
Imports DigitalData.Modules.Logging
Imports DigitalData.Modules.Filesystem
Imports MultiTool.Shared.Documents
Imports System.Text
Namespace Winline
Public Class WebService
Inherits BaseClass
Private ReadOnly Config As Config
Private ReadOnly Serializer As Serializer
Private ReadOnly Mapper As AutoMapper.Mapper
Private ReadOnly FileEx As File
Public Sub New(pLogConfig As LogConfig, pConfig As Config)
MyBase.New(pLogConfig, pLogConfig.GetLogger())
FileEx = New File(pLogConfig)
Serializer = New Serializer(pLogConfig)
Config = pConfig
'Mapper = MapperFactory.GetMapper()
End Sub
Public Async Function TransferDocumentToWinline(pDocument As Document) As Task(Of Boolean)
Dim oBytes As Byte() = GetBytesFromDocument(pDocument)
Dim oWS As Config.WebServiceConfig = Config.Webservice
' --- Get and create path for request/response files
Dim oPath As String = GetBaseWebServicePath()
If IO.Directory.Exists(oPath) = False Then
IO.Directory.CreateDirectory(oPath)
End If
' --- Build all teh filenamez and pathz
Dim oBaseFileName As String = GetBaseFilenameForRequest()
Dim oFileName = GetXmlFilenameWithSuffix(oBaseFileName, "Request", "xml")
' Relative Path for Webservice Call
Dim oImportRelativeFilePath = IO.Path.Combine(GetDateSubDirectoryPath(Config.Webservice.ImportRelativePath), oFileName)
' Absolute Path to copy Request file
Dim oImportAbsolutePath = IO.Path.Combine(Config.Webservice.ImportBasePath, Config.Webservice.ImportRelativePath)
Dim oImportAbsoluteFilePath = IO.Path.Combine(GetDateSubDirectoryPath(oImportAbsolutePath), oFileName)
' --- Serialize Data into XML string
Dim oOutputFilePath = IO.Path.Combine(GetBaseWebServicePath(), oFileName)
IO.File.WriteAllBytes(oOutputFilePath, oBytes)
' --- Copy file to Winline Import Directory
Try
IO.File.Copy(oOutputFilePath, oImportAbsoluteFilePath, True)
Catch ex As Exception
Logger.Error(ex)
Throw ex
End Try
' --- Prepare URL and HTTP Client
Dim oTemplateType = pDocument.TemplateType
Dim oTemplateName = pDocument.TemplateName
' ActionCode: Should this be a test or not?
' 0 = Testcall
' 1 = Real call
Dim oActionCode = 1
' Byref: Should data be supplied as file or as string?
' 0 = As String
' 1 = As File (relative to Winline Server directory)
Dim oByref = 1
Dim oURL As String = $"{oWS.BaseUrl}/ewlservice/import?User={oWS.Username}&Password={oWS.Password}&Company={pDocument.Mandator.Id}&Type={oTemplateType}&Vorlage={oTemplateName}&ActionCode={oActionCode}&Byref={oByref}&Data={oImportRelativeFilePath}"
Dim oClient As New HttpClient()
Logger.Info("Creating HTTP Request to [{0}]", oWS.BaseUrl)
' --- Bring the action!
Try
Dim oResponse As HttpResponseMessage = Await oClient.GetAsync(oURL)
Await HandleResponse(oResponse, oPath, oBaseFileName)
Return True
Catch ex As Exception
Logger.Error(ex)
Throw ex
Finally
oClient.Dispose()
End Try
End Function
Private Async Function HandleResponse(pResponse As HttpResponseMessage, pPath As String, pBaseFileNAme As String) As Task
pResponse.EnsureSuccessStatusCode()
Dim oResponseBody As String = Await pResponse.Content.ReadAsStringAsync()
Dim oContentType = pResponse.Content.Headers.ContentType.MediaType
Dim oSerializer = Serializer.GetSerializer(GetType(Schemas.MESOWebServiceResult))
Select Case oContentType
Case "text/xml"
WriteResponseFile(pPath, pBaseFileNAme, oResponseBody, "xml")
Dim oBytes As Byte() = Encoding.UTF8.GetBytes(oResponseBody)
Using oStream As New IO.MemoryStream(oBytes)
Dim oResponseObject As Schemas.MESOWebServiceResult = oSerializer.Deserialize(oStream)
Dim oErrorStrings As New List(Of String)
For Each oDetails As Schemas.MESOWebServiceResultResultDetails In oResponseObject.ResultDetails
If oDetails.Success = True Then
Logger.Info("KeyValue: [{0}]", oDetails.KeyValue)
Logger.Info("VoucherNumber: [{0}]", oDetails.VoucherNumber)
Else
Logger.Warn("ErrorCode: [{0}]", oDetails.ErrorCode)
Logger.Warn("ErrorText: [{0}]", oDetails.ErrorText)
oErrorStrings.Add($"[{oDetails.ErrorCode}] {oDetails.ErrorText}")
End If
Next
If oResponseObject.OverallSuccess = False Then
Dim oMessage = $"Request to Webservice was unsuccessful:{vbNewLine}{vbNewLine}{String.Join(vbNewLine, oErrorStrings.ToArray)}"
Throw New ApplicationException(oMessage)
End If
End Using
Case "text/html"
WriteResponseFile(pPath, pBaseFileNAme, oResponseBody, "txt")
Throw New ApplicationException(oResponseBody)
Case Else
Throw New ApplicationException(oResponseBody)
End Select
End Function
Private Function WriteResponseFile(pPath As String, pBaseFileName As String, pResponseBody As String, pExtension As String)
Try
Dim oRequestFileName As String = GetXmlFilenameWithSuffix(pBaseFileName, "Response", pExtension)
Dim oFilePath As String = IO.Path.Combine(pPath, oRequestFileName)
IO.File.WriteAllText(oFilePath, pResponseBody)
Return True
Catch ex As Exception
Logger.Error(ex)
Return False
End Try
End Function
Private Function GetBytesFromDocument(pDocument As Document) As Byte()
Dim oFilteredFields As New List(Of String) From {
"Fakt_Name",
"Lief_Name"
}
Using oStream As New IO.MemoryStream()
Dim w = XmlWriter.Create(oStream)
w.WriteStartDocument()
w.WriteStartElement("MESOWebService")
w.WriteAttributeString("Template", pDocument.TemplateName)
w.WriteAttributeString("TemplateType", pDocument.TemplateType)
w.WriteAttributeString("option", pDocument.Option)
w.WriteAttributeString("printVoucher", pDocument.PrintVoucher)
For Each oRow In pDocument.Rows
w.WriteStartElement(oRow.Name)
For Each oField As KeyValuePair(Of String, DocumentRow.FieldValue) In oRow.Fields
If oField.Value.Final = String.Empty Then
Continue For
End If
If oFilteredFields.Contains(oField.Key) Then
Continue For
End If
w.WriteStartElement(oField.Key)
w.WriteValue(oField.Value.Final)
w.WriteEndElement() ' Field
Next
w.WriteEndElement() ' Row
Next
w.WriteEndElement() ' MESOWebService
w.WriteEndDocument() ' Document
w.Close()
Return oStream.ToArray()
End Using
End Function
'Private Function TransformOrderToOutput(pData As Schemas.Orders.Input.MESOWebService) As Schemas.Orders.Output.MESOWebService
' Dim oData As Schemas.Orders.Input.MESOWebService = pData
' Dim oResult As Schemas.Orders.Output.MESOWebService = Mapper.Map(Of Schemas.Orders.Output.MESOWebService)(oData)
' Dim oItems = oData.Items.
' Select(Function(i)
' If TypeOf i Is Schemas.Orders.Input.MESOWebServiceEXIMVRG_ordersT025 Then
' Return Mapper.Map(Of Schemas.Orders.Output.MESOWebServiceEXIMVRG_ordersT025)(i)
' Else
' Return Mapper.Map(Of Schemas.Orders.Output.MESOWebServiceEXIMVRG_ordersT026)(i)
' End If
' End Function).
' ToList()
' oResult.Items = oItems.ToArray()
' Return oResult
'End Function
'Private Function SerializeOrder(pData As Schemas.Orders.Output.MESOWebService, pFileName As String) As String
' Dim oSerializer = Serializer.GetSerializer(GetType(Schemas.Orders.Output.MESOWebService))
' Dim oPath As String = GetBaseWebServicePath()
' Dim oFilePath As String = IO.Path.Combine(oPath, pFileName)
' Using oWriter = XmlWriter.Create(oFilePath, New XmlWriterSettings With {.Indent = True})
' oSerializer.Serialize(oWriter, pData)
' End Using
' Return oFilePath
'End Function
Private Function GetBaseWebServicePath() As String
Return IO.Path.Combine(FileEx.GetAppDataPath("Digital Data", "EDI Document Importer"), "WebService")
End Function
Private Function GetBaseFilenameForRequest() As String
Return $"{Now:yyyy-MM-dd_hh-mm-ffff}"
End Function
Private Function GetXmlFilenameWithSuffix(pBaseString As String, pSuffix As String, pExtension As String)
Return $"{pBaseString}-{pSuffix}.{pExtension}"
End Function
Private Function GetDateSubDirectoryPath(pBasePath As String)
Dim oDirectoryPath As String = Now.ToString("yyyy\\MM\\dd")
Dim oFullPath As String = IO.Path.Combine(pBasePath, oDirectoryPath)
If IO.Directory.Exists(oFullPath) = False Then
Try
IO.Directory.CreateDirectory(oFullPath)
Return oFullPath
Catch ex As Exception
Logger.Error(ex)
Return Nothing
End Try
Else
Return oFullPath
End If
End Function
End Class
End Namespace