Database: WIP Dispatcher

This commit is contained in:
Jonathan Jenne 2022-09-27 15:00:27 +02:00
parent 790715d0a2
commit 2144d7e771
6 changed files with 329 additions and 103 deletions

View File

@ -3,18 +3,16 @@ Imports System.Data.Common
Imports System.Data.SqlClient Imports System.Data.SqlClient
Imports DigitalData.Modules.Encryption Imports DigitalData.Modules.Encryption
Imports DigitalData.Modules.Logging Imports DigitalData.Modules.Logging
Imports DigitalData.Modules.Base
Public Class MSSQLServer Public Class MSSQLServer
Implements IDatabase Implements IDatabase
Public DBInitialized As Boolean = False Public Property DBInitialized As Boolean = False Implements IDatabase.DBInitialized
Public CurrentSQLConnectionString As String = "" Public Property ConnectionString As String = "" Implements IDatabase.ConnectionString
Public Const TIMEOUT_DEFAULT As Integer = 120 Private ReadOnly QueryTimeout As Integer
Public Const TABLE_DEFAULT As String = "DDRESULT" Private ReadOnly Logger As Logger
Private ReadOnly _Timeout As Integer
Private ReadOnly _Logger As Logger
Public Enum TransactionMode Public Enum TransactionMode
<Description("Use no transaction, neither internal nor external")> <Description("Use no transaction, neither internal nor external")>
@ -25,31 +23,29 @@ Public Class MSSQLServer
WithTransaction WithTransaction
End Enum End Enum
Public Sub New(LogConfig As LogConfig, ConnectionString As String, Optional Timeout As Integer = 120) Public Sub New(pLogConfig As LogConfig, pConnectionString As String, Optional pTimeout As Integer = Constants.DEFAULT_TIMEOUT)
_Logger = LogConfig.GetLogger() Logger = pLogConfig.GetLogger()
_Timeout = Timeout QueryTimeout = pTimeout
CurrentSQLConnectionString = ConnectionString
Try Try
DBInitialized = TestCanConnect() DBInitialized = TestCanConnect()
ConnectionString = pConnectionString
Catch ex As Exception Catch ex As Exception
DBInitialized = False DBInitialized = False
_Logger.Error(ex) Logger.Error(ex)
End Try End Try
End Sub End Sub
Public Sub New(LogConfig As LogConfig, Server As String, Database As String, UserId As String, Password As String, Optional Timeout As Integer = 120) Public Sub New(pLogConfig As LogConfig, Server As String, Database As String, UserId As String, Password As String, Optional Timeout As Integer = Constants.DEFAULT_TIMEOUT)
_Logger = LogConfig.GetLogger() Logger = pLogConfig.GetLogger()
_Timeout = Timeout QueryTimeout = Timeout
CurrentSQLConnectionString = GetConnectionString(Server, Database, UserId, Password)
Try Try
DBInitialized = TestCanConnect() DBInitialized = TestCanConnect()
ConnectionString = GetConnectionString(Server, Database, UserId, Password)
Catch ex As Exception Catch ex As Exception
DBInitialized = False DBInitialized = False
_Logger.Error(ex) Logger.Error(ex)
End Try End Try
End Sub End Sub
@ -88,7 +84,7 @@ Public Class MSSQLServer
Dim oConnectionStringBuilder As New SqlConnectionStringBuilder() With { Dim oConnectionStringBuilder As New SqlConnectionStringBuilder() With {
.DataSource = Server, .DataSource = Server,
.InitialCatalog = Database, .InitialCatalog = Database,
.UserId = UserId, .UserID = UserId,
.Password = Password .Password = Password
} }
@ -101,7 +97,7 @@ Public Class MSSQLServer
Dim oConnection = GetSQLConnection() Dim oConnection = GetSQLConnection()
Return oConnection Return oConnection
Catch ex As Exception Catch ex As Exception
_Logger.Error(ex) Logger.Error(ex)
Return Nothing Return Nothing
End Try End Try
End Function End Function
@ -133,7 +129,7 @@ Public Class MSSQLServer
Transaction.Commit() Transaction.Commit()
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
Case Else Case Else
@ -148,10 +144,10 @@ Public Class MSSQLServer
Public Function Get_ConnectionStringforID(pConnectionId As Integer) As String Public Function Get_ConnectionStringforID(pConnectionId As Integer) As String
Dim oConnectionString As String = String.Empty Dim oConnectionString As String = String.Empty
_Logger.Debug("Getting ConnectionString for ConnectionId [{0}]", pConnectionId) Logger.Debug("Getting ConnectionString for ConnectionId [{0}]", pConnectionId)
If pConnectionId = 0 Then If pConnectionId = 0 Then
_Logger.Warn("ConnectionId was 0. Falling back to default connection.") Logger.Warn("ConnectionId was 0. Falling back to default connection.")
Return String.Empty Return String.Empty
End If End If
@ -181,17 +177,17 @@ Public Class MSSQLServer
End If End If
Case Else Case Else
_Logger.Warn("Provider [{0}] not supported!", oProvider) Logger.Warn("Provider [{0}] not supported!", oProvider)
End Select End Select
Else Else
_Logger.Warn("No entry for Connection-ID: [{0}] ", pConnectionId.ToString) Logger.Warn("No entry for Connection-ID: [{0}] ", pConnectionId.ToString)
End If End If
Catch ex As Exception Catch ex As Exception
_Logger.Error(ex) Logger.Error(ex)
_Logger.Warn("Error in Get_ConnectionStringforID") Logger.Warn("Error in Get_ConnectionStringforID")
End Try End Try
Return DecryptConnectionString(oConnectionString) Return DecryptConnectionString(oConnectionString)
@ -199,12 +195,12 @@ Public Class MSSQLServer
<DebuggerStepThrough()> <DebuggerStepThrough()>
Private Function TestCanConnect() As Boolean Private Function TestCanConnect() As Boolean
Return TestCanConnect(CurrentSQLConnectionString) Return TestCanConnect(ConnectionString)
End Function End Function
Private Function TestCanConnect(ConnectionString As String) As Boolean Private Function TestCanConnect(ConnectionString As String) As Boolean
Try Try
_Logger.Debug("Testing connection to [{0}]", MaskConnectionString(ConnectionString)) Logger.Debug("Testing connection to [{0}]", MaskConnectionString(ConnectionString))
Dim oDecryptedConnectionString = DecryptConnectionString(ConnectionString) Dim oDecryptedConnectionString = DecryptConnectionString(ConnectionString)
Dim oConnection As New SqlConnection(oDecryptedConnectionString) Dim oConnection As New SqlConnection(oDecryptedConnectionString)
@ -212,7 +208,7 @@ Public Class MSSQLServer
oConnection.Close() oConnection.Close()
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
@ -220,17 +216,17 @@ Public Class MSSQLServer
Private Function TestCanConnect(Connection As SqlConnection) As Boolean Private Function TestCanConnect(Connection As SqlConnection) As Boolean
Try Try
If Connection Is Nothing Then If Connection Is Nothing Then
_Logger.Warn("TestCanConnect: Connection is nothing!") Logger.Warn("TestCanConnect: Connection is nothing!")
Return False Return False
End If End If
_Logger.Debug("Testing connection to [{0}]", MaskConnectionString(Connection.ConnectionString)) Logger.Debug("Testing connection to [{0}]", MaskConnectionString(Connection.ConnectionString))
OpenSQLConnection(Connection) OpenSQLConnection(Connection)
Connection.Close() Connection.Close()
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
@ -250,7 +246,7 @@ Public Class MSSQLServer
<DebuggerStepThrough()> <DebuggerStepThrough()>
Private Function GetSQLConnection() As SqlConnection Private Function GetSQLConnection() As SqlConnection
Return GetConnection(CurrentSQLConnectionString) Return GetConnection(ConnectionString)
End Function End Function
Private Function GetConnection(ConnectionString As String) As SqlConnection Private Function GetConnection(ConnectionString As String) As SqlConnection
@ -259,11 +255,11 @@ Public Class MSSQLServer
oConnection = OpenSQLConnection(oConnection) oConnection = OpenSQLConnection(oConnection)
Dim oMaskedConnectionString = MaskConnectionString(ConnectionString) Dim oMaskedConnectionString = MaskConnectionString(ConnectionString)
_Logger.Debug("The Following Connection is open: {0}", oMaskedConnectionString) Logger.Debug("The Following Connection is open: {0}", oMaskedConnectionString)
Return oConnection Return oConnection
Catch ex As Exception Catch ex As Exception
_Logger.Error(ex) Logger.Error(ex)
Return Nothing Return Nothing
End Try End Try
@ -280,14 +276,14 @@ Public Class MSSQLServer
Dim oConnectionString = ConnectionString.Replace(oBuilder.Password, "XXXXX") Dim oConnectionString = ConnectionString.Replace(oBuilder.Password, "XXXXX")
Return oConnectionString Return oConnectionString
Catch ex As Exception Catch ex As Exception
_Logger.Error(ex) Logger.Error(ex)
Return "Invalid ConnectionString" Return "Invalid ConnectionString"
End Try End Try
End Function End Function
'<DebuggerStepThrough()> '<DebuggerStepThrough()>
Public Function GetDatatable(SqlCommand As String) As DataTable Implements IDatabase.GetDatatable Public Function GetDatatable(SqlCommand As String) As DataTable Implements IDatabase.GetDatatable
Return GetDatatable(SqlCommand, _Timeout) Return GetDatatable(SqlCommand, QueryTimeout)
End Function End Function
''' <summary> ''' <summary>
@ -302,19 +298,19 @@ Public Class MSSQLServer
End Function End Function
'<DebuggerStepThrough()> '<DebuggerStepThrough()>
Public Function GetDatatable(SqlCommand As String, Transaction As SqlTransaction, Optional Timeout As Integer = 120) As DataTable Public Function GetDatatable(SqlCommand As String, Transaction As SqlTransaction, Optional Timeout As Integer = Constants.DEFAULT_TIMEOUT) As DataTable
Using oSqlConnection = GetSQLConnection() Using oSqlConnection = GetSQLConnection()
Return GetDatatableWithConnectionObject(SqlCommand, oSqlConnection, TransactionMode.ExternalTransaction, Transaction, Timeout) Return GetDatatableWithConnectionObject(SqlCommand, oSqlConnection, TransactionMode.ExternalTransaction, Transaction, Timeout)
End Using End Using
End Function End Function
'<DebuggerStepThrough()> '<DebuggerStepThrough()>
Public Async Function GetDatatableAsync(SqlCommand As String, Optional Timeout As Integer = 120) As Task(Of DataTable) Public Async Function GetDatatableAsync(SqlCommand As String, Optional Timeout As Integer = Constants.DEFAULT_TIMEOUT) As Task(Of DataTable)
Return Await Task.Run(Function() GetDatatable(SqlCommand, Timeout)) Return Await Task.Run(Function() GetDatatable(SqlCommand, Timeout))
End Function End Function
'<DebuggerStepThrough()> '<DebuggerStepThrough()>
Public Function GetDatatableWithConnection(SqlCommand As String, ConnectionString As String, Optional Timeout As Integer = 120) As DataTable Public Function GetDatatableWithConnection(SqlCommand As String, ConnectionString As String, Optional Timeout As Integer = Constants.DEFAULT_TIMEOUT) As DataTable
Using oConnection = GetConnection(ConnectionString) Using oConnection = GetConnection(ConnectionString)
Return GetDatatableWithConnectionObject(SqlCommand, oConnection, Timeout:=Timeout) Return GetDatatableWithConnectionObject(SqlCommand, oConnection, Timeout:=Timeout)
End Using End Using
@ -323,9 +319,9 @@ Public Class MSSQLServer
Public Function GetDatatableWithConnectionObject(SqlCommand As String, SqlConnection As SqlConnection, Public Function GetDatatableWithConnectionObject(SqlCommand As String, SqlConnection As SqlConnection,
Optional TransactionMode As TransactionMode = TransactionMode.WithTransaction, Optional TransactionMode As TransactionMode = TransactionMode.WithTransaction,
Optional Transaction As SqlTransaction = Nothing, Optional Transaction As SqlTransaction = Nothing,
Optional Timeout As Integer = 120) As DataTable Optional Timeout As Integer = Constants.DEFAULT_TIMEOUT) As DataTable
Dim oTransaction As SqlTransaction = MaybeGetTransaction(SqlConnection, TransactionMode, Transaction) Dim oTransaction As SqlTransaction = MaybeGetTransaction(SqlConnection, TransactionMode, Transaction)
Dim oTable As New DataTable() With {.TableName = TABLE_DEFAULT} Dim oTable As New DataTable() With {.TableName = Constants.DEFAULT_TABLE}
Try Try
Dim oAdapter As New SqlDataAdapter(New SqlCommand With { Dim oAdapter As New SqlDataAdapter(New SqlCommand With {
@ -335,12 +331,12 @@ Public Class MSSQLServer
.CommandTimeout = Timeout .CommandTimeout = Timeout
}) })
_Logger.Debug("GetDatatableWithConnectionObject: Running Query [{0}]", SqlCommand) Logger.Debug("GetDatatableWithConnectionObject: Running Query [{0}]", SqlCommand)
oAdapter.Fill(oTable) oAdapter.Fill(oTable)
Catch ex As Exception Catch ex As Exception
_Logger.Error(ex) Logger.Error(ex)
_Logger.Warn("GetDatatableWithConnectionObject: Error in GetDatatableWithConnection while executing command: [{0}]", SqlCommand) Logger.Warn("GetDatatableWithConnectionObject: Error in GetDatatableWithConnection while executing command: [{0}]", SqlCommand)
Throw ex Throw ex
Finally Finally
MaybeCommitTransaction(oTransaction, TransactionMode) MaybeCommitTransaction(oTransaction, TransactionMode)
@ -352,7 +348,7 @@ Public Class MSSQLServer
'<DebuggerStepThrough()> '<DebuggerStepThrough()>
Public Function ExecuteNonQuery(SQLCommand As String) As Boolean Implements IDatabase.ExecuteNonQuery Public Function ExecuteNonQuery(SQLCommand As String) As Boolean Implements IDatabase.ExecuteNonQuery
Using oConnection = GetSQLConnection() Using oConnection = GetSQLConnection()
Return ExecuteNonQueryWithConnectionObject(SQLCommand, oConnection, TransactionMode.WithTransaction, Nothing, _Timeout) Return ExecuteNonQueryWithConnectionObject(SQLCommand, oConnection, TransactionMode.WithTransaction, Nothing, QueryTimeout)
End Using End Using
End Function End Function
@ -364,19 +360,19 @@ Public Class MSSQLServer
End Function End Function
'<DebuggerStepThrough()> '<DebuggerStepThrough()>
Public Function ExecuteNonQuery(SQLCommand As String, Transaction As SqlTransaction, Optional Timeout As Integer = 120) As Boolean Public Function ExecuteNonQuery(SQLCommand As String, Transaction As SqlTransaction, Optional Timeout As Integer = Constants.DEFAULT_TIMEOUT) As Boolean
Using oConnection = GetSQLConnection() Using oConnection = GetSQLConnection()
Return ExecuteNonQueryWithConnectionObject(SQLCommand, Transaction.Connection, TransactionMode.ExternalTransaction, Transaction, Timeout) Return ExecuteNonQueryWithConnectionObject(SQLCommand, Transaction.Connection, TransactionMode.ExternalTransaction, Transaction, Timeout)
End Using End Using
End Function End Function
'<DebuggerStepThrough()> '<DebuggerStepThrough()>
Public Async Function ExecuteNonQueryAsync(SQLCommand As String, Optional Timeout As Integer = 120) As Task(Of Boolean) Public Async Function ExecuteNonQueryAsync(SQLCommand As String, Optional Timeout As Integer = Constants.DEFAULT_TIMEOUT) As Task(Of Boolean)
Return Await Task.Run(Function() ExecuteNonQuery(SQLCommand, Timeout)) Return Await Task.Run(Function() ExecuteNonQuery(SQLCommand, Timeout))
End Function End Function
'<DebuggerStepThrough()> '<DebuggerStepThrough()>
Public Function ExecuteNonQueryWithConnection(pSQLCommand As String, ConnString As String, Optional Timeout As Integer = 120) As Boolean Public Function ExecuteNonQueryWithConnection(pSQLCommand As String, ConnString As String, Optional Timeout As Integer = Constants.DEFAULT_TIMEOUT) As Boolean
Using oConnection = GetConnection(ConnString) Using oConnection = GetConnection(ConnString)
Return ExecuteNonQueryWithConnectionObject(pSQLCommand, oConnection, TransactionMode.WithTransaction, Nothing, Timeout) Return ExecuteNonQueryWithConnectionObject(pSQLCommand, oConnection, TransactionMode.WithTransaction, Nothing, Timeout)
End Using End Using
@ -385,11 +381,11 @@ Public Class MSSQLServer
Public Function ExecuteNonQueryWithConnectionObject(SqlCommand As String, SqlConnection As SqlConnection, Public Function ExecuteNonQueryWithConnectionObject(SqlCommand As String, SqlConnection As SqlConnection,
Optional TransactionMode As TransactionMode = TransactionMode.WithTransaction, Optional TransactionMode As TransactionMode = TransactionMode.WithTransaction,
Optional Transaction As SqlTransaction = Nothing, Optional Transaction As SqlTransaction = Nothing,
Optional Timeout As Integer = 120) As Boolean Optional Timeout As Integer = Constants.DEFAULT_TIMEOUT) As Boolean
Dim oTransaction As SqlTransaction = MaybeGetTransaction(SqlConnection, TransactionMode, Transaction) Dim oTransaction As SqlTransaction = MaybeGetTransaction(SqlConnection, TransactionMode, Transaction)
Try Try
_Logger.Debug("ExecuteNonQueryWithConnectionObject: Running Command [{0}]", SqlCommand) Logger.Debug("ExecuteNonQueryWithConnectionObject: Running Command [{0}]", SqlCommand)
Using oSQLCOmmand = SqlConnection.CreateCommand() Using oSQLCOmmand = SqlConnection.CreateCommand()
oSQLCOmmand.CommandText = SqlCommand oSQLCOmmand.CommandText = SqlCommand
@ -400,8 +396,8 @@ Public Class MSSQLServer
Return True Return True
Catch ex As Exception Catch ex As Exception
_Logger.Error(ex) Logger.Error(ex)
_Logger.Warn("ExecuteNonQueryWithConnectionObject: Error in ExecuteNonQueryWithConnectionObject while executing command: [{0}]-[{1}]", SqlCommand, SqlConnection.ConnectionString) Logger.Warn("ExecuteNonQueryWithConnectionObject: Error in ExecuteNonQueryWithConnectionObject while executing command: [{0}]-[{1}]", SqlCommand, SqlConnection.ConnectionString)
Return False Return False
Finally Finally
MaybeCommitTransaction(oTransaction, TransactionMode) MaybeCommitTransaction(oTransaction, TransactionMode)
@ -423,19 +419,19 @@ Public Class MSSQLServer
End Function End Function
'<DebuggerStepThrough()> '<DebuggerStepThrough()>
Public Function GetScalarValue(SQLCommand As String, Transaction As SqlTransaction, Optional Timeout As Integer = 120) As Object Public Function GetScalarValue(SQLCommand As String, Transaction As SqlTransaction, Optional Timeout As Integer = Constants.DEFAULT_TIMEOUT) As Object
Using oConnection = GetSQLConnection() Using oConnection = GetSQLConnection()
Return GetScalarValueWithConnectionObject(SQLCommand, oConnection, TransactionMode.ExternalTransaction, Transaction, Timeout) Return GetScalarValueWithConnectionObject(SQLCommand, oConnection, TransactionMode.ExternalTransaction, Transaction, Timeout)
End Using End Using
End Function End Function
'<DebuggerStepThrough()> '<DebuggerStepThrough()>
Public Async Function GetScalarValueAsync(SQLQuery As String, Optional Timeout As Integer = 120) As Task(Of Object) Public Async Function GetScalarValueAsync(SQLQuery As String, Optional Timeout As Integer = Constants.DEFAULT_TIMEOUT) As Task(Of Object)
Return Await Task.Run(Function() GetScalarValue(SQLQuery, Timeout)) Return Await Task.Run(Function() GetScalarValue(SQLQuery, Timeout))
End Function End Function
'<DebuggerStepThrough()> '<DebuggerStepThrough()>
Public Function GetScalarValueWithConnection(SQLCommand As String, ConnectionString As String, Optional Timeout As Integer = 120) As Object Public Function GetScalarValueWithConnection(SQLCommand As String, ConnectionString As String, Optional Timeout As Integer = Constants.DEFAULT_TIMEOUT) As Object
Using oConnection = GetConnection(ConnectionString) Using oConnection = GetConnection(ConnectionString)
Return GetScalarValueWithConnectionObject(SQLCommand, oConnection, TransactionMode.WithTransaction, Nothing, Timeout) Return GetScalarValueWithConnectionObject(SQLCommand, oConnection, TransactionMode.WithTransaction, Nothing, Timeout)
End Using End Using
@ -444,7 +440,7 @@ Public Class MSSQLServer
Public Function GetScalarValueWithConnectionObject(SqlCommand As String, SqlConnection As SqlConnection, Public Function GetScalarValueWithConnectionObject(SqlCommand As String, SqlConnection As SqlConnection,
Optional TransactionMode As TransactionMode = TransactionMode.WithTransaction, Optional TransactionMode As TransactionMode = TransactionMode.WithTransaction,
Optional Transaction As SqlTransaction = Nothing, Optional Transaction As SqlTransaction = Nothing,
Optional Timeout As Integer = 120) As Object Optional Timeout As Integer = Constants.DEFAULT_TIMEOUT) As Object
Dim oTransaction As SqlTransaction = MaybeGetTransaction(SqlConnection, TransactionMode, Transaction) Dim oTransaction As SqlTransaction = MaybeGetTransaction(SqlConnection, TransactionMode, Transaction)
Dim oResult As Object = Nothing Dim oResult As Object = Nothing
@ -458,8 +454,8 @@ Public Class MSSQLServer
oResult = oSQLCOmmand.ExecuteScalar() oResult = oSQLCOmmand.ExecuteScalar()
End Using End Using
Catch ex As Exception Catch ex As Exception
_Logger.Error(ex) Logger.Error(ex)
_Logger.Warn("GetDatatableWithConnectionObject: Error in GetDatatableWithConnection while executing command: [{0}]", SqlCommand) Logger.Warn("GetDatatableWithConnectionObject: Error in GetDatatableWithConnection while executing command: [{0}]", SqlCommand)
Finally Finally
MaybeCommitTransaction(oTransaction, TransactionMode) MaybeCommitTransaction(oTransaction, TransactionMode)
End Try End Try
@ -473,7 +469,7 @@ Public Class MSSQLServer
Return Nothing Return Nothing
End If End If
_Logger.Debug("GetScalarValue: Running Query [{0}]", SQLCommand) Logger.Debug("GetScalarValue: Running Query [{0}]", SQLCommand)
If SQLCommand.CommandText.Contains(" ") Then If SQLCommand.CommandText.Contains(" ") Then
SQLCommand.CommandType = CommandType.Text SQLCommand.CommandType = CommandType.Text
@ -492,8 +488,8 @@ Public Class MSSQLServer
Return SQLCommand.Parameters(OutputParameter).Value Return SQLCommand.Parameters(OutputParameter).Value
End Using End Using
Catch ex As Exception Catch ex As Exception
_Logger.Error(ex) Logger.Error(ex)
_Logger.Warn($"GetScalarValue failed SQLCommand [{SQLCommand}]") Logger.Warn($"GetScalarValue failed SQLCommand [{SQLCommand}]")
Return Nothing Return Nothing
End Try End Try
@ -501,7 +497,7 @@ Public Class MSSQLServer
'<DebuggerStepThrough()> '<DebuggerStepThrough()>
Public Function GetScalarValue(SQLCommand As SqlCommand, OutputParameter As String) As Object Public Function GetScalarValue(SQLCommand As SqlCommand, OutputParameter As String) As Object
Return GetScalarValue(SQLCommand, OutputParameter, _Timeout) Return GetScalarValue(SQLCommand, OutputParameter, QueryTimeout)
End Function End Function
''' <summary> ''' <summary>
@ -510,8 +506,8 @@ Public Class MSSQLServer
''' <param name="SqlCommand">the sql statement</param> ''' <param name="SqlCommand">the sql statement</param>
''' <param name="commandtimeout">Optional Timeout</param> ''' <param name="commandtimeout">Optional Timeout</param>
''' <remarks></remarks> ''' <remarks></remarks>
Public Sub NewExecuteNonQueryAsync(SqlCommand As String, Optional commandtimeout As Integer = 120) Public Sub NewExecuteNonQueryAsync(SqlCommand As String, Optional commandtimeout As Integer = Constants.DEFAULT_TIMEOUT)
_Logger.Debug("NewExecuteNonQueryAsync: Running Query [{0}]", SqlCommand) Logger.Debug("NewExecuteNonQueryAsync: Running Query [{0}]", SqlCommand)
Try Try
Dim oCallback As New AsyncCallback(AddressOf NewExecuteNonQueryAsync_Callback) Dim oCallback As New AsyncCallback(AddressOf NewExecuteNonQueryAsync_Callback)
@ -524,8 +520,8 @@ Public Class MSSQLServer
End Using End Using
End Using End Using
Catch ex As Exception Catch ex As Exception
_Logger.Error(ex) Logger.Error(ex)
_Logger.Warn($"NewExecuteNonQueryAsync failed SQLCommand [{SqlCommand}]") Logger.Warn($"NewExecuteNonQueryAsync failed SQLCommand [{SqlCommand}]")
End Try End Try
End Sub End Sub
@ -534,6 +530,6 @@ Public Class MSSQLServer
Private Sub NewExecuteNonQueryAsync_Callback(ByVal result As IAsyncResult) Private Sub NewExecuteNonQueryAsync_Callback(ByVal result As IAsyncResult)
Dim command As SqlCommand = CType(result.AsyncState, SqlCommand) Dim command As SqlCommand = CType(result.AsyncState, SqlCommand)
Dim res = command.EndExecuteNonQuery(result) Dim res = command.EndExecuteNonQuery(result)
_Logger.Info("Finished executing Async database operation: {0}", command.CommandText) Logger.Info("Finished executing Async database operation: {0}", command.CommandText)
End Sub End Sub
End Class End Class

View File

@ -1,27 +1,30 @@
Imports DigitalData.Modules.Logging Imports DigitalData.Modules.Encryption
Imports DigitalData.Modules.Logging
Imports Oracle.ManagedDataAccess.Client Imports Oracle.ManagedDataAccess.Client
Public Class Oracle Public Class Oracle
Public DBInitialized As Boolean = False Implements IDatabase
Public CurrentOracleConnectionString As String = ""
Private _Timeout As Integer Public Property DBInitialized As Boolean = False Implements IDatabase.DBInitialized
Private _Logger As Logger Public Property ConnectionString As String = "" Implements IDatabase.ConnectionString
Private ReadOnly _Timeout As Integer
Private ReadOnly _Logger As Logger
Public Sub New(LogConfig As LogConfig, ConnectionString As String, Optional Timeout As Integer = 120) Public Sub New(LogConfig As LogConfig, ConnectionString As String, Optional Timeout As Integer = 120)
_Timeout = Timeout _Timeout = Timeout
_Logger = LogConfig.GetLogger() _Logger = LogConfig.GetLogger()
CurrentOracleConnectionString = ConnectionString ConnectionString = ConnectionString
DBInitialized = TestCanConnect(CurrentOracleConnectionString) DBInitialized = TestCanConnect(ConnectionString)
End Sub End Sub
Public Sub New(LogConfig As LogConfig, Server As String, Database As String, UserId As String, Password As String, Optional Timeout As Integer = 120) Public Sub New(LogConfig As LogConfig, Server As String, Database As String, UserId As String, Password As String, Optional Timeout As Integer = 120)
_Timeout = Timeout _Timeout = Timeout
_Logger = LogConfig.GetLogger() _Logger = LogConfig.GetLogger()
CurrentOracleConnectionString = GetConnectionString(Server, Database, UserId, Password) ConnectionString = GetConnectionString(Server, Database, UserId, Password)
DBInitialized = TestCanConnect(CurrentOracleConnectionString) DBInitialized = TestCanConnect(ConnectionString)
End Sub End Sub
Private Function TestCanConnect(ConnectionString As String) As Boolean Private Function TestCanConnect(ConnectionString As String) As Boolean
@ -43,30 +46,36 @@ Public Class Oracle
End Function End Function
''' <summary> ''' <summary>
''' Returns a datatable for a sql-statement ''' Encrypts a connection string password.
''' </summary> ''' </summary>
''' <param name="sqlcommand">sqlcommand for datatable (select XYZ from TableORView)</param> ''' <param name="ConnectionString">A connection string with a plain-text password</param>
''' <returns>Returns a datatable</returns> ''' <returns>The connection string with the password encrypted.</returns>
Public Function GetDatatable(sqlcommand As String) As DataTable <DebuggerStepThrough()>
Try Public Shared Function EncryptConnectionString(ConnectionString As String) As String
Dim oSQLconnect As New OracleConnection Dim oEncryption As New EncryptionLegacy()
Dim oSQLCOmmand As OracleCommand Dim oBuilder As New OracleConnectionStringBuilder() With {.ConnectionString = ConnectionString}
oSQLconnect.ConnectionString = CurrentOracleConnectionString Dim oEncryptedPassword = oEncryption.EncryptData(oBuilder.Password)
oSQLconnect.Open() oBuilder.Password = oEncryptedPassword
oSQLCOmmand = oSQLconnect.CreateCommand()
oSQLCOmmand.CommandText = sqlcommand Return oBuilder.ToString()
oSQLCOmmand.CommandTimeout = _Timeout
Dim adapter1 As OracleDataAdapter = New OracleDataAdapter(oSQLCOmmand)
Dim dt As DataTable = New DataTable()
adapter1.Fill(dt)
oSQLconnect.Close()
Return dt
Catch ex As Exception
_Logger.Error(ex)
_Logger.Debug("sqlcommand: " & sqlcommand)
Return Nothing
End Try
End Function End Function
''' <summary>
''' Decrypts a connection string password.
''' </summary>
''' <param name="ConnectionString">A connection string with a encrypted password</param>
''' <returns>The connection string with the password decrypted.</returns>
<DebuggerStepThrough()>
Public Shared Function DecryptConnectionString(ConnectionString As String) As String
Dim oEncryption As New EncryptionLegacy()
Dim oBuilder As New OracleConnectionStringBuilder() With {.ConnectionString = ConnectionString}
Dim oDecryptedPassword = oEncryption.DecryptData(oBuilder.Password)
oBuilder.Password = oDecryptedPassword
Return oBuilder.ToString()
End Function
''' <summary> ''' <summary>
''' Executes the passed sql-statement ''' Executes the passed sql-statement
''' </summary> ''' </summary>
@ -76,7 +85,7 @@ Public Class Oracle
Try Try
Dim oSQLconnect As New OracleConnection Dim oSQLconnect As New OracleConnection
Dim oSQLCOmmand As OracleCommand Dim oSQLCOmmand As OracleCommand
oSQLconnect.ConnectionString = CurrentOracleConnectionString oSQLconnect.ConnectionString = ConnectionString
oSQLconnect.Open() oSQLconnect.Open()
oSQLCOmmand = oSQLconnect.CreateCommand() oSQLCOmmand = oSQLconnect.CreateCommand()
oSQLCOmmand.CommandText = executeStatement oSQLCOmmand.CommandText = executeStatement
@ -102,7 +111,7 @@ Public Class Oracle
Try Try
Dim oSQLconnect As New OracleConnection Dim oSQLconnect As New OracleConnection
Dim oSQLCOmmand As OracleCommand Dim oSQLCOmmand As OracleCommand
oSQLconnect.ConnectionString = CurrentOracleConnectionString oSQLconnect.ConnectionString = ConnectionString
oSQLconnect.Open() oSQLconnect.Open()
oSQLCOmmand = oSQLconnect.CreateCommand() oSQLCOmmand = oSQLconnect.CreateCommand()
oSQLCOmmand.CommandText = executeStatement oSQLCOmmand.CommandText = executeStatement
@ -117,4 +126,128 @@ Public Class Oracle
Throw ex Throw ex
End Try End Try
End Function End Function
Public Function GetDatatable(pSQLCommand As String, pTimeout As Integer) As DataTable Implements IDatabase.GetDatatable
Try
Using oConnection = GetConnection(ConnectionString)
Dim oSQLCommand As OracleCommand
oSQLCommand = oConnection.CreateCommand()
oSQLCommand.CommandText = pSQLCommand
oSQLCommand.CommandTimeout = pTimeout
Dim oAdapter As OracleDataAdapter = New OracleDataAdapter(oSQLCommand)
Dim oTable As DataTable = New DataTable()
_Logger.Debug("GetDatatable: Running Query [{0}]", oSQLCommand)
oAdapter.Fill(oTable)
Return oTable
End Using
Catch ex As Exception
_Logger.Error(ex)
_Logger.Warn("GetDatatable: Error in GetDatatable while executing command: [{0}]", pSQLCommand)
Return Nothing
End Try
End Function
Private Function GetDatatable(pSQLCommand As String) As DataTable Implements IDatabase.GetDatatable
Return GetDatatable(pSQLCommand, _Timeout)
End Function
Public Function ExecuteNonQuery(pSQLCommand As String, pTimeout As Integer) As Boolean Implements IDatabase.ExecuteNonQuery
Try
Using oConnection = GetConnection(ConnectionString)
Dim oSQLCOmmand As OracleCommand
oSQLCOmmand = oConnection.CreateCommand()
oSQLCOmmand.CommandText = pSQLCommand
oSQLCOmmand.CommandTimeout = pTimeout
_Logger.Debug("ExecuteNonQuery: Running Query [{0}]", oSQLCOmmand)
oSQLCOmmand.ExecuteNonQuery()
oSQLCOmmand.Dispose()
Return True
End Using
Catch ex As Exception
_Logger.Error(ex)
_Logger.Warn("ExecuteNonQuery: Error in ExecuteNonQuery while executing command: [{0}]", pSQLCommand)
Return False
End Try
End Function
Public Function ExecuteNonQuery(pSQLCommand As String) As Boolean Implements IDatabase.ExecuteNonQuery
Return ExecuteNonQuery(pSQLCommand, _Timeout)
End Function
Public Function GetScalarValue(pSQLCommand As String, pTimeout As Integer) As Object Implements IDatabase.GetScalarValue
Dim result
Try
Using oConnection = GetConnection(ConnectionString)
Dim oSQLCOmmand As OracleCommand
oSQLCOmmand = oConnection.CreateCommand()
oSQLCOmmand.CommandText = pSQLCommand
oSQLCOmmand.CommandTimeout = pTimeout
_Logger.Debug("GetScalarValue: Running Query [{0}]", oSQLCOmmand)
result = oSQLCOmmand.ExecuteScalar()
Return result
End Using
Catch ex As Exception
_Logger.Error(ex)
_Logger.Warn("GetScalarValue: Error in GetScalarValue while executing command: [{0}]", pSQLCommand)
Throw ex
End Try
End Function
Public Function GetScalarValue(pSQLCommand As String) As Object Implements IDatabase.GetScalarValue
Return GetScalarValue(pSQLCommand, _Timeout)
End Function
Private Function GetConnection(ConnectionString As String) As OracleConnection
Try
Dim oConnection As New OracleConnection(ConnectionString)
oConnection = OpenSQLConnection(oConnection)
Dim oMaskedConnectionString = MaskConnectionString(ConnectionString)
_Logger.Debug("The Following Connection is open: {0}", oMaskedConnectionString)
Return oConnection
Catch ex As Exception
_Logger.Error(ex)
Return Nothing
End Try
End Function
''' <summary>
''' This Function intentionally has no try..catch block to have any errors caught outside
''' </summary>
''' <param name="Connection"></param>
''' <returns></returns>
Private Function OpenSQLConnection(Connection As OracleConnection) As OracleConnection
If Connection.State = ConnectionState.Closed Then
Connection.Open()
End If
Return Connection
End Function
<DebuggerStepThrough()>
Private Function MaskConnectionString(ConnectionString As String) As String
Try
If ConnectionString Is Nothing OrElse ConnectionString.Length = 0 Then
Throw New ArgumentNullException("ConnectionString")
End If
Dim oBuilder As New OracleConnectionStringBuilder() With {.ConnectionString = ConnectionString}
Dim oConnectionString = ConnectionString.Replace(oBuilder.Password, "XXXXX")
Return oConnectionString
Catch ex As Exception
_Logger.Error(ex)
Return "Invalid ConnectionString"
End Try
End Function
End Class End Class

View File

@ -4,4 +4,5 @@
Public Const PROVIDER_ODBC = "ODBC" Public Const PROVIDER_ODBC = "ODBC"
Public Const DEFAULT_TIMEOUT = 120 Public Const DEFAULT_TIMEOUT = 120
Public Const DEFAULT_TABLE = "DDRESULT"
End Class End Class

View File

@ -93,6 +93,7 @@
<ItemGroup> <ItemGroup>
<Compile Include="ConnectionString.vb" /> <Compile Include="ConnectionString.vb" />
<Compile Include="Constants.vb" /> <Compile Include="Constants.vb" />
<Compile Include="Dispatcher.vb" />
<Compile Include="Exceptions.vb" /> <Compile Include="Exceptions.vb" />
<Compile Include="Adapters\Firebird.vb" /> <Compile Include="Adapters\Firebird.vb" />
<Compile Include="IDatabase.vb" /> <Compile Include="IDatabase.vb" />

View File

@ -0,0 +1,89 @@
Imports DigitalData.Modules.Base
Imports DigitalData.Modules.Logging
Public Class Dispatcher
Public ReadOnly Property Connections As New List(Of DispatcherConnection)
Public ReadOnly Logger As Logger
Public ReadOnly LogConfig As LogConfig
Public Sub New(pLogConfig As LogConfig, pConnections As List(Of DispatcherConnection))
LogConfig = pLogConfig
Logger = pLogConfig.GetLogger()
Connections = pConnections
End Sub
Public Function GetDatatable(pSQLCommand As String, pConnectionId As Integer) As DataTable
Dim oAdapter As IDatabase = GetAdapterClass(pConnectionId)
Return oAdapter.GetDatatable(pSQLCommand)
End Function
Public Function ExectueNonQuery(pSQLCommand As String, pConnectionId As Integer) As Boolean
Dim oAdapter As IDatabase = GetAdapterClass(pConnectionId)
Return oAdapter.ExecuteNonQuery(pSQLCommand)
End Function
Public Function GetScalarValue(pSQLCommand As String, pConnectionId As Integer) As Object
Dim oAdapter As IDatabase = GetAdapterClass(pConnectionId)
Return oAdapter.GetScalarValue(pSQLCommand)
End Function
Private Function GetConnection(pConnectionId As Integer) As DispatcherConnection
Dim oConnection As DispatcherConnection = Connections.
Where(Function(conn) conn.Id = pConnectionId).
FirstOrDefault()
If oConnection IsNot Nothing Then
Logger.Debug("Resolved ConnectionId [{0}] into Connection [{1}]", pConnectionId, oConnection.Name)
End If
Return oConnection
End Function
Private Function GetAdapterClass(pConnectionId As Integer) As IDatabase
Dim oConnection = GetConnection(pConnectionId)
Dim oArgs As New List(Of Object) From {LogConfig, oConnection.ConnectionString, Constants.DEFAULT_TIMEOUT}
Logger.Debug("Creating database adapter object for type [{0}]", ConnectionType.MSSQL)
' TODO: Cache Database instances to avoid constructing them for every call
Select Case oConnection.ConnectionType
Case ConnectionType.MSSQL
Return New MSSQLServer(LogConfig, oConnection.ConnectionString, Constants.DEFAULT_TIMEOUT)
Case ConnectionType.Oracle
Return New Oracle(LogConfig, oConnection.ConnectionString, Constants.DEFAULT_TIMEOUT)
Case ConnectionType.Firebird
Dim oBuilder As New FirebirdSql.Data.FirebirdClient.FbConnectionStringBuilder(oConnection.ConnectionString)
Return New Firebird(LogConfig, oBuilder.DataSource, oBuilder.Database, oBuilder.UserID, oBuilder.Password)
Case ConnectionType.ODBC
'Dim oBuilder As New Data.Odbc.OdbcConnectionStringBuilder(pConnection.ConnectionString)
'Return New ODBC(LogConfig)
Return Nothing
Case Else
Return Nothing
End Select
End Function
Public Enum ConnectionType
MSSQL
Oracle
ODBC
Firebird
End Enum
Public Class DispatcherOptions
Public Property QueryTimeout As Integer = Constants.DEFAULT_TIMEOUT
End Class
Public Class DispatcherConnection
Public Property Id As Integer
Public Property Name As String
Public Property ConnectionString As String
Public Property ConnectionType As ConnectionType
End Class
End Class

View File

@ -1,6 +1,12 @@
Imports System.Data.Common Imports System.Data.Common
Public Interface IDatabase Public Interface IDatabase
''' <summary>
''' Returns true if the initial connection to the configured database was successful.
''' </summary>
Property DBInitialized As Boolean
Property ConnectionString As String
Function GetDatatable(SqlCommand As String, Timeout As Integer) As DataTable Function GetDatatable(SqlCommand As String, Timeout As Integer) As DataTable
Function GetDatatable(SqlCommand As String) As DataTable Function GetDatatable(SqlCommand As String) As DataTable