Public Class Form1

    Private Declare Function WaitMessage Lib "user32.dll" () As Long
    Dim Session As NiApiLib.SrvrSession
    Dim Clients As NiApiLib.Table
    Dim Accounts As NiApiLib.Table
    Dim Portfolio As NiApiLib.Table
    Dim Filter As NiApiLib.Filter
    Dim FilterPortfolio As NiApiLib.Filter
    Dim Transaction As NiApiLib.Table
    Dim Row As NiApiLib.DataRow

    Dim i, j, endTimer
    Dim connresult
    Dim disconn
    Dim tableName As String



    Sub Session_OnLogin(ByVal LoginResult As Integer)
        ListBox1.Items.Add("Login with result " & LoginResult)
        ListBox1.SelectedIndex = ListBox1.Items.Count - 1
        connresult = LoginResult
        btnConnect.Enabled = False
        btnDisconnect.Enabled = True
        btnAccounts.Enabled = True
    End Sub

    Sub Session_OnMessage(ByVal Message As Object)
        ListBox1.Items.Add(" Message( [" & Message.Count & "], " & Message.Command & ", " & Message.Value(1) & ")")
        ListBox1.SelectedIndex = ListBox1.Items.Count - 1
    End Sub

    Sub Session_OnStatusMessage(ByVal Message As Object)
        ListBox1.Items.Add(" StatusMessage( [" & Message.Code & "], " & Message.Class & ", " & Message.Description & ")")
        ListBox1.SelectedIndex = ListBox1.Items.Count - 1
    End Sub

    Sub Session_OnConnectionLost()
        ListBox1.Items.Add("Connection lost")
        ListBox1.SelectedIndex = ListBox1.Items.Count - 1
        btnConnect.Enabled = True
        btnDisconnect.Enabled = False
        btnAccounts.Enabled = False
        btnPortfolio.Enabled = False
        btnSend.Enabled = False
        Session.Dispose()
    End Sub

    Sub Clients_OnData(ByVal Code As Integer, ByVal DataRowSet As Object, ByVal TableName As String)
        dgClients.RowCount = DataRowSet.Count
        For i = 0 To (DataRowSet.Count - 1)
            dgClients.Item("clmnCode", i).Value = DataRowSet.GetRow(i).Item("I_CLIENT_NAME")
            dgClients.Item("clmnUsers", i).Value = DataRowSet.GetRow(i).Item("I_CLIENT_FULLNAME")
        Next
    End Sub

    Sub Accounts_OnData(ByVal Code As Integer, ByVal DataRowSet As Object, ByVal TableName As String)
        dgAccount.RowCount = DataRowSet.Count
        For i = 0 To (DataRowSet.Count - 1)
            dgAccount.Item("clmnAccount", i).Value = DataRowSet.GetRow(i).Item("I_ACCOUNT")
            dgAccount.Item("clmnTradeboard", i).Value = DataRowSet.GetRow(i).Item("TRADEBOARD")
            dgAccount.Item("clmnCodes", i).Value = DataRowSet.GetRow(i).Item("I_CLIENT_NAME")
        Next
    End Sub

    Sub Portfolio_OnData(ByVal Code As Integer, ByVal DataRowSet As Object, ByVal TableName As String)
        dgPortfolio.RowCount = DataRowSet.Count
        For i = 0 To (DataRowSet.Count - 1)
            dgPortfolio.Item("clmnInstrument", i).Value = DataRowSet.GetRow(i).Item("I_NAME")
            dgPortfolio.Item("clmnPortfolio", i).Value = DataRowSet.GetRow(i).Item("I_CURRENT_PORTFOLIO")
            dgPortfolio.Item("clmnRid", i).Value = DataRowSet.GetRow(i).Item("I_RID")
        Next
    End Sub

    Sub Portfolio_OnModify(ByVal DataRow As Object, ByVal TableName As String)
        Dim s
        s = DataRow.Item("I_NAME")
        s = DataRow.Item("I_CURRENT_PORTFOLIO")
        s = DataRow.Item("I_RID")
        For j = 0 To dgPortfolio.RowCount - 1
            If dgPortfolio.Item("clmnRid", j).Value = DataRow.Item("I_RID") Then
                dgPortfolio.Item("clmnPortfolio", j).Value = DataRow.Item("I_CURRENT_PORTFOLIO")
            End If
        Next
    End Sub

    Public Sub Wait(ByVal seconds)
        ' включение таймера
        '        Timer1.Enabled = True
        'установка интервала для таймера
        Timer1.Start()
        endTimer = 1
        Timer1.Interval = 1000 * seconds
        While endTimer = 1
            WaitMessage()
            Application.DoEvents()
        End While
        ' выключение таймера
        Timer1.Stop()
        '       Timer1.Enabled = False
    End Sub

    Private Sub Timer1_Timer()
        Timer1.Interval = 0
    End Sub


    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
        connresult = 1
        disconn = 0
        i = 0
        Session = New NiApiLib.SrvrSession
        Clients = New NiApiLib.Table
        AddHandler Session.OnLogin, AddressOf Session_OnLogin
        AddHandler Session.OnConnectionLost, AddressOf Session_OnConnectionLost
        AddHandler Session.OnMessage, AddressOf Session_OnMessage
        AddHandler Session.OnStatusMessage, AddressOf Session_OnStatusMessage
        AddHandler Clients.OnData, AddressOf Clients_OnData

        Session.HostAddr = tbServer.Text
        Session.HostPort = tbPort.Text
        Session.Name = tbLogin.Text
        Session.Password = tbPassword.Text
        Session.Journal = "clients"
        Session.CatalogName = "catalog.xml"
        'Session.CryptoStart "d:\nisecure.dll", "d:\admin.bin", "admin", "netinvestor"
        Session.Connect()
        Do While (connresult <> 0) And (i <= 10)
            ListBox1.Items.Add("Connection attempt " & i)
            Wait(1)
            i = i + 1
        Loop
        If (connresult <> 0) Then
            ListBox1.Items.Add("connection attempt failed. " & "I tried for " & (i - 1) & " times")
        Else
            Clients.Open(Session, "CLIENTS", ETableType.tabAdrr)
            Clients.GetData()
        End If


    End Sub


    Private Sub btnDisconnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisconnect.Click
        Session.Disconnect()
    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        endTimer = 0
    End Sub

    Private Sub btnAccounts_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAccounts.Click
        Accounts = New NiApiLib.Table
        Filter = New NiApiLib.Filter
        AddHandler Accounts.OnData, AddressOf Accounts_OnData
        Accounts.Open(Session, "USERS", ETableType.tabAdrr)
        Filter.Structure = Accounts.Structure
        Filter.Add("I_CLIENT_NAME", ECondition.conEqual, tbCode.Text)
        Accounts.GetData(Filter)
        btnPortfolio.Enabled = True
    End Sub

    Private Sub btnPortfolio_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPortfolio.Click
        If cbTradeboard.SelectedIndex = -1 Then
            cbTradeboard.SelectedIndex = 0
        End If


        Select Case cbTradeboard.SelectedItem.ToString
            Case "EQBR"
                tableName = "PORTFOLIO"
                cbTradeboard.SelectedText = "EQBR"
                tbTradeboard.Text = "EQBR"
            Case "MAIN"
                tableName = "PORTFOLIOG"
                tbTradeboard.Text = "MAIN"
            Case "PSFU"
                tableName = "PORTFOLIO_PSFU"
                tbTradeboard.Text = "PSFU"
            Case "PSOP"
                tableName = "PORTFOLIO_PSOP"
                tbTradeboard.Text = "PSOP"
            Case "MSEN"
                tableName = "PORTFOLIO_MSE"
                tbTradeboard.Text = "MSEN"
            Case "PSWA"
                tableName = "PORTFOLIO_PSWA"
                tbTradeboard.Text = "PSWA"
            Case "PSCO"
                tableName = "PORTFOLIO_PSCO"
                tbTradeboard.Text = "PSCO"
            Case "RTSG"
                tableName = "PORTFOLIO_RTSG"
                tbTradeboard.Text = "RTSG"
            Case "RTSA"
                tableName = "PORTFOLIO_RTSA"
                tbTradeboard.Text = "RTSA"
            Case "RTS1"
                tableName = "PORTFOLIO_RTS1"
                tbTradeboard.Text = "RTS1"
            Case "PCOF"
                tableName = "PORTFOLIO_PCOB"
                tbTradeboard.Text = "PCOF"
            Case "PCOF"
                tableName = "PORTFOLIO_PCOF"
                tbTradeboard.Text = "PCOF"
            Case "FEV"
                tableName = "PORTFOLIO_FEV"
                tbTradeboard.Text = "FEV"
            Case "PFTS"
                tableName = "PORTFOLIO_PFTS"
                tbTradeboard.Text = "PFTS"
            Case Else
                tableName = "PORTFOLIO"
                cbTradeboard.SelectedText = "EQBR"
                tbTradeboard.Text = "EQBR"
        End Select
        Portfolio = New NiApiLib.Table
        FilterPortfolio = New NiApiLib.Filter
        AddHandler Portfolio.OnData, AddressOf Portfolio_OnData
        AddHandler Portfolio.OnModify, AddressOf Portfolio_OnModify
        Portfolio.Open(Session, tableName, ETableType.tabAdrr)
        FilterPortfolio.Structure = Portfolio.Structure
        FilterPortfolio.Add("I_CLIENT_NAME", ECondition.conEqual, tbCode.Text)
        Portfolio.GetData(FilterPortfolio)
        Portfolio.SetOnlineUpdates(ESubscribtion.subEnabled)
        btnSend.Enabled = True
    End Sub

    Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
        Transaction = New NiApiLib.Table
        Transaction.Open(Session, "NI_CHANGEPORTFOLIO", ETableType.tabAdrr)
        Row = New NiApiLib.DataRow
        Row.Structure = Transaction.Structure
        If rbIncrease.Checked Then
            Row.Item("I_DIRECTION") = 44
        Else
            Row.Item("I_DIRECTION") = 45
        End If
        Row.Item("I_PRICESIZE") = numValue.Value
        Row.Item("I_CLIENT_NAME") = tbCode.Text
        If tbInstrumentName.Text.ToLower = "рубли" Then
            Row.Item("I_INSTRUMENT_TYPE") = 1
        Else
            Row.Item("I_INSTRUMENT_TYPE") = 2
        End If
        Row.Item("TRADEBOARD") = tbTradeboard.Text.ToUpper
        Row.Item("I_NAME") = tbInstrumentName.Text
        'Row.Item("I_RID") = 1120
        Row.Item("I_ORDER_CONDITION") = ""
        Transaction.Insert(Row)
    End Sub
End Class
