VB.Net Background Workers in my code? - vb.net

I am a bit of a noobie with vb.net and I made this application that does a lot of http requests and stream reading. But when it does this it always freezes my application.
So I did a little research and found that I could use background workers to solve this. But I have no idea where to start. So if you could look at my code and tell me where and how I can add background workers to prevent the freezing that would be awesome.
Imports mshtml
Imports System.Net
Imports System.Threading
Imports System.Text
Imports System.IO
Imports System.Web
Public Class Form1
Inherits Form
Private Delegate Sub MyDelegate(show As Boolean)
Private demoThread As System.Threading.Thread = Nothing
Private demoThread2 As System.Threading.Thread = Nothing
Private Sub ShowProgressOnThread()
Dim newProgressWindow As New Form2
newProgressWindow.Show()
End Sub
Public Function GetTableText(ByVal sHTML As String) As String
Dim myDoc As mshtml.IHTMLDocument2 = New mshtml.HTMLDocument
Dim mElement As mshtml.IHTMLElement
Dim mElement2 As mshtml.IHTMLElement
Dim mECol As mshtml.IHTMLElementCollection
'initialize the document object within the HTMLDocument class...
myDoc.close()
myDoc.open("about:blank")
'write the HTML to the document using the MSHTML "write" method...
Dim clsHTML() As Object = {sHTML}
myDoc.write(clsHTML)
clsHTML = Nothing
mElement = myDoc.body()
mECol = mElement.getElementsByTagName("TD")
Dim gData As ListViewItem
For A = 3 To mECol.length - 1 Step +6
mElement2 = mECol.item(A)
gData = Me.ListView1.Items.Add(mElement2.innerText)
mElement2 = mECol.item(A - 1)
gData.SubItems.Add(mElement2.innerText.ToUpper)
'Frm.Close()
' lstResults.Items.Add("Game : " & mElement2.innerText)
Next
End Function
Private Sub wait(ByVal interval As Integer)
Dim sw As New Stopwatch
sw.Start()
Do While sw.ElapsedMilliseconds < interval
' Allows UI to remain responsive
Application.DoEvents()
Loop
sw.Stop()
End Sub
Private Sub Button__()
Me.ResetText()
Me.ToolStripStatusLabel1.Text = "Loading..."
Me.Text = "Game Finder | By Unh0ly | Loading..."
' Me.demoThread = New Thread( _
'New ThreadStart(AddressOf Me.Loader))
' Me.demoThread.Start()
'Me.Invoke(New MethodInvoker(AddressOf Me.Loader))
'Me.Frm.Show()
'Application.Run(Frm)
Dim srchText As String
srchText = TextBox1.Text.Replace(" ", "%20")
Dim request As HttpWebRequest = HttpWebRequest.Create("****" & srchText)
'Dim response As HttpWebResponse
Dim response As HttpWebResponse = request.GetResponse()
Dim sr As System.IO.StreamReader = New System.IO.StreamReader(response.GetResponseStream())
Dim sourcecode As String = sr.ReadToEnd()
If sourcecode.Contains("<td>") Then
GetTableText(sourcecode)
Me.ResetText()
Me.Text = "Game Finder | By Unh0ly"
Me.ToolStripStatusLabel1.Text = "Done"
Call wait(2500)
Me.ToolStripStatusLabel1.Text = "Status.."
'newProgressWindow.Hide()
'newProgressWindow.Dispose()
'Form2.Refresh()
ElseIf Not sourcecode.Contains("<td>") Then
' newProgressWindow.Hide()
' Progress.Dispose()
MessageBox.Show("No Results Found For: " + TextBox1.Text)
End If
'Dim sHTML = sourcecode
'For I = 2 To mECol.length - 1 Step +6
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
'Frm.Show()
Me.Invoke(New MethodInvoker(AddressOf Button__))
'Dim demoThread As System.Threading.Thread
End Sub
Private Sub CopyToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles CopyToolStripMenuItem.Click, IDAndGameNameToolStripMenuItem.Click
Try
Dim s As String
Dim lsvrow
lsvrow = ListView1.SelectedItems(0)
s = "Game Name: " + lsvrow.Text + ControlChars.NewLine + "ID: " + TextBox2.Text
Clipboard.SetDataObject(s)
Catch ex As System.Exception
MessageBox.Show("Error: " + ex.Message)
Finally
' Perform any tidy up code.
End Try
End Sub
Private Sub CopyIDToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles CopyIDToolStripMenuItem.Click, IDToolStripMenuItem.Click
Try
Dim s As String
Dim lsvrow
lsvrow = ListView1.SelectedItems(0)
s = TextBox2.Text
Clipboard.SetDataObject(s)
Catch ex As System.Exception
MessageBox.Show("Error: " + ex.Message)
Finally
' Perform any tidy up code.
End Try
End Sub
Private Sub ListView1_ItemActivate(sender As System.Object, e As System.Windows.Forms.ListViewItemSelectionChangedEventArgs) Handles ListView1.ItemSelectionChanged
TextBox2.Text = e.Item.SubItems(1).Text
End Sub
Private Sub TextBox1_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
If e.KeyCode = Keys.Enter Then
'Runs the Button1_Click Event
Button1_Click(Me, EventArgs.Empty)
End If
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click, ClearToolStripMenuItem.Click
ListView1.Items.Clear()
End Sub
Private Sub DownloadGPDToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles DownloadGPDToolStripMenuItem.Click, DownloadGPDToolStripMenuItem1.Click
Dim gpds As ArrayList = New ArrayList()
Const YOUR_DIRECTORY As String = "****"
' Get the object used to communicate with the server.
Dim request As FtpWebRequest = CType(WebRequest.Create(YOUR_DIRECTORY), FtpWebRequest)
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails
' This example assumes the FTP site uses anonymous logon.
request.Credentials = New NetworkCredential("****", "****")
Call wait(1500)
Dim response As FtpWebResponse = CType(request.GetResponse, FtpWebResponse)
Dim responseStream As Stream = response.GetResponseStream
Dim reader As StreamReader = New StreamReader(responseStream)
Dim s = reader.ReadToEnd
reader.Close()
response.Close()
If Len(TextBox2.Text) > 0 Then
If s.Contains(TextBox2.Text + ".gpd") Then
FolderBrowserDialog1.ShowDialog()
If Not FolderBrowserDialog1.SelectedPath = Nothing Then
Me.Text = "Game Finder | By Unh0ly | Downloading..."
Me.ToolStripStatusLabel1.Text = "Downloading..."
My.Computer.Network.DownloadFile("****" + TextBox2.Text + ".gpd", FolderBrowserDialog1.SelectedPath + "\" + TextBox2.Text + ".gpd", "", "", False, "100", True)
Me.ResetText()
Me.ToolStripStatusLabel1.Text = "Status.."
ElseIf FolderBrowserDialog1.SelectedPath = Nothing Then
Else
MessageBox.Show("No GPD for Selected Game")
End If
Else
MessageBox.Show("No GPD for Selected Game")
End If
Else
' Do Nothing
End If
End Sub
Private Sub ExitToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles ExitToolStripMenuItem.Click
Application.Exit()
End Sub
Private Sub CheckForUpdatesToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles CheckForUpdatesToolStripMenuItem.Click
Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create("****")
Dim response As System.Net.HttpWebResponse = request.GetResponse()
Dim sr As System.IO.StreamReader = New System.IO.StreamReader(response.GetResponseStream())
Dim newestversion As String = sr.ReadToEnd()
Dim currentversion As String = Application.ProductVersion
Dim request1 As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create("****")
Dim response1 As System.Net.HttpWebResponse = request1.GetResponse()
Dim sr1 As System.IO.StreamReader = New System.IO.StreamReader(response1.GetResponseStream())
Dim updurl As String = sr1.ReadToEnd()
If newestversion.Contains(currentversion) Then
MessageBox.Show("You have the current version", "Up to date", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
Dim result1 As DialogResult = MessageBox.Show("Newer version available" & vbCrLf & "Please Goto *** to check" + vbCrLf + "Do you want to go there now?", "Update Available", MessageBoxButtons.YesNo, MessageBoxIcon.Information)
If result1 = DialogResult.Yes Then
Process.Start(updurl)
Else
' Do Nothing
End If
End If
End Sub
Private Sub AboutToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles AboutToolStripMenuItem.Click
Dim gpds As ArrayList = New ArrayList()
Const YOUR_DIRECTORY As String = "****"
Dim request As FtpWebRequest = CType(WebRequest.Create(YOUR_DIRECTORY), FtpWebRequest)
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails
request.Credentials = New NetworkCredential("****", "****")
Call wait(100)
Dim response As FtpWebResponse = CType(request.GetResponse, FtpWebResponse)
Dim responseStream As Stream = response.GetResponseStream
Dim reader As StreamReader = New StreamReader(responseStream)
Dim s = reader.ReadToEnd
reader.Close()
response.Close()
Dim Lines() As String = s.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
MessageBox.Show("Made By Unh0ly aka Nickdudego3" & vbCrLf & "Number of GPD's: " & Lines.Length - 5 & vbCrLf & "Version: " & Application.ProductVersion, "About", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
End Sub
End Class

Here's a small sample how to use a worker..
Friend WithEvents myWorker As System.ComponentModel.BackgroundWorker
Me.myWorker = New System.ComponentModel.BackgroundWorker()
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
myWorker.RunWorkerAsync()
End Sub
Private Sub myWorker_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles myWorker.DoWork
'do your stuff here...
End Sub

The best way to find bottle neck in your code is to put Timer.Start and Timer.Stop around your methods to find out which methods are taking the longest to excute.
Once you find the offending methods, you can use ThreadPool.QueueUserWorkItem to implement a basic background threading. Threading is by no means easy and it would take some time for you figure it out all the crazy and weird things that happen when you play with threads.
Hope this helps. If you have any more question, do ask.

Related

How to get ipv4 addresses of all computers on a network in VB.NET

I have a Windows Forms app in Visual basic that is currently sending messages back and forth between two computers. Currently, the user has to manually enter the ipv4 address of the receiver of the message. what I would like to do is put the ipv4 addresses of all the computers on the network into a combo box so the user has a list to pick from.
I have searched a whole bunch of different forums and am unable to find a working solution.
Public Class Form1
Dim strHostName As String
Dim strIPAddress As String
Dim running As Boolean = False
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
strHostName = System.Net.Dns.GetHostName()
strIPAddress = System.Net.Dns.GetHostByName(strHostName).AddressList(0).ToString()
Me.Text = strIPAddress
txtIP.Text = strIPAddress
running = True
'run listener on separate thread
Dim listenTrd As Thread
listenTrd = New Thread(AddressOf StartServer)
listenTrd.IsBackground = True
listenTrd.Start()
End Sub
Private Sub Form1_FormClosing(sender As Object, e As EventArgs) Handles MyBase.FormClosing
running = False
End Sub
Sub StartServer()
Dim serverSocket As New TcpListener(CInt(txtPort.Text))
Dim requestCount As Integer
Dim clientSocket As TcpClient
Dim messageReceived As Boolean = False
While running
messageReceived = False
serverSocket.Start()
msg("Server Started")
clientSocket = serverSocket.AcceptTcpClient()
msg("Accept connection from client")
requestCount = 0
While (Not (messageReceived))
Try
requestCount = requestCount + 1
Dim networkStream As NetworkStream = clientSocket.GetStream()
Dim bytesFrom(10024) As Byte
networkStream.Read(bytesFrom, 0, bytesFrom.Length)
Dim dataFromClient As String = System.Text.Encoding.ASCII.GetString(bytesFrom)
dataFromClient = dataFromClient.Substring(0, dataFromClient.Length)
'invoke into other thread
txtOut.Invoke(Sub()
txtOut.Text += dataFromClient
txtOut.Text += vbNewLine
End Sub)
messageReceived = True
Dim serverResponse As String = "Server response " + Convert.ToString(requestCount)
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(serverResponse)
networkStream.Write(sendBytes, 0, sendBytes.Length)
networkStream.Flush()
Catch ex As Exception
End
End Try
End While
clientSocket.Close()
serverSocket.Stop()
msg("exit")
Console.ReadLine()
End While
End Sub
Sub msg(ByVal mesg As String)
mesg.Trim()
Console.WriteLine(" >> " + mesg)
End Sub
Public Sub WriteData(ByVal data As String, ByRef IP As String)
Try
txtOut.Text += data.PadRight(1)
txtOut.Text += vbNewLine
txtMsg.Clear()
Console.WriteLine("Sending message """ & data & """ to " & IP)
Dim client As TcpClient = New TcpClient()
client.Connect(New IPEndPoint(IPAddress.Parse(IP), CInt(txtPort.Text)))
Dim stream As NetworkStream = client.GetStream()
Dim sendBytes As Byte() = Encoding.ASCII.GetBytes(data)
stream.Write(sendBytes, 0, sendBytes.Length)
Catch ex As Exception
msg(ex.ToString)
End Try
End Sub
Private Sub btnSend_Click(sender As Object, e As EventArgs) Handles btnSend.Click
If Not (txtMsg.Text = vbNullString) AndAlso Not (txtIP.Text = vbNullString) Then
WriteData(txtMsg.Text, txtIP.Text)
End If
End Sub
Private Sub txtMsg_KeyDown(sender As Object, e As KeyEventArgs) Handles txtMsg.KeyDown
If e.KeyCode = Keys.Enter Then
If Not (txtMsg.Text = vbNullString) AndAlso Not (txtIP.Text = vbNullString) Then
WriteData(txtMsg.Text, txtIP.Text)
End If
End If
End Sub
Private Sub BtnFind_Click(sender As Object, e As EventArgs) Handles btnFind.Click
'find all local addresses and put in combobox (button will be removed later)
End Sub
End Class
For PC names "as you suggested in your comments", I used this at work to get pc names i was on domain, try it:
AFAIK it works on domains...
Make sure you have a listbox on your form, or change listbox and populate in your combobox directly, play with that as you like :)
Private Delegate Sub UpdateDelegate(ByVal s As String)
Dim t As New Threading.Thread(AddressOf GetNetworkComputers)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
t.IsBackground = True
t.Start()
End Sub
Private Sub AddListBoxItem(ByVal s As String)
ListBox1.Items.Add(s)
End Sub
Private Sub GetNetworkComputers()
Try
Dim alWorkGroups As New ArrayList
Dim de As New DirectoryEntry
de.Path = "WinNT:"
For Each d As DirectoryEntry In de.Children
If d.SchemaClassName = "Domain" Then alWorkGroups.Add(d.Name)
d.Dispose()
Next
For Each workgroup As String In alWorkGroups
de.Path = "WinNT://" & workgroup
For Each d As DirectoryEntry In de.Children
If d.SchemaClassName = "Computer" Then
Dim del As UpdateDelegate = AddressOf AddListBoxItem
Me.Invoke(del, d.Name)
End If
d.Dispose()
Next
Next
Catch ex As Exception
'MsgBox(Ex.Message)
End Try
End Sub
POC:

ProgressBar not updating using a For Each loop

I'm copying all the .avi and .png files from one folder into another:
Private Sub CopierSend_Button_Click(sender As Object, e As EventArgs) Handles CopierSend_Button.Click
If MessageBox.Show("Click OK to send media or just Cancel.", "Media Copier", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) = DialogResult.OK Then
For Each foundFile As String In My.Computer.FileSystem.GetFiles(FrapsFolder_, Microsoft.VisualBasic.FileIO.SearchOption.SearchTopLevelOnly, "*.avi", "*.png")
Dim foundFileInfo As New System.IO.FileInfo(foundFile)
My.Computer.FileSystem.CopyFile(foundFile, DestFolder_ & foundFileInfo.Name, Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)
Next
Else
'Nothing Yet
End If
End Sub
I want to add a ProgressBar which will count every time a file is copied, so I added this code before the For Each loop:
Dim file1() As String = IO.Directory.GetFiles(FrapsFolder_, "*.avi")
Dim file2() As String = IO.Directory.GetFiles(FrapsFolder_, "*.png")
Dim files = file1.Length + file2.Length
Copier_ProgressBar.Step = 1
Copier_ProgressBar.Maximum = files
And added this code inside the For Each loop:
Copier_ProgressBar.Value += 1
Here is all of my code:
Private Sub CopierSend_Button_Click(sender As Object, e As EventArgs) Handles CopierSend_Button.Click
If MessageBox.Show("Click OK to send media or just Cancel.", "Media Copier", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) = DialogResult.OK Then
Dim file1() As String = IO.Directory.GetFiles(FrapsFolder_, "*.avi")
Dim file2() As String = IO.Directory.GetFiles(FrapsFolder_, "*.png")
Dim files = file1.Length + file2.Length
Copier_ProgressBar.Step = 1
Copier_ProgressBar.Maximum = files
For Each foundFile As String In My.Computer.FileSystem.GetFiles(FrapsFolder_, Microsoft.VisualBasic.FileIO.SearchOption.SearchTopLevelOnly, "*.avi", "*.png")
Dim foundFileInfo As New System.IO.FileInfo(foundFile)
My.Computer.FileSystem.CopyFile(foundFile, DestFolder_ & foundFileInfo.Name, Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)
Copier_ProgressBar.Value += 1
Next
Else
'Nothing Yet
End If
End Sub
The ProgressBar updates, but only after all the files have been copied instead of updating in real time. Any idea?
As it stands it looks like the ProgressBar doesn't do anything until after all the files have copied. That isn't strictly true. Instead your UI is not updating.
Instead you should look into using a BackgroundWoker to report progress. Something like this should do the trick:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'This can also be set using the Designer
BackgroundWorker1.WorkerReportsProgress = True
End Sub
Private Sub CopierSend_Button_Click(sender As Object, e As EventArgs) Handles CopierSend_Button.Click
If MessageBox.Show("Click OK to send media or just Cancel.", "Media Copier", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) = DialogResult.OK Then
Dim file1() As String = IO.Directory.GetFiles(FrapsFolder_, "*.avi")
Dim file2() As String = IO.Directory.GetFiles(FrapsFolder_, "*.png")
Dim files As Integer = file1.Length + file2.Length
Copier_ProgressBar.Step = 1
Copier_ProgressBar.Maximum = files
BackgroundWorker1.RunWorkerAsync()
End If
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
For Each foundFile As String In My.Computer.FileSystem.GetFiles(FrapsFolder_, Microsoft.VisualBasic.FileIO.SearchOption.SearchTopLevelOnly, "*.avi", "*.png")
Dim foundFileInfo As New System.IO.FileInfo(foundFile)
My.Computer.FileSystem.CopyFile(foundFile, DestFolder_ & foundFileInfo.Name, Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)
BackgroundWorker1.ReportProgress(Copier_ProgressBar.Value + 1)
Next
End Sub
Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
Copier_ProgressBar.Value = e.ProgressPercentage
End Sub
As an additional note, for best practice, I would consider using Path.Combine instead of concatenating strings together:
My.Computer.FileSystem.CopyFile(foundFile, Path.Combine(DestFolder_, foundFileInfo.Name), Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)

Multi threading webrequests?

I'm programming a tool that'll go through a lot of websites and see if they contain a text that's in a textbox.
Now I wan't to add multi threading so it goes quite a lot faster, most preferably I'd dynamically add threads.
This is my code now but it didn't work because it says index ouf of range. And I doubt it work anyways.
Dim clsThreads As New Generic.List(Of System.Threading.Thread)
Dim numberOfthreads As Integer = 1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For Each strLine1 As String In TextBox1.Text.Split({vbCr, vbLf}, StringSplitOptions.RemoveEmptyEntries)
For Each strLine2 As String In TextBox2.Text.Split({vbCr, vbLf}, StringSplitOptions.RemoveEmptyEntries)
clsThreads(numberOfthreads) = New Thread(Sub() Me.request(strLine1, strLine2))
clsThreads(numberOfthreads).Name = "Thread: " + numberOfthreads.ToString
clsThreads(numberOfthreads).IsBackground = True
clsThreads(numberOfthreads).Start()
numberOfthreads = numberOfthreads + 1
If (numberOfthreads.Equals(20)) Then
numberOfthreads = 0
End If
Next
Next
End Sub
So, how do I implement multi threading in a smart way?
This is my request sub:
Public Sub request(ByVal username, ByVal mail)
Dim req As WebRequest = WebRequest.Create("http://localhost/" + username)
req.Method = "GET"
Dim res As WebResponse = req.GetResponse()
Dim dataStream As Stream = res.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
If responseFromServer.Contains(mail) Then
TextBox3.Text = TextBox3.Text + vbNewLine + username
End If
End Sub
End Class
Something like this?
Option Strict On
Option Explicit On
Option Infer Off
Public Class Form1
Dim ActiveThreads As New List(Of System.Threading.Thread)
Delegate Sub delRemoveThread(thread As Threading.Thread)
Sub removeThread(thread As Threading.Thread)
If Me.InvokeRequired Then
Me.Invoke(New delRemoveThread(AddressOf removeThread), thread)
Else
ActiveThreads.Remove(thread)
End If
End Sub
Private Sub Button1_Click3(sender As Object, e As EventArgs) Handles Button1.Click
For i As Integer = 1 To 20
Dim th As New Threading.Thread(New Threading.ParameterizedThreadStart(Sub()
request("username", "mail")
removeThread(Threading.Thread.CurrentThread)
End Sub))
th.Start()
Next
End Sub
Public Sub request(ByVal username As String, ByVal mail As String)
Dim req As Net.WebRequest = Net.WebRequest.Create("http://localhost/" + username)
req.Method = "GET"
Dim res As Net.WebResponse = req.GetResponse()
Dim dataStream As IO.Stream = res.GetResponseStream()
Dim reader As New IO.StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
If responseFromServer.Contains(mail) Then
TextBox3.Text = TextBox3.Text + vbNewLine + username
End If
End Sub
End Class

Sendmail Attachment Issue in VB.NET

I have a sendmail program in vb.net. I have attachments sending just fine. The problem is when there is NO ATTACHMENT, the program errors out. How do i handle no attachment to bypass and send with no attachment? The below works fine.
Yea yea i know, my naming convention is horrible. I will change once i have the logic 100% complete.
Imports System.Net.Mail
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If TextBox1.Text = "" Then
MsgBox("Please describe the issue you're having Bender, I'm not a mindreader!")
Exit Sub
Else
lblpleasewait.Visible = True
Delay(2000)
Dim Recipients As New List(Of String)
Recipients.Add("emtnap6#yahoo.com")
Dim FromEmailAddress As String = Recipients(0)
Dim Subject As String = "IT Help!"
Dim Body As String = TextBox1.Text
Dim UserName As String = "fakeout"
Dim Password As String = "fakeout"
Dim Port As Integer = 587
Dim Server As String = "smtp.gmail.com"
Dim Attachments As New List(Of String)
MsgBox(SendEmail(Recipients, FromEmailAddress, Subject, Body, UserName, Password, Server, Port, Attachments))
TextBox2.Text = "Attach Screenshot:"
TextBox2.TextAlign = HorizontalAlignment.Right
lblpleasewait.Visible = False
TextBox1.Text = ""
TextBox1.Focus()
End If
End Sub
Sub delay(ByVal delay_ms As Integer)
Dim tspan As New TimeSpan
Dim tstart = Now
While tspan.TotalMilliseconds < delay_ms
tspan = Now - tstart
Application.DoEvents()
End While
End Sub
Function SendEmail(ByVal Recipients As List(Of String), _
ByVal FromAddress As String, _
ByVal Subject As String, _
ByVal Body As String, _
ByVal UserName As String, _
ByVal Password As String, _
Optional ByVal Server As String = "smtp.gmail.com", _
Optional ByVal Port As Integer = 587, _
Optional ByVal Attachments As List(Of String) = Nothing) As String
Dim Email As New MailMessage()
Try
Dim SMTPServer As New SmtpClient
''For Each Attachment As String In Attachments
'' Email.Attachments.Add(New Attachment(Attachment))
'Next
Dim mailattach As String = TextBox2.Text
Dim attachment As System.Net.Mail.Attachment
attachment = New System.Net.Mail.Attachment(mailattach)
Email.Attachments.Add(attachment)
Email.From = New MailAddress(FromAddress)
For Each Recipient As String In Recipients
Email.Bcc.Add(Recipient)
Next
Email.Subject = Subject
Email.Body = Body
SMTPServer.Host = Server
SMTPServer.Port = Port
SMTPServer.Credentials = New System.Net.NetworkCredential(UserName, Password)
SMTPServer.EnableSsl = True
SMTPServer.Send(Email)
Email.Dispose()
Return "Email to Derek was successfully sent."
Catch ex As SmtpException
Email.Dispose()
Return "Sending Email Failed. Smtp Error."
Catch ex As ArgumentOutOfRangeException
Email.Dispose()
Return "Sending Email Failed. Check Port Number."
Catch Ex As InvalidOperationException
Email.Dispose()
Return "Sending Email Failed. Check Port Number."
End Try
End Function
Private Sub FolderBrowserDialog1_HelpRequest(sender As Object, e As EventArgs)
If (FolderBrowserDialog1.ShowDialog() = Windows.Forms.DialogResult.OK) Then
TextBox2.Text = FolderBrowserDialog1.SelectedPath
End If
End Sub
Private Sub Button2_Click(sender As Object, e As System.EventArgs) Handles Button2.Click
OpenFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
If (OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK) Then
TextBox2.Text = OpenFileDialog1.FileName
End If
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Focus()
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
If Not Environment.Is64BitProcess Then
Process.Start("C:\Windows\sysnative\SnippingTool.exe")
Else
Process.Start("C:\Windows\system32\SnippingTool.exe")
End If
End Sub
Private Sub OpenFileDialog1_FileOk(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
OpenFileDialog1.InitialDirectory = Environment.SpecialFolder.MyComputer
End Sub
End Class
This should solve the problem.
If TextBox2.text <> "" then
Dim mailattach As String = TextBox2.Text
Dim attachment As System.Net.Mail.Attachment
attachment = New System.Net.Mail.Attachment(mailattach)
Email.Attachments.Add(attachment)
End if

How to add BackgroundWorker for this code?

I've the following code, it's a code that parses an external Log file to a datagridview, however when I load a big file the operation takes time and the form freezes for a bit, what I need is to show a progress bar while it's parsing the log file.
This is the code :
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Using Reader As New Microsoft.VisualBasic.FileIO.
TextFieldParser(TextBox1.Text)
Reader.TextFieldType =
Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
Reader.SetFieldWidths(Convert.ToInt32(txtDate.Text), Convert.ToInt32(txtTime.Text), Convert.ToInt32(txtExt.Text), Convert.ToInt32(txtCO.Text), _
Convert.ToInt32(txtNumber.Text), Convert.ToInt32(txtDuration.Text), Convert.ToInt32(txtAccCode.Text))
Dim currentRow As String()
While Not Reader.EndOfData
Try
currentRow = Reader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
Dim curRowIndex = dg1.Rows.Add()
' Set the first cell of the new row....
dg1.Rows(curRowIndex).Cells(0).Value = currentRow(0)
dg1.Rows(curRowIndex).Cells(1).Value = currentRow(1)
dg1.Rows(curRowIndex).Cells(2).Value = currentRow(2)
dg1.Rows(curRowIndex).Cells(3).Value = currentRow(3)
dg1.Rows(curRowIndex).Cells(4).Value = currentRow(4)
dg1.Rows(curRowIndex).Cells(5).Value = currentRow(5)
dg1.Rows(curRowIndex).Cells(6).Value = currentRow(6)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
"is not valid and will be skipped.")
End Try
End While
MsgBox("Total records imported : " & dg1.RowCount)
lblTotal.Text = "Total Records: " & dg1.RowCount
End Using
Catch
MsgBox("Invalid file, please make sure you entered the right path")
End Try
End Sub
Add a BackgroundWorker and set its WorkerReportsProgressProperty to True.
Add a ProgressBar.
Then try this code out:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim widths() As Integer = { _
Convert.ToInt32(txtDate.Text), Convert.ToInt32(txtTime.Text), Convert.ToInt32(txtExt.Text), _
Convert.ToInt32(txtCO.Text), Convert.ToInt32(txtNumber.Text), Convert.ToInt32(txtDuration.Text), _
Convert.ToInt32(txtAccCode.Text)}
ProgressBar1.Visible = True
ProgressBar1.Style = ProgressBarStyle.Marquee ' continuos animation
Dim input As New Tuple(Of String, Integer())(TextBox1.Text, widths)
BackgroundWorker1.RunWorkerAsync(input)
Catch ex As Exception
MessageBox.Show("Invalid Width!")
End Try
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim input As Tuple(Of String, Integer()) = DirectCast(e.Argument, Tuple(Of String, Integer()))
Try
Using Reader As New Microsoft.VisualBasic.FileIO.TextFieldParser(input.Item1)
Reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
Reader.SetFieldWidths(input.Item2)
Dim currentRow() As String
While Not Reader.EndOfData
Try
currentRow = Reader.ReadFields()
BackgroundWorker1.ReportProgress(-1, New Object() { _
currentRow(0), currentRow(1), currentRow(2), _
currentRow(3), currentRow(4), currentRow(5), _
currentRow(6)})
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MessageBox.Show("Line is not valid and will be skipped." & vbCrLf & vbCrLf & ex.Message)
End Try
End While
End Using
Catch
MsgBox("Invalid file, please make sure you entered the right path")
End Try
End Sub
Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
Dim values() As Object = DirectCast(e.UserState, Object())
dg1.Rows.Add(values)
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
MessageBox.Show("Total records imported : " & dg1.RowCount)
lblTotal.Text = "Total Records: " & dg1.RowCount
ProgressBar1.Style = ProgressBarStyle.Continuous
ProgressBar1.Visible = False
End Sub