Binding an observable collection to a printer queue - vb.net

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

Related

How to show menu text in custom ToolStripItem?

Mainform VB.Net:
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()>
Partial Class Form1
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<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
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()>
Private Sub InitializeComponent()
Me.tsBasket = New System.Windows.Forms.ToolStrip()
Me.tsiFruit = New System.Windows.Forms.ToolStripDropDownButton()
Me.tsBasket.SuspendLayout()
Me.SuspendLayout()
'
'tsBasket
'
Me.tsBasket.Dock = System.Windows.Forms.DockStyle.None
Me.tsBasket.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden
Me.tsBasket.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.tsiFruit})
Me.tsBasket.Location = New System.Drawing.Point(355, 213)
Me.tsBasket.Name = "tsBasket"
Me.tsBasket.Size = New System.Drawing.Size(121, 25)
Me.tsBasket.TabIndex = 5
'
'tsiFruit
'
Me.tsiFruit.ImageTransparentColor = System.Drawing.Color.Magenta
Me.tsiFruit.Name = "tsiFruit"
Me.tsiFruit.Size = New System.Drawing.Size(87, 22)
Me.tsiFruit.Text = "add fruit"
'
'Form1
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(800, 450)
Me.Controls.Add(Me.tsBasket)
Me.Name = "Form1"
Me.Text = "Form1"
Me.tsBasket.ResumeLayout(False)
Me.tsBasket.PerformLayout()
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents tsBasket As ToolStrip
Friend WithEvents tsiFruit As ToolStripDropDownButton
End Class
Form Load:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim men As New TestTool()
men.Text = "showmeplease"
men.Image = Nothing
men.NewProperty = "BO"
Dim men2 As New TestTool()
men2.Text = "showmeplease2"
men2.Image = Nothing
men2.NewProperty = "BO2"
tsiFruit.DropDownItems.Add(men)
tsiFruit.DropDownItems.Add(men2)
AddHandler men.Click, AddressOf tsiType_Click
AddHandler men2.Click, AddressOf tsiType_Click
End Sub
Private Sub tsiType_Click(sender As System.Object, e As System.EventArgs)
Dim MenuItem As TestTool = DirectCast(sender, TestTool)
MessageBox.Show(MenuItem.NewProperty & " " & MenuItem.Text)
End Sub
Custom class:
Public Class TestTool
Inherits ToolStripItem
Private newPropertyValue As String
Public Property NewProperty() As String
Get
Return newPropertyValue
End Get
Set(ByVal value As String)
newPropertyValue = value
End Set
End Property
Sub New()
' This call is required by the designer.
' InitializeComponent()
End Sub
End Class
On my custom class/Usercontrol I am getting :
The designer must create an instance of type 'System.Windows.Forms.ToolStripItem' but it cannot because the type is declared as abstract. and I am not seeing the text appear in the menu items, but the click event works fine.
Is this the correct way to extend(Inherit using OO) a ToolMenuStrip so that I can have a Display value and a Member value, I want to be able to store an object without using .Tag.
Edit:
I am getting when trying to have nested menus:
System.InvalidCastException: 'Unable to cast object of type 'System.Windows.Forms.ToolStripMenuItem' to type 'WindowsApp1.TestTool'.'
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim men As New TestTool()
men.Text = "showmeplease"
men.Image = Nothing
men.NewProperty = "BO"
Dim men2 As New TestTool()
men2.Text = "showmeplease2"
men2.Image = Nothing
men2.NewProperty = "BO2"
tsiFruit.DropDownItems.Add(men)
tsiFruit.DropDownItems.Add(men2)
Dim TypeMenuItem As TestTool = men.DropDownItems.Add("hh")
For Each mInfo As String In Moreinfo
TypeMenuItem.DropDownItems.Add(mInfo, Nothing, AddressOf tsiType_Click)
Next
AddHandler men.Click, AddressOf tsiType_Click
AddHandler men2.Click, AddressOf tsiType_Click
End Sub
Private p_Moreinfo As List(Of String)
Public Property Moreinfo() As List(Of String)
Get
Dim test As New List(Of String)
test.Add("A")
test.Add("B")
Return test
End Get
Set(ByVal value As List(Of String))
p_Moreinfo = value
End Set
End Property
If you enable the Option Strict check (you should), you will find an error with the line below in the Form1_Load event:
' Error: Option Strict On disallows implicit conversions from ToolStrinpItem
' to TestTool.
Dim TypeMenuItem As TestTool = men.DropDownItems.Add("hh")
Because the .DropDownItems.Add(String) overload returns a ToolStripItem and not an object of type TestTool. The .DropDownItems don't inherit the type of the owner item.
' Compiles.
Dim TypeMenuItem As ToolStripItem = men.DropDownItems.Add("hh")
' Compiles.
Dim TypeMenuItem As ToolStripMenuItem = DirectCast(men.DropDownItems.Add("hh"), ToolStripMenuItem)
' Throws System.InvalidCastException.
Dim TypeMenuItem As TestTool = DirectCast(men.DropDownItems.Add("hh"), TestTool)
So, the code in Load event should be like:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim men As New TestTool With {
.Text = "showmeplease",
.NewProperty = "BO"
}
Dim men2 As New TestTool With {
.Text = "showmeplease2",
.NewProperty = "BO2"
}
tsiFruit.DropDownItems.Add(men)
tsiFruit.DropDownItems.Add(men2)
Dim TypeMenuItem As New TestTool() With {.NewProperty = "hh", .Text = "SomeText"}
men.DropDownItems.Add(TypeMenuItem)
For Each mInfo As String In Moreinfo
Dim item = New TestTool With {.NewProperty = mInfo, .Text = "SomeText"}
AddHandler item.Click, AddressOf tsiType_Click
TypeMenuItem.DropDownItems.Add(item)
Next
AddHandler men.Click, AddressOf tsiType_Click
AddHandler men2.Click, AddressOf tsiType_Click
End Sub
Likewise, to avoid throwing exceptions in the tsiType_Click event, just in case:
Private Sub tsiType_Click(sender As Object, e As EventArgs)
Dim item = TryCast(sender, TestTool)
If item IsNot Nothing Then
MessageBox.Show($"{item.NewProperty} {item.Text}")
Else
MessageBox.Show(DirectCast(sender, ToolStripItem).Text)
End If
End Sub
I believe you have modified the TestTool class as #jmcilhinney commented to something like:
Public Class TestTool
Inherits ToolStripMenuItem
Sub New()
MyBase.New
End Sub
Public Property NewProperty As String
End Class

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

Using SqlDependency with named Queues in vb.net to populate the datagridview each time there is a change in database

Am developing an interface that needs to get data from the database and post to main system in real time.ie when a transcation is initiated in need to hit the main system in realtime for responce fo futher proccessing. i am creating an interface for the application which uses sql server.
i am trying to use the sqldependancy with the following code
Option Strict On
Option Explicit On
Imports System.Data.SqlClient
Imports System.Security.Permissions
mports System.ComponentModel
Public Class Home
Private Sub Home_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'BillPaymentsDataSet.Transactions_Temp' table. You can move, or remove it, as needed.
Me.Transactions_TempTableAdapter.Fill(Me.BillPaymentsDataSet.Transactions_Temp)
End Sub
Private Function GetConnectionString() As String
Return My.Settings.BillPaymentsConnectionString
End Function
Sub Initialization()
Dim con As New SqlConnection(My.Settings.BillPaymentsConnectionString)
SqlDependency.Start(My.Settings.BillPaymentsConnectionString)
End Sub
Private Function CanRequestNotifications() As Boolean
Dim permission As New SqlClientPermission( _
PermissionState.Unrestricted)
Try
permission.Demand()
Return True
Catch ex As Exception
Return False
End Try
End Function
Private Sub GetData()
BillPaymentsDataSet = Nothing
dt = New DataTable()
BillPaymentsDataSet.Clear()
SqlDependency.Stop(GetConnectionString())
SqlDependency.Start(GetConnectionString())
command.Notification = Nothing
If con Is Nothing Then
con = New SqlConnection(GetConnectionString())
End If
Dim dependency As New SqlDependency(command)
AddHandler dependency.OnChange, AddressOf dependency_OnChange
con.Open()
Using Transactions_TempTableAdapter As New SqlDataAdapter(command)
Me.Transactions_TempTableAdapter.Fill(Me.BillPaymentsDataSet.Transactions_Temp)
Me.DataGridView1.DataSource = BillPaymentsDataSet.Transactions_Temp
End Using
End Sub
Private Sub UserMantainanceToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles UserMantainanceToolStripMenuItem.Click
UserMantain.Show()
End Sub
Private Sub dependency_OnChange( _
ByVal sender As Object, ByVal e As SqlNotificationEventArgs)
Dim changeCount As Integer = 0
Const statusMessage As String = _
"{0} changes have occurred."
Dim i As ISynchronizeInvoke = CType(Me, ISynchronizeInvoke)
If i.InvokeRequired Then
' Create a delegate to perform the thread switch
Dim tempDelegate As New OnChangeEventHandler( _
AddressOf dependency_OnChange)
Dim args() As Object = {sender, e}
' Marshal the data from the worker thread
' to the UI thread.
i.BeginInvoke(tempDelegate, args)
Return
End If
' Remove the handler since it's only good
' for a single notification
Dim dependency As SqlDependency = _
CType(sender, SqlDependency)
RemoveHandler dependency.OnChange, _
AddressOf dependency_OnChange
' At this point, the code is executing on the
' UI thread, so it is safe to update the UI.
changeCount += 1
Me.Label1.Text = String.Format(statusMessage, changeCount)
' Add information from the event arguments to the list box
' for debugging purposes only.
With Me.ListBox1.Items
.Clear()
.Add("Info: " & e.Info.ToString())
.Add("Source: " & e.Source.ToString())
.Add("Type: " & e.Type.ToString())
End With
' Reload the dataset that's bound to the grid.
GetData()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
End Sub
End Class

Real time tick to tick stock quotes in Listview but CPU usage goes to high

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

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 ?