How to download multiple files in list box using vb.net - vb.net

I want to download multiples files and the download links in list box, Is there any way to do that using WebClient, i saw people do that by download file by file by it look difficult way and i want to show current downloading speed ,current file size and progress of total process

I solved this proplem by that way:
Imports System.Net
Public Class Form1
Private WithEvents DonloadFile As WebClient
Dim stopwatch As Stopwatch = New Stopwatch
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ListBox1.SelectedIndex = 0
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
stopwatch.Start()
DonloadFile = New WebClient
Try
DonloadFile.DownloadFileAsync(New Uri(ListBox1.SelectedItem.ToString), "C:\Users\" & Environment.UserName & "\Desktop\" & IO.Path.GetFileName(ListBox1.SelectedItem.ToString))
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub DonloadFile_DownloadProgressChanged(sender As Object, e As DownloadProgressChangedEventArgs) Handles DonloadFile.DownloadProgressChanged
Dim y As Integer = (e.BytesReceived / 1024) / 1024
Label6.Text = "Download Speed: " & String.Format("{0} MB/s", (y / (stopwatch.Elapsed.TotalSeconds)).ToString("0.00"))
Label2.Text = "Current File Size: " & Math.Round(e.TotalBytesToReceive / (1024 * 1024), 1) & " MB"
Label3.Text = "Current File Persent: " & e.ProgressPercentage
Label1.Text = "Total Files: " & ListBox1.Items.Count.ToString()
If ListBox1.Items.Count.ToString > (ListBox1.SelectedIndex + 1) Then
If e.ProgressPercentage = 100 Then
ListBox1.SelectedIndex += 1
End If
Else
MessageBox.Show("Download completed successful", "Info")
End If
End Sub
Private Sub DonloadFile_DownloadDataCompleted(sender As Object, e As DownloadDataCompletedEventArgs) Handles DonloadFile.DownloadDataCompleted
stopwatch.Reset()
End Sub
End Class
thanks for #Fawlty

Here is some code I wrote to demonstrate how you could do this. I created a FileDownloader class as this will allow you to get the source url and destination filename when the download completes. I have also added an event for progress. The problem with just using the WebClient class on its own is that you lose track of which file is being processed in the events.
Imports System.ComponentModel
Imports System.Net
' A class for downloading files, with progress and finished events
Public Class FileDownloader
' Private storage
Private FileURL As String = ""
Private SaveToPath As String = ""
' A class to return our result in
Public Class FileDownloaderFileDownloadedEventArgs
Public Property DownloadedURL As String
Public Property SaveToPath As String
Public Sub New(DownloadedURL As String, SaveToPath As String)
Me.DownloadedURL = DownloadedURL
Me.SaveToPath = SaveToPath
End Sub
End Class
' A class to show progress
Public Class FileDownloaderProgressEventArgs
Public Property DownloadURL As String
Public Property SaveToPath As String
Public Property TotalBytes As Long
Public Property ProgressBytes As Long
Public Property ProgressPercent As Integer
Public Property UserState As Object
Public Sub New(DownloadURL As String, SaveToPath As String, TotalBytes As Long, ProgressBytes As Long, ProgressPercent As Integer, UserState As Object)
Me.DownloadURL = DownloadURL
Me.SaveToPath = SaveToPath
Me.TotalBytes = TotalBytes
Me.ProgressBytes = ProgressBytes
Me.ProgressPercent = ProgressPercent
Me.UserState = UserState
End Sub
End Class
' The event to raise when the file is downloaded
Public Event FileDownloaded(sender As Object, e As FileDownloaderFileDownloadedEventArgs)
' The event to raise when there is progress
Public Event Progress(sender As Object, e As FileDownloaderProgressEventArgs)
' Pass in the URL and FilePath when creating the downloader object
Public Sub New(FileURL As String, SaveToPath As String)
Me.FileURL = FileURL
Me.SaveToPath = SaveToPath
End Sub
' Call Download() to do the work
Public Sub Download()
Using wc As New WebClient
AddHandler wc.DownloadFileCompleted, AddressOf DownloadFileCompleted
AddHandler wc.DownloadProgressChanged, AddressOf DownloadProgressChanged
wc.DownloadFileAsync(New Uri(FileURL), SaveToPath)
End Using
End Sub
' Catch the download complete and raise our event
Private Sub DownloadProgressChanged(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs)
RaiseEvent Progress(Me, New FileDownloaderProgressEventArgs(FileURL, SaveToPath, e.TotalBytesToReceive, e.BytesReceived, e.ProgressPercentage, e.UserState))
End Sub
Private Sub DownloadFileCompleted(sender As Object, e As AsyncCompletedEventArgs)
' Some code you want to run after each file has downloaded
RaiseEvent FileDownloaded(Me, New FileDownloaderFileDownloadedEventArgs(FileURL, SaveToPath))
End Sub
End Class
#Region "How to use the FileDownloader class"
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
' Loop the URLs in the ListBox
For Each item In ListBox1.Items
' Create a FileDownloader object to handler each one
Dim FD = New FileDownloader(item, "c:\temp\" & IO.Path.GetFileName(item))
' Attach the event handlers
AddHandler FD.FileDownloaded, AddressOf FileDownloaded
AddHandler FD.Progress, AddressOf Progress
' Start the download
FD.Download()
Next
End Sub
' Event handler for file download completed
Private Sub FileDownloaded(sender As Object, e As FileDownloader.FileDownloaderFileDownloadedEventArgs)
tb_Log.AppendText(e.DownloadedURL & " Downloaded To: " & e.SaveToPath & vbCrLf)
End Sub
' Event handler for progress
Private Sub Progress(sender As Object, e As FileDownloader.FileDownloaderProgressEventArgs)
tb_Log.AppendText(IO.Path.GetFileName(e.DownloadURL) & " " & e.ProgressPercent & "% downloaded" & vbCrLf)
End Sub
#End Region

Related

File synchronization Visual Studio 2015 error

I'm coming back to you because I still have a problem in my source code, I'll remind you that I'm trying to do an FTP synchronization from the following source that I copied
Video: https://www.youtube.com/watch?v=E5qSxrbrf9I
Error:
BC31143 La méthode 'Private Sub File_Downloaded(sender As Object, e As AsyncCompletedEventArgs)' n'a pas de signature compatible avec le délégué 'Delegate Sub DownloadProgressChangedEventHandler(sender As Object, e As DownloadProgressChangedEventArgs)'.
Erreur BC30311 Impossible de convertir une valeur de type 'FtpWebResponse' en 'FtpWebRequest'.
Erreur BC30456 'GetResponseStream' n'est pas un membre de 'FtpWebRequest'.
FTPManager.vb (Class)
Public Class FTPManager
Private Shared ConfigFile As String =
Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) & "\config.txt"
Public Shared Folder As String = "Client_Pokemonia"
Public Shared ServerRootPatch As String
Public Shared User As String
Public Shared PW As String
Public Shared Sub loadConfig()
If IO.File.Exists(ConfigFile) Then
Dim lines = IO.File.ReadAllLines(ConfigFile)
ServerRootPatch = lines(0)
User = lines(1)
PW = lines(2)
End If
End Sub
End Class
Form1.vb
Imports System.ComponentModel
Imports System.Net
Public Class Form1
Private LocalPath As String = "Downloadedfiles"
Private missingFiles As New List(Of String)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
FTPManager.loadConfig()
createLocalFolderIfNotExistes()
btnRefresh.performClick()
End Sub
Private Sub createLocalFolderIfNotExistes()
If Not IO.Directory.Exists(LocalPath) Then IO.Directory.CreateDirectory(LocalPath)
End Sub
Private Sub getLocalFiles()
dgvLocal.Rows.clear
Dim files = IO.Directory.GetFiles(LocalPath)
If files.Count > 0 Then
For Each f In files
Me.dgvLocal.Rows.Add(f.Split("\c").Last())
Next
End If
End Sub
Private Sub getFTPFiles()
dgvFTP.Rows.Clear()
missingFiles.Clear()
Dim request = FtpWebRequest.Create(FTPManager.ServerRootPatch)
request.Method = WebRequestMethods.Ftp.ListDirectory
request.Credentials = New NetworkCredential(FTPManager.User, FTPManager.PW)
Dim response As FtpWebRequest = CType(request.GetResponse(), FtpWebResponse)
Using myReader As New IO.StreamReader(response.GetResponseStream())
Do Until Not myReader.EndOfStream
Dim file = myReader.ReadLine()
Me.dgvFTP.Rows.Add(file)
If Not IO.File.Exists(LocalPath & "\" & file) Then
dgvFTP.Rows(dgvFTP.Rows.Count - 1).defaultCellStyle.BackColor = Color.FromArgb(255, 192, 192)
missingFiles.Add(file)
Else : dgvFTP.Rows(dgvFTP.Rows.Count - 1).DefaultCellStyle.BackColor = Color.FromArgb(192, 255, 192)
End If
Loop
End Using
End Sub
Private Sub btnRefresh_Click(sender As Object, e As EventArgs) Handles btnRefresh.Click
' If Not btnRefresh Then
' btnRefresh.Enabled = False
' Await Task.Delay(2000)
' getLocalFiles()
' getFTPFiles()
' btnSync.Enabled = True
' Else : MessageBox.Show("please wait")
' End If
dgvFTP.ClearSelection()
dgvLocal.ClearSelection()
End Sub
Private Sub btnSync_Click(sender As Object, e As EventArgs) Handles btnSync.Click
If missingFiles.Count > 0 Then
Donwload_File(New Uri(FTPManager.ServerRootPatch & FTPManager.Folder & "/" & missingFiles(0)))
Else : MessageBox.Show("No files to downlaod")
End If
End Sub
Private Sub Donwload_File(URI As Uri)
Dim filename = URI.ToString().Split("/c").Last()
prgb.Value = 0
'lblFile.text = filename
Using wc As New WebClient
wc.Credentials = New NetworkCredential(FTPManager.User, FTPManager.PW)
AddHandler wc.DownloadProgressChanged, AddressOf File_DLProgressChanged
AddHandler wc.DownloadProgressChanged, AddressOf File_Downloaded
wc.DownloadFileAsync(URI, LocalPath & "\" & filename)
End Using
End Sub
Private Sub File_DLProgressChanged(sender As Object, e As DownloadProgressChangedEventArgs)
prgb.Value = e.ProgressPercentage
End Sub
Private Sub File_Downloaded(sender As Object, e As AsyncCompletedEventArgs)
Dim deletedFile = missingFiles(0)
missingFiles.RemoveAt(0)
If missingFiles.Count > 0 Then
Donwload_File(New Uri(FTPManager.ServerRootPatch & FTPManager.Folder & "/" & missingFiles(0)))
Else
btnRefresh.PerformClick()
MessageBox.Show("niquel")
End If
End Sub
End Class
The issue is here:
Dim response As FtpWebRequest = CType(request.GetResponse(), FtpWebResponse)
read what the error message is telling you and then read that line. You call GetResponse and cast the result as type FtpWebResponse, then you try to assign that top a variable of type FtpWebRequest. The error message is telling you that you can't convert an object of one type to the other, which would be required for that assignment to work.

VB.NET: Code runs without error, but does not add item to listbox

I've got this embedded CMD on my form which I created using another person's code and everything works right. Inside one of the Private Subs (that seems to run every time a new line is written in the CMD output textbox), I've got a line which adds a item to a listbox (listboxs name is txtPlayerList) on another form labelled Status.
When this area of the code runs, it doesn't throw up any errors (and if I put a msgbox() on the same line, the msgbox() works). If I put the add to listbox line on form_load it works perfectly?
Here is my code, I've included everything from that form just in case (it is in the third sub from the top with the asterisks and comment "Get players and maybe other stuff as well"
Imports System.IO
Public Class Console
Public WithEvents MyProcess As Process
Private Delegate Sub AppendOutputTextDelegate(ByVal text As String)
Public LastLine As String
Public LastLineFormatted As String
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim LocalpathParent As String = Application.StartupPath() + "\MCserver"
'loads embed cmd
Me.AcceptButton = ExecuteButton
MyProcess = New Process
With MyProcess.StartInfo
.FileName = "CMD.EXE"
.UseShellExecute = False
.CreateNoWindow = True
.RedirectStandardInput = True
.RedirectStandardOutput = True
.RedirectStandardError = True
.WorkingDirectory = LocalpathParent
End With
MyProcess.Start()
MyProcess.BeginErrorReadLine()
MyProcess.BeginOutputReadLine()
AppendOutputText("Process Started at: " & MyProcess.StartTime.ToString)
'Resize with parent mdi container. Needs to be anchored & StartPosition = manual in properties
Me.WindowState = FormWindowState.Maximized
End Sub
Private Sub MyProcess_ErrorDataReceived(ByVal sender As Object, ByVal e As System.Diagnostics.DataReceivedEventArgs) Handles MyProcess.ErrorDataReceived
AppendOutputText(vbCrLf & "Error: " & e.Data)
End Sub
Private Sub MyProcess_OutputDataReceived(ByVal sender As Object, ByVal e As System.Diagnostics.DataReceivedEventArgs) Handles MyProcess.OutputDataReceived
AppendOutputText(vbCrLf & e.Data)
'*****************************************
'Get Players and maybe other stuff as well
'*****************************************
LastLine = Me.OutputTextBox.Lines.Last
If Status.ServerStarted = True Then
If Me.LastLine.Contains(" joined the game") Then
LastLineFormatted = Me.LastLine
LastLineFormatted = LastLineFormatted.Replace(" joined the game", "")
'***THIS LINE BELOW WORKS IN FORM LOAD, BUT NOT HERE FOR SOME REASON???***
Status.txtPlayersList.Items.Add(LastLineFormatted)
MsgBox("add lastlineformatted")
ElseIf Me.LastLine.Contains(" left the game") Then
LastLineFormatted = Me.LastLine
LastLineFormatted = LastLineFormatted.Replace(" left the game", "")
Status.txtPlayersList.Items.Remove(LastLineFormatted)
End If
End If
End Sub
Private Sub ExecuteButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExecuteButton.Click
MyProcess.StandardInput.WriteLine(InputTextBox.Text)
MyProcess.StandardInput.Flush()
InputTextBox.Text = ""
End Sub
Private Sub AppendOutputText(ByVal text As String)
If OutputTextBox.InvokeRequired Then
Dim myDelegate As New AppendOutputTextDelegate(AddressOf AppendOutputText)
Try
Me.Invoke(myDelegate, text)
Catch
End Try
Else
Try
OutputTextBox.AppendText(text)
Catch
End Try
End If
End Sub
End Class
EDIT: Below is the code I have for form1 per request
'code
Public Class Form1
Public Localpath As String
Public Downloadpath As String
Public LocalpathParent As String
'when this form is closing, send stop to console to make sure it has closed and saved
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
Console.MyProcess.StandardInput.WriteLine("stop") 'send an EXIT command to the Command Prompt
Application.Exit()
End
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'load stuff in background n stuff
Me.Show()
Me.Focus()
Configure.Show()
Configure.Hide()
Status.Show()
Status.Hide()
Console.Show()
Console.Hide()
End Sub
'CONSOLE.form
Private Sub ConsoleToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles ConsoleToolStripMenuItem1.Click
'Hide all forms
Status.Hide()
Configure.Hide()
'Shown Form that you want to load
Console.Opacity = 100
Console.Show()
WindowState = FormWindowState.Normal
Console.MdiParent = Me
Console.OutputTextBox.SelectionStart = Console.OutputTextBox.Text.Length
Console.OutputTextBox.ScrollToCaret()
End Sub
'STATUS.form
Private Sub StatusToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles StatusToolStripMenuItem1.Click
'hide all forms
Console.Hide()
Configure.Hide()
'Show Form that you want to load
Status.Opacity = 100
Status.Show()
WindowState = FormWindowState.Maximized
Configure.Size = Me.Size
Status.MdiParent = Me
End Sub
'CONFIGURE.form
Private Sub ConfigurationToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles ConfigurationToolStripMenuItem1.Click
'hide all forms
Status.Hide()
Console.Hide()
'Show form that you want to load
Configure.Opacity = 100
Configure.Show()
WindowState = FormWindowState.Maximized
Configure.Size = Me.Size
Configure.MdiParent = Me
End Sub
End Class
'code
It seems that your original code to create an embeded CMD window was interfering with the code to update the listbox in another mdi child. After finding another way to embed a cmd console, and some fiddling around, It seems to be working Ok. I haven't been able to test pure server output yet though.
THere have been quite a few changes to the code that are too big to post here, but the Alternative embedded CMD is this.
Place this in general form declarations
'command prompt variables
Private strResults As String
Private intStop As Integer
Private swWriter As System.IO.StreamWriter
Friend thrdCMD As System.Threading.Thread
Private Delegate Sub cmdUpdate()
Private uFin As New cmdUpdate(AddressOf UpdateText)
Public WithEvents procCMDWin As New Process
This in your form_load Sub
thrdCMD = New System.Threading.Thread(AddressOf Prompt)
thrdCMD.IsBackground = True
thrdCMD.Start()
and these declarations within your form Class
Private Sub Prompt()
AddHandler procCMDWin.OutputDataReceived, AddressOf CMDOutput
AddHandler procCMDWin.ErrorDataReceived, AddressOf CMDOutput
procCMDWin.StartInfo.RedirectStandardOutput = True
procCMDWin.StartInfo.RedirectStandardInput = True
procCMDWin.StartInfo.CreateNoWindow = True
procCMDWin.StartInfo.UseShellExecute = False
procCMDWin.StartInfo.FileName = "cmd.exe"
procCMDWin.StartInfo.WorkingDirectory = LocalpathParent
procCMDWin.Start()
procCMDWin.BeginOutputReadLine()
swWriter = procCMDWin.StandardInput
Do Until (procCMDWin.HasExited)
Loop
procCMDWin.Dispose()
End Sub
Private Sub UpdateText()
OutputTextBox.Text += strResults
OutputTextBox.SelectionStart = OutputTextBox.TextLength - 1
InputTextBox.Focus()
intStop = OutputTextBox.SelectionStart
OutputTextBox.ScrollToCaret()
If OutputTextBox.Lines.Count > 2 Then
LastLine = OutputTextBox.Lines.ElementAt(OutputTextBox.Lines.Count - 2)
If Status.ServerStarted = True Then
'get element 1 of split
If LastLine.Contains(" joined the game") Then
LastLineFormatted = ExtractName(LastLine, " joined the game")
'If listlineformatted.contains(Players.allitems) then do
Status.txtPlayersList.Items.Add(LastLineFormatted)
Status.Show()
ElseIf Me.LastLine.Contains(" left the game") Then
LastLineFormatted = ExtractName(LastLine, " left the game")
'If listlineformatted.contains(Players.allitems) then do
Status.txtPlayersList.Items.Remove(LastLineFormatted)
MsgBox("remove lastlineformatted")
End If
End If
End If
End Sub
Private Function ExtractName(unformattedString As String, stringToRemove As String) As String
Dim temp As String = Split(unformattedString, "Server]")(1).ToString
ExtractName = temp.Replace(stringToRemove, "")
End Function
Private Sub CMDOutput(ByVal Sender As Object, ByVal OutputLine As DataReceivedEventArgs)
strResults = OutputLine.Data & Environment.NewLine
Invoke(uFin)
End Sub

BackgroundWorker's ProgressChanged not updating UI until end of work loop

I am coding a WPF application that will grab email's off of an IMAP account, and then export them into a user-selected folder.
I use a BackgroundWorker to download the emails. However, my UI isn't being updated until the loop is over.
Any tips would be appreciated.
Class MainWindow
Public MailRepo As MailRepository
Private bw_Connect As New BackgroundWorker
Private bw_Save As New BackgroundWorker
Public Sub New()
InitializeComponent()
bw_Connect.WorkerReportsProgress = True
bw_Connect.WorkerSupportsCancellation = True
AddHandler bw_Connect.DoWork, AddressOf bw_Connect_DoWork
bw_Save.WorkerReportsProgress = True
bw_Save.WorkerSupportsCancellation = True
AddHandler bw_Save.DoWork, AddressOf bw_Save_DoWork
AddHandler bw_Save.ProgressChanged, AddressOf bw_Save_ProgressChanged
End Sub
Private Sub bw_Save_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
If bw_Connect.CancellationPending = True Then
e.Cancel = True
Else
SaveEmails()
End If
End Sub
Private Sub SaveEmails()
Dim allMails As IEnumerable(Of Message)
'Get All Emails in Mailbox
Try
Dim mailBox As String
Dispatcher.Invoke(DirectCast(Sub()
mailBox = comboBoxEmailFolders.SelectedValue
End Sub, Action))
allMails = MailRepo.GetAllMails(mailBox)
Catch i4e As Imap4Exception
MsgBox("Error: Folder not found" & vbCrLf & i4e.Message)
Return
End Try
Dim msg As Message
Dim msgInt As Integer = 1
'Save each message
For Each msg In allMails
bw_Save.ReportProgress(100 / allMails.Count * msgInt, Nothing)
SaveMessage(msg)
msgInt += 1
Next
End Sub
Private Sub bw_Save_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs)
Dim percentDone As String = e.ProgressPercentage.ToString() & "%"
updateStatus("Saving Emails " & percentDone & " done.")
progressBarStatus.Value = e.ProgressPercentage
End Sub

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

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