using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Diagnostics;
using System.Threading;

using nsAlienRFID2;

namespace Ex3
{
	public delegate void displayMessageDlgt(string msg);

	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class Form1 : System.Windows.Forms.Form
	{
		private clsReader mReader;
		private ReaderInfo mReaderInfo;
		private ComInterface meReaderInterface = ComInterface.enumTCPIP;

		#region Auto generated code

		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.TextBox textBox1;
		private System.Windows.Forms.NumericUpDown PortUD;
		private System.Windows.Forms.Button btnDisconnect;
		private System.Windows.Forms.Button btnConnect;
		private System.Windows.Forms.Button btnDeleteMacro;
		private System.Windows.Forms.Button btnRunMacro;
		private System.Windows.Forms.TextBox txtCommand;
		private System.Windows.Forms.GroupBox grpNetwork;
		private System.Windows.Forms.GroupBox grpSerial;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.Label label5;
		private System.Windows.Forms.GroupBox grpConnection;
		private System.Windows.Forms.RadioButton rdoSerial;
		private System.Windows.Forms.RadioButton rdoTCP;
		private System.Windows.Forms.NumericUpDown ReceiveUP;
		private System.Windows.Forms.TextBox txtAsyncResponse;
		private System.Windows.Forms.Label lblMacroContents;
        private System.Windows.Forms.Label label7;
		private System.Windows.Forms.ComboBox cboPorts;
        private System.Windows.Forms.Label label8;
		private System.Windows.Forms.ComboBox cboHostBaudRate;
		private System.Windows.Forms.Label label4;
        private Label label9;
        private ComboBox cboMacros;
        private Button btnSaveMacro;
        private Button btnDeleteAll;
        private Button btnClear;
        private ToolTip toolTip1;
        private Button btnAdd;
        private Button btnInsert;
        private VScrollBar vScrollBar1;
        private ListBox lstMacroContents;
        private IContainer components;

		public Form1()
		{
			//
			// 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 );
		}
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            this.components = new System.ComponentModel.Container();
            this.grpNetwork = new System.Windows.Forms.GroupBox();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.label2 = new System.Windows.Forms.Label();
            this.PortUD = new System.Windows.Forms.NumericUpDown();
            this.label1 = new System.Windows.Forms.Label();
            this.txtAsyncResponse = new System.Windows.Forms.TextBox();
            this.txtCommand = new System.Windows.Forms.TextBox();
            this.btnDisconnect = new System.Windows.Forms.Button();
            this.btnConnect = new System.Windows.Forms.Button();
            this.btnDeleteMacro = new System.Windows.Forms.Button();
            this.btnRunMacro = new System.Windows.Forms.Button();
            this.grpSerial = new System.Windows.Forms.GroupBox();
            this.cboHostBaudRate = new System.Windows.Forms.ComboBox();
            this.label4 = new System.Windows.Forms.Label();
            this.ReceiveUP = new System.Windows.Forms.NumericUpDown();
            this.label8 = new System.Windows.Forms.Label();
            this.cboPorts = new System.Windows.Forms.ComboBox();
            this.label3 = new System.Windows.Forms.Label();
            this.label5 = new System.Windows.Forms.Label();
            this.rdoSerial = new System.Windows.Forms.RadioButton();
            this.rdoTCP = new System.Windows.Forms.RadioButton();
            this.grpConnection = new System.Windows.Forms.GroupBox();
            this.lblMacroContents = new System.Windows.Forms.Label();
            this.label7 = new System.Windows.Forms.Label();
            this.label9 = new System.Windows.Forms.Label();
            this.cboMacros = new System.Windows.Forms.ComboBox();
            this.btnSaveMacro = new System.Windows.Forms.Button();
            this.btnDeleteAll = new System.Windows.Forms.Button();
            this.btnClear = new System.Windows.Forms.Button();
            this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
            this.btnAdd = new System.Windows.Forms.Button();
            this.btnInsert = new System.Windows.Forms.Button();
            this.vScrollBar1 = new System.Windows.Forms.VScrollBar();
            this.lstMacroContents = new System.Windows.Forms.ListBox();
            this.grpNetwork.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.PortUD)).BeginInit();
            this.grpSerial.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.ReceiveUP)).BeginInit();
            this.grpConnection.SuspendLayout();
            this.SuspendLayout();
            // 
            // grpNetwork
            // 
            this.grpNetwork.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.grpNetwork.Controls.Add(this.textBox1);
            this.grpNetwork.Controls.Add(this.label2);
            this.grpNetwork.Controls.Add(this.PortUD);
            this.grpNetwork.Controls.Add(this.label1);
            this.grpNetwork.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.grpNetwork.Location = new System.Drawing.Point(576, 125);
            this.grpNetwork.Name = "grpNetwork";
            this.grpNetwork.Size = new System.Drawing.Size(176, 112);
            this.grpNetwork.TabIndex = 5;
            this.grpNetwork.TabStop = false;
            this.grpNetwork.Text = "Network Settings";
            // 
            // textBox1
            // 
            this.textBox1.Location = new System.Drawing.Point(80, 64);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(87, 20);
            this.textBox1.TabIndex = 10;
            this.textBox1.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
            // 
            // label2
            // 
            this.label2.Location = new System.Drawing.Point(16, 64);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(80, 20);
            this.label2.TabIndex = 9;
            this.label2.Text = "IP Address:";
            // 
            // PortUD
            // 
            this.PortUD.Location = new System.Drawing.Point(80, 31);
            this.PortUD.Maximum = new decimal(new int[] {
            10000,
            0,
            0,
            0});
            this.PortUD.Name = "PortUD";
            this.PortUD.Size = new System.Drawing.Size(60, 20);
            this.PortUD.TabIndex = 8;
            this.PortUD.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
            this.PortUD.Value = new decimal(new int[] {
            23,
            0,
            0,
            0});
            this.PortUD.ValueChanged += new System.EventHandler(this.MyUpDowns_ValueChanged);
            // 
            // label1
            // 
            this.label1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.label1.Location = new System.Drawing.Point(16, 36);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(67, 20);
            this.label1.TabIndex = 6;
            this.label1.Text = "Telnet Port:";
            // 
            // txtAsyncResponse
            // 
            this.txtAsyncResponse.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.txtAsyncResponse.BackColor = System.Drawing.SystemColors.WindowFrame;
            this.txtAsyncResponse.ForeColor = System.Drawing.SystemColors.Info;
            this.txtAsyncResponse.Location = new System.Drawing.Point(31, 227);
            this.txtAsyncResponse.Multiline = true;
            this.txtAsyncResponse.Name = "txtAsyncResponse";
            this.txtAsyncResponse.ScrollBars = System.Windows.Forms.ScrollBars.Both;
            this.txtAsyncResponse.Size = new System.Drawing.Size(529, 211);
            this.txtAsyncResponse.TabIndex = 12;
            // 
            // txtCommand
            // 
            this.txtCommand.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.txtCommand.Location = new System.Drawing.Point(332, 24);
            this.txtCommand.Name = "txtCommand";
            this.txtCommand.Size = new System.Drawing.Size(168, 20);
            this.txtCommand.TabIndex = 15;
            this.toolTip1.SetToolTip(this.txtCommand, "Type in a new command and press [ENTER]");
            // 
            // btnDisconnect
            // 
            this.btnDisconnect.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.btnDisconnect.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.btnDisconnect.Enabled = false;
            this.btnDisconnect.ForeColor = System.Drawing.SystemColors.WindowText;
            this.btnDisconnect.Location = new System.Drawing.Point(607, 70);
            this.btnDisconnect.Name = "btnDisconnect";
            this.btnDisconnect.Size = new System.Drawing.Size(120, 35);
            this.btnDisconnect.TabIndex = 21;
            this.btnDisconnect.Text = "&Disconnect";
            this.btnDisconnect.UseVisualStyleBackColor = false;
            this.btnDisconnect.Click += new System.EventHandler(this.btnDisconnect_Click);
            // 
            // btnConnect
            // 
            this.btnConnect.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.btnConnect.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.btnConnect.ForeColor = System.Drawing.SystemColors.WindowText;
            this.btnConnect.Location = new System.Drawing.Point(607, 30);
            this.btnConnect.Name = "btnConnect";
            this.btnConnect.Size = new System.Drawing.Size(120, 35);
            this.btnConnect.TabIndex = 18;
            this.btnConnect.Text = "Co&nnect + Login";
            this.btnConnect.UseVisualStyleBackColor = false;
            this.btnConnect.Click += new System.EventHandler(this.btnConnect_Click);
            // 
            // btnDeleteMacro
            // 
            this.btnDeleteMacro.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.btnDeleteMacro.Enabled = false;
            this.btnDeleteMacro.ForeColor = System.Drawing.SystemColors.WindowText;
            this.btnDeleteMacro.Location = new System.Drawing.Point(91, 100);
            this.btnDeleteMacro.Name = "btnDeleteMacro";
            this.btnDeleteMacro.Size = new System.Drawing.Size(79, 30);
            this.btnDeleteMacro.TabIndex = 17;
            this.btnDeleteMacro.Text = "&Delete Macro";
            this.btnDeleteMacro.UseVisualStyleBackColor = false;
            this.btnDeleteMacro.Click += new System.EventHandler(this.btnDeleteMacro_Click);
            // 
            // btnRunMacro
            // 
            this.btnRunMacro.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.btnRunMacro.Enabled = false;
            this.btnRunMacro.ForeColor = System.Drawing.SystemColors.WindowText;
            this.btnRunMacro.Location = new System.Drawing.Point(91, 145);
            this.btnRunMacro.Name = "btnRunMacro";
            this.btnRunMacro.Size = new System.Drawing.Size(79, 30);
            this.btnRunMacro.TabIndex = 16;
            this.btnRunMacro.Text = "&Run Macro";
            this.btnRunMacro.UseVisualStyleBackColor = false;
            this.btnRunMacro.Click += new System.EventHandler(this.btnRunMacro_Click);
            // 
            // grpSerial
            // 
            this.grpSerial.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.grpSerial.Controls.Add(this.cboHostBaudRate);
            this.grpSerial.Controls.Add(this.label4);
            this.grpSerial.Controls.Add(this.ReceiveUP);
            this.grpSerial.Controls.Add(this.label8);
            this.grpSerial.Controls.Add(this.cboPorts);
            this.grpSerial.Controls.Add(this.label3);
            this.grpSerial.Enabled = false;
            this.grpSerial.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.grpSerial.Location = new System.Drawing.Point(576, 324);
            this.grpSerial.Name = "grpSerial";
            this.grpSerial.Size = new System.Drawing.Size(176, 112);
            this.grpSerial.TabIndex = 22;
            this.grpSerial.TabStop = false;
            this.grpSerial.Text = "Com Port";
            // 
            // cboHostBaudRate
            // 
            this.cboHostBaudRate.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cboHostBaudRate.Items.AddRange(new object[] {
            "115200",
            "57600",
            "38400",
            "19200",
            "9600"});
            this.cboHostBaudRate.Location = new System.Drawing.Point(96, 80);
            this.cboHostBaudRate.Name = "cboHostBaudRate";
            this.cboHostBaudRate.Size = new System.Drawing.Size(64, 21);
            this.cboHostBaudRate.TabIndex = 15;
            this.cboHostBaudRate.SelectedIndexChanged += new System.EventHandler(this.cboHostBaudRate_SelectedIndexChanged);
            // 
            // label4
            // 
            this.label4.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.label4.Location = new System.Drawing.Point(10, 83);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(100, 16);
            this.label4.TabIndex = 16;
            this.label4.Text = "Host Baud Rate:";
            // 
            // ReceiveUP
            // 
            this.ReceiveUP.Increment = new decimal(new int[] {
            100,
            0,
            0,
            0});
            this.ReceiveUP.Location = new System.Drawing.Point(96, 51);
            this.ReceiveUP.Maximum = new decimal(new int[] {
            2147483647,
            0,
            0,
            0});
            this.ReceiveUP.Minimum = new decimal(new int[] {
            60000,
            0,
            0,
            0});
            this.ReceiveUP.Name = "ReceiveUP";
            this.ReceiveUP.Size = new System.Drawing.Size(64, 20);
            this.ReceiveUP.TabIndex = 8;
            this.ReceiveUP.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
            this.ReceiveUP.ThousandsSeparator = true;
            this.ReceiveUP.Value = new decimal(new int[] {
            60000,
            0,
            0,
            0});
            this.ReceiveUP.ValueChanged += new System.EventHandler(this.MyUpDowns_ValueChanged);
            // 
            // label8
            // 
            this.label8.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.label8.Location = new System.Drawing.Point(12, 25);
            this.label8.Name = "label8";
            this.label8.Size = new System.Drawing.Size(72, 20);
            this.label8.TabIndex = 14;
            this.label8.Text = "Port Name:";
            // 
            // cboPorts
            // 
            this.cboPorts.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cboPorts.Items.AddRange(new object[] {
            "COM1:",
            "COM2:",
            "COM3:",
            "COM4:",
            "COM5:",
            "COM6:",
            "COM7:",
            "COM8:",
            "COM9:"});
            this.cboPorts.Location = new System.Drawing.Point(97, 22);
            this.cboPorts.Name = "cboPorts";
            this.cboPorts.Size = new System.Drawing.Size(62, 21);
            this.cboPorts.TabIndex = 13;
            this.cboPorts.SelectedIndexChanged += new System.EventHandler(this.cboPorts_SelectedIndexChanged);
            // 
            // label3
            // 
            this.label3.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.label3.Location = new System.Drawing.Point(10, 46);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(88, 31);
            this.label3.TabIndex = 6;
            this.label3.Text = "Completion Timeout (msec):";
            // 
            // label5
            // 
            this.label5.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.label5.Location = new System.Drawing.Point(276, 27);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(59, 20);
            this.label5.TabIndex = 23;
            this.label5.Text = "Command: ";
            // 
            // rdoSerial
            // 
            this.rdoSerial.BackColor = System.Drawing.SystemColors.ControlText;
            this.rdoSerial.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.rdoSerial.Location = new System.Drawing.Point(96, 16);
            this.rdoSerial.Name = "rdoSerial";
            this.rdoSerial.Size = new System.Drawing.Size(56, 21);
            this.rdoSerial.TabIndex = 1;
            this.rdoSerial.Text = "Seria&l";
            this.rdoSerial.UseVisualStyleBackColor = false;
            this.rdoSerial.CheckedChanged += new System.EventHandler(this.rdoSerial_CheckedChanged);
            // 
            // rdoTCP
            // 
            this.rdoTCP.BackColor = System.Drawing.SystemColors.ControlText;
            this.rdoTCP.Checked = true;
            this.rdoTCP.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.rdoTCP.Location = new System.Drawing.Point(24, 16);
            this.rdoTCP.Name = "rdoTCP";
            this.rdoTCP.Size = new System.Drawing.Size(46, 21);
            this.rdoTCP.TabIndex = 0;
            this.rdoTCP.TabStop = true;
            this.rdoTCP.Text = "TC&P";
            this.rdoTCP.UseVisualStyleBackColor = false;
            this.rdoTCP.CheckedChanged += new System.EventHandler(this.rdoTCP_CheckedChanged);
            // 
            // grpConnection
            // 
            this.grpConnection.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.grpConnection.BackColor = System.Drawing.SystemColors.ControlText;
            this.grpConnection.Controls.Add(this.rdoSerial);
            this.grpConnection.Controls.Add(this.rdoTCP);
            this.grpConnection.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.grpConnection.Location = new System.Drawing.Point(576, 255);
            this.grpConnection.Name = "grpConnection";
            this.grpConnection.Size = new System.Drawing.Size(176, 48);
            this.grpConnection.TabIndex = 24;
            this.grpConnection.TabStop = false;
            this.grpConnection.Text = "Connection";
            // 
            // lblMacroContents
            // 
            this.lblMacroContents.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.lblMacroContents.Location = new System.Drawing.Point(285, 55);
            this.lblMacroContents.Name = "lblMacroContents";
            this.lblMacroContents.Size = new System.Drawing.Size(94, 19);
            this.lblMacroContents.TabIndex = 26;
            this.lblMacroContents.Tag = "Macro Contents";
            this.lblMacroContents.Text = "Macro Contents:";
            this.lblMacroContents.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // label7
            // 
            this.label7.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.label7.Location = new System.Drawing.Point(31, 209);
            this.label7.Name = "label7";
            this.label7.Size = new System.Drawing.Size(108, 14);
            this.label7.TabIndex = 27;
            this.label7.Text = "Reader Rersponses: ";
            // 
            // label9
            // 
            this.label9.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.label9.Location = new System.Drawing.Point(36, 24);
            this.label9.Name = "label9";
            this.label9.Size = new System.Drawing.Size(59, 26);
            this.label9.TabIndex = 23;
            this.label9.Text = "Current MACRO: ";
            // 
            // cboMacros
            // 
            this.cboMacros.Location = new System.Drawing.Point(92, 24);
            this.cboMacros.Name = "cboMacros";
            this.cboMacros.Size = new System.Drawing.Size(164, 21);
            this.cboMacros.TabIndex = 13;
            this.toolTip1.SetToolTip(this.cboMacros, "Select an existing or enter name of a new MACRO.");
            this.cboMacros.SelectedIndexChanged += new System.EventHandler(this.cboMacros_SelectedIndexChanged);
            this.cboMacros.KeyUp += new System.Windows.Forms.KeyEventHandler(this.cboMacros_KeyUp);
            // 
            // btnSaveMacro
            // 
            this.btnSaveMacro.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.btnSaveMacro.ForeColor = System.Drawing.SystemColors.WindowText;
            this.btnSaveMacro.Location = new System.Drawing.Point(176, 145);
            this.btnSaveMacro.Name = "btnSaveMacro";
            this.btnSaveMacro.Size = new System.Drawing.Size(79, 30);
            this.btnSaveMacro.TabIndex = 16;
            this.btnSaveMacro.Text = "&Save Macro";
            this.btnSaveMacro.UseVisualStyleBackColor = false;
            this.btnSaveMacro.Click += new System.EventHandler(this.btnSaveMacro_Click);
            // 
            // btnDeleteAll
            // 
            this.btnDeleteAll.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.btnDeleteAll.Enabled = false;
            this.btnDeleteAll.ForeColor = System.Drawing.SystemColors.WindowText;
            this.btnDeleteAll.Location = new System.Drawing.Point(176, 100);
            this.btnDeleteAll.Name = "btnDeleteAll";
            this.btnDeleteAll.Size = new System.Drawing.Size(79, 30);
            this.btnDeleteAll.TabIndex = 17;
            this.btnDeleteAll.Text = "Delete All";
            this.btnDeleteAll.UseVisualStyleBackColor = false;
            this.btnDeleteAll.Click += new System.EventHandler(this.btnDeleteAll_Click);
            // 
            // btnClear
            // 
            this.btnClear.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.btnClear.ForeColor = System.Drawing.SystemColors.WindowText;
            this.btnClear.Location = new System.Drawing.Point(201, 197);
            this.btnClear.Name = "btnClear";
            this.btnClear.Size = new System.Drawing.Size(54, 24);
            this.btnClear.TabIndex = 17;
            this.btnClear.Text = "&Clear";
            this.btnClear.UseVisualStyleBackColor = false;
            this.btnClear.Click += new System.EventHandler(this.btnClear_Click);
            // 
            // btnAdd
            // 
            this.btnAdd.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.btnAdd.ForeColor = System.Drawing.SystemColors.WindowText;
            this.btnAdd.Location = new System.Drawing.Point(506, 41);
            this.btnAdd.Name = "btnAdd";
            this.btnAdd.Size = new System.Drawing.Size(54, 24);
            this.btnAdd.TabIndex = 17;
            this.btnAdd.Text = "&Add";
            this.toolTip1.SetToolTip(this.btnAdd, "Add new command");
            this.btnAdd.UseVisualStyleBackColor = false;
            this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);
            // 
            // btnInsert
            // 
            this.btnInsert.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.btnInsert.ForeColor = System.Drawing.SystemColors.WindowText;
            this.btnInsert.Location = new System.Drawing.Point(506, 12);
            this.btnInsert.Name = "btnInsert";
            this.btnInsert.Size = new System.Drawing.Size(54, 24);
            this.btnInsert.TabIndex = 17;
            this.btnInsert.Text = "&Insert";
            this.toolTip1.SetToolTip(this.btnInsert, "Insert new command instead of a selected one");
            this.btnInsert.UseVisualStyleBackColor = false;
            this.btnInsert.Click += new System.EventHandler(this.btnInsert_Click);
            // 
            // vScrollBar1
            // 
            this.vScrollBar1.Location = new System.Drawing.Point(522, 77);
            this.vScrollBar1.Name = "vScrollBar1";
            this.vScrollBar1.Size = new System.Drawing.Size(30, 28);
            this.vScrollBar1.TabIndex = 34;
            this.toolTip1.SetToolTip(this.vScrollBar1, "Move selected Macro line up or down");
            this.vScrollBar1.Visible = false;
            this.vScrollBar1.Scroll += new System.Windows.Forms.ScrollEventHandler(this.vScrollBar1_Scroll);
            // 
            // lstMacroContents
            // 
            this.lstMacroContents.FormattingEnabled = true;
            this.lstMacroContents.Location = new System.Drawing.Point(263, 77);
            this.lstMacroContents.Name = "lstMacroContents";
            this.lstMacroContents.Size = new System.Drawing.Size(256, 134);
            this.lstMacroContents.TabIndex = 35;
            this.lstMacroContents.SelectedIndexChanged += new System.EventHandler(this.lstMacroContents_SelectedIndexChanged);
            this.lstMacroContents.KeyUp += new System.Windows.Forms.KeyEventHandler(this.lstMacroContents_KeyUp);
            // 
            // Form1
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.BackColor = System.Drawing.SystemColors.ControlText;
            this.ClientSize = new System.Drawing.Size(764, 463);
            this.Controls.Add(this.lstMacroContents);
            this.Controls.Add(this.vScrollBar1);
            this.Controls.Add(this.grpSerial);
            this.Controls.Add(this.label7);
            this.Controls.Add(this.cboMacros);
            this.Controls.Add(this.txtCommand);
            this.Controls.Add(this.txtAsyncResponse);
            this.Controls.Add(this.grpConnection);
            this.Controls.Add(this.btnInsert);
            this.Controls.Add(this.btnAdd);
            this.Controls.Add(this.btnClear);
            this.Controls.Add(this.btnDeleteAll);
            this.Controls.Add(this.btnDeleteMacro);
            this.Controls.Add(this.btnDisconnect);
            this.Controls.Add(this.btnConnect);
            this.Controls.Add(this.btnSaveMacro);
            this.Controls.Add(this.btnRunMacro);
            this.Controls.Add(this.grpNetwork);
            this.Controls.Add(this.label9);
            this.Controls.Add(this.label5);
            this.Controls.Add(this.lblMacroContents);
            this.Name = "Form1";
            this.Text = "Alien Example 12 (MACROs)";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.Closing += new System.ComponentModel.CancelEventHandler(this.Form1_Closing);
            this.grpNetwork.ResumeLayout(false);
            this.grpNetwork.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.PortUD)).EndInit();
            this.grpSerial.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.ReceiveUP)).EndInit();
            this.grpConnection.ResumeLayout(false);
            this.ResumeLayout(false);
            this.PerformLayout();

		}

		[STAThread]
		static void Main() 
		{
			try
			{
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false); 
                Application.Run(new Form1());
			}
			catch(Exception ex)
			{
				Trace.WriteLine(ex.Message);
			}
		}

		#endregion

		private void Form1_Load(object sender, System.EventArgs e)
		{
            string exePath = Application.ExecutablePath;
            int idx = exePath.LastIndexOf("\\");
            if (idx != -1)
                AlienLog.Path = exePath.Substring(0, idx + 1);
            AlienLog.WriteLine(true, "Starting the 'Ex12-Working with MACROs' application.");

            mReader = new clsReader(true);
            mReader.KeepNetworkConnectionAlive = true;

			mReaderInfo = mReader.ReaderSettings;
			mReader.Disconnected += new nsAlienRFID2.clsReader.DisconnectedEventHandler(mReader_Disconnected);
			mReader.Connected +=new nsAlienRFID2.clsReader.ConnectedEventHandler(mReader_Connected);
            mReader.MessageReceived += new nsAlienRFID2.clsReader.MessageReceivedEventHandler(mReader_MessageReceived);
            cboPorts.SelectedIndex = 0;

			this.Text = "Alien Library .NET - Testing MACROS";
			Thread.CurrentThread.Name = "Alien-Ex.12: Test MACROS";

		}


		#region Reader Events
		private void mReader_Connected()
		{
			DisplayText("\r\nFrom Connected event:\r\n" + "---------------------------------\r\nConnected\r\n");
			btnDisconnect.Enabled = true;	
			btnConnect.Enabled = false;
			grpConnection.Enabled = true;
			btnRunMacro.Enabled = true;
			btnDeleteMacro.Enabled = true;
			grpSerial.Enabled = false;
			grpNetwork.Enabled = false;
		}

		private void mReader_DataReceived(string data)
		{
			DisplayText("\r\nFrom DataReceived event:\r\n" + "----------------------------------------\r\n" + data);
		}
		private void mReader_MessageReceived(string data)
		{
			String stemp = "";
			if (data.Length > 1)
				stemp = "\r\nFrom MessageReceived event:\r\n" + "-------------------------------------------------\r\n" + data;
			else
				stemp = data;

			DisplayText(stemp);
		}

		private void mReader_Disconnected(string data)
		{
			DisplayText("\r\nFrom Disconnected event:\r\n" + "---------------------------------\r\n" + data);
		}

		#endregion

		private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
		{
			if (mReader != null)
			{
				mReader.Dispose();
			}
		}

		private void MyUpDowns_ValueChanged(object sender, System.EventArgs e)
		{
			NumericUpDown who = (NumericUpDown)sender;
			if (who.Name == "PortUD")
			{
				mReaderInfo.TelnetPort = Convert.ToInt32(who.Value);
				mReader.ReaderSettings = mReaderInfo;
			}
			else
				mReader.ComTimeOutInterval = Convert.ToInt32(who.Value);
		}

		private void DisplayText(String data)
		{
			try
			{
				if (this.InvokeRequired)
				{
					object[] temp = {data};
					this.Invoke(new displayMessageDlgt(DisplayText),temp);
					return;
				}
				else
				{	//supress the login prompt after connecting
					if (data.IndexOf("Username>") != -1)
						data = data.Substring(0, data.Length - 10);

                    if (data.ToLower().Contains("connection closed") ||
                        data.ToLower().Contains("disconnected"))
                    {
                        btnDisconnect.Enabled = false;
                        btnConnect.Enabled = true;
                        grpConnection.Enabled = true;
                        btnRunMacro.Enabled = false;
                        btnDeleteMacro.Enabled = false;
                        if (meReaderInterface == ComInterface.enumTCPIP)
                            grpNetwork.Enabled = true;
                        else
                            grpSerial.Enabled = true;
                    }
					txtAsyncResponse.AppendText(data.Replace("\0", ""));
					txtAsyncResponse.Focus();
					txtAsyncResponse.SelectAll();
					txtAsyncResponse.ScrollToCaret();
					this.Cursor = Cursors.Default;
					txtCommand.Focus();
					return;
				}
			}
			catch(Exception ex)
			{
				Debug.WriteLine("Exception in the DiscplayText: " + ex.Message);
			}
		}

		
		private void btnConnect_Click(object sender, System.EventArgs e)
		{
			String result;
			this.Cursor = Cursors.WaitCursor;
			try		// extra precausion though it shouldn't throw exceptions
			{
				if (meReaderInterface == ComInterface.enumTCPIP)
					mReader.InitOnNetwork(textBox1.Text, Convert.ToInt32(PortUD.Value));
				else
					mReader.InitOnCom();

				DisplayText("\r\nConnecting to the reader...\r\n");
				this.Cursor = Cursors.WaitCursor;

				result = mReader.Connect();
				if (!mReader.IsConnected)
				{
					txtAsyncResponse.AppendText ("\r\nCan't connect\r\n");
				}
				else
				{
					if (meReaderInterface == ComInterface.enumTCPIP)
					{
						DisplayText("\r\nLogging in...\r\n");
						this.Cursor = Cursors.WaitCursor;
						if (!mReader.Login("alien", "password"))		//returns result synchronously
						{
							DisplayText ("\r\nLogin failed! Calling Disconnect()...\r\n");
							mReader.Disconnect();
							return;
						}
						DisplayText("\r\nLogged in - OK!\r\n");
					}
					btnDisconnect.Enabled = true;
					btnConnect.Enabled = false;
					grpConnection.Enabled = false;
					btnRunMacro.Enabled = true;
					btnDeleteMacro.Enabled = true;

                    string macros = mReader.SendReceive("MacroList", false);
                    string[] tokens = macros.Replace("\0", "").Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                    if ((tokens != null) && (tokens.Length > 0))
                    {
                        cboMacros.Items.Clear();
                        cboMacros.Items.AddRange(tokens);
                        cboMacros.DroppedDown = true;
                    }
				}
			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
			this.Cursor = Cursors.Default;
		}


		private void btnDisconnect_Click(object sender, System.EventArgs e)
		{
			this.Cursor = Cursors.WaitCursor;		
			mReader.Disconnect();
			this.Cursor = Cursors.Default;	
			btnDisconnect.Enabled = false;	
			btnConnect.Enabled = true;
			grpConnection.Enabled = true;
			btnRunMacro.Enabled = false;
			btnDeleteMacro.Enabled = false;
			if (meReaderInterface == ComInterface.enumTCPIP)
				grpNetwork.Enabled = true;
			else
				grpSerial.Enabled = true;
		}


		private void rdoSerial_CheckedChanged(object sender, System.EventArgs e)
		{
			bool state = rdoSerial.Checked;
			grpSerial.Enabled = state;
			grpNetwork.Enabled = !state;
			btnConnect.Text = (state ? "Co&nnect" : "Co&nnect + Login");
			meReaderInterface = (state ? ComInterface.enumSerial : ComInterface.enumTCPIP);
			mReaderInfo.InterfaceType = meReaderInterface;
			mReader.ReaderSettings = mReaderInfo;
		}

		private void rdoTCP_CheckedChanged(object sender, System.EventArgs e)
		{
			bool state = rdoTCP.Checked;
			grpSerial.Enabled = !state;
			grpNetwork.Enabled = state;
			btnConnect.Text = (state ? "Co&nnect + Login" : "Co&nnect" );
			meReaderInterface = (state ? ComInterface.enumTCPIP : ComInterface.enumSerial);
			mReaderInfo.InterfaceType = meReaderInterface;
			mReader.ReaderSettings = mReaderInfo;
		}

		private void cboPorts_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			mReader.SerialPort = cboPorts.Text;
		}

		private void cboHostBaudRate_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			if (cboHostBaudRate.Enabled)
				mReader.HostBaudRate = int.Parse(cboHostBaudRate.Text);
        }


        private void btnSaveMacro_Click(object sender, EventArgs e)
        {
            if (lstMacroContents.Items.Count == 0)
                return;

            try
            {
                mReader.Send("MacroStartRec " + cboMacros.Text.Trim(), false);
                for (int i = 0; i < lstMacroContents.Items.Count; i++)
                {
                    mReader.Send(lstMacroContents.Items[i] as string, false);
                }
                mReader.Send("MacroStopRec", false);
                if (!cboMacros.Items.Contains(cboMacros.Text.Trim()))
                {
                    cboMacros.Items.Add(cboMacros.Text.Trim());
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void txtCommand_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                lstMacroContents.Items.Add(txtCommand.Text);
                txtCommand.SelectAll();
            }
        }

        private void btnRunMacro_Click(object sender, EventArgs e)
        {
            mReader.Send("MacroRun " + cboMacros.Text, false);
        }

        private void cboMacros_SelectedIndexChanged(object sender, EventArgs e)
        {
            string name = cboMacros.Text.Trim();
            string macro = mReader.SendReceive("MacroView " + name, false);
            string[] tokens = macro.Replace("\0", "").Split(new string[] { "\r\n" }, StringSplitOptions.None);
            lstMacroContents.Items.Clear();
            for (int i = 0; i < tokens.Length; i++)
            {
                lstMacroContents.Items.Add(tokens[i]);
            }
            lblMacroContents.Text = "'" + name + "' Contents:";
        }

        private void btnDeleteMacro_Click(object sender, EventArgs e)
        {
            string macro = cboMacros.Text.Trim();
            if (!string.IsNullOrEmpty(macro))
            {
                mReader.Send("MacroDel " + macro, false);
                //lstMacroContents.Clear();
                if (cboMacros.Items.Contains(macro))
                    cboMacros.Items.Remove(macro);
            }
        }

        private void btnDeleteAll_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(
                "Are you sure you want to delete ALL macros?", 
                "Are you sure?", 
                MessageBoxButtons.YesNo, 
                MessageBoxIcon.Question) == DialogResult.Yes)
                mReader.Send("MacroDelAll", false);
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            txtAsyncResponse.Clear();
            lstMacroContents.Items.Clear();
            lblMacroContents.Text = "";
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            lstMacroContents.Items.Add(txtCommand.Text);
            lstMacroContents.SelectedIndex = lstMacroContents.Items.Count - 1;
            txtCommand.SelectAll();
        }

        private void swapItems(int idx1, int idx2)
        {
            string text1 = lstMacroContents.Items[idx1] as string;
            string text2 = lstMacroContents.Items[idx2] as string;
            lstMacroContents.Items.RemoveAt(idx2);
            lstMacroContents.Items.Insert(idx2, text1);
            lstMacroContents.Items.RemoveAt(idx1);
            lstMacroContents.Items.Insert(idx1, text2);
        }

        private void vScrollBar1_Scroll(object sender, ScrollEventArgs e)
        {
            if (lstMacroContents.SelectedIndices.Count == 0)
                return;
            int idx1 = lstMacroContents.SelectedIndices[0];
            int idx2 = -1;
            switch (e.Type)
            {
                case ScrollEventType.SmallIncrement:
                    {
                        if (idx1 == lstMacroContents.Items.Count - 1)
                            return;
                        idx2 = idx1 + 1;
                    }
                    break;
                case ScrollEventType.SmallDecrement:
                    {
                        if (idx1 == 0)
                            return;
                        idx2 = idx1 - 1;
                    }
                    break;
                default: return;
            }
            swapItems(idx1, idx2);
            lstMacroContents.SelectedIndex = idx2;
        }

        private void lstMacroContents_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lstMacroContents.SelectedIndices.Count == 0)
            {
                vScrollBar1.Visible = false;
                return;
            }
            vScrollBar1.Visible = true;
            bool insideSelected = false;
            if (insideSelected)
                return;
            insideSelected = true;

            string line = lstMacroContents.SelectedItems[0] as string;
            txtCommand.Text = line;

            vScrollBar1.Top = lstMacroContents.GetItemRectangle(lstMacroContents.SelectedIndex).Y + lstMacroContents.Top;
            vScrollBar1.Refresh();

            insideSelected = false;
        }

        private void cboMacros_KeyUp(object sender, KeyEventArgs e)
        {
            lblMacroContents.Text = cboMacros.Text;
        }

        private void btnInsert_Click(object sender, EventArgs e)
        {
            int idx = lstMacroContents.SelectedIndex;
            if (idx <= 0)
                idx = 0;
            else
                idx--;
            lstMacroContents.Items.Insert(idx, txtCommand.Text);
            lstMacroContents.SelectedIndex = idx;
        }

        private void lstMacroContents_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                if (lstMacroContents.SelectedIndices.Count > 0)
                {
                    lstMacroContents.Items.RemoveAt(lstMacroContents.SelectedIndices[0]);
                }
            }
        }
	}
}
