File synchronization Visual Studio 2015 error - vb.net

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.

Related

How to download multiple files in list box using 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

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:

Increasing memory usage while scrolling on listview items in vb.net

In a WinForm i have two listview(lvwTemplateCategory) one is listing folders at given directory and if you select folder, other listview(lvwTemplates) shows the files under this directory. I have also one picturebox(picTemplateImage) to show preview screenshot of that file.
While i'm scrolling on that form for 2-3 folders and 9-10 files it's memory usage goes from 62 MB to 120 MB.
I don't know how to manage the memory source also i tried to implement IDisposable but not know where to implement.
P.S. I'm using VS 2017 and calling that WinForm with .Show() method.
Also if you see non-logic codes please let me know.
Option Explicit On
Option Strict On
Imports System.IO
Public Class frmCreateNewModel
Implements IDisposable
Private Sub LoadForm(sender As Object, e As EventArgs) Handles MyBase.Load
Call AddRootDatabase()
splCreateNewModel.Panel2Collapsed = True
Size = New Size(946, 800)
End Sub
Private Sub ViewLargeIcons(sender As Object, e As EventArgs) Handles cmdViewLargeIcons.Click
lvwTemplateCategory.View = View.LargeIcon
End Sub
Private Sub ViewListIcons(sender As Object, e As EventArgs) Handles cmdViewList.Click
lvwTemplateCategory.View = View.List
End Sub
Private Sub AddRootDatabase()
Try
Dim DirDB As String = My.Settings.str_db__path_tpl
Dim DirInfoDB As New DirectoryInfo(DirDB)
For Each TplDirDB As DirectoryInfo In DirInfoDB.GetDirectories
If Not (TplDirDB.Attributes And FileAttributes.Hidden) = FileAttributes.Hidden Then
cboTemplateDatabase.Items.Add(TplDirDB.Name)
End If
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub SelectRootDatabase(sender As Object, e As EventArgs) Handles cboTemplateDatabase.SelectedIndexChanged
Try
lvwTemplateCategory.Items.Clear()
lvwTemplates.Items.Clear()
Dim DirTempRootDir As String = My.Settings.str_db__path_tpl & "\" & cboTemplateDatabase.SelectedItem.ToString
Dim DirTempDbInfo As New DirectoryInfo(DirTempRootDir)
Dim lstIcon As Integer
For Each TplCatDir As DirectoryInfo In DirTempDbInfo.GetDirectories
If Not (TplCatDir.Attributes And FileAttributes.Hidden) = FileAttributes.Hidden Then
If imgIcons.Images.ContainsKey(TplCatDir.Name) = True Then
lstIcon = imgIcons.Images.IndexOfKey(TplCatDir.Name)
Else
lstIcon = imgIcons.Images.IndexOfKey("default")
End If
lvwTemplateCategory.Items.Add(TplCatDir.Name, lstIcon)
End If
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub SelectTemplateCategory(sender As Object, e As EventArgs) Handles lvwTemplateCategory.SelectedIndexChanged
If (CInt(lvwTemplateCategory.SelectedItems.Count.ToString) = 0) Then
Return
End If
Dim DirTempCatDir As String = My.Settings.str_db__path_tpl & "\" & cboTemplateDatabase.SelectedItem.ToString & "\" & lvwTemplateCategory.SelectedItems(0).Text.ToString
Dim DirTempInfo As New DirectoryInfo(DirTempCatDir)
lvwTemplates.Items.Clear()
Try
For Each TplFile As FileInfo In DirTempInfo.GetFiles
If Not (TplFile.Attributes And FileAttributes.Hidden) = FileAttributes.Hidden Then
If Path.GetExtension(TplFile.Name) = ".spck" Or Path.GetExtension(TplFile.Name) = ".buspck" Then
lvwTemplates.Items.Add(TplFile.Name)
End If
End If
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub SelectTemplate(sender As Object, e As EventArgs) Handles lvwTemplates.SelectedIndexChanged
If (CInt(lvwTemplates.SelectedItems.Count.ToString) = 0) Then
cmdQuickConfigure.Enabled = False
Return
End If
cmdQuickConfigure.Enabled = True
Dim TemplFileName As String = Path.GetFileNameWithoutExtension(lvwTemplates.SelectedItems(0).Text.ToString)
Dim DirTempDir As String = My.Settings.str_db__path_tpl & "\" & cboTemplateDatabase.SelectedItem.ToString & "\" & lvwTemplateCategory.SelectedItems(0).Text.ToString & "\" & TemplFileName
Dim imagePath As String = DirTempDir & ".png"
If File.Exists(imagePath) Then
picTemplateImage.ImageLocation = (imagePath)
picTemplateImage.SizeMode = PictureBoxSizeMode.StretchImage
picTemplateImage.Load()
Else
picTemplateImage.Image = picTemplateImage.ErrorImage
End If
txtModelName.Text = lvwTemplates.SelectedItems(0).Text.ToString
End Sub
Private Sub VisualViewControl(sender As Object, e As EventArgs) Handles cmdVisualControl.Click
If splCreateNewModel.Panel2Collapsed = False Then
splCreateNewModel.Panel2Collapsed = True
Size = New Size(946, 800)
cmdVisualControl.Text = ">>"
Else
cmdVisualControl.Text = "<<"
splCreateNewModel.Panel2Collapsed = False
Size = New Size(1300, 800)
End If
End Sub
Private Sub BrowseDirectory(sender As Object, e As EventArgs) Handles cmdBrowseDirectory.Click
Try
Dim sfd As New SelectFolderDialog With {
.Title = "Select a folder"
}
If sfd.ShowDialog(Me) = DialogResult.OK Then
txtModelDirectory.Text = sfd.FolderName
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub DialogOK(sender As Object, e As EventArgs) Handles cmdOk.Click
CreateModel()
Close()
End Sub
Private Sub DialogCancel(sender As Object, e As EventArgs) Handles cmdCancel.Click
Close()
End Sub
End Class

How to save all items listed on listbox with my.settings

I Try to save all the items from a list box with MY.SETTINGS
And Retrieved again on load
But it seems i made an error but i cannot figure out what.
its give 2 error
This is the errors
Error 3 'itemmd5' is not a member of 'MediaAdsAntivirus.My.MySettings'.
Error 2 'myitems' is not a member of 'MediaAdsAntivirus.My.MySettings'.
For this errors i just figure out i forgot to add it on settings
but now i just have a new error
This Is My New Error
Error 2 Value of type 'System.Windows.Forms.ListBox.ObjectCollection' cannot be converted to 'String'.
And i need to load them on loadfrom
How Can I List All Items Again In To It
This Is My Code:
Imports System.IO
Imports System.Security
Imports System.Security.Cryptography
Imports System.Text
Imports System.Net
Public Class form15
Dim md5hashindexer = 1
Dim md5namesave = "Hashes"
#Region "Atalhos para o principal hash_generator função"
Function md5_hash(ByVal file_name As String)
Return hash_generator("md5", file_name)
End Function
Function sha_1(ByVal file_name As String)
Return hash_generator("sha1", file_name)
End Function
Function sha_256(ByVal file_name As String)
Return hash_generator("sha256", file_name)
End Function
#End Region
Function hash_generator(ByVal hash_type As String, ByVal file_name As String)
Dim hash
If hash_type.ToLower = "md5" Then
hash = MD5.Create
ElseIf hash_type.ToLower = "sha1" Then
hash = SHA1.Create()
ElseIf hash_type.ToLower = "sha256" Then
hash = SHA256.Create()
Else
MsgBox("Type de hash inconnu : " & hash_type, MsgBoxStyle.Critical)
Return False
End If
Dim hashValue() As Byte
Dim fileStream As FileStream = File.OpenRead(file_name)
fileStream.Position = 0
hashValue = hash.ComputeHash(fileStream)
Dim hash_hex = PrintByteArray(hashValue)
fileStream.Close()
Return hash_hex
End Function
Public Function PrintByteArray(ByVal array() As Byte)
Dim hex_value As String = ""
Dim i As Integer
For i = 0 To array.Length - 1
hex_value += array(i).ToString("X2")
Next i
Return hex_value.ToLower
End Function
Private Sub BT_Parcourir_Click(sender As System.Object, e As System.EventArgs) Handles BT_Parcourir.Click
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim path As String = OpenFileDialog1.FileName
TB_path.Text = path
LB_md5.Text = md5_hash(path)
LB_sha1.Text = sha_1(path)
LB_sha256.Text = sha_256(path)
ListBox1.Items.Add(LB_md5.Text)
ListBox1.SelectedIndex += 1
Dim itemmd5 = LB_sha256.Text
Dim itemname = md5namesave + md5hashindexer
For Each line As String In ListBox1.Items
itemmd5 = My.Settings.myitems
My.Settings.itemmd5 = ListBox1.Items
Next
End If
End Sub
Private Sub LB_sha256_Click(sender As Object, e As EventArgs) Handles LB_sha256.Click
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs)
End Sub
Private Sub form15_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
End Class
I finally decide to save in txt file and load The data again from it
This Is The Working Code
Imports System.IO
Imports System.Security
Imports System.Security.Cryptography
Imports System.Text
Imports System.Net
Public Class form15
Dim md5hashindexer = 1
#Region "Atalhos para o principal hash_generator função"
Function md5_hash(ByVal file_name As String)
Return hash_generator("md5", file_name)
End Function
Function sha_1(ByVal file_name As String)
Return hash_generator("sha1", file_name)
End Function
Function sha_256(ByVal file_name As String)
Return hash_generator("sha256", file_name)
End Function
#End Region
Function hash_generator(ByVal hash_type As String, ByVal file_name As String)
Dim hash
If hash_type.ToLower = "md5" Then
hash = MD5.Create
ElseIf hash_type.ToLower = "sha1" Then
hash = SHA1.Create()
ElseIf hash_type.ToLower = "sha256" Then
hash = SHA256.Create()
Else
MsgBox("Type de hash inconnu : " & hash_type, MsgBoxStyle.Critical)
Return False
End If
Dim hashValue() As Byte
Dim fileStream As FileStream = File.OpenRead(file_name)
fileStream.Position = 0
hashValue = hash.ComputeHash(fileStream)
Dim hash_hex = PrintByteArray(hashValue)
fileStream.Close()
Return hash_hex
End Function
Public Function PrintByteArray(ByVal array() As Byte)
Dim hex_value As String = ""
Dim i As Integer
For i = 0 To array.Length - 1
hex_value += array(i).ToString("X2")
Next i
Return hex_value.ToLower
End Function
Private Sub BT_Parcourir_Click(sender As System.Object, e As System.EventArgs) Handles BT_Parcourir.Click
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim path As String = OpenFileDialog1.FileName
TB_path.Text = path
LB_md5.Text = md5_hash(path)
LB_sha1.Text = sha_1(path)
LB_sha256.Text = sha_256(path)
ListBox1.Items.Add(LB_md5.Text)
ListBox1.SelectedIndex += 1
Dim itemmd5 = LB_sha256.Text
'For Each line As String In ListBox1.Items
'My.Settings.itemsmd5 = itemmd5
'md5hashindexer += 1
'Next
End If
Dim sb As New System.Text.StringBuilder()
For Each o As Object In ListBox1.Items
sb.AppendLine(o)
Next
System.IO.File.WriteAllText("c:\checkedfilesmd5.txt", sb.ToString())
End Sub
Private Sub LB_sha256_Click(sender As Object, e As EventArgs) Handles LB_sha256.Click
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs)
End Sub
Private Sub form15_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim lines() As String = IO.File.ReadAllLines("c:\checkedfilesmd5.txt")
ListBox1.Items.AddRange(lines)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim sb As New System.Text.StringBuilder()
For Each o As Object In ListBox1.Items
sb.AppendLine(o)
Next
System.IO.File.WriteAllText("c:\checkedfilesmd5.txt", sb.ToString())
MsgBox("Dados Guardados")
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim lines() As String = IO.File.ReadAllLines("c:\checkedfilesmd5.txt")
ListBox1.Items.AddRange(lines)
End Sub
Private Sub Label6_Click(sender As Object, e As EventArgs) Handles Label6.Click
ListBox1.Items.Clear()
End Sub
Private Sub Label7_Click(sender As Object, e As EventArgs) Handles Label7.Click
MsgBox("Atençao Voce Vai Apagar Todos Os Dados Ja Escaneados")
ListBox1.Items.Clear()
System.IO.File.Delete("c:\checkedfilesmd5.txt")
End Sub
End Class

VB.Net Background Workers in my code?

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.