/* 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 this 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 this 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 this sample program or any derivative  */
/*work,  must include the above copyright notice and disclaimer of   */
/*warranty.                                                          */
/*                                                                   */

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Data;
using GBS.Data.GBasedbt;
using System.Xml;

namespace HelloWorldConnect
{
    class Program
    {
        #region data members

        private IfxConnection               _connection;
        private StreamWriter                _outStream;
        
        #endregion

        #region internal functions 

        /// <summary>
        /// Constructor
        /// </summary>
        public Program()
        {
            _connection = null;
            _outStream = new StreamWriter(Console.OpenStandardOutput());
            _outStream.AutoFlush = true;
        }

        /// <summary>
        /// Property to set the output stream for the application
        /// </summary>
        public StreamWriter OutStream
        {
            get { return _outStream; }
            set { _outStream = value; }
        }

        /// <summary>
        /// Establishes connection with the server
        /// </summary>
        /// <param name="connectionString"></param>
        /// <returns>bool</returns>
        public bool EstablishConnection(String connectionString)
        {
            try
            {
                _connection = new IfxConnection(connectionString);
                _connection.Open();
            }
            catch (Exception excep)
            {
                WriteLine(String.Format("Connection Error: {0}", excep.Message));
                return false;
            }

            return true;
        }

        /// <summary>
        /// Displays the connection object attributes
        /// </summary>
        /// <param name="connectionString"></param>
        /// <returns>bool</returns>
        public bool DisplayConnectionInfo()
        {
            try
            {
                WriteLine(String.Format("Server: {0}, Server Version: {1}", _connection.Server, _connection.ServerVersion));
                WriteLine(String.Format("Client Locale: {0}", _connection.ClientLocale));
                WriteLine(String.Format("Database: {0}", _connection.Database));
                WriteLine(String.Format("Database Locale: {0}", _connection.DatabaseLocale));
                WriteLine(String.Format("Data Source: {0}", _connection.DataSource));
            }
            catch (Exception excep)
            {
                WriteLine(String.Format("Connection Error: {0}", excep.Message));
                return false;
            }

            return true;
        }

        /// <summary>
        /// Clean up
        /// </summary>
        public void CleanUp()
        {
            if (_connection != null)
                _connection.Close();

            _outStream.Close();
        }

        /// <summary>
        /// Write status messages to file/console
        /// </summary>
        /// <param name="logMessage"></param>
        public void WriteLine(string logMessage)
        {
            _outStream.WriteLine(logMessage);
        }

        #endregion

        /// <summary>
        /// The demo app needs to be invoked as  EXE_Name -conn "connection string" -log "log filename"
        /// Eg: HelloWorldConnect.exe //This will pick the connection string from ConnInfo.xml
        /// OR
        /// HelloWorldConnect.exe -conn "DataBase=perf;Server=ol_ids_1150_1;User ID=gbasedbt;Password=gbasedbt123;"
        /// OR
        /// HelloWorldConnect.exe -conn "DataBase=perf;Server=ol_ids_1150_1;User ID=gbasedbt;Password=gbasedbt123;" -log log.txt
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            bool bResult = false;
            String connString = String.Empty;
            String logFile = String.Empty;

            Program prg = new Program();
            
            if (args.Length == 0)
            {
                try
                {
                    XmlReaderSettings settings = new XmlReaderSettings();
                    settings.ConformanceLevel = ConformanceLevel.Auto;
                    using (XmlReader reader = XmlReader.Create("ConnInfo.xml", settings))
                    {
                        try
                        {
                            connString = reader.ReadElementString("ConnectionString");
                            logFile = reader.ReadElementString("LogFile");
                        }
                        catch (Exception)
                        {
                            //Ignore this error
                        }
                    }
                }
                catch (System.Exception excep)
                {
                    Console.WriteLine(excep.Message);
                    Console.WriteLine("Problem reading ConnInfo.xml file, either use");
                    Console.WriteLine("HelloWorldConnect.exe //This will pick the connection string from ConnInfo.xml");
                    Console.WriteLine("HelloWorldConnect.exe -conn \"DataBase=perf;Server=ol_ids_1150_1;User ID=gbasedbt;Password=gbasedbt123;\" OR");
                    Console.WriteLine("HelloWorldConnect.exe -conn \"DataBase=perf;Server=ol_ids_1150_1;User ID=gbasedbt;Password=gbasedbt123;\" -log log.txt");
                }
            }

            if (args.Length > 1)
               connString = args[1];

            if (args.Length == 4)
              logFile = args[3];
            
            if(logFile.Length != 0)
              prg.OutStream = new StreamWriter(logFile, false);

            if(connString.Length != 0)
                bResult = prg.EstablishConnection(connString);
            else
                prg.WriteLine("*****    Connection Failed!!!     *****");

            if (bResult == false)
            {
                prg.WriteLine("There is an ERROR in the execution!");
            }
            else
            {
                prg.WriteLine("***** Hello World *****");
                prg.WriteLine("***** Connection to server succeeded!!! *****");
                prg.DisplayConnectionInfo();
            }

            if (logFile.Length != 0)
            {
                Console.WriteLine("Execution Complete!");
                Console.WriteLine("Refer to results in the log file: {0}", logFile);
            }

            prg.CleanUp();

        }
    }
}
