/****************************************************************************
** (c) Copyright IBM Corp. 2007 All rights reserved.
**
** The following sample of source code ("Sample") is owned by International
** Business Machines Corporation or one of its subsidiaries ("IBM") and is
** copyrighted and licensed, not sold. You may use, copy, modify, and
** distribute the Sample in any form without payment to IBM, for the purpose of
** assisting you in the development of your applications.
**
** The Sample code 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 PARTICULAR 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, copying, modifying or
** distributing the Sample, even if IBM has been advised of the possibility of
** such damages.
*****************************************************************************
**
** SOURCE FILE NAME: DbEvent.cs
**
** SAMPLE: How to use DB2DataAdapter events: RowUpdating and RowUpdated 
**         with the DB2 .Net Data Provider
**
** SQL Statements USED:
**         CREATE TABLE
**         DROP TABLE
**         INSERT
**         SELECT
**
** DB2 .NET Data Provider Classes USED:
**         DB2Connection
**         DB2Command
**
**                          
*****************************************************************************
**
** Building and Running the sample program 
**
** 1. Compile the DbEvent.cs file with bldapp.bat by entering the following 
**    at the command prompt:
**
**      bldapp DbEvent
**
**    or compile DbEvent.cs with the makefile by entering the following at 
**    the command prompt:
**
**      nmake DbEvent
**
** 2. Run the DbEvent program by entering the program name at the command 
**    prompt:
**
**      DbEvent
**
*****************************************************************************
**
** For more information on the sample programs, see the README file.
**
** For information on developing applications, see the Application
** Development Guide.
**
** For information on using SQL statements, see the SQL Reference.
**
** For the latest information on programming, compiling, and running DB2
** applications, visit the DB2 Information Center at
**     http://publib.boulder.ibm.com/infocenter/db2luw/v9r7/index.jsp
**
****************************************************************************/


using System;
using System.Data;
using System.IO;
using IBM.Data.DB2;

class DbEvent
{
  public static void Main(String[] args)
  {
    // Declare a DB2Connection and a DB2Command
    DB2Connection conn = null;
    DB2Command cmd = null;
    try
    {
      Console.WriteLine();
      Console.WriteLine("  THIS SAMPLE SHOWS HOW TO USE DB2DataAdapter " + 
                        "EVENTS:\n  RowUpdating and RowUpdated");
      Console.WriteLine();
 
      // Connect to a database
      Console.WriteLine("  Connecting to a database ...");
      conn = ConnectDb(args);

      // Create a DB2DataAdapter, a DB2CommandBuilder and a DataSet
      DB2DataAdapter adp = new DB2DataAdapter();
      DB2CommandBuilder cb = null;
      DataSet dset = new DataSet();

      cmd = conn.CreateCommand();
 
      // Create a table 'empsamp' in the SAMPLE database      
      Console.WriteLine("\n  CREATE A TABLE empsamp WITH ATTRIBUTES:\n" +
                        "    ID SMALLINT NOT NULL,\n" +
                        "    NAME VARCHAR(9),\n" +
                        "    JOB CHAR(5),\n" +
                        "    SALARY DEC(7,2),\n" +
                        "    PRIMARY KEY(ID)");
      cmd.CommandText = "CREATE TABLE EMPSAMP (" +
                        "  ID SMALLINT NOT NULL," +
                        "  NAME VARCHAR(9)," +
                        "  JOB CHAR(5)," +
                        "  SALARY DEC(7,2)," +
                        "  PRIMARY KEY(ID))";
      cmd.ExecuteNonQuery();
      Console.WriteLine();

      // Insert some rows in the empty table 'empsamp'
      Console.WriteLine(
        "  INSERT THE FOLLOWING ROWS IN EMPSAMP:\n" +
        "    (270, 'EMP1', 'CLERK', 4500),\n" +
        "    (280, 'EMP2', 'MGR', 13500.50),\n" +
        "    (290, 'EMP3', 'SALES', 11000.40)");
      cmd.CommandText =
        "INSERT INTO empsamp(id, name, job, salary) " +
        "  VALUES (270, 'EMP1', 'CLERK', 4500), "+
        "         (280, 'EMP2', 'MGR', 13500.50), " +
        "         (290, 'EMP3', 'SALES', 11000.40) ";
      Console.WriteLine();
      cmd.ExecuteNonQuery();

      // Intialize the SELECT command of the DB2DataAdapter
      adp.SelectCommand = new DB2Command("SELECT * FROM empsamp",conn);
      Console.WriteLine("\n  USE CLASS DB2CommandBuilder TO GENERATE" + 
                        " THE INSERT, UPDATE AND DELETE\n" +
                        "  COMMANDS FOR THE DB2DataAdapter");  

      // Initialize a DB2CommandBuilder instance that generates the UPDATE,
      // DELETE and INSERT commands for the DB2DataAdapter
      cb = new DB2CommandBuilder(adp);

      // Define the parameters for the generated UPDATE, DELETE and INSERT
      // commands of the DB2DataAdapter
      AddParameters(cb);
      Console.WriteLine("\n  " +
                        "FILL THE DATASET WITH THE Fill METHOD OF " +
                        "DB2DataAdapter");

      // Fill the DataSet with the data in table 'empsamp'
      adp.Fill(dset,"empsamp");

      // Make changes to the DataSet and respond to the RowUpdating and
      // RowUpdated events raised before and after the Update() method of
      // DB2DataAdapter is processed for each row
      EventHandler(adp,dset);

      // Drop the table 'empsamp'
      cmd.CommandText = "DROP TABLE empsamp";
      cmd.ExecuteNonQuery();

      // Disconnect from the database
      Console.WriteLine("\n  Disconnect from the database");
      conn.Close();
    }
    catch(Exception e)
    {
      cmd.CommandText = "DROP TABLE empsamp";
      cmd.ExecuteNonQuery();
      conn.Close();
      Console.WriteLine(e.Message);
    }
  }

  // Helper method: This method establishes a connection to a database
  public static DB2Connection ConnectDb(String[] argv)
  {
    String server = "";
    String alias = "";
    String userId = "";
    String password = "";
    Int32 portNumber = -1;
    String connectString;

    if( argv.Length > 5 ||
        ( argv.Length == 1 &&
          ( String.Compare(argv[0],"?") == 0           ||
            String.Compare(argv[0],"-?") == 0          ||
            String.Compare(argv[0],"/?") == 0          ||
            String.Compare(argv[0],"-h",true) == 0     ||
            String.Compare(argv[0],"/h",true) == 0     ||
            String.Compare(argv[0],"-help",true) == 0  ||
            String.Compare(argv[0],"/help",true) == 0 ) ) )
    {
      throw new Exception(
        "Usage: prog_name [dbAlias] [userId passwd] \n" +
        "       prog_name [dbAlias] server portNum userId passwd");
    }

    switch (argv.Length)
    {
      case 0:  // Use all defaults
        alias = "sample";
        userId = "";
        password = "";
        break;
      case 1:  // dbAlias specified
        alias = argv[0];
        userId = "";
        password = "";
        break;
      case 2:  // userId & passwd specified
        alias = "sample";
        userId = argv[0];
        password = argv[1];
        break;
      case 3:  // dbAlias, userId & passwd specified
        alias = argv[0];
        userId = argv[1];
        password = argv[2];
        break;
      case 4:  // use default dbAlias
        alias = "sample";
        server = argv[0];
        portNumber = Convert.ToInt32(argv[1]);
        userId = argv[2];
        password = argv[3];
        break;
      case 5:  // everything specified
        alias = argv[0];
        server = argv[1];
        portNumber = Convert.ToInt32(argv[2]);
        userId = argv[3];
        password = argv[4];
        break;
    }

    if(portNumber==-1)
    {
      connectString = "Database=" + alias;
    }
    else
    {
      connectString = "Server=" + server + ":" + portNumber +
                      ";Database=" + alias;
    }
    
    if(userId != "")
    { 
      connectString += ";UID=" + userId + ";PWD=" + password;
    }

    DB2Connection conn = new DB2Connection(connectString);
    conn.Open();
    Console.WriteLine("  Connected to the " + alias + " database");
    return conn;

  } // ConnectDb

  // This method defines the parameters for the UPDATE, DELETE and INSERT
  // commands of the DB2DataAdapter
  public static void AddParameters(DB2CommandBuilder cb)
  {
    try
    {
      // Define the parameters for the INSERT command in different ways
      cb.GetInsertCommand().Parameters.Add("@empid", 
                                           DB2Type.SmallInt, 
                                           5, 
                                           "ID").SourceVersion = 
                                           DataRowVersion.Original;
      cb.GetInsertCommand().Parameters.Add(
        new DB2Parameter("@empname",
                         DB2Type.VarChar,
                         9,
                         ParameterDirection.Input,
                         false,
                         0,
                         0,
                         "NAME",
                         DataRowVersion.Current,
                         ""));
      cb.GetInsertCommand().Parameters.Add(new DB2Parameter("@empjob",
                                                            DB2Type.Char,
                                                            5,
                                                            "JOB"));
      cb.GetInsertCommand().Parameters.Add("@empsalary",
                                           DB2Type.Decimal,
                                           7);

      // Define the parameters for the UPDATE command in different ways
      cb.GetUpdateCommand().Parameters.Add(
        new DB2Parameter("@empname", DB2Type.VarChar, 9));

      cb.GetUpdateCommand().Parameters.Add("@empsalary", 
                                           DB2Type.Decimal,
                                           7,
                                           "SALARY");
      cb.GetUpdateCommand().Parameters.Add("@empid",
                                           DB2Type.SmallInt,
                                           5).SourceVersion =
                                           DataRowVersion.Original;
    
      DB2Parameter param = new DB2Parameter("@empjob", DB2Type.Char);
      cb.GetUpdateCommand().Parameters.Add(param);

      // Define the parameter for the DELETE command
      cb.GetDeleteCommand().Parameters.Add("@empid",
                                           DB2Type.SmallInt).SourceVersion =
                                           DataRowVersion.Original;
    }
    catch (Exception e)
    {
      Console.WriteLine(e.Message);
    }
  } // AddParameters

  // This method creates and demonstrates the use of event handlers
  public static void EventHandler(DB2DataAdapter adp, DataSet dset)
  {
    try
    {
      // Add event handlers.
      adp.RowUpdating += new DB2RowUpdatingEventHandler(UpdatingRow);
      adp.RowUpdated += new DB2RowUpdatedEventHandler(UpdatedRow);

      // Make changes to the DataSet
      Console.WriteLine("\n  MAKE CHANGES TO THE DATASET");
      int i;
      for(i=0; i<dset.Tables["empsamp"].Rows.Count; i++)
      {
        if(((Int16)dset.Tables["empsamp"].Rows[i]["id"]) == 270)
        { 
          dset.Tables["empsamp"].Rows[i]["name"] = "LARRY";
          dset.Tables["empsamp"].Rows[i]["job"] = "MGR";
          dset.Tables["empsamp"].Rows[i]["salary"] = 3500;
          break;
        }
      }
      for(i=0; i<dset.Tables["empsamp"].Rows.Count; i++)
      {
        if(((Int16)dset.Tables["empsamp"].Rows[i]["id"]) == 290)
        {
          dset.Tables["empsamp"].Rows[i].Delete();
          break;
        }
      }

      // Update 'empsamp' to reflect the changes made to the Dataset 
      // and in the process, raise events: RowUpdating and RowUpdated
      Console.WriteLine("\n  " + 
                        "UPDATE 'empsamp' TO REFLECT CHANGES MADE TO THE" +
                        " DATASET,\n  IN THE PROCESS INVOKING EVENTS: " +
                        "RowUpdating and RowUpdated");
      adp.Update(dset,"empsamp");
      Console.WriteLine("\n  EMPSAMP UPDATED");

      // Remove event handlers.
      adp.RowUpdating -= new DB2RowUpdatingEventHandler(UpdatingRow);
      adp.RowUpdated -= new DB2RowUpdatedEventHandler(UpdatedRow);
    }
    catch (Exception e)
    {
      Console.WriteLine(e.Message);
    }
  } // EventHandler

  // This method handles the 'RowUpdating' event
  public static void UpdatingRow(Object sender, DB2RowUpdatingEventArgs args)
  {
    // Display what type of operation is to be performed
    Console.WriteLine("\n    EVENT: RowUpdating");
    Console.WriteLine("\n    ATTEMPTING TO " + 
                      args.StatementType.ToString().ToUpper() +
                      " THIS ROW\n");

    // Display contents of the row before it is updated or deleted
    if (args.StatementType == StatementType.Delete ||
        args.StatementType == StatementType.Update)
    {
      DisplayRow(args.Row,DataRowVersion.Original);
    }
  } // UpdatingRow

  // This method handles the 'RowUpdated' event
  public static void UpdatedRow(Object sender, DB2RowUpdatedEventArgs args)
  {
    Console.WriteLine("\n    EVENT: RowUpdated");
    
    // Check if errors occured when the row was being updated
    if (args.Status == UpdateStatus.ErrorsOccurred)
    {
      // Skip updating this row and proceed to updating the next row
      Console.WriteLine("\n    AN ERROR OCCURRED WHILE UPDATING THIS ROW");
      args.Row.RowError = args.Errors.Message;
      args.Status = UpdateStatus.SkipCurrentRow;
    }
    else
    {
      Console.WriteLine("\n    THE " +
                        args.StatementType.ToString().ToUpper() +
                        " OPERATION WAS PERFORMED SUCCESFULLY");

      // Display contents of the row after if has been updated
      if(args.StatementType == StatementType.Update)
      {
        Console.WriteLine("\n    DETAILS OF ROW AFTER UPDATE:\n");
        DisplayRow(args.Row,DataRowVersion.Current);
      }
    }
  } // UpdatedRow

  // Helper method: This method displays the contents of a DataRow
  public static void DisplayRow(DataRow row, DataRowVersion version)
  {
    // Obtain the DataTable corresponding to the DataRow 
    DataTable table = row.Table;

    // Display column names
    Console.Write("  ");
    foreach(DataColumn col in table.Columns)
    {
      Console.Write("    " + col.ColumnName);
    }
    Console.WriteLine();
    Console.Write("      ");
    foreach(DataColumn col in table.Columns)
    {
      int length = 8;
      if(col.DataType == Type.GetType("System.Int32") ||
         col.DataType == Type.GetType("System.Int16"))
      {
        length = 3;
      }
      else if(col.DataType == Type.GetType("System.String"))
      {
        length = 7;
      }
      for(int i = 0; i < length; i++)
      {
        Console.Write("-");
      }
      Console.Write(" ");
    }
    Console.WriteLine();
    Console.Write("     ");

    // Display column entries of each row
    foreach(DataColumn col in table.Columns)
    {
      Object data = row[col.ColumnName, version];
      if(data is Int32 || data is Int16)
      {
        Console.Write(" " + data.ToString().PadRight(3));
      }
      else if (data is String)
      {
        Console.Write(" " + ((String)data).PadRight(7));
      }
      else
      {
        String str = String.Format("{0:f2}" ,data);
        Console.Write(" " + str.PadLeft(8));
      }  
    }
    Console.WriteLine();
  } // DisplayRow

} // DbEvent