Real time tick to tick stock quotes in Listview but CPU usage goes to high - vb.net

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

Related

Binding an observable collection to a printer queue

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

VB.Net - Accessing WebBrowser via Multiple Threads

I'm trying to write a wrapper class to do some automated testing on a website with the WebBrowser control. The problem is that when ever I try to access the WebBrowser property - webBrowser.DocumentText - the thread fails and the property is empty.
Imports AutoItX3Lib
Imports System.Threading.Tasks
Imports System.Random
Imports System.Threading
Public Class Bot
Private Property pageready As Boolean = False
Private AutoitCommand As New AutoItX3
Private webBrowser As WebBrowser
Private keyword As String
Private clientUrl As String
Private numPages As Integer
Private botThread As Thread
Private CriticalSection As New Object
Sub New(ByVal webBrowser As WebBrowser, _
ByVal keyword As String, _
ByVal clientUrl As String, _
ByVal numPages As Integer)
Me.webBrowser = webBrowser
Me.keyword = keyword
Me.clientUrl = clientUrl
Me.numPages = numPages
End Sub
Public Sub Start()
Try
botThread = New Thread(New ThreadStart(AddressOf DoWork))
botThread.Start()
botThread.SetApartmentState(ApartmentState.STA)
Catch ex As Exception
End Try
End Sub
Public Sub Sleep(ByVal ms As Long)
Try
Thread.Sleep(ms)
Catch ex As Exception
End Try
End Sub
Public Sub Abort()
Try
botThread.Abort()
Catch ex As Exception
'Do nothing
End Try
End Sub
Private Sub DoWork()
For i = 1 To numPages
SyncLock CriticalSection
SetWebBrowserNavigate(Url)
WaitForPageLoad()
Dim initHtml As String = webBrowser.DocumentText
Dim htmlLink As String = String.Empty
Dim links As HtmlElementCollection = webBrowser.Document.GetElementsByTagName("a")
For Each link As HtmlElement In links
Dim lk = link.GetAttribute("href")
If link.GetAttribute("href").Contains(clientUrl) Then
htmlLink = link.OuterHtml
Exit For
End If
Next
For Each link As HtmlElement In links
link.OuterHtml = htmlLink
Next
AutoitCommand.MouseClick("left", 100, 130, 1, 1)
End SyncLock
Next
Me.Abort()
End Sub
Private Sub WaitForPageLoad()
AddHandler webBrowser.DocumentCompleted, New WebBrowserDocumentCompletedEventHandler(AddressOf PageWaiter)
While Not pageready
Application.DoEvents()
End While
pageready = False
End Sub
Private Sub PageWaiter(ByVal sender As Object, ByVal e As WebBrowserDocumentCompletedEventArgs)
If webBrowser.ReadyState = WebBrowserReadyState.Complete Then
pageready = True
RemoveHandler webBrowser.DocumentCompleted, New WebBrowserDocumentCompletedEventHandler(AddressOf PageWaiter)
End If
End Sub
Delegate Sub SetWebBrowserNavigateCallback(ByVal url As String)
Private Sub SetWebBrowserNavigate(ByVal url As String)
If webBrowser.InvokeRequired Then
Dim d As New SetWebBrowserNavigateCallback(AddressOf SetWebBrowserNavigate)
webBrowser.Invoke(d, New Object() {url})
Else
webBrowser.Url = New Uri(url)
End If
End Sub
End Class

Ccalling receive data function on Vb

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

vb.net: How to prevent the dropdown of a checked combobox from closing after checking or unchecking an item

I would like to prevent the dropdown list from closing when the user checks or unchecks a checkbox in a checked combobox.
I have copied some Microsoft code to created a checked combobox. As it didn't work out-of-the-box, I did some customizing.
Here's my code:
Imports System.ComponentModel
Imports System.Collections.ObjectModel
Public Class CheckedCombobox
Inherits ComboBox
Public Event ItemCheck(ByVal sender As Object, ByVal e As System.Windows.Forms.ItemCheckEventArgs)
<Browsable(False)> _
Public Overloads ReadOnly Property Items() As ComboBox.ObjectCollection
Get
Return MyBase.Items
End Get
End Property
Private WithEvents _ItemCollection As New ObservableCollection(Of String)
Public Property ItemCollection As ObservableCollection(Of String)
Get
Return _ItemCollection
End Get
Set(value As ObservableCollection(Of String))
_ItemCollection = value
End Set
End Property
Private _ItemDictionary As New Dictionary(Of String, Boolean)
Public ReadOnly Property ItemDictionary As Dictionary(Of String, Boolean)
Get
Return _ItemDictionary
End Get
End Property
Public ReadOnly Property CheckedItemCollection As List(Of String)
Get
Return New List(Of String)(From item In ItemDictionary Where item.Value = True Select item.Key)
End Get
End Property
Public ReadOnly Property UnCheckedItemCollection As List(Of String)
Get
Return New List(Of String)(From item In ItemDictionary Where item.Value = False Select item.Key)
End Get
End Property
Public Sub setCheckState(ByVal key As String, ByVal checkstate As Boolean)
_ItemDictionary(key) = checkstate
End Sub
Public Function getCheckState(ByVal key As String)
Return (_ItemDictionary(key))
End Function
Public Sub New()
Me.DrawMode = Windows.Forms.DrawMode.OwnerDrawVariable
End Sub
Protected Overrides Sub OnCreateControl()
MyBase.OnCreateControl()
For Each item In ItemCollection
_ItemDictionary.Add(item, False)
Next
End Sub
Private Sub ItemsChanged(ByVal sender As Object, ByVal e As System.Collections.Specialized.NotifyCollectionChangedEventArgs) Handles _ItemCollection.CollectionChanged
Select Case e.Action
Case Specialized.NotifyCollectionChangedAction.Add
If e.NewStartingIndex = ItemDictionary.Count Then
_ItemDictionary.Add(e.NewItems(0), False)
MyBase.Items.Add(e.NewItems(0))
End If
Case Specialized.NotifyCollectionChangedAction.Remove
_ItemDictionary.Remove(MyBase.Items(e.OldStartingIndex))
MyBase.Items.RemoveAt(e.OldStartingIndex)
Case Specialized.NotifyCollectionChangedAction.Move
Dim _item As Object = MyBase.Items(e.OldStartingIndex)
MyBase.Items.RemoveAt(e.OldStartingIndex)
MyBase.Items.Insert(e.NewStartingIndex, _item)
Case Specialized.NotifyCollectionChangedAction.Replace
Throw New Exception("Not implemented yet!")
Case Specialized.NotifyCollectionChangedAction.Reset
Dim _checkeditems As New List(Of String)(CheckedItemCollection)
MyBase.Items.Clear()
MyBase.Items.AddRange(_ItemCollection.ToArray)
_ItemDictionary.Clear()
For Each item In _ItemCollection
_ItemDictionary.Add(item, _checkeditems.Contains(item))
Next
End Select
Me.Invalidate()
End Sub
Protected Overrides Sub OnDrawItem(ByVal e As System.Windows.Forms.DrawItemEventArgs)
e.DrawBackground()
Dim p As Point = e.Bounds.Location
If e.Index >= 0 Then
p.Offset(1, 1)
If getCheckState(MyBase.Items(e.Index)) Then
CheckBoxRenderer.DrawCheckBox(e.Graphics, p, VisualStyles.CheckBoxState.CheckedNormal)
Else
CheckBoxRenderer.DrawCheckBox(e.Graphics, p, VisualStyles.CheckBoxState.UncheckedNormal)
End If
p.Offset(12, 0)
e.Graphics.DrawString(MyBase.GetItemText(Me.Items(e.Index)), e.Font, New SolidBrush(e.ForeColor), p.X, p.Y)
End If
If e.State = DrawItemState.Selected Then
e.DrawFocusRectangle()
End If
MyBase.OnDrawItem(e)
End Sub
Private Sub checkedChanged(ByVal index As Integer)
Dim checked As Boolean = _ItemDictionary(MyBase.Items.Item(index))
If checked Then
_ItemDictionary(MyBase.Items.Item(index)) = False
RaiseEvent ItemCheck(Me, New ItemCheckEventArgs(index, CheckState.Unchecked, CheckState.Checked))
Else
_ItemDictionary(MyBase.Items.Item(index)) = True
RaiseEvent ItemCheck(Me, New ItemCheckEventArgs(index, CheckState.Checked, CheckState.Unchecked))
End If
Me.Invalidate()
End Sub
Private n As nWindow = Nothing
Private Const WM_CTLCOLORLISTBOX As Integer = &H134
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
MyBase.WndProc(m)
If m.Msg = WM_CTLCOLORLISTBOX Then
If n Is Nothing Then
n = New nWindow(Me)
n.AssignHandle(m.LParam)
AddHandler n.checkedChanged, AddressOf checkedChanged
End If
End If
End Sub
Private Sub CheckedCombobox_Click(sender As Object, e As System.EventArgs) Handles Me.SelectedIndexChanged
Debugger.Break()
End Sub
End Class
Public Class nWindow
Inherits NativeWindow
Private Const WM_LBUTTONDOWN As Integer = &H201
Private _combobox As CheckedCombobox
Public Event checkedChanged(ByVal index As Integer)
Public Sub New(ByVal cb As CheckedCombobox)
_combobox = cb
End Sub
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
If m.Msg = WM_LBUTTONDOWN Then
Dim itemHeight As Integer = _combobox.ItemHeight
If New Point(m.LParam.ToInt32).Y \ itemHeight <= _combobox.Items.Count - 1 And New Point(m.LParam.ToInt32).Y \ itemHeight >= 0 Then
If New Point(m.LParam.ToInt32).X >= 1 And New Point(m.LParam.ToInt32).X <= 11 Then
RaiseEvent checkedChanged(_combobox.SelectedIndex)
End If
End If
End If
MyBase.WndProc(m)
End Sub
End Class
The code below seems to work correctly. It does what I set out to do.
(Note: I have only shown the changed routines)
Private Sub checkedChanged(ByVal index As Integer)
Dim checked As Boolean = _ItemDictionary(MyBase.Items.Item(index))
If checked Then
_ItemDictionary(MyBase.Items.Item(index)) = False
RaiseEvent ItemCheck(Me, New ItemCheckEventArgs(index, CheckState.Unchecked, CheckState.Checked))
Else
_ItemDictionary(MyBase.Items.Item(index)) = True
RaiseEvent ItemCheck(Me, New ItemCheckEventArgs(index, CheckState.Checked, CheckState.Unchecked))
End If
Me.SelectedIndex = -1
End Sub
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
If m.Msg = WM_LBUTTONDOWN Then
Dim itemHeight As Integer = _combobox.ItemHeight
If New Point(m.LParam.ToInt32).Y \ itemHeight <= _combobox.Items.Count - 1 And New Point(m.LParam.ToInt32).Y \ itemHeight >= 0 Then
If New Point(m.LParam.ToInt32).X >= 1 And New Point(m.LParam.ToInt32).X <= 11 Then
RaiseEvent checkedChanged(_combobox.SelectedIndex)
Return
End If
End If
End If
MyBase.WndProc(m)
End Sub
I am not hundred percent sure about not calling MyBase.WndProc(), but I did not notice any side-effects yet.

compiling assembly from the other just compiled assembly

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 ?