VB.Net Create a ImageGenerator process - vb.net

I want to know how can i make a process..
Im actually doing this with a For like this:
timeCount = 0
Timer.Start()
Dim Count As Integer = 1, next As Boolean
For Each dataRow As DataRow In DataBase.Rows
nextImage = False
Do While nextImage = False
Try
Dim Ext As String = ".png"
If rbJPG.Checked = True Then Ext = ".jpg"
GenerateImage(dataRow, ImageFrom, FBD.SelectedPath, Ext, Count)
nextImage = True
Catch ex As Exception
Timer.Stop()
Dim Result As DialogResult = MessageBox.Show(ex.Message, "ERROR", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error)
If Result = Windows.Forms.DialogResult.Ignore Then
Timer.Start()
nextImage = True
ElseIf Result = Windows.Forms.DialogResult.Retry Then
Timer.Start()
nextImage = False
ElseIf Result = Windows.Forms.DialogResult.Abort Then
prgGenerate.Value = 0
Exit For
End If
End Try
Loop
Count += 1
prgGenerate.Increment(1)
Next
But this colapse my program and uses a lot of RAM.
I cant show nothing during the process, for example: Elapsed Time. And the timer never start.
Sorry for bad english.

It's not clear to me how you're setting the ImageFrom variable, but here's a simple example using the BackgroundWorker():
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
timeCount = 0
Me.Invoke(Sub()
Timer.Start()
End Sub)
Dim Count As Integer = 1, nextImage As Boolean
For Each dataRow As DataRow In Database.Rows
nextImage = False
Do While nextImage = False
Try
Dim Ext As String = ".png"
If rbJPG.Checked = True Then Ext = ".jpg"
GenerateImage(dataRow, ImageFrom, FBD.SelectedPath, Ext, Count)
nextImage = True
Catch ex As Exception
Me.Invoke(Sub()
Timer.Stop()
Dim Result As DialogResult = MessageBox.Show(ex.Message, "ERROR", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error)
If Result = Windows.Forms.DialogResult.Ignore Then
Timer.Start()
nextImage = True
ElseIf Result = Windows.Forms.DialogResult.Retry Then
Timer.Start()
nextImage = False
ElseIf Result = Windows.Forms.DialogResult.Abort Then
prgGenerate.Value = 0
Exit For
End If
End Sub)
End Try
Loop
Count += 1
Me.Invoke(Sub()
prgGenerate.Increment(1)
End Sub)
Next
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
MessageBox.Show("Done!")
End Sub
You'd start the background thread with:
BackgroundWorker1.RunWorkerAsync()

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

Webpages load really slow when boleean is true. How to speed things up?

I have a working code but my web pages load very slow when boolean is true. Any way to speed things up? Here is the code:
Private Property bool2 As Boolean
Private Sub WebBrowserCheck(sender As Object, e As WebBrowserNavigatedEventArgs)
bool2 = True
Dim token As String
Dim pretoken As String
pretoken = WebBrowser1.Url.ToString
token = pretoken.Substring(27, 9)
Dim tvshowcheck As String
tvshowcheck = "https://www.imdb.com/title/" & token & "/episodes"
Dim req As System.Net.WebRequest
Dim res As System.Net.WebResponse
req = System.Net.WebRequest.Create(tvshowcheck)
Try
res = req.GetResponse()
Catch nub As WebException
bool2 = False
End Try
If bool2 = True Then
TextBox2.Visible = True
TextBox3.Visible = True
TextBox4.Visible = True
TextBox5.Visible = True
Else
TextBox2.Visible = False
TextBox3.Visible = False
TextBox4.Visible = False
TextBox5.Visible = False
End If
End Sub
Private Sub WebBrowserCheckHandler()
AddHandler WebBrowser1.Navigated, New WebBrowserNavigatedEventHandler(AddressOf WebBrowserCheck)
End Sub
Private Sub WebBrowser1_Navigated(sender As Object, e As WebBrowserNavigatedEventArgs) Handles WebBrowser1.Navigated
If WebBrowser1.ReadyState = WebBrowserReadyState.Complete Then
WebBrowserCheckHandler()
End If
End Sub
The part untill End Try runs very well.

cancelling async task using progress bar causes targetinvocationexception error using vb.net

I am trying to load a datatable async so that the UI remains responsive. I've used the dt.RowChanged event to handle reporting progress back to the progress bar and label. But when the Stop button is clicked, it causes the following error:
An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll.
I'm not sure how to find my way around this issue. Any guidance is appreciated. The following is code from sample project using AdventureWorks DB
Imports System.Threading
Imports System.Threading.Tasks
Public Class AsyncProgressCancel
Public strConnectionString As String = "data source=010XXX01;initial catalog=AdventureWorks2012;integrated security=SSPI;"
Private dt As DataTable
Private ds As DataSet
Dim dataset
Dim RecordCount As Integer = 1000000
Dim Counter As Integer
Dim myProgress As Progress(Of Integer)
Private Delegate Sub AsyncDelegate(ByVal value As Integer)
Private ProgressUpdater As New AsyncDelegate(AddressOf UpdateProgress)
Private TargetCounter As Integer = 1000
Private cts As CancellationTokenSource
Private Cancelled As Boolean
Private Sub AsyncProgressCancel_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ProgressBar1.Visible = False
lblProgress.Visible = False
btnStop.Enabled = False
End Sub
Private Async Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click
btnStart.Enabled = False
btnStop.Enabled = True
Cancelled = False
ProgressBar1.Value = 0
ProgressBar1.Maximum = RecordCount
ProgressBar1.Visible = True
lblProgress.Visible = True
DataGridView1.Enabled = False
cts = New CancellationTokenSource()
Try
Dim completed As Boolean = Await LoadDataAsync(myProgress, cts.Token)
Catch ex As OperationCanceledException
lblProgress.Text = "Retrieve cancelled."
DataGridView1.DataSource = Nothing
DataGridView1.Enabled = True
btnStop.Enabled = False
btnStart.Enabled = True
ProgressBar1.Visible = False
Catch ex As Exception
MsgBox(ex)
End Try
End Sub
Private Sub UpdateProgress(ByVal value As Integer)
If Cancelled = True Then
cts.Cancel()
Else
If ProgressBar1.InvokeRequired Then
ProgressBar1.Invoke(ProgressUpdater, New Object() {value})
ElseIf value > ProgressBar1.Maximum Then
value = ProgressBar1.Maximum
ProgressBar1.Value = value
End If
lblProgress.Text = Math.Round((value / RecordCount) * 100).ToString & "% complete" '"Step Number: " & myInt.ToString
ProgressBar1.Value = value
End If
End Sub
Private Async Function LoadDataAsync(ByVal myProgress As IProgress(Of Integer), token As CancellationToken) As Task(Of Boolean)
Dim comSQL As SqlClient.SqlCommand
Dim strSQL As String
Dim da As SqlClient.SqlDataAdapter
Dim dt As New DataTable
Dim ReturnValue As Boolean
Try
DataGridView1.Enabled = Await Task(Of Boolean).Run(Function()
Using conn As SqlClient.SqlConnection = New SqlClient.SqlConnection(strConnectionString)
conn.Open()
strSQL = "SELECT * FROM (SELECT TOP 1000000 PRODUCTION.PRODUCT.* FROM sales.SalesOrderDetail CROSS JOIN production.Product) A"
comSQL = New SqlClient.SqlCommand(strSQL, conn)
da = New SqlClient.SqlDataAdapter(comSQL)
AddHandler dt.RowChanged, Sub(obj, e)
If e.Action.Add Then
Counter = obj.Rows.Count
If Counter > RecordCount Then
Counter = RecordCount
Else
Counter = Counter + 1 ' Math.Ceiling(0.1 * RecordCount)
End If
End If
If token.IsCancellationRequested = True Then
token.ThrowIfCancellationRequested()
Else
If Counter = TargetCounter Then
UpdateProgress(Counter)
TargetCounter = TargetCounter + 1000
End If
End If
End Sub
If Counter > 0 Then
myProgress.Report(Counter)
End If
da.Fill(dt)
dataset = dt
ReturnValue = True
Return ReturnValue
End Using
End Function, token)
Catch ex As Exception
MsgBox(ex)
End Try
End Function
Private Sub btnStop_Click(sender As Object, e As EventArgs) Handles btnStop.Click
Try
If Not cts Is Nothing Then
cts.Cancel()
End If
Catch ex As Exception
MsgBox(ex)
End Try
End Sub
End Class

How to show MsgBox after finishing unzip process

I have this code:
Private Sub KickoffExtract()
actionStatus.Text = "Se instaleaza actualizarea.. va rugam asteptati."
lblProgress.Text = "Se extrage..."
Dim args(2) As String
args(0) = GetSettingItem("./updUrl.info", "UPDATE_FILENAME")
args(1) = extractPath
_backgroundWorker1 = New System.ComponentModel.BackgroundWorker()
_backgroundWorker1.WorkerSupportsCancellation = False
_backgroundWorker1.WorkerReportsProgress = False
AddHandler Me._backgroundWorker1.DoWork, New DoWorkEventHandler(AddressOf Me.UnzipFile)
_backgroundWorker1.RunWorkerAsync(args)
End Sub
Private Sub UnzipFile(ByVal sender As Object, ByVal e As DoWorkEventArgs)
Dim extractCancelled As Boolean = False
Dim args() As String = e.Argument
Dim zipToRead As String = args(0)
Dim extractDir As String = args(1)
Try
Using zip As ZipFile = ZipFile.Read(zipToRead)
totalEntriesToProcess = zip.Entries.Count
SetProgressBarMax(zip.Entries.Count)
AddHandler zip.ExtractProgress, New EventHandler(Of ExtractProgressEventArgs)(AddressOf Me.zip_ExtractProgress)
zip.ExtractAll(extractDir, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently)
End Using
Catch ex1 As Exception
MessageBox.Show(String.Format("Actualizatorul a intampinat o problema in extragerea pachetului. {0}", ex1.Message), "Error Extracting", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)
End Try
End Sub
Private Sub SetProgressBarMax(ByVal n As Integer)
If ProgBar.InvokeRequired Then
ProgBar.Invoke(New Action(Of Integer)(AddressOf SetProgressBarMax), New Object() {n})
Else
ProgBar.Value = 0
ProgBar.Maximum = n
ProgBar.Step = 1
End If
End Sub
Private Sub zip_ExtractProgress(ByVal sender As Object, ByVal e As ExtractProgressEventArgs)
If _operationCanceled Then
e.Cancel = True
Return
End If
If (e.EventType = Ionic.Zip.ZipProgressEventType.Extracting_AfterExtractEntry) Then
StepEntryProgress(e)
ElseIf (e.EventType = ZipProgressEventType.Extracting_BeforeExtractAll) Then
End If
End Sub
Private Sub StepEntryProgress(ByVal e As ExtractProgressEventArgs)
If ProgBar.InvokeRequired Then
ProgBar.Invoke(New ZipProgress(AddressOf StepEntryProgress), New Object() {e})
Else
ProgBar.PerformStep()
System.Threading.Thread.Sleep(100)
nFilesCompleted = nFilesCompleted + 1
lblProgress.Text = String.Format("{0} din {1} fisiere...({2})", nFilesCompleted, totalEntriesToProcess, e.CurrentEntry.FileName)
Me.Update()
End If
End Sub
and this code on a button:
If Not File.Exists("./" + GetSettingItem("./updUrl.info", "UPDATE_FILENAME")) Then
MessageBox.Show("Actualizarea nu s-a descarcat corespunzator.", "Nu se poate extrage", MessageBoxButtons.OK)
End If
If Not String.IsNullOrEmpty("./" + GetSettingItem("./updUrl.info", "UPDATE_FILENAME")) And
Not String.IsNullOrEmpty(extractPath) Then
If Not Directory.Exists(extractPath) Then
Directory.CreateDirectory(extractPath)
End If
nFilesCompleted = 0
_operationCanceled = False
btnUnzip.Enabled = False
KickoffExtract()
End If
How can I show a message after completing the UnZip process? I tried
If ProgBar.Maximum Then
MsgBox("finish")
End If
but it doesn't work. I'm using dotnetzip 1.9, and the most of the code is from UnZip example.
If you check the documentation of BackgroundWorker you will notice that there are two events that can be linked to an event handler in your code.
One of them is the RunWorkerCompleted and in the MSDN page they say
Occurs when the background operation has completed, has been canceled,
or has raised an exception.
So, it is just a matter to write an event handler and bind the event.
AddHandler Me._backgroundWorker1.RunWorkerCompleted, New RunWorkerCompletedEventHandler(AddressOf Me.UnzipComplete)
and then
Private Sub UnzipComplete(ByVal sender As System.Object, _
ByVal e As RunWorkerCompletedEventArgs)
If e.Cancelled = True Then
MessageBox.Show("Canceled!")
ElseIf e.Error IsNot Nothing Then
MessageBox.Show("Error: " & e.Error.Message)
Else
MessageBox.Show("Unzip Completed!")
End If
End Sub

No body returned from MailKit fetch

I started working with MailKit and have run into an issue where no body is returned for any of the fetched messages. I've tried both a fetch and a search, without luck.
My code is below:
Private strErrMsg As String
Private objClient As ImapClient
Private objDataTable As DataTable
Private Sub frmEmalTest2_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
If objClient IsNot Nothing Then
If objClient.IsConnected Then
objClient.Disconnect(True)
objClient.Dispose()
End If
End If
End Sub
Private Sub frmEmalTest2_Load(sender As Object, e As EventArgs) Handles Me.Load
objDataTable = New DataTable
With objDataTable.Columns
.Add("msgdate", Type.GetType("System.String"))
.Add("sender", Type.GetType("System.String"))
.Add("subject", Type.GetType("System.String"))
.Add("msgid", Type.GetType("System.String"))
.Add("attachments", Type.GetType("System.Int32"))
End With
grdMessages.DataSource = objDataTable
End Sub
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
Try
If txtUserName.Text = "" Then
Exit Sub
End If
If txtPassword.Text = "" Then
Exit Sub
End If
Dim logger = New ProtocolLogger(Console.OpenStandardError())
objClient = New ImapClient(logger)
Dim credentials = New NetworkCredential(txtUserName.Text, txtPassword.Text)
Dim uri = New Uri("imaps://imap.gmail.com")
With objClient
.Connect(uri)
.AuthenticationMechanisms.Remove("XOAUTH2")
.Authenticate(credentials)
End With
lblMsg.Text = "Connected"
Catch ex As Exception
strErrMsg = ex.Message
lblMsg.Text = "Connection failed!"
End Try
End Sub
Private Sub btnMessages_Click(sender As Object, e As EventArgs) Handles btnMessages.Click
Dim objRow As DataRow
Dim objMultipart As BodyPartMultipart
Dim objBasic As BodyPartBasic
Dim objMessage As IMessageSummary
Dim intAttachments As Integer = 0
Dim objMessages As IList(Of IMessageSummary) = Nothing
Try
If Not objClient.IsConnected Then
Exit Sub
End If
objClient.Inbox.Open(FolderAccess.[ReadOnly])
objMessages = objClient.Inbox.Fetch(0, -1, MessageSummaryItems.All).ToList()
If objMessages.Count > 0 Then
lblRecCnt.Text = objMessages.Count.ToString + " message(s)"
Else
lblRecCnt.Text = "(no messages)"
End If
objDataTable.Rows.Clear()
If objMessages.Count > 0 Then
For Each objMessage In objMessages
intAttachments = 0
objBasic = TryCast(objMessage.Body, BodyPartBasic)
objMultipart = TryCast(objMessage.Body, BodyPartMultipart)
objRow = objDataTable.NewRow
objRow("msgid") = objMessage.UniqueId
objRow("msgdate") = objMessage.Date.ToString("M/d/yyyy h:mmtt")
objRow("subject") = objMessage.Envelope.Subject
objRow("sender") = objMessage.Envelope.From.Mailboxes(0).Name + " (" + objMessage.Envelope.From.Mailboxes(0).Address + ")"
If objMultipart Is Nothing Then
If objBasic IsNot Nothing AndAlso objBasic.IsAttachment Then
intAttachments += 1
End If
Else
For Each objItem As BodyPartBasic In objMultipart.BodyParts.OfType(Of BodyPartBasic)()
Select Case objItem.ContentType.MediaType
Case "APPLICATION", "IMAGE"
intAttachments += 1
End Select
Next objItem
End If
objRow("attachments") = intAttachments
objDataTable.Rows.Add(objRow)
If objRow("attachments") > 0 Then
grdMessages.Rows(objDataTable.Rows.Count - 1).Cells(0).Value = My.Resources.attach
End If
Next
End If
Catch ex As Exception
strErrMsg = ex.Message
End Try
End Sub
My fault!!
If I change MessageSummaryItems.All to MessageSummaryItems.Full I can see the body. However, it adds about 5 seconds to the fetch time.