Increasing memory usage while scrolling on listview items in vb.net - 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

Related

How To Fetch Webpage Source simultaneously from thousands of URLs

I am attempting to load thousands of URLs into a list, then simultaneously download the webpage source of all of those URLs. I thought I had a clear understanding of how to accomplish this but it seems that the process goes 1 by 1 (which is painstakingly slow).
Is there a way to make this launch all of these URLs at once, or perhaps more than 1 at a time?
Public Partial Class MainForm
Dim ImportList As New ListBox
Dim URLList As String
Dim X1 As Integer
Dim CurIndex As Integer
Public Sub New()
Me.InitializeComponent()
End Sub
Sub MainFormLoad(sender As Object, e As EventArgs)
Try
Dim lines() As String = IO.File.ReadAllLines("C:\URLFile.txt")
ImportList.Items.AddRange(lines)
Catch ex As Exception
MessageBox.Show(ex.ToString)
Finally
label1.Text = "File Loaded"
X1 = ImportList.Items.Count
timer1.Enabled = True
If Not backgroundWorker1.IsBusy Then
backgroundWorker1.RunWorkerAsync()
End If
End Try
End Sub
Sub BackgroundWorker1DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs)
URLList = ""
For Each item As String In ImportList.Items
CheckName(item)
CurIndex = CurIndex + 1
Next
End Sub
Sub BW1_Completed()
timer1.Enabled = False
label1.Text = "Done"
End Sub
Sub CheckName(ByVal CurUrl As String)
Dim RawText As String
Try
RawText = New System.Net.WebClient().DownloadString(CurUrl)
Catch ex As Exception
MessageBox.Show(ex.ToString)
Finally
If RawText.Contains("404") Then
If URLList = "" Then
URLList = CurUrl
Else
URLList = URLList & vbCrLf & CurUrl
End If
End If
End Try
End Sub
Sub Timer1Tick(sender As Object, e As EventArgs)
label1.Text = CurIndex.ToString & " of " & X1.ToString
If Not URLList = "" Then
textBox1.Text = URLList
End If
End Sub
Sub Button1Click(sender As Object, e As EventArgs)
Clipboard.Clear
Clipboard.SetText(URLList)
End Sub
End Class

How to delete a file used by another Process

Public Class frmMainCetegory
Private Sub frmMainCetegory_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'PosDatabaseDataSet.tblItemMainCategory' table. You can move, or remove it, as needed.
Me.TblItemMainCategoryTableAdapter.Fill(Me.PosDatabaseDataSet.tblItemMainCategory)
Me.CenterToParent()
Me.btnAddNew.Select()
End Sub
Private Sub btnAddNew_Click(sender As Object, e As EventArgs) Handles btnAddNew.Click
Try
Me.TblItemMainCategoryBindingSource.AddNew()
Me.txtMainCategory.Select()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Try
If Me.txtMainCategory.Text = "" Then
MsgBox("Please Enter Main Category Name!", vbInformation)
Exit Sub
End If
Me.imgMainCategoryImage.Image.Save(Application.StartupPath & "\Images\" & Me.txtMainCategory.Text & ".jpeg", System.Drawing.Imaging.ImageFormat.Jpeg)
Me.TblItemMainCategoryBindingSource.EndEdit()
Me.TblItemMainCategoryTableAdapter.Update(Me.PosDatabaseDataSet.tblItemMainCategory)
Me.TblItemMainCategoryTableAdapter.Fill(Me.PosDatabaseDataSet.tblItemMainCategory)
Me.btnAddNew.Select()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Try
Dim MainCatName As String
MainCatName = Me.TblItemMainCategoryDataGridView.CurrentRow.Cells("MainCategoryName").Value
If Me.TblItemMainCategoryDataGridView.Rows.Count - 1 > 0 Then
'check before delting, if this main category is used in sub category then It can not be deleted.
Dim I As Integer
I = frmSubCategories.TblItemSubCategoryTableAdapter.qryCountMainCategoryUnderSubCategory(MainCatName)
If I > 0 Then
MsgBox(MainCatName & " is used under Sub Category(s), Please Delete Sub Category(s) First!", vbOK)
Exit Sub
End If
End If
Me.TblItemMainCategoryBindingSource.RemoveCurrent()
Me.TblItemMainCategoryTableAdapter.Update(Me.PosDatabaseDataSet.tblItemMainCategory)
Me.TblItemMainCategoryTableAdapter.Fill(Me.PosDatabaseDataSet.tblItemMainCategory)
'Delete the Main Category Image if this exists
If System.IO.File.Exists(Application.StartupPath & "\Images\" & MainCatName & ".JPEG") Then
System.IO.File.Delete(Application.StartupPath & "\Images\" & MainCatName & ".JPEG")
MsgBox("Image Deleted Successfull")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnBrowse_Click(sender As Object, e As EventArgs) Handles btnBrowse.Click
Try
Me.OpenFileDialog1.Filter = "Bitmaps(*.JPG, *.PNG, *.JPEG, *.BMP, *.TIF, *.GIF, *.TIFF)|"
Me.OpenFileDialog1.FileName = ""
If OpenFileDialog1.ShowDialog(Me) = DialogResult.OK Then
Dim img As String = Me.OpenFileDialog1.FileName
Me.imgMainCategoryImage.Image = System.Drawing.Bitmap.FromFile(img)
Me.btnSave.Select()
Else
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub TblItemMainCategoryDataGridView_SelectionChanged(sender As Object, e As EventArgs) Handles TblItemMainCategoryDataGridView.SelectionChanged
Try
Me.imgMainCategoryImage.Image = DirectCast(Image.FromFile(Application.StartupPath & "\Images\" & Me.TblItemMainCategoryDataGridView.CurrentRow.Cells("MainCategoryName").Value & ".JPEG").Clone(), Image)
' Me.imgMainCategoryImage.Image = System.Drawing.Bitmap.FromFile(Application.StartupPath & "\Images\" & Me.TblItemMainCategoryDataGridView.CurrentRow.Cells("MainCategoryName").Value & ".JPEG")
Catch ex As Exception
Me.imgMainCategoryImage.Image = My.Resources.imgEmpty 'if image path not found then select empty image
End Try
End Sub
Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
Me.Close()
End Sub
End Class
Above code give me an error message:
image is used in another process, can't be deleted
when I delete the image file. The image is assigned to a PictureBox with selection event of the DataGridView. Since I have deleted the DataGridView row, as shown in the above code, it changes the image in the PictureBox.
Here I am unable to delete the image file related to the removed row.
Please guide and let me know if you need any further details.

Problems Reading File

Currently having issues reading data from a file, and assigning it to the text-boxes on my form. The code runs without throwing an error, but no data/values are passed to the text-boxes and they remain blank. Below is my code:
Imports System.IO
Public Class ReadingEmployeeData
' Declare filename
Dim FileName As String
Private Sub NextButton_Click(sender As Object, e As EventArgs) Handles NextButton.Click
' Constant for holding the number of fields
Const NumFields As Integer = 8
' Declare variables
Dim FileStream As StreamReader
Dim Count As Integer
Try
' Open file
FileStream = File.OpenText(FileName)
' Read the data
For Count = 1 To NumFields
FirstText.Text = FileStream.ReadLine()
MiddleText.Text = FileStream.ReadLine()
LastText.Text = FileStream.ReadLine()
NumberText.Text = FileStream.ReadLine()
DepartmentText.Text = FileStream.ReadLine()
PhoneText.Text = FileStream.ReadLine()
ExtText.Text = FileStream.ReadLine()
EmailText.Text = FileStream.ReadLine()
Next Count
Catch ex As Exception
MessageBox.Show("That file can not be opened.")
Finally
FileStream.Close()
End Try
End Sub
Private Sub ReadingEmployeeData_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Get the filename from user
FileName = InputBox("Please enter the name of the file")
End Sub
Private Sub ExitButton_Click(sender As Object, e As EventArgs) Handles ExitButton.Click
Me.Close()
End Sub
End Class
Try using Io.StreamReader, And there is no need to NumFields:
Imports System.IO
Public Class ReadingEmployeeData
' Declare filename
Dim FileName As String
Private Sub NextButton_Click(sender As Object, e As EventArgs) Handles NextButton.Click
' Declare variables
Dim FileStream As StreamReader
Dim Count As Integer
Try
' Open file
Using sr As New Io.StreamReader(FileName)
' Read the data
FirstText.Text = sr.ReadLine()
MiddleText.Text = sr.ReadLine()
LastText.Text = sr.ReadLine()
NumberText.Text = sr.ReadLine()
DepartmentText.Text = sr.ReadLine()
PhoneText.Text = sr.ReadLine()
ExtText.Text = sr.ReadLine()
EmailText.Text = sr.ReadLine()
sr.Close()
End Using
Catch ex As Exception
MessageBox.Show("That file can not be opened.")
End Try
End Sub
Private Sub ReadingEmployeeData_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Get the filename from user
FileName = InputBox("Please enter the name of the file")
End Sub
Private Sub ExitButton_Click(sender As Object, e As EventArgs) Handles ExitButton.Click
Me.Close()
End Sub
End Class

STAThreadAttribute with SaveFileDialog VB.NET

I have an application to export ListView to Excel sheet , and im trying to do this in background but i have error in SaveFileDialog.showdialog().This is the error :
An exception of type 'System.Threading.ThreadStateException' occurred
in System.Windows.Forms.dll but was not handled in user code
Additional information: Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it. This exception is only raised if a debugger is attached to the process.
and this is my code :
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
BackgroundWorker1.RunWorkerAsync()
End Sub
Public Sub saveExcelFile(ByVal FileName As String)
Try
Dim xls As New Excel.Application
Dim sheet As Excel.Worksheet
Dim i As Integer
xls.Workbooks.Add()
sheet = xls.ActiveWorkbook.ActiveSheet
Dim row As Integer = 1
Dim col As Integer = 1
For i = 0 To Me.ListView1.Columns.Count - 1
sheet.Cells(1, i + 1) = Me.ListView1.Columns(i).Text
Next
For i = 0 To Me.ListView1.Items.Count - 1
For j = 0 To Me.ListView1.Items(i).SubItems.Count - 1
sheet.Cells(i + 2, j + 1) = Me.ListView1.Items(i).SubItems(j).Text
Next
Next
row += 1
col = 1
' for the header
sheet.Rows(1).Font.Name = "Cooper Black"
sheet.Rows(1).Font.size = 12
sheet.Rows(1).HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter
Dim mycol As System.Drawing.Color = System.Drawing.ColorTranslator.FromHtml("#148cf7")
sheet.Rows(1).Font.color = mycol
' for all the sheet without header
sheet.Range("a2", "z1000").Font.Name = "Arial"
sheet.Range("a2", "z1000").Font.Size = 13
sheet.Range("a2", "z1000").HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter
sheet.Range("A1:X1").EntireColumn.AutoFit()
sheet.Range("A1:X1").EntireRow.AutoFit()
xls.ActiveWorkbook.SaveAs(FileName)
xls.Workbooks.Close()
xls.Quit()
Catch ex As Exception
End Try
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Try
Dim saveFileDialog1 As New SaveFileDialog
saveFileDialog1.Filter = "Excel File|*.xlsx"
saveFileDialog1.Title = "Save an Excel File"
saveFileDialog1.ShowDialog()
If saveFileDialog1.FileName <> "" Then
saveExcelFile(saveFileDialog1.FileName)
End If
Catch ex As Exception
End Try
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
MsgBox("done")
End Sub
You could move everything concerning SaveFileDialog1 to Button3_Click and store the filename in a Private variable, so it can be used later in BackgroundWorker1_DoWork.
Private _filename As String
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
SaveFileDialog1.Title = "Save Excel File"
SaveFileDialog1.Filter = "Excel files (*.xls)|*.xls|Excel Files (*.xlsx)|*.xslx"
SaveFileDialog1.ShowDialog()
'exit if no file selected
If SaveFileDialog1.FileName = "" Then
Exit Sub
End If
_filename = SaveFileDialog1.FileName
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
...
book.SaveAs(_filename)
...
End Sub
i put this code in load form and everything is perfect:
Control.CheckForIllegalCrossThreadCalls = False

Error : file is being used by another process

I have a problem where it says that a file is already being used by another process
But I am pretty sure it's not being used anywhere else..
Imports System.IO
Public Class Browse
Private Sub add_Click(sender As Object, e As EventArgs) Handles add.Click
Dim Files As New OpenFileDialog
Dim Folder As New FolderBrowserDialog
Dim Filelist As String = "C:\Program Files\FTP-Sync\Files.txt"
Dim FileP As String = ""
Dim list() As String = IO.File.ReadAllLines(Filelist)
If fileb.Checked Then
Try
If System.IO.File.Exists(Filelist) = True And Files.ShowDialog = Windows.Forms.DialogResult.OK Then
FileP = Files.FileName
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
If folderb.Checked Then
Try
If System.IO.File.Exists(Filelist) = True And Folder.ShowDialog = Windows.Forms.DialogResult.OK Then
FileP = Folder.SelectedPath
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
pathtxt.Text = FileP
End Sub
Private Sub ok_Click(sender As Object, e As EventArgs) Handles ok.Click
Dim Filelist As String = "C:\Program Files\FTP-Sync\Files.txt"
Dim writer As StreamWriter = New StreamWriter(Filelist)
Dim FileP As String = ""
Try
If pathtxt.Text = "" Then
MsgBox("No folder or file has been choosen")
Else
writer = File.AppendText(Filelist)
writer.WriteLine(pathtxt.Text)
pathtxt.Text = FileP
writer.Close()
Me.Hide()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub cancel_Click(sender As Object, e As EventArgs) Handles cancel.Click
Me.Hide()
End Sub
Private Sub Browse_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
End Class
Thanks in advance!
It was because of this:
Dim writer As StreamWriter = New StreamWriter(Filelist)
i changed it to
Dim writer As StreamWriter
and it work like a charm.. dont know if it is the right way.. but it worked.