using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using NiApiLib;

namespace TestCOM
{
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class MainForm : System.Windows.Forms.Form
	{
		private NiApiLib.SrvrSession SrvrSession;
		private NiApiLib.Table tblFev;
		private NiApiLib.Filter myFiltr;
		private NiApiLib.Structure myStructure;
		private NiApiLib.DataRow drFev;
		private System.Data.DataTable dtTickers;
        private System.Data.DataTable dtSelectedTickers;
		private DataSet myDataSet;
		private NiApiLib.DataRowSet myDataRowSet;
		private System.Boolean UpdatesOn;
		private System.Boolean Connected;
        private System.Boolean SetFilter;
        private ArrayList tickersNameArray;
        private string[] selectedTickersArray;
        private NiApiLib.Transaction niTransaction;
        private string tableName;
        private int transactNum;
        private int connectionsNum;
        private Boolean Crypto;
        private string cryptoLibrary;
        private string keyBase;
        private string userKey;
        private string serverKey;
       
     		
		//---------------------------------------------------------------------

		private System.Windows.Forms.Button btnConnect;
		private System.Windows.Forms.Button btnDisconnect;
		private System.Windows.Forms.GroupBox gbConnectionSettings;
		private System.Windows.Forms.Label lblServerAddress;
		private System.Windows.Forms.Label lblPort;
		private System.Windows.Forms.Label lblLoginName;
		private System.Windows.Forms.Label lblPassword;
		private System.Windows.Forms.Label lblConnectionStatus;
		private System.Windows.Forms.Label lblConnectionStatuseMsg;
		private System.Windows.Forms.TextBox tbServerAddress;
		private System.Windows.Forms.TextBox tbPort;
		private System.Windows.Forms.TextBox tbLoginName;
		private System.Windows.Forms.TextBox tbPassword;
        private System.Windows.Forms.DataGrid dgTickers;
		private System.Windows.Forms.Button btnUpdates;
        private Button btSetFilter;
        private Button btClearFilters;
        private ListBox lbMessages;
        private Label lblMessages;
        private TextBox textBox1;
        private Label label1;
        private Button btnTransaction;
        private Button btnOpenCatalog;
        private OpenFileDialog ofdCatalog;
        private TextBox tbCatalogPath;
        private Label lblServerKey;
        private Label lblUserKey;
        private CheckBox checkBox1;
        private Button btnCryptoLibrary;
        private TextBox tbServerKey;
        private TextBox tbUserKey;
        private TextBox tbKeyBase;
        private TextBox tbCryptoLibrary;
        private Button btnKeyBase;
		
		
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		public MainForm()
		{
			InitializeComponent();

			this.SrvrSession = new NiApiLib.SrvrSessionClass();
			this.tblFev= new TableClass();
			this.myFiltr=new FilterClass();
            this.myStructure=new NiApiLib.StructureClass();
			this.drFev=new NiApiLib.DataRowClass();
			this.myDataRowSet=new DataRowSetClass();
			this.UpdatesOn=false;
			this.Connected=false;
            this.SetFilter = false;
            this.dtSelectedTickers = new DataTable();
            this.niTransaction = new Transaction();
            this.myDataSet = new DataSet("myDataSet");
            this.transactNum = 0;
            this.connectionsNum = 0;
            this.tickersNameArray = new ArrayList();
            this.Crypto = false;
			

			this.SrvrSession.OnMessage+=new _ISrvrSessionEvents_OnMessageEventHandler(SrvrSession_OnMessage);
            this.SrvrSession.OnStatusMessage += new _ISrvrSessionEvents_OnStatusMessageEventHandler(SrvrSession_OnMessage);
			this.SrvrSession.OnLogin+=new _ISrvrSessionEvents_OnLoginEventHandler(SrvrSession_OnLogin);
			this.tblFev.OnData+=new _ITableEvents_OnDataEventHandler(tblFev_OnData);
			this.tblFev.OnDataComplete+=new _ITableEvents_OnDataCompleteEventHandler(tblFev_OnDataComplete);
		    this.tblFev.OnInsert += new _ITableEvents_OnInsertEventHandler(tblFev_OnModify);
            this.tblFev.OnModify+=new _ITableEvents_OnModifyEventHandler(tblFev_OnModify);
			
		}

		/// <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.btnConnect = new System.Windows.Forms.Button();
            this.btnDisconnect = new System.Windows.Forms.Button();
            this.gbConnectionSettings = new System.Windows.Forms.GroupBox();
            this.btnKeyBase = new System.Windows.Forms.Button();
            this.tbServerKey = new System.Windows.Forms.TextBox();
            this.tbUserKey = new System.Windows.Forms.TextBox();
            this.tbKeyBase = new System.Windows.Forms.TextBox();
            this.tbCryptoLibrary = new System.Windows.Forms.TextBox();
            this.btnCryptoLibrary = new System.Windows.Forms.Button();
            this.lblServerKey = new System.Windows.Forms.Label();
            this.lblUserKey = new System.Windows.Forms.Label();
            this.checkBox1 = new System.Windows.Forms.CheckBox();
            this.tbCatalogPath = new System.Windows.Forms.TextBox();
            this.btnOpenCatalog = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.tbPassword = new System.Windows.Forms.TextBox();
            this.tbLoginName = new System.Windows.Forms.TextBox();
            this.tbPort = new System.Windows.Forms.TextBox();
            this.tbServerAddress = new System.Windows.Forms.TextBox();
            this.lblPassword = new System.Windows.Forms.Label();
            this.lblLoginName = new System.Windows.Forms.Label();
            this.lblPort = new System.Windows.Forms.Label();
            this.lblServerAddress = new System.Windows.Forms.Label();
            this.lblConnectionStatus = new System.Windows.Forms.Label();
            this.lblConnectionStatuseMsg = new System.Windows.Forms.Label();
            this.dgTickers = new System.Windows.Forms.DataGrid();
            this.btnUpdates = new System.Windows.Forms.Button();
            this.btSetFilter = new System.Windows.Forms.Button();
            this.btClearFilters = new System.Windows.Forms.Button();
            this.lbMessages = new System.Windows.Forms.ListBox();
            this.lblMessages = new System.Windows.Forms.Label();
            this.btnTransaction = new System.Windows.Forms.Button();
            this.ofdCatalog = new System.Windows.Forms.OpenFileDialog();
            this.gbConnectionSettings.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.dgTickers)).BeginInit();
            this.SuspendLayout();
            // 
            // btnConnect
            // 
            this.btnConnect.Location = new System.Drawing.Point(8, 294);
            this.btnConnect.Name = "btnConnect";
            this.btnConnect.Size = new System.Drawing.Size(89, 20);
            this.btnConnect.TabIndex = 0;
            this.btnConnect.Text = "Connect";
            this.btnConnect.Click += new System.EventHandler(this.button1_Click);
            // 
            // btnDisconnect
            // 
            this.btnDisconnect.Location = new System.Drawing.Point(114, 295);
            this.btnDisconnect.Name = "btnDisconnect";
            this.btnDisconnect.Size = new System.Drawing.Size(89, 20);
            this.btnDisconnect.TabIndex = 1;
            this.btnDisconnect.Text = "Disconnect";
            this.btnDisconnect.Click += new System.EventHandler(this.btnDisconnect_Click);
            // 
            // gbConnectionSettings
            // 
            this.gbConnectionSettings.Controls.Add(this.btnKeyBase);
            this.gbConnectionSettings.Controls.Add(this.tbServerKey);
            this.gbConnectionSettings.Controls.Add(this.tbUserKey);
            this.gbConnectionSettings.Controls.Add(this.tbKeyBase);
            this.gbConnectionSettings.Controls.Add(this.tbCryptoLibrary);
            this.gbConnectionSettings.Controls.Add(this.btnCryptoLibrary);
            this.gbConnectionSettings.Controls.Add(this.lblServerKey);
            this.gbConnectionSettings.Controls.Add(this.lblUserKey);
            this.gbConnectionSettings.Controls.Add(this.checkBox1);
            this.gbConnectionSettings.Controls.Add(this.tbCatalogPath);
            this.gbConnectionSettings.Controls.Add(this.btnOpenCatalog);
            this.gbConnectionSettings.Controls.Add(this.label1);
            this.gbConnectionSettings.Controls.Add(this.textBox1);
            this.gbConnectionSettings.Controls.Add(this.tbPassword);
            this.gbConnectionSettings.Controls.Add(this.tbLoginName);
            this.gbConnectionSettings.Controls.Add(this.tbPort);
            this.gbConnectionSettings.Controls.Add(this.tbServerAddress);
            this.gbConnectionSettings.Controls.Add(this.lblPassword);
            this.gbConnectionSettings.Controls.Add(this.lblLoginName);
            this.gbConnectionSettings.Controls.Add(this.lblPort);
            this.gbConnectionSettings.Controls.Add(this.lblServerAddress);
            this.gbConnectionSettings.Location = new System.Drawing.Point(8, 8);
            this.gbConnectionSettings.Name = "gbConnectionSettings";
            this.gbConnectionSettings.Size = new System.Drawing.Size(324, 280);
            this.gbConnectionSettings.TabIndex = 3;
            this.gbConnectionSettings.TabStop = false;
            this.gbConnectionSettings.Text = "Connection Settings";
            // 
            // btnKeyBase
            // 
            this.btnKeyBase.Enabled = false;
            this.btnKeyBase.Location = new System.Drawing.Point(6, 204);
            this.btnKeyBase.Name = "btnKeyBase";
            this.btnKeyBase.Size = new System.Drawing.Size(103, 20);
            this.btnKeyBase.TabIndex = 28;
            this.btnKeyBase.Text = "Choose key base";
            this.btnKeyBase.UseVisualStyleBackColor = true;
            this.btnKeyBase.Click += new System.EventHandler(this.btnKeyBase_Click);
            // 
            // tbServerKey
            // 
            this.tbServerKey.Enabled = false;
            this.tbServerKey.Location = new System.Drawing.Point(115, 253);
            this.tbServerKey.Name = "tbServerKey";
            this.tbServerKey.Size = new System.Drawing.Size(201, 20);
            this.tbServerKey.TabIndex = 27;
            this.tbServerKey.Text = "netinvestor";
            // 
            // tbUserKey
            // 
            this.tbUserKey.Enabled = false;
            this.tbUserKey.Location = new System.Drawing.Point(115, 229);
            this.tbUserKey.Name = "tbUserKey";
            this.tbUserKey.Size = new System.Drawing.Size(201, 20);
            this.tbUserKey.TabIndex = 26;
            this.tbUserKey.Text = "admin";
            // 
            // tbKeyBase
            // 
            this.tbKeyBase.Enabled = false;
            this.tbKeyBase.Location = new System.Drawing.Point(115, 205);
            this.tbKeyBase.Name = "tbKeyBase";
            this.tbKeyBase.Size = new System.Drawing.Size(201, 20);
            this.tbKeyBase.TabIndex = 25;
            this.tbKeyBase.Text = "admin.bin";
            // 
            // tbCryptoLibrary
            // 
            this.tbCryptoLibrary.Enabled = false;
            this.tbCryptoLibrary.Location = new System.Drawing.Point(116, 181);
            this.tbCryptoLibrary.Name = "tbCryptoLibrary";
            this.tbCryptoLibrary.Size = new System.Drawing.Size(201, 20);
            this.tbCryptoLibrary.TabIndex = 24;
            this.tbCryptoLibrary.Text = "NiSecure.dll";
            // 
            // btnCryptoLibrary
            // 
            this.btnCryptoLibrary.Enabled = false;
            this.btnCryptoLibrary.Location = new System.Drawing.Point(7, 180);
            this.btnCryptoLibrary.Name = "btnCryptoLibrary";
            this.btnCryptoLibrary.Size = new System.Drawing.Size(102, 20);
            this.btnCryptoLibrary.TabIndex = 23;
            this.btnCryptoLibrary.Text = "Choose Library";
            this.btnCryptoLibrary.UseVisualStyleBackColor = true;
            this.btnCryptoLibrary.Click += new System.EventHandler(this.btnCryptoLibrary_Click);
            // 
            // lblServerKey
            // 
            this.lblServerKey.Enabled = false;
            this.lblServerKey.Location = new System.Drawing.Point(4, 256);
            this.lblServerKey.Name = "lblServerKey";
            this.lblServerKey.Size = new System.Drawing.Size(88, 16);
            this.lblServerKey.TabIndex = 22;
            this.lblServerKey.Text = "Server key";
            // 
            // lblUserKey
            // 
            this.lblUserKey.Enabled = false;
            this.lblUserKey.Location = new System.Drawing.Point(4, 232);
            this.lblUserKey.Name = "lblUserKey";
            this.lblUserKey.Size = new System.Drawing.Size(88, 16);
            this.lblUserKey.TabIndex = 21;
            this.lblUserKey.Text = "User key";
            // 
            // checkBox1
            // 
            this.checkBox1.AutoSize = true;
            this.checkBox1.Location = new System.Drawing.Point(4, 164);
            this.checkBox1.Name = "checkBox1";
            this.checkBox1.Size = new System.Drawing.Size(123, 17);
            this.checkBox1.TabIndex = 18;
            this.checkBox1.Text = "Enable cryptography";
            this.checkBox1.UseVisualStyleBackColor = true;
            this.checkBox1.CheckedChanged += new System.EventHandler(this.checkBox1_CheckedChanged);
            // 
            // tbCatalogPath
            // 
            this.tbCatalogPath.Location = new System.Drawing.Point(116, 139);
            this.tbCatalogPath.Name = "tbCatalogPath";
            this.tbCatalogPath.Size = new System.Drawing.Size(201, 20);
            this.tbCatalogPath.TabIndex = 17;
            this.tbCatalogPath.Text = "catalog.xml";
            // 
            // btnOpenCatalog
            // 
            this.btnOpenCatalog.Location = new System.Drawing.Point(6, 138);
            this.btnOpenCatalog.Name = "btnOpenCatalog";
            this.btnOpenCatalog.Size = new System.Drawing.Size(103, 20);
            this.btnOpenCatalog.TabIndex = 16;
            this.btnOpenCatalog.Text = "Choose catalog";
            this.btnOpenCatalog.UseVisualStyleBackColor = true;
            this.btnOpenCatalog.Click += new System.EventHandler(this.btnOpenCatalog_Click);
            // 
            // label1
            // 
            this.label1.Location = new System.Drawing.Point(8, 117);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(88, 16);
            this.label1.TabIndex = 16;
            this.label1.Text = "Table Name";
            // 
            // textBox1
            // 
            this.textBox1.Location = new System.Drawing.Point(116, 114);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(202, 20);
            this.textBox1.TabIndex = 15;
            this.textBox1.Text = "ORDERS";
            // 
            // tbPassword
            // 
            this.tbPassword.Location = new System.Drawing.Point(116, 88);
            this.tbPassword.Name = "tbPassword";
            this.tbPassword.Size = new System.Drawing.Size(202, 20);
            this.tbPassword.TabIndex = 7;
            this.tbPassword.Text = "tester";
            // 
            // tbLoginName
            // 
            this.tbLoginName.Location = new System.Drawing.Point(116, 64);
            this.tbLoginName.Name = "tbLoginName";
            this.tbLoginName.Size = new System.Drawing.Size(202, 20);
            this.tbLoginName.TabIndex = 6;
            this.tbLoginName.Text = "tester";
            // 
            // tbPort
            // 
            this.tbPort.Location = new System.Drawing.Point(116, 40);
            this.tbPort.Name = "tbPort";
            this.tbPort.Size = new System.Drawing.Size(202, 20);
            this.tbPort.TabIndex = 5;
            this.tbPort.Text = "2900";
            // 
            // tbServerAddress
            // 
            this.tbServerAddress.Location = new System.Drawing.Point(116, 16);
            this.tbServerAddress.Name = "tbServerAddress";
            this.tbServerAddress.Size = new System.Drawing.Size(202, 20);
            this.tbServerAddress.TabIndex = 4;
            this.tbServerAddress.Text = "10.200.200.161";
            // 
            // lblPassword
            // 
            this.lblPassword.Location = new System.Drawing.Point(8, 96);
            this.lblPassword.Name = "lblPassword";
            this.lblPassword.Size = new System.Drawing.Size(88, 16);
            this.lblPassword.TabIndex = 3;
            this.lblPassword.Text = "Password";
            // 
            // lblLoginName
            // 
            this.lblLoginName.Location = new System.Drawing.Point(8, 72);
            this.lblLoginName.Name = "lblLoginName";
            this.lblLoginName.Size = new System.Drawing.Size(88, 16);
            this.lblLoginName.TabIndex = 2;
            this.lblLoginName.Text = "Login Name";
            // 
            // lblPort
            // 
            this.lblPort.Location = new System.Drawing.Point(8, 48);
            this.lblPort.Name = "lblPort";
            this.lblPort.Size = new System.Drawing.Size(88, 16);
            this.lblPort.TabIndex = 1;
            this.lblPort.Text = "Port";
            // 
            // lblServerAddress
            // 
            this.lblServerAddress.Location = new System.Drawing.Point(8, 24);
            this.lblServerAddress.Name = "lblServerAddress";
            this.lblServerAddress.Size = new System.Drawing.Size(88, 16);
            this.lblServerAddress.TabIndex = 0;
            this.lblServerAddress.Text = "Server Address";
            // 
            // lblConnectionStatus
            // 
            this.lblConnectionStatus.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
            this.lblConnectionStatus.ForeColor = System.Drawing.SystemColors.ControlText;
            this.lblConnectionStatus.Location = new System.Drawing.Point(335, 8);
            this.lblConnectionStatus.Name = "lblConnectionStatus";
            this.lblConnectionStatus.Size = new System.Drawing.Size(120, 16);
            this.lblConnectionStatus.TabIndex = 4;
            this.lblConnectionStatus.Text = "Connection Status:";
            // 
            // lblConnectionStatuseMsg
            // 
            this.lblConnectionStatuseMsg.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
            this.lblConnectionStatuseMsg.ForeColor = System.Drawing.SystemColors.ActiveCaption;
            this.lblConnectionStatuseMsg.Location = new System.Drawing.Point(335, 28);
            this.lblConnectionStatuseMsg.Name = "lblConnectionStatuseMsg";
            this.lblConnectionStatuseMsg.Size = new System.Drawing.Size(120, 16);
            this.lblConnectionStatuseMsg.TabIndex = 5;
            // 
            // dgTickers
            // 
            this.dgTickers.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.dgTickers.DataMember = "";
            this.dgTickers.HeaderForeColor = System.Drawing.SystemColors.ControlText;
            this.dgTickers.Location = new System.Drawing.Point(6, 342);
            this.dgTickers.Name = "dgTickers";
            this.dgTickers.ReadOnly = true;
            this.dgTickers.Size = new System.Drawing.Size(822, 349);
            this.dgTickers.TabIndex = 6;
            // 
            // btnUpdates
            // 
            this.btnUpdates.Location = new System.Drawing.Point(8, 316);
            this.btnUpdates.Name = "btnUpdates";
            this.btnUpdates.Size = new System.Drawing.Size(89, 20);
            this.btnUpdates.TabIndex = 10;
            this.btnUpdates.Text = "Updates on";
            this.btnUpdates.Click += new System.EventHandler(this.btnUpdates_Click);
            // 
            // btSetFilter
            // 
            this.btSetFilter.Location = new System.Drawing.Point(114, 316);
            this.btSetFilter.Name = "btSetFilter";
            this.btSetFilter.Size = new System.Drawing.Size(89, 20);
            this.btSetFilter.TabIndex = 11;
            this.btSetFilter.Text = "Set Filter";
            this.btSetFilter.Click += new System.EventHandler(this.btSetFilter_Click);
            // 
            // btClearFilters
            // 
            this.btClearFilters.Location = new System.Drawing.Point(223, 316);
            this.btClearFilters.Name = "btClearFilters";
            this.btClearFilters.Size = new System.Drawing.Size(89, 20);
            this.btClearFilters.TabIndex = 12;
            this.btClearFilters.Text = "Clear Filters";
            this.btClearFilters.UseVisualStyleBackColor = true;
            this.btClearFilters.Click += new System.EventHandler(this.btClearFilters_Click);
            // 
            // lbMessages
            // 
            this.lbMessages.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.lbMessages.FormattingEnabled = true;
            this.lbMessages.HorizontalScrollbar = true;
            this.lbMessages.Location = new System.Drawing.Point(338, 73);
            this.lbMessages.Name = "lbMessages";
            this.lbMessages.Size = new System.Drawing.Size(490, 264);
            this.lbMessages.TabIndex = 13;
            // 
            // lblMessages
            // 
            this.lblMessages.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
            this.lblMessages.ForeColor = System.Drawing.SystemColors.ControlText;
            this.lblMessages.Location = new System.Drawing.Point(335, 54);
            this.lblMessages.Name = "lblMessages";
            this.lblMessages.Size = new System.Drawing.Size(120, 16);
            this.lblMessages.TabIndex = 14;
            this.lblMessages.Text = "Messages:";
            // 
            // btnTransaction
            // 
            this.btnTransaction.Location = new System.Drawing.Point(223, 294);
            this.btnTransaction.Name = "btnTransaction";
            this.btnTransaction.Size = new System.Drawing.Size(89, 20);
            this.btnTransaction.TabIndex = 15;
            this.btnTransaction.Text = "Transaction";
            this.btnTransaction.UseVisualStyleBackColor = true;
            this.btnTransaction.Click += new System.EventHandler(this.btnTransaction_Click);
            // 
            // ofdCatalog
            // 
            this.ofdCatalog.FileName = "openFileDialog1";
            // 
            // MainForm
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(832, 703);
            this.Controls.Add(this.btnTransaction);
            this.Controls.Add(this.lblMessages);
            this.Controls.Add(this.lbMessages);
            this.Controls.Add(this.btClearFilters);
            this.Controls.Add(this.btSetFilter);
            this.Controls.Add(this.btnUpdates);
            this.Controls.Add(this.dgTickers);
            this.Controls.Add(this.lblConnectionStatuseMsg);
            this.Controls.Add(this.lblConnectionStatus);
            this.Controls.Add(this.gbConnectionSettings);
            this.Controls.Add(this.btnDisconnect);
            this.Controls.Add(this.btnConnect);
            this.Name = "MainForm";
            this.Text = "TestCom Application";
            this.gbConnectionSettings.ResumeLayout(false);
            this.gbConnectionSettings.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.dgTickers)).EndInit();
            this.ResumeLayout(false);

		}
		#endregion

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

		private void button1_Click(object sender, System.EventArgs e)
		{
			if(this.Connected==false)
			{
                //
                // Установка параметров для объекта SrvrSession (тип NiApiLib.SrvrSession)
                // Параметры заданы по умолчанию или вводятся пользователем с помощью textBox'ов 
                //
                
				this.SrvrSession.HostAddr=this.tbServerAddress.Text;
				this.SrvrSession.HostPort=System.Convert.ToInt32(this.tbPort.Text);
				this.SrvrSession.Name=this.tbLoginName.Text;
				this.SrvrSession.Password=this.tbPassword.Text;

                //
                // Журналирование сессии
                //
                this.SrvrSession.Journal = "test_infomain";
             

                //
                //Криптозащита
                //
                

                //             string file_name - путь к библиотеке безопасности
                //             string base_name - имя базы ключей, или хранилища настроек;
                //             string node_name - имя ключа/сертификата пользователя;
                //             string remote_name - имя ключа/сертификата сервера;

                if (Crypto == true)
                {
                    try
                    {
                       if(this.connectionsNum==0)
                        this.SrvrSession.CryptoStart(this.cryptoLibrary, this.keyBase, this.userKey, this.serverKey);
                    }
                    catch (System.ArgumentException eCryptInvArg)
                    {

                        MessageBox.Show("Неверные параметры криптозащиты.\n" + eCryptInvArg.Message);
                        this.Close();
                    }
                    catch (System.FieldAccessException eFaildArg)
                    {

                        MessageBox.Show("Неудалось активизировать криптозащиту.");
                        this.Close();
                    }
                    catch (System.NotImplementedException eNotEmpl)
                    {
                        MessageBox.Show("Не удалось инициализировать систему криптозащитыю\n"+eNotEmpl.Message);
                    }
                    catch (System.Exception exp)
                    {
                        MessageBox.Show("Неверное имя файла базы ключа или ключ пользователя");
                        this.Close();
                    }

                }
                else
                {
                    try
                    {
                        this.SrvrSession.CryptoStop();
                    }
                    catch (System.UnauthorizedAccessException eCrypt)
                    {
                        // криптосистема не была инициализированна
                    }
                }
                //
                // Соединение с сервером
                //
				this.SrvrSession.Connect();
				
		
                //
                // Проверка: создан ли объект tblFev (тип NiApiLib.Table)
                // Если нет (это возможно, если была нажата кнопка Disconnect), то создаем объект и 
                // регестрируем обработчики событий OnData и OnInsert
                //
				if(this.tblFev==null)
				{
                    this.myDataSet = new DataSet();
                    this.tblFev= new TableClass();
					this.tblFev.OnData+=new _ITableEvents_OnDataEventHandler(tblFev_OnData);
					this.tblFev.OnInsert += new _ITableEvents_OnInsertEventHandler(tblFev_OnModify);
				}
				this.lblConnectionStatuseMsg.Text="Connecting...";
			}
			
		}


        //
        // Обработчик событий OnMessage и OnStatusMessage для объекта SrvrSession (тип NiApiLib.SrvrSession)
        //
		private void SrvrSession_OnMessage(object Msg)
		{

            try
            {
                NiApiLib.StatusMessage statusMessage = (NiApiLib.StatusMessage)Msg;
                NiApiLib.Message message = (NiApiLib.Message)statusMessage.Message;
                string str = " Message( [" + message.Count().ToString() + "], " + message.Command().ToString() + ", " + message.Value(1).ToString() + ") ";
                for (int i = 0; i < message.Count() - 1; i++)
                {
                    str += " : " + message.Separator(i) + " : " + message.Value(i);
                }
                this.lbMessages.Items.Add(str);

            }
            catch (Exception e)
            {
                try
                {
                    NiApiLib.Message message = (NiApiLib.Message)Msg;
                    string str = " Message( [" + message.Count().ToString() + "], " + message.Command().ToString() + ", " + message.Value(1).ToString() + ") ";
                    for (int i = 0; i < message.Count() - 1; i++)
                    {
                        str += " : " + message.Separator(i) + " : " + message.Value(i);
                    }
                    this.lbMessages.Items.Add(str);

                }
                catch (Exception e2)
                {

                }
            }
            
    	}



        //
        // Обработчик события OnLogin для объекта SrvrSession (тип NiApiLib.SrvrSession)
        //
		private void SrvrSession_OnLogin(int LoginResult)
		{
            this.Connected = true;
            this.connectionsNum++;
			this.lblConnectionStatuseMsg.Text="Logged";

            //
            //Открываем таблицу с именем tableName с помощью объекта tblFev (тип NiApiLib.Table)
            //При открытии таблички необходимо учитывать "адресность"
            // 
            tableName = this.textBox1.Text;
            if (this.tableName == "ORDERS")
            {
                this.tblFev.Open(this.SrvrSession, tableName, NiApiLib.ETableType.tabAdrr);
            }
            else
            {
                this.tblFev.Open(this.SrvrSession, tableName, NiApiLib.ETableType.tabNoneAddr);
            }
			this.lblConnectionStatuseMsg.Text="Table Opened";

					

            //
            //Создаем структуру myStructure (тип NiApiLib.Structure), идентичную структуре таблицы tblFev
            //
			this.myStructure=(NiApiLib.Structure)this.tblFev.Structure;
		
			this.myFiltr.Structure=this.tblFev.Structure;

            //
            // Получаем данные таблицы 
            //

            if (this.tableName == "ORDERS")
            {
                this.tblFev.GetData(this.myFiltr);
            }
            else 
            {
                this.tblFev.GetSlice(this.myFiltr);            
            }


            
            
            dtTickers = new DataTable("Tickers");

            //
            //цикл по всем полям строки myrow (тип NiApiLib.DataRow) - первой строки в таблице 
            //полученных данных
            //
            Console.WriteLine("myStructure.Count: "+myStructure.Count.ToString());
            for (int i = 0; i < this.myStructure.Count; i++)
            {
                //в таблице для отображения данных dtTickers (тип System.Data.DataTable) создаются колонки 
                //по количеству полей в строке myrow
                dtTickers.Columns.Add();
                //названия заголовков колонок устанавливаются на значение свойства myStructure.FieldDispName
                //то есть на название полей в таблице данных с сервера 
                if (this.myStructure.FieldDispName(i) != "")
                {
                    dtTickers.Columns[i].ColumnName = this.myStructure.FieldDispName(i);
                }


            }


            myDataSet.Tables.Add(dtTickers);
            this.dgTickers.DataSource = this.myDataSet;
            this.dgTickers.DataMember = "Tickers";

			
		
		}

        private void btnDisconnect_Click(object sender, System.EventArgs e)
		{
            if (Connected)
            {
                //
                //отключаем подписку на он-лайн обновления
                //
                this.tblFev.SetOnlineUpdates(NiApiLib.ESubscribtion.subDisabled);
                this.UpdatesOn = false;
                this.btnUpdates.Text = "Updates on";

                //
                //удаляем все фильтры
                //
                if (this.SetFilter == true)
                {
                    this.tblFev.DeleteUpdateFilter(0);
                    selectedTickersArray = null;
                }

                //
                // Разрываем соединение с сервером
                //
                this.SrvrSession.Disconnect();
                this.lblConnectionStatuseMsg.Text = "Disconnected";
      

                //
                // Освобождаем объект tblFev и myDataSet, удаляем список инструментов для формы фильтров
                //
                this.tblFev = null;
                this.myDataSet.Clear();
                this.myDataSet=null;
                this.tickersNameArray = null;
                this.Connected = false;
            }

	
		}


        //
        // Обработчик события OnData таблицы tblFev (тип NiApiLib.Table)
        //
		private void tblFev_OnData(int Code, object DataRowSet, string TableName)
		{
            //
            //преведение типа объекта-параметра object DataRowSet к типу NiApiLib.DataRowSet
            //
            myDataRowSet=(NiApiLib.DataRowSet)DataRowSet;

			NiApiLib.DataRow myrow=new NiApiLib.DataRowClass();
			object o=new object();
			int k=1;
			o=(object)k;
			myrow=(NiApiLib.DataRow)myDataRowSet.GetRow(0);

 			
		
			
			string [] rowArray = new string[myrow.Count];
            System.Data.DataRow row;
            row = dtTickers.NewRow();
	
            //
            //цикл заполнения строк таблицы для отображения данных dtTickers (тип System.Data.DataTable)
            //
            Console.WriteLine("myDataRowSet.Count: "+myDataRowSet.Count.ToString());
            
			for(int i=0;i<myDataRowSet.Count;i++)
			{
                //
                //в этом цикле ивлекаются данные из i-ой строки  myDataRowSet, полученной от сервера
                //
				for(int j=0;j<myrow.Count;j++)
				{
                    row = dtTickers.NewRow();
                    myrow=(NiApiLib.DataRow)myDataRowSet.GetRow(i);
					int t=j;
					o=(object)t;
                    if (myrow != null)
                    {
                        rowArray[j] = myrow.get_Item(ref o).ToString();
                    }
                    else
                    {
                        rowArray[j] = "";
                    }

                    if(j==1)
                    {
                        this.tickersNameArray.Add(myrow.get_Item(ref o).ToString());
                    }


				}

                row.ItemArray = rowArray;
                dtTickers.Rows.Add(row);
                row = null;
           }

            myDataSet.AcceptChanges();

		}


        //
        //Обработчик события OnDataComplete таблицы tblFev (тип NiApiLib.Table)
        //
		private void tblFev_OnDataComplete(int Code, string TableName)
		{
           // MessageBox.Show("ondatacomplete");
		}


        private void btnUpdates_Click(object sender, System.EventArgs e)
		{
			if(this.tblFev!=null  && this.Connected==true)
			{
				if(this.UpdatesOn==false)
				{
                    //
                    //если кнопка btnUpdates нажимается в первый, или любой другой НЕЧЕТНЫЙ, раз
                    //это означает, что апдэйты выключены и их необходимо включить.
                    //Свойство SetOnlineUpdates таблицы tblFev (тип NiApiLib.Table) устанавливается 
                    //на subEnabled
                    //
					this.tblFev.SetOnlineUpdates(NiApiLib.ESubscribtion.subEnabled);
					this.UpdatesOn=true;
                    this.btnUpdates.Text = "Updates off";
				}
				else
				{
                    //
                    //если кнопка btnUpdates нажимается во второй, или любой другой ЧЕТНЫЙ, раз
                    //это означает, что апдэйты включены и их необходимо выключить.
                    //Свойство SetOnlineUpdates таблицы tblFev (тип NiApiLib.Table) 
                    //устанавливается на subDisabled
                    //
					this.tblFev.SetOnlineUpdates(NiApiLib.ESubscribtion.subDisabled);
					this.UpdatesOn=false;
                    this.btnUpdates.Text = "Updates on";
				}
			}
		}

	
        //
        // Обработчик событий OnModify и OnInsert таблицы tblFev (тип NiApiLib.Table)
        //
		void tblFev_OnModify(object NiDataRow, string TableName)
		{
            if (this.tableName == "QUOTES" || this.tableName == "quotes")
            {
                //
                //преведение типа объекта-параметра object NiDataRow к типу NiApiLib.DataRow
                //
                NiApiLib.DataRow niRow = (NiApiLib.DataRow)NiDataRow;
                string[] array = new string[niRow.Count];

                //
                //Цикл по всем строкам таблицы данных
                //Сопоставляем полученные изменения и существующие данных по значению поля FieldName
                //
                for (int k = 0; k < this.dtTickers.Rows.Count; k++)
                {

                    object o = (int)1;
                    object key = niRow.get_Item(ref o);
               //     Console.WriteLine(key.ToString());
                    if (this.dtTickers.Rows[k].ItemArray[1].ToString() == key.ToString())
                    {
                        for (int j = 0; j < niRow.Count; j++)
                        {
                            o = j;
                            if (niRow.get_Item(ref o) != null)
                            {
                                array[j] = niRow.get_Item(ref o).ToString();
                            }
                            else
                            {
                                array[j] = this.dtTickers.Rows[k].ItemArray[j].ToString();
                            }
                        }
                       

                        //
                        //При нахождении совпадения исходных данных с изменениями
                        // по полю FieldName, заменяем в таблице отображения данных исходные данные на измененные 
                        //
                        this.dtTickers.Rows[k].ItemArray = array;
                        break;
                    }
                }

                this.myDataSet.AcceptChanges();
            }
            else
            {
               
                NiApiLib.DataRow myrow = (NiApiLib.DataRow)NiDataRow;
                System.Data.DataRow row;

                row = dtTickers.NewRow();

                string[] rowArray = new string[myrow.Count];


                //
                //в этом цикле ивлекаются данные из i-ой строки  myDataRowSet, полученной от сервера
                //
                int j;
                object o = new object();

              Console.WriteLine("_______________");
                for (j = 0; j < myrow.Count; j++)
                {
                    o = (object)j;
                    if (myrow.get_Item(ref o) != null)
                    {
                        rowArray[j] = myrow.get_Item(ref o).ToString();
                    }
                    else 
                    {
                        rowArray[j] = "";
                    }
                   Console.WriteLine(rowArray[j] + "\n_______________");
                }
                
                row.ItemArray = rowArray;
                dtTickers.Rows.Add(row);

                this.myDataSet.AcceptChanges();


            }
		}


        //
        // Обработчик события Click кнопки btSetFilter
        // Здесь добавляются фильтры на обновление данных
        //
        private void btSetFilter_Click(object sender, EventArgs e)
        {
            if (this.Connected == true)
            {
                SetFilterForm myForm = new SetFilterForm();
                myForm.tickersArray = new ArrayList();
                for (int i = 0; i < this.tickersNameArray.Count; i++)
                {
                    myForm.tickersArray.Add(this.tickersNameArray[i]) ;
                }

                if (selectedTickersArray != null)
                {
                    myForm.previousSelectedTickers = new string[selectedTickersArray.Length];
                    for (int i = 0; i < selectedTickersArray.Length; i++)
                    {
                        myForm.previousSelectedTickers[i] = selectedTickersArray[i];
                    }
                }


                myForm.ShowDialog();

                if (myForm.selectedTickersArrey != null)
                {
                   int length=0;

                    if (selectedTickersArray != null)
                    {
                        length = selectedTickersArray.Length;

                        this.selectedTickersArray = new string[myForm.selectedTickersArrey.Length];
                        length = selectedTickersArray.Length;
                        string[] tmp = new string[length + myForm.selectedTickersArrey.Length];
                        for (int i = 0; i < length; i++)
                        {
                            tmp[i] = selectedTickersArray[i];
                        }

                        selectedTickersArray = null;
                        selectedTickersArray = tmp;
                    }
                    else
                    {
                        selectedTickersArray = new string[myForm.selectedTickersArrey.Length];
                    }
                                         

                    object fieldNum = (int)1;


                    //
                    // В selectedTickersArrey получаем список инструментов, по которым надо получать
                    // обновления
                    // В цикле добавляем фильтры к таблице tblFev (тип NiApiLib.Table)
                    for (int i = 0; i < myForm.selectedTickersArrey.Length; i++)
                    {
                        selectedTickersArray[i + length] = (string)myForm.selectedTickersArrey[i];
                        object value = (string)myForm.selectedTickersArrey[i];
                        this.tblFev.AddUpdateFilter(0, ELogicalOperation.logOr, ref fieldNum, ECondition.conEqual, ref value);
                    }

                    this.SetFilter = true;
                }


            }
        }

        
        private void btClearFilters_Click(object sender, EventArgs e)
        {
            if (Connected)
            {
                //
                //Удаляем все фильтры таблицы tblFev (тип NiApiLib.Table)
                //
                this.tblFev.DeleteUpdateFilter(0);
                selectedTickersArray = null;
            }
        }

        private void btnTransaction_Click(object sender, EventArgs e)
        {
            TransactionForm newTransForm = new TransactionForm();

            if (newTransForm.ShowDialog() == DialogResult.OK)
            {
                   
                //string I_NONE = newTransForm.I_NONE;
                //string I_ACCOUNT = newTransForm.I_ACCOUNT;
                //string I_BUYSELL = newTransForm.I_BUYSELL;
                //string I_MKTLIMIT = newTransForm.I_MKTLIMIT;
                //string I_SPLITFLAG = newTransForm.I_SPLITFLAG;
                //string I_IMMCANCEL = newTransForm.I_IMMCANCEL;
                //string I_PRICEYIELDENTERTYPE = newTransForm.I_PRICEYIELDENTERTYPE;
                //string I_SECBOARD = newTransForm.I_SECBOARD;
                //string I_SECCODE = newTransForm.I_SECCODE;
                //string I_PRICE = newTransForm.I_PRICE;
                //string I_QUANTITY = newTransForm.I_QUANTITY;

                
                if (this.transactNum == 0)
               {
                   this.niTransaction.Open(this.SrvrSession, "ORDER", ETableType.tabAdrr); 
                }

                    this.transactNum++;
                
                NiApiLib.DataRow row = new NiApiLib.DataRow();
                row.Structure = niTransaction.Structure;

                object o = new object();
                string str;
                for (int i = 1; i < 12; i++)
                {
                    o = i;
                    str = newTransForm.ValueArray[i - 1];
                    row.set_Item(ref o, (object)str);
                }


                this.niTransaction.Execute((object)row);
            }

        }

        private void btnOpenCatalog_Click(object sender, EventArgs e)
        {
            if (this.ofdCatalog.ShowDialog() == DialogResult.OK)
            {
                this.SrvrSession.CatalogName = this.ofdCatalog.FileName;
                this.tbCatalogPath.Text = this.ofdCatalog.FileName;
            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (this.checkBox1.Checked == true)
            {
                this.btnKeyBase.Enabled = true;
                this.lblUserKey.Enabled = true;
                this.lblServerKey.Enabled = true;

                this.btnCryptoLibrary.Enabled = true;
                this.tbCryptoLibrary.Enabled = true;
                this.tbKeyBase.Enabled = true;
                this.tbUserKey.Enabled = true;
                this.tbServerKey.Enabled = true;

                Crypto = true;

                this.keyBase = this.tbKeyBase.Text;
                this.userKey = this.tbUserKey.Text;
                this.serverKey = this.tbServerKey.Text;
                this.cryptoLibrary = this.tbCryptoLibrary.Text;
            }
            else
            {
                this.btnKeyBase.Enabled = false;
                this.lblUserKey.Enabled = false;
                this.lblServerKey.Enabled = false;

                this.btnCryptoLibrary.Enabled = false;
                this.tbCryptoLibrary.Enabled = false;
                this.tbKeyBase.Enabled = false;
                this.tbUserKey.Enabled = false;
                this.tbServerKey.Enabled = false;

               Crypto = false;
            }

        }

        private void btnCryptoLibrary_Click(object sender, EventArgs e)
        {
            string library;
            if (ofdCatalog.ShowDialog() == DialogResult.OK)
            {
                library = ofdCatalog.FileName;
                this.tbCryptoLibrary.Text = library;
                this.cryptoLibrary = library;    
            }
        }

        private void btnKeyBase_Click(object sender, EventArgs e)
        {
            string keyBasePath;
            if (ofdCatalog.ShowDialog() == DialogResult.OK)
            {
                keyBasePath = ofdCatalog.FileName;
                this.tbKeyBase.Text = keyBasePath;
                this.keyBase = keyBasePath;
            }
        }


	}
}
