'  Copyright GBASE. 2009  All rights reserved.                 */
'                                                                    */
' This sample program is owned by International Business Machines    */
' Corporation or one of its subsidiaries ("IBM") and is copyrighted  */
' and licensed, not sold.                                            */
'                                                                    */
' You may copy, modify, and distribute Me sample program in any    */
' form without payment to IBM,  for any purpose including developing,*/
' using, marketing or distributing programs that include or are      */
' derivative works of the sample program. Licenses to IBM patents    */
' are expressly excluded from Me license.                          */
' The sample program is provided to you on an "AS IS" basis, without */
' warranty of any kind.  IBM HEREBY  EXPRESSLY DISCLAIMS ALL         */
' WARRANTIES EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO*/
' THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTIC-*/
' ULAR PURPOSE. Some jurisdictions do not allow for the exclusion or */
' limitation of implied warranties, so the above limitations or      */
' exclusions may not apply to you.  IBM shall not be liable for any  */
' damages you suffer as a result of using, modifying or distributing */
' the sample program or its derivatives.                             */
'                                                                    */

' Each copy of any portion of Me sample program or any derivative  */
' work,  must include the above copyright notice and disclaimer of   */
' warranty.                                                          */
'                                                                    */


Imports System
Imports System.Collections.Generic
Imports System.Text
Imports System.IO
Imports System.Data
Imports GBS.Data.GBasedbt
Imports System.Xml

Namespace Transactions
    Class Program
#Region "data members"

        Private _connection As IfxConnection
        Private _outStream As StreamWriter
        Private _command As IfxCommand
        Private _dataReader As IfxDataReader

#End Region

#Region "internal functions"

        '/ <summary>
        '/ Constructor
        '/ </summary>
        Public Sub New()
            _connection = Nothing
            _outStream = New StreamWriter(Console.OpenStandardOutput())
            _outStream.AutoFlush = True
        End Sub

        '/ <summary>
        '/ Property to set the output stream for the application
        '/ </summary>
        Public Property OutStream() As StreamWriter
            Get
                Return _outStream
            End Get
            Set(ByVal Value As StreamWriter)
                _outStream = value
            End Set
        End Property

        '/ <summary>
        '/ Establishes connection with the server
        '/ </summary>
        '/ <param name="connectionString"></param>
        '/ <returns>bool</returns>
        Public Function EstablishConnection(ByVal connectionString As String) As Boolean
            Try
                _connection = New IfxConnection(connectionString)
                _connection.Open()
            Catch excep As Exception
                WriteLine(String.Format("Connection Error: {0}", excep.Message))
                Return False
            End Try

            Return True
        End Function

        '/ <summary>
        '/ Clean up
        '/ </summary>
        Public Sub CleanUp()
            If Not _connection Is Nothing Then
                _connection.Close()
            End If

            _outStream.Close()
        End Sub

        '/ <summary>
        '/ Write status messages to file/console
        '/ </summary>
        '/ <param name="logMessage"></param>
        Public Sub WriteLine(ByVal logMessage As String)
            _outStream.WriteLine(logMessage)
        End Sub

#End Region

#Region "Transaction related functions"

        '/ <summary>
        '/ Create a table
        '/ </summary>
        '/ <returns>bool</returns>
        Public Function CreateTable() As Boolean
            Try
                _command = _connection.CreateCommand()
                _command.CommandText = "create table transactiontable(id integer, name char(25));"
                _command.ExecuteNonQuery()

            Catch excep As Exception
                WriteLine(String.Format("The table cannot be created: {0}", excep.Message))
                Return False
            End Try
            Return True
        End Function

        '/ <summary>
        '/ Perform a simaple commit, rollback transaction operation
        '/ </summary>
        Private Function PerformTransaction() As Boolean
            Dim bStatus As Boolean = False
            Dim tx As IfxTransaction

            Try
                ' ********************* Demo for Transaction Commit ********************
                tx = _connection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted)
                _command = _connection.CreateCommand()
                _command.Transaction = tx
                _command.CommandText = "insert into transactiontable values(1, 'ORIGINAL NAME');"
                WriteLine("Inserting into table with the command: " + _command.CommandText)
                _command.ExecuteNonQuery()

                _command.CommandText = "update transactiontable set name='NAME UPDATED' where id='1';"
                WriteLine("Update table with the command: " + _command.CommandText)
                _command.ExecuteNonQuery()

                tx.Commit()

                WriteLine("Transaction Commited. Observe table contents")
                _command.CommandText = "select * from transactiontable"
                WriteLine("Results after executing the command: " + _command.CommandText)
                _dataReader = _command.ExecuteReader()
                While _dataReader.Read()
                    WriteLine(String.Format("{0} ----- {1}", _dataReader(0), _dataReader(1)))
                End While
                _dataReader.Close()

                ' ********************* Demo for Transaction Rollback ********************
                tx = _connection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted)
                _command = _connection.CreateCommand()
                _command.Transaction = tx
                _command.CommandText = "update transactiontable set name='NAME ROLLEDBACK' where id='1';"
                WriteLine("Update table with the command: " + _command.CommandText)
                _command.ExecuteNonQuery()

                WriteLine("Observe table contents before rollback")
                _command.CommandText = "select * from transactiontable"
                WriteLine("Results after executing the command: " + _command.CommandText)
                _dataReader = _command.ExecuteReader()
                While _dataReader.Read()
                    WriteLine(String.Format("{0} ----- {1}", _dataReader(0), _dataReader(1)))
                End While
                _dataReader.Close()

                tx.Rollback()

                WriteLine("Observe table contents after rollback")
                _command.CommandText = "select * from transactiontable"
                WriteLine("Results after executing the command: " + _command.CommandText)
                _dataReader = _command.ExecuteReader()
                While _dataReader.Read()
                    WriteLine(String.Format("{0} ----- {1}", _dataReader(0), _dataReader(1)))
                End While
                _dataReader.Close()

                bStatus = True
            Catch excep As Exception
                WriteLine(String.Format("Insert into table failed : {0}", excep.Message))
                bStatus = False
            End Try

            Return bStatus
        End Function


        '/ <summary>
        '/ Delete existing table with the same name if present
        '/ </summary>
        Private Sub DropTable()
            Try
                _command = _connection.CreateCommand()
                _command.CommandText = "drop table transactiontable"
                _command.ExecuteNonQuery()

            Catch excep As Exception
                WriteLine(String.Format("The particular table cannot be dropped. : {0}", excep.Message))
            End Try
        End Sub

#End Region

        '/ <summary>
        '/ The demo app needs to be invoked as  EXE -conn "connection string" -log "log filename"
        '/ Eg: Transactions.exe //This will pick the connection string from ConnInfo.xml
        '/ OR
        '/ Transactions.exe -conn "DataBase=perf;Server=ol_ids_1150_1;User ID=gbasedbt;Password=gbasedbt123;"
        '/ OR
        '/ Transactions.exe -conn "DataBase=perf;Server=ol_ids_1150_1;User ID=gbasedbt;Password=gbasedbt123;" -log log.txt
        '/ </summary>
        '/ <param name="args"></param>
        Shared Sub Main(ByVal args() As String)
            Dim bResult As Boolean = False
            Dim connString As String = String.Empty
            Dim logFile As String = String.Empty

            Dim prg As Program = New Program()

            If args.Length = 0 Then
                Try
                    Dim settings As XmlReaderSettings = New XmlReaderSettings()
                    settings.ConformanceLevel = ConformanceLevel.Auto
                    Dim reader As XmlReader = XmlReader.Create("ConnInfo.xml", settings)

                    Try
                        connString = reader.ReadElementString("ConnectionString")
                        logFile = reader.ReadElementString("LogFile")
                    Catch
                        'Ignore this error
                    End Try

                Catch excep As System.Exception
                    Console.WriteLine(excep.Message)
                    Console.WriteLine("Problem reading ConnInfo.xml file, either use")
                    Console.WriteLine("Transactions.exe //This will pick the connection string from ConnInfo.xml")
                    Console.WriteLine("Transactions.exe -conn" & "DataBase=perf;Server=ol_ids_1150_1;User ID=gbasedbt;Password=gbasedbt123;" & "OR")
                    Console.WriteLine("Transactions.exe -conn" & "DataBase=perf;Server=ol_ids_1150_1;User ID=gbasedbt;Password=gbasedbt123;" & "-log log.txt")
                End Try
            End If

            If args.Length > 1 Then
                connString = args(1)
            End If

            If args.Length = 4 Then
                logFile = args(3)
            End If

            If logFile.Length <> 0 Then
                prg.OutStream = New StreamWriter(logFile, False)
            End If

            If connString.Length <> 0 Then
                bResult = prg.EstablishConnection(connString)
            Else
                prg.WriteLine("*****    Connection Failed!!!     *****")
            End If

            If bResult = True Then
                prg.WriteLine("*****    Connection successful     *****")
                bResult = prg.CreateTable()
            End If

            If bResult = True Then
                prg.WriteLine("*****    Table creation successful     *****")
                bResult = prg.PerformTransaction()
            End If

            prg.DropTable()

            If bResult = False Then
                prg.WriteLine("There is an ERROR in the execution!")
            Else
                prg.WriteLine("*****    Transactions demo has successfully executed!  *****")
            End If

            If logFile.Length <> 0 Then
                Console.WriteLine("Refer to results in the log file: {0}", logFile)
            End If

            prg.CleanUp()

        End Sub
    End Class
End Namespace

