using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using Pervasive.Data.SqlClient;

namespace Escapes
{
	/// <summary>
	/// Summary description for Escapes.
	/// </summary>
	public class Escapes : System.Windows.Forms.Form
	{
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.ComboBox Function;
		private System.Windows.Forms.Button Execute;
		private System.Windows.Forms.Button Done;
		private System.Windows.Forms.RichTextBox ResultSet;
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		public Escapes()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.label1 = new System.Windows.Forms.Label();
			this.Function = new System.Windows.Forms.ComboBox();
			this.Execute = new System.Windows.Forms.Button();
			this.Done = new System.Windows.Forms.Button();
			this.ResultSet = new System.Windows.Forms.RichTextBox();
			this.SuspendLayout();
			// 
			// label1
			// 
			this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Underline), System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.label1.Location = new System.Drawing.Point(104, 16);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(216, 23);
			this.label1.TabIndex = 0;
			this.label1.Text = "Escape Functions Demo";
			this.label1.Click += new System.EventHandler(this.label1_Click);
			// 
			// Function
			// 
			this.Function.Items.AddRange(new object[] {
														  "SELECT {fn DAYOFMONTH(hiredate)} FROM myEmp WHERE empno = 1",
														  "SELECT {fn ASIN(0)} FROM myEmp WHERE empno = 1",
														  "SELECT {fn LEFT(ename,1)} FROM myEmp WHERE empno = 1",
														  "SELECT {fn USER()} FROM myEmp WHERE empno = 1",
														  "SELECT ename FROM {oj myEmp LEFT OUTER JOIN myDept on myEmp.dept = myDept.deptno} group b" +
														  "y ename"});
			this.Function.Location = new System.Drawing.Point(16, 64);
			this.Function.Name = "Function";
			this.Function.Size = new System.Drawing.Size(416, 21);
			this.Function.TabIndex = 1;
			this.Function.Text = "Select a function query";
			this.Function.SelectedIndexChanged += new System.EventHandler(this.Function_SelectedIndexChanged);
			// 
			// Execute
			// 
			this.Execute.Location = new System.Drawing.Point(160, 96);
			this.Execute.Name = "Execute";
			this.Execute.Size = new System.Drawing.Size(80, 24);
			this.Execute.TabIndex = 2;
			this.Execute.Text = "Execute";
			this.Execute.Click += new System.EventHandler(this.Execute_Click);
			// 
			// Done
			// 
			this.Done.Location = new System.Drawing.Point(160, 232);
			this.Done.Name = "Done";
			this.Done.Size = new System.Drawing.Size(80, 24);
			this.Done.TabIndex = 3;
			this.Done.Text = "Done";
			this.Done.Click += new System.EventHandler(this.Done_Click);
			// 
			// ResultSet
			// 
			this.ResultSet.Location = new System.Drawing.Point(8, 136);
			this.ResultSet.Name = "ResultSet";
			this.ResultSet.ReadOnly = true;
			this.ResultSet.Size = new System.Drawing.Size(424, 88);
			this.ResultSet.TabIndex = 4;
			this.ResultSet.Text = "";
			this.ResultSet.TextChanged += new System.EventHandler(this.ResultSet_TextChanged);
			// 
			// Escapes
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(440, 266);
			this.Controls.AddRange(new System.Windows.Forms.Control[] {
																		  this.ResultSet,
																		  this.Done,
																		  this.Execute,
																		  this.Function,
																		  this.label1});
			this.Name = "Escapes";
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
			this.Text = "Escapes";
			this.Load += new System.EventHandler(this.Escapes_Load);
			this.ResumeLayout(false);

		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new Escapes());
		}

		private void label1_Click(object sender, System.EventArgs e)
		{
		
		}

		private void Function_SelectedIndexChanged(object sender, System.EventArgs e)
		{
		
		}

		private void Execute_Click(object sender, System.EventArgs e)
		{
			// Select statement containing the escape function calls
			//CR 60683 - mberis - 8/12/2011
            string SelectSQL = "";
            if (Function.SelectedIndex >= 0)
            {
                SelectSQL = Function.SelectedItem.ToString();
            }
            else
            {
                MessageBox.Show("Please select a function to test.");
                return;
            }
			//CR 60683 - mberis - 8/12/2011
			StringWriter writer = new StringWriter();
			// Psql Command
			PsqlCommand   DBCmd;
			// Change the connection string to match your servers
            PsqlConnection Conn = new PsqlConnection("Host=localhost;Port=1583;Database=demodata;");

			try 
			{
				// Open the connection
				Conn.Open();
			}
			catch (PsqlException ex)
			{
				// Connection failed
				writer.WriteLine(ex.Message);
				return;
			}
			try
			{
				DBCmd = new PsqlCommand(SelectSQL, Conn);
				//PsqlDataReader called on the Command object
				PsqlDataReader dataReader = DBCmd.ExecuteReader();
				// Print the resultset on the Result window
				printReader(dataReader, writer);
				// Close the DataReader
				dataReader.Close();
			}
			catch (Exception ex)
			{
				// Display the exception
				writer.WriteLine(ex.Message);
			}
			// Dump the output  onto the Result Window
			flush(writer);
			// Close the connection
			Conn.Close();
		}

		private void Done_Click(object sender, System.EventArgs e)
		{
			this.Close();
		}

		private void ResultSet_TextChanged(object sender, System.EventArgs e)
		{
		
		}

		// This method call dumps the StringWriter contents on to the ResultSet window
		private void flush (StringWriter writer)
		{
			ResultSet.Clear();
			ResultSet.AppendText (writer.ToString ());
			ResultSet.Refresh();
			writer.GetStringBuilder ().Length = 0;
		}

		// This method call will print out the result set on to the ResultSet window
		public void printReader( IDataReader reader, StringWriter writer)
		{
			bool fMoreRows;
			int i;
			int length = 0;
			bool fFirst = true;
			for (i = 0; i < reader.FieldCount; ++i) 
			{
				if (!fFirst) 
				{
					writer.Write(", ");
				}
				fFirst = false;
				writer.Write(reader.GetName(i));
				length = length + (reader.GetName(i).Length);
			}
			writer.WriteLine ("");
			for ( int z = 0; z < length+((reader.FieldCount)*2); z++ )
			{
				writer.Write("-");
			}
			writer.WriteLine ("");
			do 
			{
				fMoreRows = reader.Read();
				if (fMoreRows) 
				{
					fFirst = true;
					for (i = 0; i < reader.FieldCount; ++i) 
					{
						if (!fFirst) 
						{
							writer.Write(", ");
						}
						fFirst = false;

						if (reader.IsDBNull (i)) 
						{
							writer.Write("<null>");
						}
						else 
						{
							string str;
							object obj = reader.GetValue(i);
							if (obj is DateTime) 
							{
								str = ((DateTime)obj).ToString("yyyy-MM-dd HH:mm:ss.fff");
							}
							else 
							{
								str = obj.ToString();
							}

							writer.Write(str);
						}
					}
					writer.WriteLine ("");
				}
			} while (fMoreRows);
		}

		private void Escapes_Load(object sender, System.EventArgs e)
		{
		
		}
	}
}
