Add MSSQL Functions to ZUGFeRD Service

This commit is contained in:
Jonathan Jenne 2019-04-05 15:51:42 +02:00
parent caad7eda42
commit 720618f29b
10 changed files with 122 additions and 43 deletions

View File

@ -31,6 +31,12 @@
<setting name="JOB_INTERVAL" serializeAs="String"> <setting name="JOB_INTERVAL" serializeAs="String">
<value>10</value> <value>10</value>
</setting> </setting>
<setting name="MSSQL_CONNECTIONSTRING" serializeAs="String">
<value />
</setting>
<setting name="MSSQL_ENABLED" serializeAs="String">
<value>False</value>
</setting>
</DDZUGFeRDService.My.MySettings> </DDZUGFeRDService.My.MySettings>
</applicationSettings> </applicationSettings>
</configuration> </configuration>

View File

@ -116,6 +116,24 @@ Namespace My
Return CType(Me("JOB_INTERVAL"),Integer) Return CType(Me("JOB_INTERVAL"),Integer)
End Get End Get
End Property End Property
<Global.System.Configuration.ApplicationScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("")> _
Public ReadOnly Property MSSQL_CONNECTIONSTRING() As String
Get
Return CType(Me("MSSQL_CONNECTIONSTRING"),String)
End Get
End Property
<Global.System.Configuration.ApplicationScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("False")> _
Public ReadOnly Property MSSQL_ENABLED() As Boolean
Get
Return CType(Me("MSSQL_ENABLED"),Boolean)
End Get
End Property
End Class End Class
End Namespace End Namespace

View File

@ -23,5 +23,11 @@
<Setting Name="JOB_INTERVAL" Type="System.Int32" Scope="Application"> <Setting Name="JOB_INTERVAL" Type="System.Int32" Scope="Application">
<Value Profile="(Default)">10</Value> <Value Profile="(Default)">10</Value>
</Setting> </Setting>
<Setting Name="MSSQL_CONNECTIONSTRING" Type="System.String" Scope="Application">
<Value Profile="(Default)" />
</Setting>
<Setting Name="MSSQL_ENABLED" Type="System.Boolean" Scope="Application">
<Value Profile="(Default)">False</Value>
</Setting>
</Settings> </Settings>
</SettingsFile> </SettingsFile>

View File

@ -22,18 +22,27 @@ Public Class ThreadRunner
Private _originalEmailDirectory As String Private _originalEmailDirectory As String
Private _zugferd As ZUGFeRDInterface Private _zugferd As ZUGFeRDInterface
Private _jobArguments As WorkerArgs Private _jobArguments As WorkerArgs
Private _mssql As MSSQLServer
Private Const TIMER_INTERVAL_MS = 10_000 Private Const TIMER_INTERVAL_MS = 10_000
Public Sub New(LogConfig As LogConfig, Firebird As Firebird) Public Sub New(LogConfig As LogConfig, Firebird As Firebird, Optional MSSQL As MSSQLServer = Nothing)
_logConfig = LogConfig _logConfig = LogConfig
_logger = _logConfig.GetLogger() _logger = _logConfig.GetLogger()
_firebird = Firebird _firebird = Firebird
_zugferd = New ZUGFeRDInterface(_logConfig) _zugferd = New ZUGFeRDInterface(_logConfig)
_mssql = MSSQL
Dim args As New WorkerArgs() Dim args As New WorkerArgs()
args = LoadFolderConfig(args) args = LoadFolderConfig(args)
args = LoadPropertyMapFor(args, "DEFAULT") args = LoadPropertyMapFor(args, "DEFAULT")
' Use MSSQL Server if available
If _mssql IsNot Nothing Then
_logger.Debug("Data will be inserted into MSSQL Server.")
args.InsertIntoSQLServer = True
End If
_jobArguments = args _jobArguments = args
_logger.Debug("Checking SuccessDirectory {0}", args.SuccessDirectory) _logger.Debug("Checking SuccessDirectory {0}", args.SuccessDirectory)
@ -104,7 +113,7 @@ Public Class ThreadRunner
_logger.Debug("Background worker running..") _logger.Debug("Background worker running..")
Dim job As New ImportZUGFeRDFiles(_logConfig, _firebird) Dim job As New ImportZUGFeRDFiles(_logConfig, _firebird, _mssql)
job.Start(args) job.Start(args)
Catch ex As Exception Catch ex As Exception
_logger.Warn("Background worker failed!") _logger.Warn("Background worker failed!")

View File

@ -7,6 +7,7 @@ Public Class ZUGFeRDService
Private _logConfig As LogConfig Private _logConfig As LogConfig
Private _logger As Logger Private _logger As Logger
Private _firebird As Firebird Private _firebird As Firebird
Private _mssql As MSSQLServer = Nothing
Private _threadRunner As ThreadRunner Private _threadRunner As ThreadRunner
@ -21,14 +22,22 @@ Public Class ZUGFeRDService
Dim oUser As String = My.Settings.DB_USER Dim oUser As String = My.Settings.DB_USER
Dim oPassword As String = My.Settings.DB_PASSWORD Dim oPassword As String = My.Settings.DB_PASSWORD
Dim oJobInterval As Integer = My.Settings.JOB_INTERVAL Dim oJobInterval As Integer = My.Settings.JOB_INTERVAL
Dim oMSSQLConnectionString As String = My.Settings.MSSQL_CONNECTIONSTRING
_logger.Debug("Datasource: {0}", oDataSource) Dim oMSSQLEnabled As Boolean = My.Settings.MSSQL_ENABLED
_logger.Debug("Database: {0}", oDatabase)
_firebird = New Firebird(_logConfig, oDataSource, oDatabase, oUser, oPassword) _firebird = New Firebird(_logConfig, oDataSource, oDatabase, oUser, oPassword)
If oMSSQLEnabled = True Then
_mssql = New MSSQLServer(_logConfig, oMSSQLConnectionString)
If _mssql.DBInitialized = False Then
_logger.Warn("MSSQL Connection could not be initialized. Disabling MSSQL.")
_mssql = Nothing
End If
End If
Try Try
_threadRunner = New ThreadRunner(_logConfig, _firebird) _threadRunner = New ThreadRunner(_logConfig, _firebird, _mssql)
_threadRunner.Start(oJobInterval) _threadRunner.Start(oJobInterval)
Catch ex As Exception Catch ex As Exception
_logger.Error(ex) _logger.Error(ex)

View File

@ -24,13 +24,15 @@ Public Class ImportZUGFeRDFiles
Private _zugferd As ZUGFeRDInterface Private _zugferd As ZUGFeRDInterface
Private _firebird As Firebird Private _firebird As Firebird
Private _filesystem As Filesystem.File Private _filesystem As Filesystem.File
Private _mssql As MSSQLServer
Public Sub New(LogConfig As LogConfig, Firebird As Firebird) Public Sub New(LogConfig As LogConfig, Firebird As Firebird, Optional MSSQL As MSSQLServer = Nothing)
_logConfig = LogConfig _logConfig = LogConfig
_logger = LogConfig.GetLogger() _logger = LogConfig.GetLogger()
_firebird = Firebird _firebird = Firebird
_filesystem = New Filesystem.File(_logConfig) _filesystem = New Filesystem.File(_logConfig)
_zugferd = New ZUGFeRDInterface(_logConfig) _zugferd = New ZUGFeRDInterface(_logConfig)
_mssql = MSSQL
End Sub End Sub
Private Function RandomValue(lowerBound As Integer, upperBound As Integer) As Integer Private Function RandomValue(lowerBound As Integer, upperBound As Integer) As Integer
@ -182,7 +184,7 @@ Public Class ImportZUGFeRDFiles
Public Sub Start(Arguments As Object) Implements IJob.Start Public Sub Start(Arguments As Object) Implements IJob.Start
Dim args As WorkerArgs = Arguments Dim args As WorkerArgs = Arguments
_logger.Info("Starting Job {0}", Me.GetType.Name) _logger.Info("Starting Job {0}", [GetType].Name)
Try Try
For Each oPath As String In args.WatchDirectories For Each oPath As String In args.WatchDirectories
@ -276,9 +278,17 @@ Public Class ImportZUGFeRDFiles
Dim oTableName = Item.Value.TableName Dim oTableName = Item.Value.TableName
Dim oCommand = $"INSERT INTO {oTableName} (REFERENCE_GUID, ITEM_DESCRIPTION, ITEM_VALUE) VALUES ('{oFileGroupId}', '{propertyDescripton}', '{propertyValue}')" Dim oCommand = $"INSERT INTO {oTableName} (REFERENCE_GUID, ITEM_DESCRIPTION, ITEM_VALUE) VALUES ('{oFileGroupId}', '{propertyDescripton}', '{propertyValue}')"
_logger.Debug("Mapping Property {0} to value {1}. Will be inserted into table {2}", propertyDescripton, propertyValue, oTableName) _logger.Debug("Mapping Property {0} to value {1}. Will be inserted into table {2}", propertyDescripton, propertyValue, oTableName)
' Insert into SQL Server
If args.InsertIntoSQLServer = True Then
Dim oResult = _mssql.NewExecutenonQuery(oCommand)
If oResult = False Then
_logger.Warn("SQL Command was not successful. Check the log.")
End If
End If
' Insert into Firebird
_firebird.ExecuteNonQueryWithConnection(oCommand, oConnection, Firebird.TransactionMode.ExternalTransaction, oTransaction) _firebird.ExecuteNonQueryWithConnection(oCommand, oConnection, Firebird.TransactionMode.ExternalTransaction, oTransaction)
Next Next

View File

@ -7,6 +7,7 @@ Public Class WorkerArgs
Public OriginalEmailDirectory As String Public OriginalEmailDirectory As String
Public RejectedEmailDirectory As String Public RejectedEmailDirectory As String
Public PropertyMap As Dictionary(Of String, XmlItemProperty) Public PropertyMap As Dictionary(Of String, XmlItemProperty)
Public InsertIntoSQLServer As Boolean
Public Sub New() Public Sub New()
WatchDirectories = New List(Of String) WatchDirectories = New List(Of String)
@ -15,5 +16,6 @@ Public Class WorkerArgs
OriginalEmailDirectory = Nothing OriginalEmailDirectory = Nothing
RejectedEmailDirectory = Nothing RejectedEmailDirectory = Nothing
PropertyMap = New Dictionary(Of String, XmlItemProperty) PropertyMap = New Dictionary(Of String, XmlItemProperty)
InsertIntoSQLServer = False
End Sub End Sub
End Class End Class

View File

@ -1,29 +1,27 @@
Imports System.Data.SqlClient Imports System.Data.SqlClient
Imports DigitalData.Modules.Logging
Public Class MSSQLServer Public Class MSSQLServer
Private Shared Logger As NLog.Logger = NLog.LogManager.GetCurrentClassLogger
Public DBInitialized As Boolean = False Public DBInitialized As Boolean = False
Public CurrentSQLConnectionString As String = "" Public CurrentSQLConnectionString As String = ""
Private CurrentSQLConnection As SqlClient.SqlConnection Private CurrentSQLConnection As SqlConnection
Public Sub New(CONSTRING As String) Private _Logger As Logger
Init(CONSTRING)
End Sub Public Sub New(LogConfig As LogConfig, ConnectionString As String)
Public Function Init(CONSTRING As String) _Logger = LogConfig.GetLogger()
Try Try
Dim oSQLconnect As New SqlClient.SqlConnection Dim oSQLconnect As New SqlConnection
oSQLconnect.ConnectionString = CONSTRING oSQLconnect.ConnectionString = ConnectionString
oSQLconnect.Open() oSQLconnect.Open()
oSQLconnect.Close() oSQLconnect.Close()
CurrentSQLConnectionString = CONSTRING CurrentSQLConnectionString = ConnectionString
DBInitialized = True DBInitialized = True
Return True
Catch ex As Exception Catch ex As Exception
DBInitialized = False DBInitialized = False
Logger.Error(ex) _Logger.Error(ex)
'clsLogger.Add("Error in DatabaseInit: " & ex.Message, True)
Return False
End Try End Try
End Function End Sub
Private Function GetSQLConnection() Private Function GetSQLConnection()
Try Try
@ -32,22 +30,21 @@ Public Class MSSQLServer
oSQLconnect.ConnectionString = CurrentSQLConnectionString oSQLconnect.ConnectionString = CurrentSQLConnectionString
CurrentSQLConnection = oSQLconnect CurrentSQLConnection = oSQLconnect
CurrentSQLConnection.Open() CurrentSQLConnection.Open()
Else Else
If CurrentSQLConnection.State <> ConnectionState.Open Then If CurrentSQLConnection.State <> ConnectionState.Open Then
Logger.Warn($"Actual ConnectionState is: '{CurrentSQLConnection.State.ToString}'") _Logger.Warn($"Actual ConnectionState is: '{CurrentSQLConnection.State.ToString}'")
Try Try
CurrentSQLConnection.Open() CurrentSQLConnection.Open()
Return True Return True
Catch ex As Exception Catch ex As Exception
Logger.Warn("Could not reconnect to database!") _Logger.Warn("Could not reconnect to database!")
Return False Return False
End Try End Try
End If End If
End If End If
Return True Return True
Catch ex As Exception Catch ex As Exception
Logger.Error(ex) _Logger.Error(ex)
Return False Return False
End Try End Try
End Function End Function
@ -65,18 +62,18 @@ Public Class MSSQLServer
Return Nothing Return Nothing
End If End If
Dim oSQLCOmmand As SqlClient.SqlCommand Dim oSQLCOmmand As SqlCommand
oSQLCOmmand = CurrentSQLConnection.CreateCommand() oSQLCOmmand = CurrentSQLConnection.CreateCommand()
oSQLCOmmand.CommandText = sqlcommand oSQLCOmmand.CommandText = sqlcommand
oSQLCOmmand.CommandTimeout = commandtimeout oSQLCOmmand.CommandTimeout = commandtimeout
Dim adapter1 As SqlClient.SqlDataAdapter = New SqlClient.SqlDataAdapter(oSQLCOmmand) Dim adapter1 As SqlDataAdapter = New SqlDataAdapter(oSQLCOmmand)
adapter1.Fill(dt) adapter1.Fill(dt)
Return dt Return dt
Catch ex As Exception Catch ex As Exception
Logger.Error(ex) _Logger.Error(ex)
Logger.Debug("sqlcommand: " & sqlcommand) _Logger.Debug("sqlcommand: " & sqlcommand)
Return Nothing Return Nothing
End Try End Try
End Function End Function
@ -93,7 +90,7 @@ Public Class MSSQLServer
Return Nothing Return Nothing
End If End If
'Dim oSQLconnect As New SqlClient.SqlConnection 'Dim oSQLconnect As New SqlClient.SqlConnection
Dim oSQLCOmmand As SqlClient.SqlCommand Dim oSQLCOmmand As SqlCommand
oSQLCOmmand = CurrentSQLConnection.CreateCommand() oSQLCOmmand = CurrentSQLConnection.CreateCommand()
oSQLCOmmand.CommandText = executeStatement oSQLCOmmand.CommandText = executeStatement
@ -102,8 +99,8 @@ Public Class MSSQLServer
oSQLCOmmand.Dispose() oSQLCOmmand.Dispose()
Return True Return True
Catch ex As Exception Catch ex As Exception
Logger.Error(ex) _Logger.Error(ex)
Logger.Debug("executeStatement: " & executeStatement) _Logger.Debug("executeStatement: " & executeStatement)
Return False Return False
End Try End Try
End Function End Function
@ -118,8 +115,8 @@ Public Class MSSQLServer
Exit Sub Exit Sub
End If End If
Dim oSQLCOmmand As SqlClient.SqlCommand Dim oSQLCOmmand As SqlCommand
Dim callback As New AsyncCallback(AddressOf Execute_non_Query_Async_Callback) Dim callback As New AsyncCallback(AddressOf NewExecuteNonQueryAsync_Callback)
Try Try
oSQLCOmmand = CurrentSQLConnection.CreateCommand() oSQLCOmmand = CurrentSQLConnection.CreateCommand()
oSQLCOmmand.CommandText = executeStatement oSQLCOmmand.CommandText = executeStatement
@ -127,15 +124,15 @@ Public Class MSSQLServer
oSQLCOmmand.BeginExecuteNonQuery(callback, oSQLCOmmand) oSQLCOmmand.BeginExecuteNonQuery(callback, oSQLCOmmand)
oSQLCOmmand.Dispose() oSQLCOmmand.Dispose()
Catch ex As Exception Catch ex As Exception
Logger.Error(ex) _Logger.Error(ex)
Logger.Debug("executeStatement: " & executeStatement) _Logger.Debug("executeStatement: " & executeStatement)
End Try End Try
End Sub End Sub
Private Sub Execute_non_Query_Async_Callback(ByVal result As IAsyncResult) Private Sub NewExecuteNonQueryAsync_Callback(ByVal result As IAsyncResult)
Dim command As SqlClient.SqlCommand = CType(result.AsyncState, SqlClient.SqlCommand) Dim command As SqlCommand = CType(result.AsyncState, SqlCommand)
Dim res = command.EndExecuteNonQuery(result) Dim res = command.EndExecuteNonQuery(result)
Logger.Info(String.Format("Finished executing Async database operation: {0}", command.CommandText)) _Logger.Info(String.Format("Finished executing Async database operation: {0}", command.CommandText))
End Sub End Sub
''' <summary> ''' <summary>
''' Executes the passed sql-statement as Scalar ''' Executes the passed sql-statement as Scalar
@ -159,8 +156,8 @@ Public Class MSSQLServer
oSQLCOmmand.Dispose() oSQLCOmmand.Dispose()
Return result Return result
Catch ex As Exception Catch ex As Exception
Logger.Error(ex) _Logger.Error(ex)
Logger.Debug("executeStatement: " & executeStatement) _Logger.Debug("executeStatement: " & executeStatement)
Return Nothing Return Nothing
End Try End Try
End Function End Function

View File

@ -26,6 +26,7 @@ Partial Class Form1
Me.Button1 = New System.Windows.Forms.Button() Me.Button1 = New System.Windows.Forms.Button()
Me.ListBox1 = New System.Windows.Forms.ListBox() Me.ListBox1 = New System.Windows.Forms.ListBox()
Me.Button2 = New System.Windows.Forms.Button() Me.Button2 = New System.Windows.Forms.Button()
Me.Button3 = New System.Windows.Forms.Button()
Me.SuspendLayout() Me.SuspendLayout()
' '
'OpenFileDialog1 'OpenFileDialog1
@ -58,11 +59,21 @@ Partial Class Form1
Me.Button2.Text = "Validate Single File" Me.Button2.Text = "Validate Single File"
Me.Button2.UseVisualStyleBackColor = True Me.Button2.UseVisualStyleBackColor = True
' '
'Button3
'
Me.Button3.Location = New System.Drawing.Point(12, 70)
Me.Button3.Name = "Button3"
Me.Button3.Size = New System.Drawing.Size(221, 23)
Me.Button3.TabIndex = 3
Me.Button3.Text = "Load Single File"
Me.Button3.UseVisualStyleBackColor = True
'
'Form1 'Form1
' '
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(916, 435) Me.ClientSize = New System.Drawing.Size(916, 435)
Me.Controls.Add(Me.Button3)
Me.Controls.Add(Me.Button2) Me.Controls.Add(Me.Button2)
Me.Controls.Add(Me.ListBox1) Me.Controls.Add(Me.ListBox1)
Me.Controls.Add(Me.Button1) Me.Controls.Add(Me.Button1)
@ -76,4 +87,5 @@ Partial Class Form1
Friend WithEvents Button1 As Button Friend WithEvents Button1 As Button
Friend WithEvents ListBox1 As ListBox Friend WithEvents ListBox1 As ListBox
Friend WithEvents Button2 As Button Friend WithEvents Button2 As Button
Friend WithEvents Button3 As Button
End Class End Class

View File

@ -90,4 +90,14 @@ Public Class Form1
_zugferd.ValidateZUGFeRDFile(OpenFileDialog1.FileName) _zugferd.ValidateZUGFeRDFile(OpenFileDialog1.FileName)
End If End If
End Sub End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim oResult = OpenFileDialog1.ShowDialog()
If oResult = DialogResult.OK Then
Dim oDoc = _zugferd.ValidateZUGFeRDFile(OpenFileDialog1.FileName)
Dim oZUGFERD = _zugferd.SerializeZUGFeRDDocument(oDoc)
Console.WriteLine()
End If
End Sub
End Class End Class