Imports Oracle.ManagedDataAccess.Client
Public Class frmConnection
    Dim formloaded As Boolean = False
    Private Sub cmbDbArt_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles cmbDbArt.SelectedIndexChanged
        load_controls

    End Sub
    Sub load_controls()
        If Me.cmbDbArt.SelectedIndex <> -1 And formloaded = True Then
            Chckwin_aut.Visible = False
            chkOR_ohne_TNS.Visible = False
            Select Case Me.cmbDbArt.SelectedItem
                Case "MS-SQL"
                    Me.SERVERTextBox.Visible = True
                    Me.txtUserId.Visible = True
                    Me.txtPassword.Visible = True
                    Me.lblDataSource.Text = "SQL-Server (IP oder Name):"

                    Me.lblDataSource.Visible = True
                    Me.SERVERTextBox.ReadOnly = False
                    Me.btnMdbLocation.Visible = False
                    Me.btnMdbLöschen.Visible = False
                    Me.lblUserId.Visible = True
                    Me.lblUserId.Text = "UserId:"
                    Me.lblPassword.Visible = True
                    Me.lblPassword.Text = "Passwort:"
                    Me.lblDatasource2.Visible = True
                    Me.lblDatasource2.Text = "Datenbank:"
                    'Me.txtDatasource2.Visible = True
                    Me.DATENBANKComboBox.Visible = True
                    Chckwin_aut.Visible = True
                    Me.btnCheck_Con.Visible = True

                Case "ORACLE"
                    Me.SERVERTextBox.Visible = True
                    Me.txtUserId.Visible = True
                    Me.txtPassword.Visible = True
                    Me.lblDataSource.Text = "Host (IP-Adresse):"
                    Me.SERVERTextBox.ReadOnly = False
                    Me.SERVERTextBox.BackColor = System.Drawing.SystemColors.Window
                    Me.btnMdbLocation.Visible = False
                    Me.btnMdbLöschen.Visible = False
                    Me.lblUserId.Text = "UserId:"
                    Me.lblPassword.Text = "Passwort:"
                    Me.lblDatasource2.Text = "SID:"
                    Me.lblDatasource2.Visible = True
                    'Me.txtDatasource2.Visible = True
                    Me.DATENBANKComboBox.Visible = True
                    chkOR_ohne_TNS.Visible = True
                    Me.btnCheck_Con.Visible = True
                    MsgBox("Bitte beachten Sie das Auswahllisten aktuell nur mit MS-SQl möglich sind", MsgBoxStyle.Information)
                Case "ODBC"
                    Me.lblDataSource.Text = "DSN*:"
                    Me.SERVERTextBox.ReadOnly = False
                    Me.SERVERTextBox.BackColor = System.Drawing.SystemColors.Window

                    Me.btnMdbLocation.Visible = False
                    Me.btnMdbLöschen.Visible = False
                    Me.lblUserId.Text = "UserId:"
                    Me.lblPassword.Text = "Passwort:"
                    Me.lblDatasource2.Visible = False
                    'Me.txtDatasource2.Visible = False
                    Me.DATENBANKComboBox.Visible = False
                    MsgBox("Bitte beachten Sie das Auswahllisten aktuell nur mit MS-SQl möglich sind", MsgBoxStyle.Information)
                Case "Ole (Access)"
                    Me.lblDataSource.Text = ".mdb Datei*:"
                    Me.SERVERTextBox.ReadOnly = True
                    Me.SERVERTextBox.BackColor = System.Drawing.SystemColors.Info

                    Me.btnMdbLocation.Visible = True
                    Me.btnMdbLöschen.Visible = True
                    Me.lblUserId.Text = "UserId:"
                    Me.lblPassword.Text = "Passwort:"
                    Me.lblDatasource2.Visible = False
                    'Me.txtDatasource2.Visible = False
                    Me.DATENBANKComboBox.Visible = False

            End Select
        Else
            Me.SERVERTextBox.Visible = False
            Me.txtUserId.Visible = False
            Me.txtPassword.Visible = False
        End If
    End Sub
    Private Sub btnCheck_Con_Click(sender As System.Object, e As System.EventArgs) Handles btnCheck_Con.Click
        Try
            If Me.cmbDbArt.SelectedIndex <> -1 Then
                Dim connstr As String
                Select Case Me.cmbDbArt.SelectedItem
                    Case "MS-SQL"
                        Dim con As String
                        If Chckwin_aut.Checked Then
                            'con = "Data Source=" & Me.SERVERTextBox.Text & ";Initial Catalog=" & Me.txtDatasource2.Text & ";Trusted_Connection=True;"
                            con = "Data Source=" & Me.SERVERTextBox.Text & ";Initial Catalog=" & Me.DATENBANKComboBox.Text & ";Trusted_Connection=True;"
                        Else
                            'con = "Server=" & Me.SERVERTextBox.Text & ";Database=" & Me.txtDatasource2.Text & ";User Id=" & Me.txtUserId.Text & ";Password=" & Me.txtPassword.Text & ";"
                            con = "Server=" & Me.SERVERTextBox.Text & ";Database=" & Me.DATENBANKComboBox.Text & ";User Id=" & Me.txtUserId.Text & ";Password=" & Me.txtPassword.Text & ";"
                        End If
                        Dim connection As New SqlClient.SqlConnection(con)
                        connstr = con
                        connection.Open()
                        Cursor = Cursors.Default
                        MsgBox("Die Verbindung wurde erfolgreich aufgebaut!", MsgBoxStyle.Information, "Erfolg:")
                        My.Settings.Save()
                    Case "ORACLE"
                        Try
                            Dim conn As New OracleConnectionStringBuilder
                            If chkOR_ohne_TNS.Checked Then
                                'connstr = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=" & SERVERTextBox.Text & ")(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=" &
                                '    txtDatasource2.Text & ")));User Id=" & txtUserId.Text & ";Password=" & txtPassword.Text & ";"
                                connstr = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=" & SERVERTextBox.Text & ")(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=" &
                                    DATENBANKComboBox.Text & ")));User Id=" & txtUserId.Text & ";Password=" & txtPassword.Text & ";"
                            Else
                                'conn.DataSource = txtDatasource2.Text
                                conn.DataSource = DATENBANKComboBox.Text
                                conn.UserID = txtUserId.Text
                                conn.Password = txtPassword.Text
                                conn.PersistSecurityInfo = True
                                conn.ConnectionTimeout = 120
                                connstr = conn.ConnectionString
                            End If

                            Dim connection As New OracleConnection(connstr)
                            connection.Open()

                            MsgBox("Die Verbindung wurde erfolgreich aufgebaut!", MsgBoxStyle.Information, "Erfolg:")
                        Catch ex As Exception
                            LOGGER.Error(ex)
                            MsgBox(ex.Message & vbNewLine & vbNewLine & connstr, MsgBoxStyle.Critical, "Fehler bei Verbindungsaufbau Oracle:")
                        End Try
                    Case Else
                        MsgBox("Test zur Zeit nicht möglich", MsgBoxStyle.Information, "Achtung:")
                End Select

            End If
        Catch ex As Exception
            LOGGER.Error(ex)
            Cursor = Cursors.Default
            Dim template As String = ex.Message
            MsgBox("Fehler beim Verbindungsaufbau: " & vbNewLine & ex.Message, MsgBoxStyle.Exclamation)
        End Try
    End Sub

    Private Sub TBDD_CONNECTIONBindingNavigatorSaveItem_Click(sender As System.Object, e As System.EventArgs) Handles TBDD_CONNECTIONBindingNavigatorSaveItem.Click
        Try
            Me.TBDD_CONNECTIONBindingSource.EndEdit()
            If DD_DMSLiteDataSet.TBDD_CONNECTION.GetChanges Is Nothing = False Then
                Me.GEANDERTWERTextBox.Text = USER_USERNAME
                Me.TBDD_CONNECTIONBindingSource.EndEdit()
                Me.TBDD_CONNECTIONTableAdapter.Update(DD_DMSLiteDataSet.TBDD_CONNECTION)
                MsgBox("Changes successfully saved!", MsgBoxStyle.Information)
            End If
        Catch ex As Exception
            LOGGER.Error(ex)
            MsgBox("Error sving Connection: " & vbNewLine & ex.Message, MsgBoxStyle.Exclamation)
        End Try

    End Sub

    Private Sub frmConnection_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Try

            load_connections()
        Catch ex As Exception
            LOGGER.Error(ex)
            MsgBox("Error loading basic data: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Sub load_connections()
        Try
            Me.TBDD_CONNECTIONTableAdapter.Connection.ConnectionString = CONNECTION_STRING_ECM
            Me.TBDD_CONNECTIONTableAdapter.Fill(Me.DD_DMSLiteDataSet.TBDD_CONNECTION)
            TBDD_CONNECTIONDataGridView.AutoResizeColumns()
        Catch ex As Exception
            LOGGER.Error(ex)
            MsgBox("Error loading connections: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Private Sub Chckwin_aut_CheckedChanged(sender As Object, e As EventArgs) Handles Chckwin_aut.CheckedChanged
        If Chckwin_aut.Checked Then
            Me.txtUserId.Enabled = False
            Me.txtPassword.Enabled = False
            Me.txtUserId.Text = "WINAUTH"
            Me.txtPassword.Text = ""
            Me.txtPassword.Enabled = False
        Else
            Me.txtUserId.Enabled = True
            Me.txtPassword.Enabled = True
            Me.txtUserId.Text = ""
            Me.txtPassword.Text = ""
            Me.txtPassword.Enabled = True
        End If
    End Sub

    Private Sub frmConnection_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        formloaded = True
        load_controls()
    End Sub

    Private Sub TBDD_CONNECTIONBindingSource_AddingNew(sender As Object, e As System.ComponentModel.AddingNewEventArgs) Handles TBDD_CONNECTIONBindingSource.AddingNew
        DD_DMSLiteDataSet.TBDD_CONNECTION.ERSTELLTWERColumn.DefaultValue = USER_USERNAME
        DD_DMSLiteDataSet.TBDD_CONNECTION.SQL_PROVIDERColumn.DefaultValue = "MS-SQL"
    End Sub

    Private Sub TBDD_CONNECTIONBindingSource_PositionChanged(sender As Object, e As EventArgs) Handles TBDD_CONNECTIONBindingSource.PositionChanged
        load_controls()
    End Sub

    Private Sub chkOR_ohne_TNS_CheckedChanged(sender As Object, e As EventArgs) Handles chkOR_ohne_TNS.CheckedChanged
        If chkOR_ohne_TNS.Checked Then
            Me.lblDatasource2.Visible = True
            'Me.txtDatasource2.Visible = True
            Me.DATENBANKComboBox.Visible = True
        Else
            Me.lblDatasource2.Visible = False
            'Me.txtDatasource2.Visible = False
            'Me.txtDatasource2.Text = ""
            Me.DATENBANKComboBox.Visible = True
            Me.DATENBANKComboBox.Text = False
        End If
    End Sub

    Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs) Handles ToolStripButton1.Click
        TBDD_CONNECTIONBindingSource.AddNew()
        ' Me.grpbx_ConnAdd.Visible = True
    End Sub

    'Private Sub btnadd_Click(sender As Object, e As EventArgs) Handles btnadd.Click
    '    Try
    '        Select Case cmbDbArt.Text
    '            Case "ORACLE"
    '            Case "MS-SQL"
    '                If Me.txtUserId.Text = "WINAUTH" Then
    '                    TBDD_CONNECTIONTableAdapter.CmdInsert(txtBezeichnung.Text, cmbDbArt.Text, SERVERTextBox.Text, txtDatasource2.Text, "WINAUTH", "", "", True, USER_USERNAME)
    '                Else
    '                    TBDD_CONNECTIONTableAdapter.CmdInsert(txtBezeichnung.Text, cmbDbArt.Text, SERVERTextBox.Text, txtDatasource2.Text, txtUserId.Text, txtPassword.Text, "", True, USER_USERNAME)
    '                End If

    '        End Select
    '    Catch ex As Exception
    '        MsgBox("Fehler bei Insert Connection: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
    '    End Try

    '    load_connections()
    'End Sub

    Private Sub TBDD_CONNECTIONDataGridView_SelectionChanged(sender As Object, e As EventArgs) Handles TBDD_CONNECTIONDataGridView.SelectionChanged
        ' grpbx_ConnAdd.Visible = False
    End Sub

    Private Sub ToolStripButton2_Click(sender As Object, e As EventArgs) Handles ToolStripButton2.Click
        Try
            If GUIDTextBox.Text <> "" Then
                Dim result As MsgBoxResult = MsgBox("Wollen Sie die Connection wirklich löschen?", MsgBoxStyle.YesNo, "Bestätigung erforderlich:")
                ' wenn Löschen ja
                If result = MsgBoxResult.Yes Then
                    TBDD_CONNECTIONTableAdapter.Delete(GUIDTextBox.Text)
                    load_connections()
                End If
            End If
            'Dim i, ID As Integer
            'i = TBDD_CONNECTIONDataGridView.CurrentRow.Index
            'ID = TBDD_CONNECTIONDataGridView.Item(0, i).Value
            'If ID > 0 Then

            'End If
        Catch ex As Exception
            LOGGER.Error(ex)
            MsgBox("Fehler bei Löschen Connection: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub btnMdbLöschen_Click(sender As Object, e As EventArgs) Handles btnMdbLöschen.Click

    End Sub

    Private Sub txtUserId_TextChanged(sender As Object, e As EventArgs) Handles txtUserId.TextChanged
        If Me.txtUserId.Text = "WINAUTH" Then
            Me.Chckwin_aut.Checked = True
        Else
            Me.Chckwin_aut.Checked = False
        End If
    End Sub
    Private Sub ToolStripButton3_Click(sender As Object, e As EventArgs) Handles ToolStripButton3.Click
        load_connections()
    End Sub

    Private Sub DATENBANKComboBox_Click(sender As Object, e As EventArgs) Handles DATENBANKComboBox.Click
        Try
            Me.Cursor = Cursors.WaitCursor
            Dim csb As New SqlClient.SqlConnectionStringBuilder

            If SERVERTextBox.Text = String.Empty Then
                MsgBox("Please add a server!")
                Exit Sub
            End If

            If Chckwin_aut.Checked Then
                csb.DataSource = SERVERTextBox.Text
                csb.IntegratedSecurity = True
            Else
                If txtUserId.Text = String.Empty Or txtPassword.Text = String.Empty Then
                    MsgBox("Please add user and password!")
                    Exit Sub
                End If

                csb.DataSource = SERVERTextBox.Text
                csb.IntegratedSecurity = False
                csb.UserID = txtUserId.Text
                csb.Password = txtPassword.Text
            End If

            Dim connection As New SqlClient.SqlConnection(csb.ToString)
            connection.Open()

            Dim cmd As New SqlClient.SqlCommand("sp_databases", connection) With {.CommandType = CommandType.StoredProcedure}
            Dim dr As SqlClient.SqlDataReader = cmd.ExecuteReader

            If dr.HasRows Then
                DATENBANKComboBox.Items.Clear()
                Do While dr.Read
                    DATENBANKComboBox.Items.Add(dr.Item("Database_Name"))
                Loop
                DATENBANKComboBox.DroppedDown = True
            Else
                MsgBox("The standard-databases could not be retrieved. The default database will be set!" & vbNewLine & "Check rights in sql-server for user", MsgBoxStyle.Exclamation)
            End If

            connection.Close()
        Catch ex As Exception
            LOGGER.Error(ex)
            MsgBox("Error while loading Databases. Default Database will be set!" & vbCrLf & ex.Message, MsgBoxStyle.Critical)
        Finally
            Me.Cursor = Cursors.Default
        End Try
    End Sub

    Private Sub SYS_CONNECTIONCheckBox_CheckedChanged(sender As Object, e As EventArgs) Handles SYS_CONNECTIONCheckBox.CheckedChanged
        If SYS_CONNECTIONCheckBox.Checked Then
            GroupBox1.Enabled = False
        Else
            GroupBox1.Enabled = True
        End If
    End Sub
End Class