VB.NET - Data not sending until the stream is closed - vb.net

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.

Related

Sending an receiving two types of data across TCP connection

On the Client I want to -
I want to send a screenimage from the client and receive a string with cursor coordinates in.
On the server I want to receive and display the screenimage on Form2
and then send back my cursor coordinates to the client.
I can successfully send text messages from the client and receive them on the server using this code -
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
senddata("CHAT|" & TextBox3.Text) 'send the data with CHAT| as header
TextBox4.Text &= "You: " & " " & TextBox3.Text.Split("|")(0) & vbNewLine
End Sub
Sub senddata(ByVal message As String)
Dim sw As New StreamWriter(t.GetStream) 'declare a new streamwriter
sw.WriteLine(message) 'write the message
sw.Flush()
End Sub
and receive it on the server with this code -
Imports System.IO
Imports System.Net.Sockets
Public Class ConnectedClient
Private cli As TcpClient 'decleare a tcp client which will be the client that we assign to an instance of this class
Private uniqueid As String 'this will be used for the name property
Public Property name ''This will be the name of the ID containing its Unique ID
Get
Return uniqueid 'when we want to get it, it will return the Unique ID
End Get
Set(ByVal value)
uniqueid = value 'Used for setting the name
End Set
End Property
Sub New(ByVal client As TcpClient)
Dim r As New Random 'create a new random to serve as way to create our unique ID
Dim x As String = String.Empty 'declare a new variable to hold the ID
For i = 0 To 7 'we are goign to have an ID of 7 randomly generated characters
x &= Chr(r.Next(65, 89)) 'create a generate dnumber between 65 and 89 and get the letter that has the same ascii value (A-Z)
' and add it onto the ID string
Next
Me.name = client.Client.RemoteEndPoint.ToString().Remove(client.Client.RemoteEndPoint.ToString().LastIndexOf(":")) & " - " & x 'set the name to the Unique ID
cli = client 'assign the client specified to the TCP client variable to we can operate with it
cli.GetStream.BeginRead(New Byte() {0}, 0, 0, AddressOf read, Nothing) 'start reading using the read subroutine
End Sub
Public Event gotmessage(ByVal message As String, ByVal client As ConnectedClient) 'this is raised when we get a message from the client
Public Event disconnected(ByVal client As ConnectedClient) 'this is raised when we get the client disconnects
Sub read(ByVal ar As IAsyncResult) 'this will process all messages being recieved
Try
Dim sr As New StreamReader(cli.GetStream) 'initialize a new streamreader which will read from the client's stream
Dim msg As String = sr.ReadLine() 'create a new variable which will be used to hold the message being read
RaiseEvent gotmessage(msg, Me) 'tell the server a message has been recieved. Me is passed as an argument which represents
' the current client which it has recieved the message from to perform any client specific
' tasks if needed
cli.GetStream.BeginRead(New Byte() {0}, 0, 0, AddressOf read, Nothing) 'continue reading from the stream
Catch ex As Exception
Try 'if an error occurs in the reading purpose, we will try to read again to see if we still can read
Dim sr As New StreamReader(cli.GetStream) 'initialize a new streamreader which will read from the client's stream
Dim msg As String = sr.ReadLine() 'create a new variable which will be used to hold the message being read
RaiseEvent gotmessage(msg, Me) 'tell the server a message has been recieved. Me is passed as an argument which represents
' the current client which it has recieved the message from to perform any client specific
' tasks if needed
cli.GetStream.BeginRead(New Byte() {0}, 0, 0, AddressOf read, Nothing) 'continue reading from the stream
Catch ' IF WE STILL CANNOT READ
RaiseEvent disconnected(Me) 'WE CAN ASSUME THE CLIENT HAS DISCONNECTED
End Try
End Try
End Sub
Sub senddata(ByVal message As String) 'this is used to deal with sending out messages
Dim sw As New StreamWriter(cli.GetStream) 'declare a new streamwrite to write to the stream between the client and the server
sw.WriteLine(message) 'write the message to the stream
sw.Flush()
End Sub
Sub listen(ByVal port As Integer)
Try
Dim t As New TcpListener(IPAddress.Any, port) 'declare a new tcplistener
t.Start() 'start the listener
Do
Dim client As New ConnectedClient(t.AcceptTcpClient) 'initialize a new connected client
AddHandler client.gotmessage, AddressOf recieved 'add the handler which will raise an event when a message is recieved
AddHandler client.disconnected, AddressOf disconnected 'add the handler which will raise an event when the client disconnects
Loop Until False
Catch
End Try
End Sub
In a totally different application I can successfully send the screen image from the client using this code
Imports System.Net.Sockets
Imports System.Threading
Imports System.Drawing
Imports System.Runtime.Serialization.Formatters.Binary
Public Class Form1
Dim client As New TcpClient
Dim ns As NetworkStream
Dim port As Integer
Dim server As TcpListener
Dim listening As New Thread(AddressOf Listen)
Dim GetImage As New Thread(AddressOf ReceiveCursor)
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles btnConnect.Click
port = CInt(txtPort.Text)
Try
If btnConnect.Text = "Connect" Then
client.Connect(txtIP.Text, port)
'MsgBox("Client connected !")
Timer1.Start()
btnConnect.Text = "Disconnect"
Else
btnConnect.Text = "Connect"
Timer1.Stop()
End If
Catch ex As Exception
MsgBox("Failed to connect..." + ex.Message)
End Try
End Sub
Public Function Desktop() As Image
Dim bounds As Rectangle = Nothing
Dim screenshot As System.Drawing.Bitmap = Nothing
Dim graph As Graphics = Nothing
bounds = Screen.PrimaryScreen.Bounds
screenshot = New Bitmap(bounds.Width, bounds.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb)
graph = Graphics.FromImage(screenshot)
graph.CopyFromScreen(bounds.X, bounds.Y, 0, 0, bounds.Size, CopyPixelOperation.SourceCopy)
Return screenshot
End Function
Private Sub SendDesktop()
Dim bf As New BinaryFormatter
ns = client.GetStream
bf.Serialize(ns, Desktop())
End Sub
Private Sub BtnShare_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnShare.Click
If btnShare.Text.StartsWith("Share") Then
Timer1.Start()
'port = Integer.Parse(Me.txtPort.Text)
'server = New TcpListener(port)
'listening.Start()
btnShare.Text = "Stop Sharing"
Else
Timer1.Stop()
btnShare.Text = "Share Desktop"
End If
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
SendDesktop()
' SetCursorPosition()
End Sub
Private Sub ReceiveCursor()
Dim bf As New BinaryFormatter
While client.Connected = True
ns = client.GetStream
txtCursorPosition.Text = bf.Deserialize(ns)
End While
End Sub
Private Sub Listen()
While client.Connected = False
server.Start()
client = server.AcceptTcpClient
End While
GetImage.Start()
End Sub
Public Sub StopListening()
GetImage.Abort()
server.Stop()
client = Nothing
If listening.IsAlive Then
listening.Abort()
End If
End Sub
End Class
and receive it on the server using this code -
Imports System.Net.Sockets
Imports System.Threading
Imports System.Drawing
Imports System.Runtime.Serialization.Formatters.Binary
Public Class Form2
Dim port As Integer
Dim client As New TcpClient
Dim ns As NetworkStream
Dim server As TcpListener
Dim listening As New Thread(AddressOf Listen)
Dim GetImage As New Thread(AddressOf ReceiveImage)
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Start the timer, obtain the port and start listening
Timer1.Start()
port = Integer.Parse(Form1.txtPort.Text)
server = New TcpListener(port)
listening.Start()
End Sub
Private Sub ReceiveImage()
Dim bf As New BinaryFormatter
While client.Connected = True
ns = client.GetStream
PictureBox1.Image = bf.Deserialize(ns)
End While
End Sub
Private Sub Listen()
While client.Connected = False
server.Start()
client = server.AcceptTcpClient
End While
GetImage.Start()
End Sub
Public Sub StopListening()
GetImage.Abort()
server.Stop()
client = Nothing
If listening.IsAlive Then
listening.Abort()
End If
End Sub
End Class
Is there a way of doing both using the same connection and somehow detecting which is text and which is the screenimage?

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

Issue with "Get" message with gmail api v1 (Net)

Im trying to get info of a gmail message in a datagridview but only returns the datagridview empty (even when I erase the "return nothing" line) but when I try in apis-explorer I get the 200 ok response. What am I doing wrong?
The code Im using is from the google developers documentation:
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Services
Imports Google.Apis.Tasks.v1
Imports Google.Apis.Tasks.v1.Data.Tasks
Imports Google.Apis.Tasks.v1.Data
Imports System.Collections.Generic
Imports Google.Apis.Util.Store
Imports System.Threading
Imports System
Imports Google.Apis.Gmail.v1
Imports Google.Apis.Gmail.v1.Data
Public Class Form1
Dim Secrets = New ClientSecrets()
Dim scope = New List(Of String)
Dim initializer = New BaseClientService.Initializer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Secrets.ClientId = "CLIENT_ID"
Secrets.ClientSecret = "CLIENT_SECRET"
End Sub
Public Shared Function GetMessage(service As GmailService, userId As [String], messageId As [String]) As Message
Try
Return service.Users.Messages.Get(userId, messageId).Execute()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
'Return Nothing
End Function
Private Sub Button14_Click(sender As Object, e As EventArgs) Handles Button14.Click
Dim userId As String = "GMAIL ACCOUNT"
Dim messageId As String = "MESSAGE ID"
Try
scope.Add(GmailService.Scope.MailGoogleCom)
Dim credential = GoogleWebAuthorizationBroker.AuthorizeAsync(Secrets, scope, "XXXXXXXXXXXX#developer.gserviceaccount.google.com", CancellationToken.None).Result()
initializer.HttpClientInitializer = credential
initializer.ApplicationName = "APP NAME"
Dim service = New GmailService(initializer)
Me.DataGridView1.DataSource = GetMessage(service, userId, messageId)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
Thanks Eric but I already solved making some changes. I hope this helps other people because the google developers documentation its not too clear
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Services
Imports System.Collections.Generic
Imports Google.Apis.Util.Store
Imports System.Threading
Imports System
Imports Google.Apis.Gmail.v1
Imports Google.Apis.Gmail.v1.Data
Public Class Form1
Dim Secrets = New ClientSecrets()
Dim scope = New List(Of String)
Dim initializer = New BaseClientService.Initializer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Secrets.ClientId = "CLIENT ID"
Secrets.ClientSecret = "CLIENT SECRET"
End Sub
Public Shared Function GetMessage(service As GmailService, userId As [String], messageId As [String]) As Message
Try
Return service.Users.Messages.Get(userId, messageId).Execute
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Return Nothing
End Function
Private Sub Button14_Click(sender As Object, e As EventArgs) Handles Button14.Click
Try
scope.Add(GmailService.Scope.MailGoogleCom)
Dim credential = GoogleWebAuthorizationBroker.AuthorizeAsync(Secrets, scope, "XXXXXXXXXXXXX#developer.gserviceaccount.google.com", CancellationToken.None).Result()
initializer.HttpClientInitializer = credential
initializer.ApplicationName = "APP NAME"
Dim service = New GmailService(initializer)
Dim userId As String = "EMAIL"
Dim messageId As String = "MESSAGE ID"
Me.DataGridView1.DataSource = GetMessage(service, userId, messageId).Payload.Headers
TextBox1.Text = (GetMessage(service, userId, messageId).Snippet)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
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 ?