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 CommandBuilder
{
	/// <summary>
	/// Summary description for CB.
	/// </summary>
	public class CB : System.Windows.Forms.Form
	{
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.Button Execute;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.RichTextBox ResultSet;
		private System.Windows.Forms.RichTextBox SelectStatement;
		private System.Windows.Forms.Button Done;
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		public CB()
		{
			//
			// 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.Execute = new System.Windows.Forms.Button();
			this.label2 = new System.Windows.Forms.Label();
			this.label3 = new System.Windows.Forms.Label();
			this.ResultSet = new System.Windows.Forms.RichTextBox();
			this.SelectStatement = new System.Windows.Forms.RichTextBox();
			this.Done = new System.Windows.Forms.Button();
			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(128, 16);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(200, 23);
			this.label1.TabIndex = 0;
			this.label1.Text = "CommandBuilder Demo";
			this.label1.Click += new System.EventHandler(this.label1_Click);
			// 
			// Execute
			// 
			this.Execute.Location = new System.Drawing.Point(144, 112);
			this.Execute.Name = "Execute";
			this.Execute.Size = new System.Drawing.Size(144, 23);
			this.Execute.TabIndex = 1;
			this.Execute.Text = "Execute Query";
			this.Execute.Click += new System.EventHandler(this.Execute_Click);
			// 
			// label2
			// 
			this.label2.Location = new System.Drawing.Point(16, 48);
			this.label2.Name = "label2";
			this.label2.Size = new System.Drawing.Size(152, 16);
			this.label2.TabIndex = 2;
			this.label2.Text = "Select Statement: (Editable)";
			this.label2.Click += new System.EventHandler(this.label2_Click);
			// 
			// label3
			// 
			this.label3.Location = new System.Drawing.Point(16, 144);
			this.label3.Name = "label3";
			this.label3.Size = new System.Drawing.Size(56, 16);
			this.label3.TabIndex = 3;
			this.label3.Text = "DataSet:";
			this.label3.Click += new System.EventHandler(this.label3_Click);
			// 
			// ResultSet
			// 
			this.ResultSet.Location = new System.Drawing.Point(16, 160);
			this.ResultSet.Name = "ResultSet";
			this.ResultSet.ReadOnly = true;
			this.ResultSet.Size = new System.Drawing.Size(448, 72);
			this.ResultSet.TabIndex = 4;
			this.ResultSet.Text = "";
			this.ResultSet.TextChanged += new System.EventHandler(this.ResultSet_TextChanged);
			// 
			// SelectStatement
			// 
			this.SelectStatement.Location = new System.Drawing.Point(16, 64);
			this.SelectStatement.Name = "SelectStatement";
			this.SelectStatement.Size = new System.Drawing.Size(448, 24);
			this.SelectStatement.TabIndex = 5;
			this.SelectStatement.Text = "SELECT * FROM myEmp";
			this.SelectStatement.TextChanged += new System.EventHandler(this.SelectStatement_TextChanged);
			// 
			// Done
			// 
			this.Done.Location = new System.Drawing.Point(168, 240);
			this.Done.Name = "Done";
			this.Done.TabIndex = 6;
			this.Done.Text = "Done";
			this.Done.Click += new System.EventHandler(this.Done_Click);
			// 
			// CB
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(472, 266);
			this.Controls.AddRange(new System.Windows.Forms.Control[] {
																		  this.Done,
																		  this.SelectStatement,
																		  this.ResultSet,
																		  this.label3,
																		  this.label2,
																		  this.Execute,
																		  this.label1});
			this.Name = "CB";
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
			this.Text = "CB";
			this.Load += new System.EventHandler(this.CB_Load);
			this.ResumeLayout(false);

		}
		#endregion

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

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

		private void Execute_Click(object sender, System.EventArgs e)
		{
			StringWriter writer = new StringWriter();
			// 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 (Exception ex)
			{
				// Connection failed
				writer.WriteLine(ex.Message);
				// Write the exception onto the Result window
				flush(writer);
				return;
			}
			// Select statement, captured from the GUI
			string SelectSQL = SelectStatement.Text;
			// PsqlDataAdapter
			PsqlDataAdapter    dataAdapter = new PsqlDataAdapter();
			PsqlCommand   DBCmd = new PsqlCommand(SelectSQL, Conn);
			// Set the PsqlCommand as a SelectCommand for the PsqlDataAdapter
			dataAdapter.SelectCommand = DBCmd;

			// Set up the CommandBuilder
			PsqlCommandBuilder  CommBuild = new PsqlCommandBuilder(dataAdapter);
			DataSet      dataSet = new DataSet();
			try 
			{
				// Fill the DataSet with the Results from the DataAdapter
				dataAdapter.Fill(dataSet);
				// Print the DataSet onto the Result window
				printDataSet(dataSet, writer);
				// Now change the salary of the first employee
				DataRow     row;
				row = dataSet.Tables["Table"].Rows[0];
				row["sal"] = 95000;

				// Tell the DataAdapter to resynch with the Psql server.
				// Without the CommandBuilder, this line would fail.
				dataAdapter.Update(dataSet);
				writer.WriteLine ("Update with CommandBuilder Successful!");
				// Confirm the update
				writer.WriteLine("Confirmation");
				DBCmd = new PsqlCommand("select * from myEmp where sal = 95000", Conn);
				dataAdapter.SelectCommand = DBCmd;
				dataSet.Clear();
				dataAdapter.Fill(dataSet);
				printDataSet(dataSet, writer);
			}
			catch (Exception ex) 
			{
				// Display any exceptions 
				writer.WriteLine (ex.Message);
			}
			// Write out the output to the Result window
			flush(writer);
			// Close the connection
			Conn.Close();
		}

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

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

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

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

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

		// 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 prints the result set in the DataSet onto the ResultSet window
		protected void printDataSet(DataSet ds, StringWriter writer)
		{
			foreach (DataTable table in ds.Tables)
			{
				bool fFirst = true;
				foreach(DataColumn col in table.Columns)
				{
					if (!fFirst) 
					{
						writer.Write(", ");
					}
					fFirst = false;
					writer.Write(col.ColumnName);
				}
				writer.WriteLine ("");
				foreach(DataRow row in table.Rows)
				{
					fFirst = true;
					foreach(DataColumn col in table.Columns)
					{
						if (!fFirst) 
						{
							writer.Write(", ");
						}
						fFirst = false;
						if ( row[col].ToString().Equals(""))
						{
							writer.Write("<null>");
						}
						else
						{
							object obj =row[col];
							string	str = obj.ToString();
							writer.Write(str);
						}
					}
					writer.WriteLine ("");
				}
			}
		}

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