using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NiApiLib;

namespace GetDeals
{
    class Program
    {
        static void Main(string[] args)
        {
            Connection c = new Connection();
            c.connect();
            Console.ReadLine();
            c.disconnect();
        }
    }
    class Connection
    {
        NiApiLib.SrvrSession Session = new NiApiLib.SrvrSessionClass();
        NiApiLib.Table Tbl = new NiApiLib.TableClass();
        NiApiLib.Filter Flt = new NiApiLib.FilterClass();
        NiApiLib.DataRowSet DrowSet= new NiApiLib.DataRowSetClass();
        NiApiLib.DataRow row = new NiApiLib.DataRowClass();
        public void connect()
        {
            Session.HostAddr = "nidemo.mfd.ru";
            Session.HostPort = 2900;
            Session.Name = "AFedin";
            Session.Password = "12345";
            Session.CatalogName = "catalog.xml";
            Session.OnLogin+=new _ISrvrSessionEvents_OnLoginEventHandler(Session_OnLogin);
            Tbl.OnInsert+=new _ITableEvents_OnInsertEventHandler(Tbl_OnInsert);
            Tbl.OnData+=new _ITableEvents_OnDataEventHandler(Tbl_OnData);
            Session.Connect();
        }
        public void disconnect() 
        {
            Session.Disconnect();  
        }
        public void Session_OnLogin(int LoginResult)
        {
            if (LoginResult == 0)
            {
                Console.WriteLine("[System] Соединение установлено");
                Tbl.Open(Session, "DEALS", ETableType.tabAdrr);
                Tbl.SetOnlineUpdates(ESubscribtion.subEnabled);
                Console.WriteLine("[System] Соединение установлено");
                Flt.Structure = Tbl.Structure;
                Tbl.GetData(Flt);
            }
            else
            {
                Console.WriteLine("[System] Ошибка подключения");
            }
        }
        public void Tbl_OnData(int Code,object DataRowSet, string TableName)
        {
            DrowSet = (NiApiLib.DataRowSet)DataRowSet;
            for (int get_i=0; get_i <= DrowSet.Count-1; get_i++)
            {
                Console.Write(" [Slice] ");
                row = (NiApiLib.DataRow)DrowSet.GetRow(get_i);   
                for (int get_j = 0; get_j <= row.Count-1; get_j++)
                {
                    object get_ondate = get_j;
                    Console.Write(row.get_Item(ref get_ondate) + " | ");
                }
                Console.WriteLine(" \n\n");
            }
        }
        public void Tbl_OnInsert(object NiDataRow, string TableName)
        {
            row = (NiApiLib.DataRow)NiDataRow;
            Console.Write(" [Update] ");
            for (int ins_i=0; ins_i<=row.Count-1;ins_i++)
            {
                object get_insert = ins_i;
                Console.Write(row.get_Item(ref get_insert) + " | ");
            }
            Console.WriteLine(" ");
        }

    }
}
