I am implementing a psuedo console using textbox. Compiler throws the following error: 'GetUserInputLine' is not a member of 'Form1'.
I don't know why this line 'TempString = myForm.GetUserString()' throws this error.
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Linq
Imports System.Text
Imports System.Windows.Forms
Public Class Form1
Inherits Form
Dim WithEvents textBox1 As TextBox
Dim UserString As String
Public Sub New()
InitializeComponent()
End Sub
Private Sub InitializeComponent()
Me.textBox1 = New System.Windows.Forms.TextBox()
Me.SuspendLayout()
'
' textBox1
'
Me.textBox1.AcceptsReturn = True
Me.textBox1.AcceptsTab = True
Me.textBox1.Dock = System.Windows.Forms.DockStyle.Fill
Me.textBox1.Multiline = True
Me.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Vertical
'
' Form1
'
Me.ClientSize = New System.Drawing.Size(284, 264)
Me.Controls.Add(Me.textBox1)
Me.Text = "PseudoGUIConsole Example"
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Private Sub textBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles textBox1.KeyDown
Dim LastLine() As String
If e.KeyCode = Keys.Enter Then
LastLine = Split(textBox1.Text, vbCrLf)
If LastLine(Ubound(LastLine)) = "" Then
Exit Sub 'Do Nothing
Else
UserString = LastLine(Ubound(LastLine))
End If
e.Handled = True
textBox1.Focus()
End If
End Sub
Private Sub PrintLine(ByVal UserText As String)
textBox1.AppendText(vbCrLf & UserText)
End Sub
Private Function GetUserInputLine() As String
GetUserInputLine = UserString
End Function
<STAThreadAttribute()> _
Public Shared Sub Main()
Dim myForm As New Form1()
Dim TempString As String
myForm.PrintLine("Enter a String?") 'Prompt and
TempString = myForm.GetUserString() 'wait for the input
myForm.PrintLine("You Entered:: " & TempString)
Application.Run( myForm )
End Sub
End Class
Related
I'm trying to make a program that sends the client's screen to the server on load but the data doesn't send until the datastream is closed in the client program. I know flush is supposed to send the data but there is no difference when there is and when there isn't flush in the program.
Here is the main server code:
Imports System.IO
Imports System.Drawing.Imaging
Public Class Form1
Dim encodeType As ImageFormat = ImageFormat.Bmp
Dim decodingString As String = String.Empty
Dim encodingTypeString = "data:image/bmp;base64"
Public Function base64c(ByVal base64code As String) As Image
Dim imageBytes As Byte() = Convert.FromBase64String(base64code)
Dim ms As New MemoryStream(imageBytes, 0, imageBytes.Length)
Return Image.FromStream(ms, True)
End Function
Private Server As TCPControl
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Server = New TCPControl
AddHandler Server.MessageReceived, AddressOf OnLineReceived
End Sub
Private Delegate Sub UpdateDesktopDelegate(Img As PictureBox, base64 As String)
' update image
Private Sub OnLineReceived(sender As TCPControl, Data As String)
Desktop.Image = base64c(Data)
End Sub
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
Server.IsListening = False
End Sub
End Class
The TCPControl server code:
Imports System.IO
Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
Public Class TCPControl
Public Event MessageReceived(sender As TCPControl, Data As String)
'Config
Public ServerIp As IPAddress = IPAddress.Parse("192.168.254.14")
Public ServerPort As Integer = 64555
Public Server As TcpListener
Private CommThread As Thread
Public IsListening As Boolean = True
'Clients
Private Client As TcpClient
Private ClientData As StreamReader
Public Sub New()
Server = New TcpListener(ServerIp, ServerPort)
Server.Start()
CommThread = New Thread(New ThreadStart(AddressOf Listening))
CommThread.Start()
End Sub
Private Sub Listening()
' create listener loop
Do Until IsListening = False
' accept incoming connections
If Server.Pending = True Then
Client = Server.AcceptTcpClient
ClientData = New StreamReader(Client.GetStream)
End If
' raise event for incoming messages
Try
RaiseEvent MessageReceived(Me, ClientData.ReadLine)
Catch ex As Exception
End Try
Thread.Sleep(300)
Loop
End Sub
End Class
The main client code:
Imports System.IO
Imports System.Threading
Imports System.Drawing.Imaging
Public Class Form1
Private Client As TCPControl
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Client = New TCPControl("192.168.254.14", 64555)
Do Until False
If Client.Client.Connected = True Then
Dim bounds As Rectangle
Dim screenshot As System.Drawing.Bitmap
Dim newimg As System.Drawing.Bitmap
Dim graph As Graphics
bounds = Screen.PrimaryScreen.Bounds
bounds.Size = New Size(1920, 1080)
screenshot = New System.Drawing.Bitmap(2600, 1330, System.Drawing.Imaging.PixelFormat.Format32bppArgb)
graph = Graphics.FromImage(screenshot)
graph.CopyFromScreen(bounds.X, bounds.Y, 0, 0, bounds.Size, CopyPixelOperation.SourceCopy)
Using ms As New MemoryStream()
newimg = New Bitmap(screenshot, New Size(960, 540))
newimg.Save(ms, ImageFormat.Bmp)
Dim imageBytes As Byte() = ms.ToArray()
Client.Send(Convert.ToBase64String(imageBytes))
End Using
Thread.Sleep(333)
End If
Loop
End Sub
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
If Client.Client.Connected = True Then
Client.DataStream.Close()
Client.Client.Close()
End If
End Sub
End Class
And the client TCPControl code:
Imports System.Net
Imports System.Net.Sockets
Imports System.IO
Public Class TCPControl
Public Client As TcpClient
Public DataStream As StreamWriter
Public Sub New(Host As String, Port As Integer)
' client
Client = New TcpClient(Host, Port)
DataStream = New StreamWriter(Client.GetStream)
End Sub
Public Sub Send(Data)
DataStream.Write(Data)
DataStream.Flush()
End Sub
End Class
I have been trying to solve this problem for hours now and posting on this website was my last resort. If any code is unorganized or is not as it should be then it is because I haven't focused on checking my code yet.
I am trying to monitor a print queue using a Observable Collection however when an item is added to the printer queue it does not updated. am I missing something. Here is my code so far.
Imports System.Printing
Imports System.Text
Imports System.IO
Imports System.Collections
Imports System.Management
Imports System.Drawing.Printing
Imports System.Collections.ObjectModel
Imports System.Collections.Specialized
Public Class Form1
Dim localPrintServer2 As LocalPrintServer
Dim defaultPrintQueue2 As PrintQueue
Dim listSentToPrinter As New List(Of String)()
Dim listPrinterQueue As New List(Of String)()
Dim listJobsInQueue As New List(Of String)()
' Private m_queueObList As New ObservableCollection(Of String)
Public queueObList As New ObservableCollection(Of String)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AddHandler queueObList.CollectionChanged, AddressOf Me.OnCollectionChanged
End Sub
Private Sub OnCollectionChanged(sender As Object, e As NotifyCollectionChangedEventArgs)
Try
Dim obsSender As ObservableCollection(Of String) = TryCast(sender, ObservableCollection(Of String))
Dim editedOrRemovedItems As New List(Of String)()
getPrintQueue()
If e.Action = NotifyCollectionChangedAction.Add Then
MsgBox("Item Added")
'search listSentToPrinter
End If
If e.Action = NotifyCollectionChangedAction.Remove Then
MsgBox("Item Removed")
End If
'Label1.Text = queueObList.Count
Dim action As NotifyCollectionChangedAction = e.Action
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub getPrintQueue()
Try
localPrintServer2 = New LocalPrintServer()
defaultPrintQueue2 = LocalPrintServer.GetDefaultPrintQueue()
Timer1.Enabled = True
Timer1.Interval = 50
Dim jobs As PrintJobInfoCollection = defaultPrintQueue2.GetPrintJobInfoCollection
For Each job As PrintSystemJobInfo In jobs
'listPrinterQueue.Add(job.Name)
queueObList.Add(job.Name)
Label1.Text = queueObList.Count
'lstPrinterQueue.Items.Add(job.Name & " " & job.JobStatus)
Next
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub Iletarerate()
ListBox1.Items.Clear()
For Each item As String In queueObList
ListBox1.Items.Add(item)
Next
End Sub
Public Sub FindJobInQueue(ByVal item As String)
If listJobsInQueue.Contains(item) Then
Else
If (listPrinterQueue.Count >= 1) Then
If listPrinterQueue.Contains(item) Then
lstJobInQueue.Items.Add("Found " & item)
listJobsInQueue.Add(item)
'Update stutus if successfully updated
listSentToPrinter.Remove(item)
End If
Else
' list is empty
End If
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
queueObList.RemoveAt(0)
Iletarerate()
End Sub
End Class
The code works to add everything to the observable collection which is in the queue. The buttons work to add and remove items. The actual print queue does not update the collection
I have gone through the Link vb serial communication. They ar eusing below function for getting data. My question are as follows
How to call this below function on VB
My data from serial are CSV value how to separate and display in a text box
Updating the text box values?
Function ReceiveSerialData() As String
' Receive strings from a serial port.
Dim returnStr As String = ""
Dim com3 As IO.Ports.SerialPort = Nothing
Try
com3 = My.Computer.Ports.OpenSerialPort("COM3")
com3.ReadTimeout = 10000
Do
Dim Incoming As String = com3.ReadLine()
If Incoming Is Nothing Then
Exit Do
Else
returnStr &= Incoming & vbCrLf
End If
Loop
Catch ex As TimeoutException
returnStr = "Error: Serial Port read timed out."
Finally
If com3 IsNot Nothing Then com3.Close()
End Try
Return returnStr
End Function
MY compelte code aS BELOW
Imports System
Imports System.IO.Ports
Imports System.ComponentModel
Imports System.Threading
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Windows.Forms
Imports Microsoft.VisualBasic.FileIO
Imports System.IO
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim myPort As Array
myPort = IO.Ports.SerialPort.GetPortNames()
PortComboBox.Items.AddRange(CType(myPort, Object()))
BaudComboBox.Items.Add(9600)
BaudComboBox.Items.Add(19200)
BaudComboBox.Items.Add(38400)
BaudComboBox.Items.Add(57600)
BaudComboBox.Items.Add(115200)
ConnectButton.Enabled = True
DisconnectButton.Enabled = False
Timer1.Interval = 1000
Timer1.Start()
Receive.Text = ReceiveSerialData()
End Sub
Private Sub ConnectButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ConnectButton.Click
SerialPort1.PortName = PortComboBox.Text
SerialPort1.BaudRate = CInt(BaudComboBox.Text)
SerialPort1.Open()
Timer1.Start()
'lblMessage.Text = PortComboBox.Text & " Connected."
ConnectButton.Enabled = False
DisconnectButton.Enabled = True
End Sub
Private Sub DisconnectButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DisconnectButton.Click
SerialPort1.Close()
DisconnectButton.Enabled = False
ConnectButton.Enabled = True
End Sub
Function ReceiveSerialData() As String
' Receive strings from a serial port.
Dim returnStr As String = ""
Dim com3 As IO.Ports.SerialPort = Nothing
Try
com3 = My.Computer.Ports.OpenSerialPort("COM3")
com3.ReadTimeout = 10000
Do
Dim Incoming As String = com3.ReadLine()
If Incoming Is Nothing Then
Exit Do
Else
returnStr &= Incoming & vbCrLf
End If
Loop
Catch ex As TimeoutException
returnStr = "Error: Serial Port read timed out."
Finally
If com3 IsNot Nothing Then com3.Close()
End Try
Return returnStr
End Function
End Class
i am trying to create a short sample for you but you need to understand threading and serial working for this. follow the steps to create this sample
add new class module to your code with name mySerial and past following code in it (replace code)
Imports System.Threading
Imports System.IO.Ports
Imports System.ComponentModel
Public Class dataReceivedEventArgs
Inherits EventArgs
Private m_StringData As String
Public Sub New(strData As String)
Me.m_StringData = strData
End Sub
Public ReadOnly Property ReceivedData As String
Get
Return m_StringData
End Get
End Property
End Class
Public Class mySerial
Private ReadThread As Thread
Dim SPort As SerialPort
Private syncContext As SynchronizationContext
Public Event DataReceived(Sender As Object, ByVal e As dataReceivedEventArgs)
Public Sub New(ByVal COMMPORT As String, ByVal BaudRate As Integer)
Me.New(COMMPORT, BaudRate, Parity.None, 8, StopBits.One)
End Sub
Public Sub New(ByVal _COMMPORT As String, ByVal _BaudRate As Integer, ByVal _Parity As Parity, ByVal _DataBits As Integer, ByVal _StopBits As StopBits)
SPort = New SerialPort
With SPort
.PortName = _COMMPORT
.BaudRate = _BaudRate
.Parity = _Parity
.DataBits = _DataBits
.StopBits = _StopBits
.Handshake = Handshake.XOnXOff
.DtrEnable = True
.RtsEnable = True
.NewLine = vbCrLf
End With
Me.syncContext = AsyncOperationManager.SynchronizationContext
ReadThread = New Thread(AddressOf ReadPort)
End Sub
Public Sub OpenPort()
If Not SPort.IsOpen Then
SPort.Open()
SPort.DiscardNull = True
SPort.Encoding = System.Text.Encoding.ASCII
ReadThread.Start()
End If
End Sub
Public Sub ClosePort()
If SPort.IsOpen Then
SPort.Close()
End If
End Sub
Private Sub ReadPort()
Do While SPort.IsOpen
Dim ReceviceData As String = String.Empty
Do While SPort.BytesToRead <> 0 And SPort.IsOpen And ReceviceData.Length < 5000
Try
ReceviceData &= SPort.ReadExisting()
Thread.Sleep(100)
Catch ex As Exception
End Try
Loop
If ReceviceData <> String.Empty Then
'raise event and provide data
syncContext.Post(New SendOrPostCallback(AddressOf onDataReceived), ReceviceData)
End If
Thread.Sleep(500)
Loop
End Sub
Private Sub onDataReceived(ByVal ReceivedData As String)
RaiseEvent DataReceived(Me, New dataReceivedEventArgs(ReceivedData))
End Sub
End Class
this is class which will work as wrapper class for you, now to make it work add a form with name frmSerial and a textBox with name txtData and set multiline=true, scrollbars=both, now past following code in it
Public Class frmSerial
Dim WithEvents _Serial As mySerial
Private Sub frmSerial_FormClosed(sender As Object, e As FormClosedEventArgs) Handles Me.FormClosed
_Serial.ClosePort()
End Sub
Private Sub frmSerial_Shown(sender As Object, e As EventArgs) Handles Me.Shown
_Serial = New mySerial("COM1", 9600)
_Serial.OpenPort()
End Sub
Private Sub _Serial_DataReceived(Sender As Object, e As dataReceivedEventArgs) Handles _Serial.DataReceived
txtData.Text &= e.ReceivedData
txtData.SelectionStart = txtData.Text.Length
txtData.ScrollToCaret()
End Sub
End Class
hop this helps you and people like you
I am new in stock trading application and I am working on this application since last 9 months in vb.net
I am successful to display real time data in listview and I used threadpool to complete this task but when application display real time stock quotes, system CPU usage goes to high (around 30 to 45%) so how can I reduce tends to 0 to 5%
I visited this link Real-Time-Data-Grid but I am not exactly satisfied with this link (but it is useful for C# only) so any perfect suggestion in vb.net.?
And in my application I am reading real time data from excel sheet of third party software. So I want to know that is COM reading in vb.net heavy loaded process.?
Or If any other suggestion for free real time tick to tick data API of indian stock market excepting Google finance and Yahoo finance
Here it is code:
I define class for real time data feed which named RTDFeed.vb
Imports System.Data.OleDb
Imports Microsoft.Win32
Imports System.Security
Imports Microsoft.VisualBasic
Imports System.IO
Imports System.Text
Imports System.Security.AccessControl
Imports System.Threading
Imports System.ComponentModel
Imports System.Windows
Imports System.Windows.Forms
Imports System.Drawing.Color
Imports System.Net
Imports System.Data.SqlClient
Imports System.Drawing
Public Class RTDFeed
''Class varialbal Data
Private SyncRoot As New Object()
Private _numRow As Integer = 0
Private _stTime As DateTime
Private _EndTime As DateTime
Private _Exchg As String = String.Empty
Private _Description As String = String.Empty
Private _ScpCode As String = String.Empty
Private _Connfrom As String = String.Empty
Private _IsRunning As Boolean = False
Private _EventStopped As EventWaitHandle
''Delegates and Event
Public Event OnRowUpdate As RowUpdateEventHandler
Public Delegate Sub RowUpdateEventHandler(ByVal sender As System.Object, ByVal e As RowUpdateEventArgs)
Public Event OnStarted As OnStartedHandler
Public Delegate Sub OnStartedHandler(ByVal Sender As System.Object, ByVal e As EventArgs)
Public Event OnStopped As OnStoppedHandler
Public Delegate Sub OnStoppedHandler(ByVal Sender As System.Object, ByVal e As EventArgs)
''Public constructor
Public Sub New(ByVal numrow As Integer, ByVal Excg As String, ByVal Description As String, ByVal ConnFrom As String, ByVal ScpCode As String)
Me._numRow = numrow
Me._Exchg = Excg
Me._Description = Description
Me._ScpCode = ScpCode
Me._Connfrom = ConnFrom
Me._EventStopped = New ManualResetEvent(False)
End Sub
Public Sub New(ByVal numrow As Integer, ByVal Excg As String, ByVal Description As String, ByVal ConnFrom As String)
Me._numRow = numrow
Me._Exchg = Excg
Me._Description = Description
Me._ScpCode = ScpCode
Me._Connfrom = ConnFrom
Me._EventStopped = New ManualResetEvent(False)
End Sub
''Public Method
Public Sub StartProc()
SyncLock Me.SyncRoot
If Not Me._IsRunning Then
Me._EventStopped.Reset()
ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf Me.ThreadGetstockproc))
End If
End SyncLock
End Sub
Public Sub StopAsync()
Dim Ts As New ThreadStart(AddressOf Me.StopProc)
Dim Thd As New Thread(Ts)
Thd.Start()
End Sub
''Private Method
Private Sub StopProc()
SyncLock Me.SyncRoot
If Me._IsRunning Then
Me._IsRunning = False
Me._EventStopped.WaitOne()
RaiseEvent OnStopped(Me, EventArgs.Empty)
End If
End SyncLock
End Sub
Private Sub ThreadGetstockproc(ByVal stateinfo As Object)
Me._IsRunning = True
RaiseEvent OnStarted(Me, EventArgs.Empty)
Try
While Not Thread.CurrentThread.ThreadState = ThreadState.AbortRequested
'Me._stTime = DateTime.Now
If Me.GetStock.Count > 0 Then
RaiseEvent OnRowUpdate(Nothing, New RowUpdateEventArgs(Me._numRow, Me.GetStock))
End If
'Dim Ts As TimeSpan = Me._EndTime - Me._stTime
'Dim delay As Integer = Ts.Milliseconds
Thread.Sleep(250) 'delay)
If Not Me._IsRunning Then
Thread.CurrentThread.Abort()
End If
End While
Catch ex As Exception
MsgBox(ex.Message)
Finally
Me._EventStopped.Set()
End Try
End Sub
Dim i As Double = 0
Private Function GetStock() As List(Of Double)
Dim CelUpdt As New List(Of Double)
Dim Querystr As String = ""
Dim cmd As OleDbCommand
Dim Chang As Double
i += 1
CelUpdt.Clear()
Querystr = "Select F1,F2,F4,F5,F6,F7,F12,F15,F16,F18 From [Sheet1$] Where Trim(F1)='" & Me._Exchg & "' And Trim(F2)='" & Me._Description & "' And Trim(F3)='" & Me._ScpCode & "'"
cmd = New OleDbCommand(Querystr, Excelcn)
Dim FReader As OleDbDataReader
FReader = cmd.ExecuteReader()
If FReader.HasRows Then
FReader.Read()
'Market Value
CelUpdt.Add(CDbl(Val(FReader.Item("F4"))))
CelUpdt.Add(CDbl(Val(FReader.Item("F5"))))
CelUpdt.Add(CDbl(Val(FReader.Item("F6"))))
CelUpdt.Add(CDbl(Val(FReader.Item("F7"))))
CelUpdt.Add(i) 'CDbl(Val(FReader.Item("F12"))))
CelUpdt.Add(CDbl(Val(FReader.Item("F15"))))
CelUpdt.Add(CDbl(Val(FReader.Item("F16"))))
Chang = ((CDbl(FReader.Item("F12")) - CDbl(FReader.Item("F18"))) / CDbl(FReader.Item("F12"))) * 100
CelUpdt.Add(Chang)
FReader.Close()
End If
'Me._EndTime = DateTime.Now
Return CelUpdt
End Function
''Class property
Public Property Numrow() As Integer
Get
Return Me._numRow
End Get
Set(ByVal value As Integer)
Me._numRow = value
End Set
End Property
Public Property Exchg() As String
Get
Return Me._Exchg
End Get
Set(ByVal value As String)
Me._Exchg = value
End Set
End Property
Public Property Desciption() As String
Get
Return Me._Description
End Get
Set(ByVal value As String)
Me._Description = value
End Set
End Property
Public Property ScpCode() As String
Get
Return Me._ScpCode
End Get
Set(ByVal value As String)
Me._ScpCode = value
End Set
End Property
Public Property ConnFrom() As String
Get
Return Me._Connfrom
End Get
Set(ByVal value As String)
Me._Connfrom = value
End Set
End Property
Public Property Isrunning() As Boolean
Get
Return Me._IsRunning
End Get
Set(ByVal value As Boolean)
Me._IsRunning = value
End Set
End Property
End Class
Public Class RowUpdateEventArgs
Inherits System.EventArgs
''class variabal Data
Private _ActiveRow As Integer
Private _CellCollection As New List(Of Double)
''Public Constructor
Public Sub New(ByVal ActRow As Integer, ByVal CellArray As List(Of Double))
_ActiveRow = ActRow
_CellCollection = CellArray
End Sub
''Public Property
Public Property ActiveRow() As Integer
Get
Return Me._ActiveRow
End Get
Set(ByVal value As Integer)
Me._ActiveRow = value
End Set
End Property
Public Property CellCollection() As List(Of Double)
Get
Return Me._CellCollection
End Get
Set(ByVal value As List(Of Double))
Me._CellCollection = value
End Set
End Property
End Class
And on a main Watch I update UI thread mean update listview Cell on OnRowupdateEventArgs
Main watch form its named watch.vb
Imports System.Data.OleDb
Imports Microsoft.Win32
Imports System.Security
Imports Microsoft.VisualBasic
Imports System.IO
Imports System.Text
Imports System.Security.AccessControl
Imports System.Threading
Imports System.ComponentModel
Imports System.Windows
Imports System.Windows.Forms
Imports System.Drawing.Color
Imports System.Net
Imports System.Data.SqlClient
Imports System.Drawing
Public Class FrmWatch
Private Sub FrmWatch_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Me.MdiParent = FrmMainscreen
Me.Icon = FrmMainscreen.Icon
Me.Width = FrmMainscreen.Width - 13
'Me.DoubleBuffered = True
LoadBackgroundWorker.WorkerReportsProgress = True
LoadBackgroundWorker.WorkerSupportsCancellation = True
FrmMainscreen.submnubuyorder.Enabled = True
FrmMainscreen.subnusellorder.Enabled = True
FrmMainscreen.submnupendingorder.Enabled = True
FrmMainscreen.ConformOrderTradeBookToolStripMenuItem.Enabled = True
FrmMainscreen.MktPicToolStripMenuItem.Enabled = True
''Load Market Column created
LoadFileFormat()
LVW.Items.Clear()
LVW.Buffer()
LVW.Columns.Add("Exchang", Clm_exchg, HorizontalAlignment.Left)
LVW.Columns.Add("Symbol", Clm_scrpt, HorizontalAlignment.Left)
LVW.Columns.Add("Ser/Exp", Clm_ExpDT, HorizontalAlignment.Left)
LVW.Columns.Add("Buy Qty", Clm_bqty, HorizontalAlignment.Right)
LVW.Columns.Add("Buy Price", Clm_bPric, HorizontalAlignment.Right)
LVW.Columns.Add("Sell Price", Clm_spric, HorizontalAlignment.Right)
LVW.Columns.Add("Sell Qty", Clm_sqty, HorizontalAlignment.Right)
LVW.Columns.Add("Last Traded Price", Clm_ltPtic, HorizontalAlignment.Right)
LVW.Columns.Add("High", Clm_high, HorizontalAlignment.Right)
LVW.Columns.Add("Low", Clm_low, HorizontalAlignment.Right)
LVW.Columns.Add("Open", Clm_open, HorizontalAlignment.Right)
LVW.Columns.Add("Close", Clm_close, HorizontalAlignment.Right)
LVW.Columns.Add("%Change", Clm_chg, HorizontalAlignment.Right)
LVW.Columns.Add("Trand", Clm_Trnd, HorizontalAlignment.Center)
LVW.Columns.Add("Scrip Code", Clm_ScpCode, HorizontalAlignment.Left)
LVW.SuspendLayout()
''call backgroundworker for Load Mkt
LoadBackgroundWorker.RunWorkerAsync()
If FrmPendingOrder.Visible = True Then
AddHandler Me.UpdatePendingOrd, AddressOf FrmPendingOrder.UpdatePendingOrderTimerFilter
End If
If FrmConformOrder.Visible = True Then
AddHandler Me.UpdateConformOrd, AddressOf FrmConformOrder.RefreshTrade
End If
Catch ex As Exception
ErrorHandler(ex, ex.StackTrace, Reflection.MethodBase.GetCurrentMethod.ToString)
End Try
End Sub
Private Sub LoadBackgroundWorker_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles LoadBackgroundWorker.DoWork
Try
LoadMarket()
Catch ex As Exception
ErrorHandler(ex, ex.StackTrace,Reflection.MethodBase.GetCurrentMethod.ToString)
End Try
End Sub
Private Sub LoadBackgroundWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles LoadBackgroundWorker.RunWorkerCompleted
Try
LVW.ResumeLayout()
If LVW.Items.Count > 0 Then
LVW.Focus()
Me.LVW.Items(0).Selected = True
End If
For i As Integer = 0 To Me.LVW.Items.Count - 1
If Me.LVW.Items(i).Text <> String.Empty And Me.LVW.Items(i).SubItems(1).Text <> String.Empty Then
Dim RTDF As New RTDFeed(i, Me.LVW.Items(i).Text, FeedDesc, CnFrm, Me.LVW.Items(i).SubItems(14).Text)
AddHandler RTDF.OnRowUpdate, AddressOf Me.OnRTDFeedRowUpdat
RTDFeed_Obj.Add(RTDF)
MAX_FEED += 1
End If
Next
For j As Integer = 0 To MAX_FEED - 1
If Not RTDFeed_Obj(j).Isrunning Then
RTDFeed_Obj(j).StartProc()
End If
Next
Catch ex As Exception
ErrorHandler(ex, ex.StackTrace,Reflection.MethodBase.GetCurrentMethod.ToString)
End Try
End Sub
Private Delegate Sub OnRTDFeedRowUpdateHandler(ByVal sender As System.Object, ByVal e As RowUpdateEventArgs)
Private Sub OnRTDFeedRowUpdat(ByVal sender As System.Object, ByVal e As RowUpdateEventArgs)
If Me.InvokeRequired Then
Me.Invoke(New OnRTDFeedRowUpdateHandler(AddressOf Me.OnRTDFeedRowUpdat), New Object() {sender, e})
Return
End If
RowUpdate(e)
End Sub
Private Sub RowUpdate(ByVal e As RowUpdateEventArgs)
SyncLock Me.SyncRoot
Try
'LVW.Items(e.ActiveRow).SubItems(3).Text = e.CellCollection(0).ToString
'LVW.Items(e.ActiveRow).SubItems(4).Text = CellArray.Item(1).ToString()
'LVW.Items(e.ActiveRow).SubItems(6).Text = CellArray.Item(2).ToString()
'LVW.Items(e.ActiveRow).SubItems(5).Text = CellArray.Item(3).ToString()
LVW.Items(e.ActiveRow).SubItems(7).Text = e.CellCollection(4).ToString 'CellArray.Item(4).ToString()
'LVW.Items(e.ActiveRow).SubItems(8).Text = CellArray.Item(5).ToString()
'LVW.Items(e.ActiveRow).SubItems(9).Text = CellArray.Item(6).ToString()
'LVW.Items(e.ActiveRow).SubItems(12).Text = CellArray.Item(7).ToString()
Catch ex As IndexOutOfRangeException
MsgBox(ex.Message)
End Try
End SyncLock
End Sub
Now My Custom Listview class Named My_Grid which is flicker free listview while updating a cell real time.
Public Class My_GRID
Inherits ListView
Public Sub Buffer()
Me.DoubleBuffered = True
End Sub
End Class
I need to compile assembly in memory, that can compile another one. There is a form with one button. Here is a code of the form
Imports System
Imports System.Threading
Imports System.CodeDom
Imports System.CodeDom.Compiler
Imports System.Collections
Imports System.ComponentModel
Imports System.Diagnostics
Imports System.Drawing
Imports System.IO
Imports System.Windows.Forms
Imports Microsoft.VisualBasic
Public Class testtwo
Shared str_tb As String
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Call openkubik()
End Sub
Private Sub openkubik()
Dim th As Thread = New Thread(AddressOf sborkakub)
th.Start()
End Sub
Private Sub sborkakub()
Dim evi As System.Security.Policy.Evidence = AppDomain.CurrentDomain.Evidence
Dim assemblyDomain As AppDomain
Dim assemblyDomainSetup As AppDomainSetup = New AppDomainSetup
assemblyDomainSetup.ApplicationBase = System.Environment.CurrentDirectory
assemblyDomainSetup.DisallowBindingRedirects = False
assemblyDomainSetup.DisallowCodeDownload = True
assemblyDomainSetup.ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile
assemblyDomainSetup.LoaderOptimization = LoaderOptimization.MultiDomainHost
assemblyDomain = AppDomain.CreateDomain("AssemblyDomain", evi, assemblyDomainSetup)
assemblyDomain.DoCallBack(AddressOf assamblykub)
Call assamblykub()
End Sub
Private Shared Sub assamblykub()
Call createtext()
Dim objCodeCompiler As System.CodeDom.Compiler.CodeDomProvider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("VB")
Dim objCompilerParameters As New System.CodeDom.Compiler.CompilerParameters()
For Each asm In AppDomain.CurrentDomain.GetAssemblies()
objCompilerParameters.ReferencedAssemblies.Add(asm.Location)
Next
objCompilerParameters.CompilerOptions = "/target:winexe"
objCompilerParameters.GenerateExecutable = True
objCompilerParameters.GenerateInMemory = True
objCompilerParameters.IncludeDebugInformation = False
Dim objCompileResults As System.CodeDom.Compiler.CompilerResults = objCodeCompiler.CompileAssemblyFromSource(objCompilerParameters, str_tb)
If objCompileResults.Errors.HasErrors Then
MessageBox.Show(String.Format("Error: Line>{0}, {1} # {2}", objCompileResults.Errors(0).Line, objCompileResults.Errors(0).ErrorText, objCompileResults.Errors(0).ErrorNumber))
Return
End If
Dim objAssembly As System.Reflection.Assembly = objCompileResults.CompiledAssembly
Dim objTheClass As Object = objAssembly.CreateInstance("MainClass")
If objTheClass Is Nothing Then
MsgBox("Can't load class...")
Exit Sub
End If
Try
objTheClass.GetType.InvokeMember("Main", System.Reflection.BindingFlags.InvokeMethod, _
Nothing, objTheClass, Nothing)
Catch ex As Exception
MsgBox("Error:" & ex.Message)
End Try
End Sub
Private Shared Sub createtext()
Dim tempfile As New IO.FileStream(Application.StartupPath & "/temp_open.txt", IO.FileMode.Open, IO.FileAccess.Read)
Dim tempfilesr As New IO.StreamReader(tempfile, System.Text.Encoding.GetEncoding(1251))
str_tb = tempfilesr.ReadToEnd
tempfilesr.Close()
tempfile.Close()
tempfile = Nothing
tempfilesr = Nothing
End Sub
End Class
And the code of "temp_open.txt" file
Imports System
Imports System.Diagnostics
Imports System.Windows.Forms
Imports System.Windows
Imports Microsoft.VisualBasic
Imports System.Threading
Imports System.IO
Public Class MainClass
Inherits MarshalByRefObject
Public Shared Sub Main()
Dim tf As New testtwo
application.run(tf)
End Sub
End Class
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class testtwo
Inherits System.Windows.Forms.Form
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
Private components As System.ComponentModel.IContainer
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.Button1 = New System.Windows.Forms.Button
Me.SuspendLayout()
Me.Button1.Location = New System.Drawing.Point(114, 40)
Me.Button1.Name = "Button1"
Me.Button1.Size = New System.Drawing.Size(231, 39)
Me.Button1.TabIndex = 0
Me.Button1.Text = "Button1"
Me.Button1.UseVisualStyleBackColor = True
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(465, 133)
Me.Controls.Add(Me.Button1)
Me.Name = "test"
Me.Text = "test"
Me.ResumeLayout(False)
End Sub
Friend WithEvents Button1 As System.Windows.Forms.Button
End Class
Public Class testtwo
Shared str_tb As String
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Call openkubik()
End Sub
Private Sub openkubik()
Dim th As Thread = New Thread(AddressOf sborkakub)
th.Start()
End Sub
Private Sub sborkakub()
Dim evi As System.Security.Policy.Evidence = AppDomain.CurrentDomain.Evidence
Dim assemblyDomain As AppDomain
Dim assemblyDomainSetup As AppDomainSetup = New AppDomainSetup
assemblyDomainSetup.ApplicationBase = System.Environment.CurrentDirectory
assemblyDomainSetup.DisallowBindingRedirects = False
assemblyDomainSetup.DisallowCodeDownload = True
assemblyDomainSetup.ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile
assemblyDomainSetup.LoaderOptimization = LoaderOptimization.MultiDomainHost
assemblyDomain = AppDomain.CreateDomain("AssemblyDomain", evi, assemblyDomainSetup)
assemblyDomain.DoCallBack(AddressOf assamblykub)
End Sub
Private Shared Sub assamblykub()
Call createtext()
Dim objCodeCompiler As System.CodeDom.Compiler.CodeDomProvider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("VB")
Dim objCompilerParameters As New System.CodeDom.Compiler.CompilerParameters()
dim asm as System.Reflection.Assembly
For Each asm In AppDomain.CurrentDomain.GetAssemblies()
objCompilerParameters.ReferencedAssemblies.Add(asm.Location)
Next
'objCompilerParameters.OutputAssembly = "res1"
objCompilerParameters.CompilerOptions = "/target:winexe"
objCompilerParameters.GenerateExecutable = True
objCompilerParameters.GenerateInMemory = True
objCompilerParameters.IncludeDebugInformation = False
Dim objCompileResults As System.CodeDom.Compiler.CompilerResults = objCodeCompiler.CompileAssemblyFromSource(objCompilerParameters, str_tb)
If objCompileResults.Errors.HasErrors Then
MessageBox.Show(String.Format("Error: Line>{0}, {1} # {2}", objCompileResults.Errors(0).Line, objCompileResults.Errors(0).ErrorText, objCompileResults.Errors(0).ErrorNumber))
Return
End If
Dim objAssembly As System.Reflection.Assembly = objCompileResults.CompiledAssembly
Dim objTheClass As Object = objAssembly.CreateInstance("MainClass")
If objTheClass Is Nothing Then
MsgBox("Can't load class...")
Exit Sub
End If
Try
objTheClass.GetType.InvokeMember("Main", System.Reflection.BindingFlags.InvokeMethod, _
Nothing, objTheClass, Nothing)
Catch ex As Exception
MsgBox("Error:" & ex.Message)
End Try
End Sub
Private Shared Sub createtext()
Dim tempfile As New IO.FileStream(Application.StartupPath & "/temp_open.txt", IO.FileMode.Open, IO.FileAccess.Read)
Dim tempfilesr As New IO.StreamReader(tempfile, System.Text.Encoding.GetEncoding(1251))
str_tb = tempfilesr.ReadToEnd
tempfilesr.Close()
tempfile.Close()
tempfile = Nothing
tempfilesr = Nothing
End Sub
End Class
When I click Button1 in first form -> appears second form. but when I click Button 1 in the second form I have an FileNotFound Exception. What am I doing wrong?
There is an interesting moment. This example with some changes work in C#(http://stackoverflow.com/questions/5729403/compilling-assembly-from-the-other-just-compilled-assembly) Maybe There are people who knows vb and c# and helps me to understand differences between two examples?
Did you tried to replace assemblyDomain.DoCallBack(AddressOf assamblykub) with simple call of assamblykub function ?