Imports System.Data.SqlClient
Imports Oracle.ManagedDataAccess.Client
Imports System.Threading.Tasks

Public Class ClassDatabase
    Private Shared SQLSERVERConnectionString As String
    Private Shared OracleConnectionString As String
    Public Shared Function Get_ConnectionString(id As Integer)
        Dim connectionString As String = ""
        Try
            'Me.TBCONNECTIONTableAdapter.FillByID(Me.DD_DMSLiteDataSet.TBCONNECTION, id)
            Dim DTConnection As DataTable = ClassDatabase.Return_Datatable("SELECT * FROM TBDD_CONNECTION WHERE GUID = " & id, "Get_ConnectionString")
            If DTConnection.Rows.Count = 1 Then
                Select Case DTConnection.Rows(0).Item("SQL_PROVIDER").ToString.ToUpper
                    Case "MS-SQL"
                        If DTConnection.Rows(0).Item("USERNAME") = "WINAUTH" Then
                            connectionString = "Server=" & DTConnection.Rows(0).Item("SERVER") & ";Database=" & DTConnection.Rows(0).Item("DATENBANK") & ";Trusted_Connection=True;"
                        Else
                            connectionString = "Server=" & DTConnection.Rows(0).Item("SERVER") & ";Database=" & DTConnection.Rows(0).Item("DATENBANK") & ";User Id=" & DTConnection.Rows(0).Item("USERNAME") & ";Password=" & DTConnection.Rows(0).Item("USERNAME") & ";Password=" & DTConnection.Rows(0).Item("PASSWORD") & ";"
                        End If
                        ' connectionString = "Server=" & DTConnection.Rows(0).Item("SERVER") & ";Database=" & DTConnection.Rows(0).Item("DATENBANK") & ";User Id=" & DTConnection.Rows(0).Item("USERNAME") & ";Password=" & DTConnection.Rows(0).Item("PASSWORD") & ";"
                    Case "Oracle"
                        If DTConnection.Rows(0).Item("BEMERKUNG").ToString.Contains("without tnsnames") Then
                            connectionString = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=" & DTConnection.Rows(0).Item("SERVER") & ")(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=" &
                               DTConnection.Rows(0).Item("DATENBANK") & ")));User Id=" & DTConnection.Rows(0).Item("USERNAME") & ";Password=" & DTConnection.Rows(0).Item("PASSWORD") & ";"
                        Else
                            connectionString = "Data Source=" & DTConnection.Rows(0).Item("SERVER") & ";Persist Security Info=True;User Id=" & DTConnection.Rows(0).Item("USERNAME") & ";Password=" & DTConnection.Rows(0).Item("PASSWORD") & ";Unicode=True"
                        End If
                        'Case "ODBC"
                        '    Dim conn As New OdbcConnection("dsn=" & DTConnection.Rows(0).Item("SERVER") & ";uid=" & DTConnection.Rows(0).Item("USERNAME") & ";pwd=" + DTConnection.Rows(0).Item("PASSWORD"))
                        '    connectionString = conn.ConnectionString
                    Case Else
                        LOGGER.Info(" - ConnectionType nicht integriert", False)
                        MsgBox("ConnectionType nicht integriert", MsgBoxStyle.Critical, "Bitte Konfiguration Connection überprüfen!")
                End Select
            Else
                LOGGER.Info(" No entry for Connection-ID: " & id.ToString, True)
            End If

        Catch ex As Exception
            LOGGER.Error(ex)
            LOGGER.Info(" - Error in bei Get ConnectionString - Fehler: " & vbNewLine & ex.Message)
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error in Get ConnectionString:")
        End Try
        Return connectionString
    End Function
    Public Shared Function Init(Optional ConString As String = "")
        Try
            If ConString = String.Empty Then
                SQLSERVERConnectionString = CONNECTION_STRING
            End If

            Dim SQLconnect As New SqlClient.SqlConnection
            If ConString <> String.Empty Then
                SQLconnect.ConnectionString = ConString
            Else
                SQLconnect.ConnectionString = SQLSERVERConnectionString
            End If

            SQLconnect.Open()
            SQLconnect.Close()
            Return True
        Catch ex As Exception
            LOGGER.Error(ex)
            If ConString <> String.Empty Then
                LOGGER.Info($"Error initializing Database [{ConString}] " & ex.Message, True)
            Else
                LOGGER.Info($"Error initializing Database [{CONNECTION_STRING}] " & ex.Message, True)
            End If

            Return False
        End Try
    End Function

    Public Shared Function Return_Datatable(pSQLCommand As String, Optional pInfo As String = "") As DataTable
        Try
            If pInfo <> "" Then
                pInfo = "[" & pInfo & "]"
            End If
            Dim SQLconnect As New SqlClient.SqlConnection
            Dim SQLcommand As SqlClient.SqlCommand
            LOGGER.Debug($"Return_Datatable[{pSQLCommand}]#{pInfo}")
            SQLconnect.ConnectionString = SQLSERVERConnectionString
            SQLconnect.Open()
            SQLcommand = SQLconnect.CreateCommand
            SQLcommand.CommandTimeout = 120
            SQLcommand.CommandText = pSQLCommand
            LOGGER.Debug("Execute ReturnDatatable: " & pSQLCommand)
            Dim adapter1 As SqlClient.SqlDataAdapter = New SqlClient.SqlDataAdapter(SQLcommand)
            Dim dt As DataTable = New DataTable()
            adapter1.Fill(dt)
            SQLconnect.Close()
            Return dt
        Catch ex As Exception
            LOGGER.Warn($"Unexpected Error in Return_Datatable{pInfo}: {ex.Message} [{pSQLCommand}]")
            Return Nothing
        End Try
    End Function

    Public Shared Async Function Return_DatatableAsync(pSQLCommand As String, Optional pInfo As String = "") As Task(Of DataTable)
        Return Await Task.Run(Function()
                                  Return Return_Datatable(pSQLCommand, pInfo)
                              End Function)
    End Function

    Public Shared Function Return_Datatable_ConId(pSQLCommand As String, ConnID As Integer, Optional pInfo As String = "")
        Try
            If pInfo <> "" Then
                pInfo = "[" & pInfo & "]"
            End If
            Dim oConnString = Get_ConnectionString(ConnID)
            LOGGER.Debug($"Return_Datatable_ConId [{ConnID}]#[{pSQLCommand}]#{pInfo}")
            Dim oSQLconnect As New SqlClient.SqlConnection
            Dim oSQLcommand As SqlClient.SqlCommand
            oSQLconnect.ConnectionString = oConnString
            oSQLconnect.Open()
            oSQLcommand = oSQLconnect.CreateCommand
            oSQLcommand.CommandText = pSQLCommand

            Dim oSQLAdapter As SqlClient.SqlDataAdapter = New SqlClient.SqlDataAdapter(oSQLcommand)
            Dim oReturnDatatable As DataTable = New DataTable()
            oSQLAdapter.Fill(oReturnDatatable)
            oSQLconnect.Close()
            Return oReturnDatatable
        Catch ex As Exception
            LOGGER.Warn($"Unexpected Error in Return_Datatable_ConId{pInfo}: {ex.Message} [{pSQLCommand}]")
            Return Nothing
        End Try
    End Function
    Public Shared Function Return_Datatable_ConStr(pSQLCommand As String, ConNStr As String, Optional pInfo As String = "")
        Try
            If pInfo <> "" Then
                pInfo = "[" & pInfo & "]"
            End If
            LOGGER.Debug("Return_Datatable_ConStr: " & pSQLCommand)

            Dim oSQLconnect As New SqlClient.SqlConnection
            Dim oSQLcommand As SqlClient.SqlCommand
            oSQLconnect.ConnectionString = ConNStr
            oSQLconnect.Open()
            oSQLcommand = oSQLconnect.CreateCommand
            oSQLcommand.CommandText = pSQLCommand

            Dim oSQLAdapter As SqlClient.SqlDataAdapter = New SqlClient.SqlDataAdapter(oSQLcommand)
            Dim oReturnDatatable As DataTable = New DataTable()
            oSQLAdapter.Fill(oReturnDatatable)
            oSQLconnect.Close()
            Return oReturnDatatable
        Catch ex As Exception
            LOGGER.Warn($"Unexpected Error in Return_Datatable_ConStr{pInfo}: {ex.Message} [{pSQLCommand}]")
            Return Nothing
        End Try
    End Function
    Public Shared Function Execute_non_Query(pSQLCommand As String, Optional pInfo As String = "")
        Try
            If pInfo <> "" Then
                pInfo = "[" & pInfo & "]"
            End If
            Dim SQLconnect As New SqlClient.SqlConnection
            Dim SQLcommand As SqlClient.SqlCommand
            SQLconnect.ConnectionString = SQLSERVERConnectionString
            SQLconnect.Open()
            SQLcommand = SQLconnect.CreateCommand
            'Update Last Created Record in Foo
            SQLcommand.CommandText = pSQLCommand
            LOGGER.Debug("Execute_non_Query Created: " & pSQLCommand)
            SQLcommand.ExecuteNonQuery()
            SQLcommand.Dispose()
            SQLconnect.Close()
            Return True
        Catch ex As Exception
            LOGGER.Warn($"Unexpected Error in Execute_non_Query{pInfo}: {ex.Message} [{pSQLCommand}]")
            Return False
        End Try
    End Function
    Public Shared Function Execute_non_Query_ConStr(pSQLCommand As String, ConnString As String, Optional pInfo As String = "")
        Try
            If pInfo <> "" Then
                pInfo = "[" & pInfo & "]"
            End If
            Dim SQLconnect As New SqlClient.SqlConnection
            Dim SQLcommand As SqlClient.SqlCommand
            SQLconnect.ConnectionString = ConnString
            SQLconnect.Open()
            SQLcommand = SQLconnect.CreateCommand
            'Update Last Created Record in Foo
            SQLcommand.CommandText = pSQLCommand
            LOGGER.Debug("Execute_non_Query_ConStr Created: " & pSQLCommand)
            SQLcommand.ExecuteNonQuery()
            SQLcommand.Dispose()
            SQLconnect.Close()
            Return True
        Catch ex As Exception
            LOGGER.Warn($"Unexpected Error in Execute_non_Query_ConStr{pInfo}: {ex.Message} [{pSQLCommand}]")
            Return False
        End Try
    End Function
    Public Shared Function Execute_Scalar(pSQLCommand As String, ConString As String, Optional pInfo As String = "")
        Dim result
        Try
            If pInfo <> "" Then
                pInfo = "[" & pInfo & "]"
            End If
            Dim SQLconnect As New SqlClient.SqlConnection
            Dim SQLcommand As SqlClient.SqlCommand
            SQLconnect.ConnectionString = ConString

            SQLconnect.Open()
            SQLcommand = SQLconnect.CreateCommand
            'Update Last Created Record in Foo
            SQLcommand.CommandText = pSQLCommand
            LOGGER.Debug("Execute_Scalar: " & pSQLCommand)
            result = SQLcommand.ExecuteScalar()
            SQLcommand.Dispose()
            SQLconnect.Close()
            Return result
        Catch ex As Exception
            LOGGER.Warn($"Unexpected Error in Execute_Scalar{pInfo}: {ex.Message} [{pSQLCommand}]")
            Return Nothing
        End Try
    End Function
    Public Shared Function Execute_Scalar_ConStr(pSQLCommand As String, ConString As String, Optional pInfo As String = "")
        Dim result
        Try
            If pInfo <> "" Then
                pInfo = "[" & pInfo & "]"
            End If
            Dim SQLconnect As New SqlClient.SqlConnection
            Dim SQLcommand As SqlClient.SqlCommand
            SQLconnect.ConnectionString = ConString
            SQLconnect.Open()
            SQLcommand = SQLconnect.CreateCommand
            'Update Last Created Record in Foo
            SQLcommand.CommandText = pSQLCommand
            LOGGER.Debug("Execute_Scalar_ConStr Scalar: " & pSQLCommand)
            result = SQLcommand.ExecuteScalar()
            SQLcommand.Dispose()
            SQLconnect.Close()
            Return result
        Catch ex As Exception
            LOGGER.Warn($"Unexpected Error in Execute_Scalar_ConStr{pInfo}: {ex.Message} [{pSQLCommand}]")
            Return Nothing
        End Try
    End Function
    Public Shared Function Execute_Scalar_ConID(pSQLCommand As String, ConnID As Integer, Optional pInfo As String = "")
        Dim result
        Try
            If pInfo <> "" Then
                pInfo = "[" & pInfo & "]"
            End If
            Dim oConnString = Get_ConnectionString(ConnID)
            LOGGER.Debug($"Execute_Scalar_ConID [{ConnID}]: " & pSQLCommand)
            Dim SQLconnect As New SqlClient.SqlConnection
            Dim SQLcommand As SqlClient.SqlCommand
            SQLconnect.ConnectionString = oConnString
            SQLconnect.Open()
            SQLcommand = SQLconnect.CreateCommand
            'Update Last Created Record in Foo
            SQLcommand.CommandText = pSQLCommand
            result = SQLcommand.ExecuteScalar()
            SQLcommand.Dispose()
            SQLconnect.Close()
            Return result
        Catch ex As Exception
            LOGGER.Warn($"Unexpected Error in Execute_Scalar_ConID{pInfo}: {ex.Message} [{pSQLCommand}]")
            Return Nothing
        End Try
    End Function
    Public Shared Function OracleExecute_Scalar(cmdscalar As String, OracleConnection As String)
        Dim result
        Try
            Dim SQLconnect As New OracleConnection
            Dim SQLcommand As New OracleCommand
            SQLconnect.ConnectionString = OracleConnection
            SQLconnect.Open()
            SQLcommand = SQLconnect.CreateCommand
            'Update Last Created Record in Foo
            SQLcommand.CommandText = cmdscalar
            result = SQLcommand.ExecuteScalar()
            SQLcommand.Dispose()
            SQLconnect.Close()
            Return result
        Catch ex As Exception
            LOGGER.Error(ex)
            LOGGER.Info("Fehler bei OracleExecute_Scalar: " & ex.Message, True)
            LOGGER.Info("#SQL: " & cmdscalar, False)
            Return Nothing
        End Try
    End Function
    Public Shared Function OracleExecute_non_Query(ExecuteCMD As String, OracleConnection As String, Optional userInput As Boolean = False)
        Try
            Dim SQLconnect As New OracleConnection
            Dim SQLcommand As OracleCommand
            SQLconnect.ConnectionString = OracleConnection
            SQLconnect.Open()
            SQLcommand = SQLconnect.CreateCommand
            'Update Last Created Record in Foo
            SQLcommand.CommandText = ExecuteCMD
            SQLcommand.ExecuteNonQuery()
            SQLcommand.Dispose()
            SQLconnect.Close()
            Return True
        Catch ex As Exception
            LOGGER.Error(ex)
            If userInput = True Then
                MsgBox("Error in OracleExecute_non_Query - Error-Message:" & vbNewLine & ex.Message & vbNewLine & "SQL-Command:" & vbNewLine & ExecuteCMD, MsgBoxStyle.Critical)
            End If
            LOGGER.Info("Fehler bei OracleExecute_non_Query: " & ex.Message, True)
            LOGGER.Info("#SQL: " & ExecuteCMD, False)

            Return False
        End Try
    End Function

    Public Shared Function Oracle_Return_Datatable(Select_anweisung As String, OracleConnection As String, Optional userInput As Boolean = False)
        Try
            Dim SQLconnect As New OracleConnection
            Dim SQLcommand As OracleCommand
            SQLconnect.ConnectionString = OracleConnection
            SQLconnect.Open()
            SQLcommand = SQLconnect.CreateCommand
            SQLcommand.CommandText = Select_anweisung

            Dim adapter1 As OracleDataAdapter = New OracleDataAdapter(SQLcommand)
            Dim dt As DataTable = New DataTable()
            adapter1.Fill(dt)
            SQLconnect.Close()
            Return dt
        Catch ex As Exception
            LOGGER.Error(ex)
            If userInput = True Then
                MsgBox("Error in Oracle Return Datatable - Error-Message:" & vbNewLine & ex.Message & vbNewLine & "SQL-Command:" & vbNewLine & Select_anweisung, MsgBoxStyle.Critical)
            End If
            LOGGER.Info("Fehler bei Oracle_Return_Datatable: " & ex.Message, True)
            LOGGER.Info("#SQL: " & Select_anweisung, False)
            Return Nothing
        End Try
    End Function
End Class
