Cancelling upload with WebClient? - vb.net

Using the following VB.Net simple code to upload files in FTP, a call to WebClient.CancelAsync() doesn't actually cancel the upload.
Does someone know why, and what can be done about this?
Private Sub UploadProgressChanged(ByVal sender As Object, ByVal e As System.Net.UploadProgressChangedEventArgs)
'TO-DO: Why is pbar empty?
ProgressBar1.Value = e.ProgressPercentage
Label1.Text = e.BytesSent & " bytes sent"
End Sub
Private Sub UploadFileCompleted(ByVal sender As Object, ByVal e As System.Net.UploadFileCompletedEventArgs)
MessageBox.Show("Done!")
Button1.Text = "Upload"
ProgressBar1.Value = 0
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim client As New WebClient
If Button1.Text = "Cancel" Then
'TO-DO: Doesn't actually cancel upload!
client.CancelAsync()
Button1.Text = "Upload"
ProgressBar1.Value = 0
Else
Button1.Text = "Cancel"
Const MYFILE = "big.file.bin"
Const LocalFile As String = "C:\" & MYFILE
Dim RemoteFile As String = "ftp://upload.acme.com/" & MYFILE
client.Credentials = New NetworkCredential("anonymous", "test")
client.Proxy = Nothing
AddHandler client.UploadFileCompleted, AddressOf UploadFileCompleted
AddHandler client.UploadProgressChanged, AddressOf UploadProgressChanged
ProgressBar1.Maximum = 100
Try
client.UploadFileAsync(New Uri(RemoteFile), LocalFile)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
client.Dispose()
End If
End Sub
Thank you.

I don't use VB myself but it looks to me like you are calling client.cancelAsync() on the wrong client.
You are making a new client each time you press the cancel/upload button.
If you want to cancel the first client you started you need to instantiate it externally to the click_handler.
Also why are you using the button label to check if the client should be cancelled?
You can do if client.IsBusy ...

Related

Running an external app in textbox (how to preserve all functionality?)

I'm trying to run a cmd like application (so no GUI) in my form. In the example down below I called it ExternalApp.exe. The code itself works; I can send commands to it by entering them in TextBox2. The issue is that ExternalApp normally uses a command prompt and supports things like displaying one single screen of output and then wait for an enter before showing the next one. This is no longer working, all output is sent to TextBox1 all at once.
Is there any way to have ExternalApp behave like it normally does? I hope I'm explained myself a bit clear. Thanks for any help in advance!
Kind regards,
Eric
Public Class Form1
Dim WithEvents P As New Process
Dim SW As System.IO.StreamWriter
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
P.EnableRaisingEvents = True
Me.Text = "My title"
AddHandler P.OutputDataReceived, AddressOf DisplayOutput
P.StartInfo.CreateNoWindow() = True
P.StartInfo.UseShellExecute = False
P.StartInfo.RedirectStandardInput = True
P.StartInfo.RedirectStandardOutput = True
P.StartInfo.FileName = "ExternalApp.exe"
P.StartInfo.Arguments = ""
P.Start()
P.SynchronizingObject = Me
P.BeginOutputReadLine()
SW = P.StandardInput
SW.WriteLine()
End Sub
Private Sub DisplayOutput(ByVal sendingProcess As Object, ByVal output As DataReceivedEventArgs)
TextBox1.AppendText(output.Data() & vbCrLf)
End Sub
Private Sub Textbox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress
If e.KeyChar = Chr(Keys.Return) Then
SW.WriteLine(TextBox2.Text)
End If
End Sub
Private Sub myProcess_Exited(ByVal sender As Object, ByVal e As System.EventArgs) Handles P.Exited
Me.Close()
End Sub End Class

opendialog to show a file and save it with checkbox vb.net

I'm trying to connect to a database (mdb file of my choice) in a login screen and i want to save it for faster logon next times i boot the software.
I click on choose database button, opendialog lets me choose the file, i click OK and the db location shows in a textbox.
there's a checkbox beneath to save it before i connect to it.
But i can't manage to keep the checkbox checked, nor the textbox filled after i restart te program.
here's my current code:
Public Class LoginScreen
Private Sub Loginscreen_load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ProgressBar2.Minimum = 0
ProgressBar2.Maximum = 100
ProgressBar2.Visible = False
Panel1.Visible = False
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Application.Exit()
End Sub
Private Sub btnExit2_Click(sender As Object, e As EventArgs) Handles btnExit2.Click
Application.Exit()
End Sub
Private Sub tmrLogin_Tick(sender As Object, e As EventArgs) Handles tmrLogin.Tick
ProgressBar2.Value = ProgressBar2.Value + 20
lblLoginMessages.Text = ProgressBar2.Value & "%" & " Completed"
If ProgressBar2.Value >= 100 Then
tmrLogin.Enabled = False
If txtUser.Text = "azert" And txtPassword.Text = "azert" Then
ProgressBar2.Value = 0
Else
lblLoginMessages.Text = "Wrong credentials, Try again!"
pboxClosed.Visible = True
PboxOpen.Visible = False
ProgressBar2.Value = 0
txtPassword.Text = ""
txtUser.Text = ""
End If
End If
End Sub
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
ProgressBar2.Visible = True
tmrLogin.Enabled = True
pboxClosed.Visible = False
PboxOpen.Visible = True
''navraag doen om dit correct in te stellen! ! ! ! !!
'If ProgressBar2.Value = 100 Then
'lblLoginMessages.Text = "Logging in..."
Me.Hide()
Mainscreen.Show()
'End If
If chkSavePassword.Checked = True Then
My.Settings.databaselocation = txtDatabaselocationshow.Text
My.Settings.SaveLocation = True
End If
End Sub
Private Sub btnDBConnect_Click(sender As Object, e As EventArgs) Handles btnDBConnect.Click
If Panel1.Visible = False Then
Panel1.Visible = True
Else
Application.Exit()
End If
End Sub
Private Sub btnChoose_Click(sender As Object, e As EventArgs) Handles btnChoose.Click
Dim strtext As String
OpenFileDialog1.Filter = "Database Files | *.mdb"
OpenFileDialog1.InitialDirectory = "F:\GoogleDrive\EINDWERK VBNET"
OpenFileDialog1.Title = "Choose your Database"
OpenFileDialog1.ShowDialog()
strtext = OpenFileDialog1.FileName
txtDatabaselocationshow.Text = strtext
'If OpenFileDialog1.ShowDialog = DialogResult.OK Then
' strtext = OpenFileDialog1.FileName
' txtDatabaselocationshow.Text = strtext
'Else
' MsgBox("Error: the database file could not be read, try again.")
'End If
End Sub
Private Sub tmrshowloginpanel_Tick(sender As Object, e As EventArgs) Handles tmrshowloginpanel.Tick
Panel1.Width += 5
If Panel1.Width >= 700 Then
tmrshowloginpanel.Stop()
End If
End Sub
End Class
i've scoured the net but can't really find what to do?
if you need more information, shoot!
Walk through this with me:
Make a new project, one form, add a textbox and a combobox.
Click the textbox:
In the properties grid at the top click (Application Settings), then the 3 dots next to Property Binding. Scroll to Text. Drop down the setting and choose New at the bottom.
Give it a name of ChosenDatabasePath or something useful and descriptive like that
Repeat from "Click the textbox" for the checkbox instead, and this time bind the Checked property not the Text property.. Call the checkbox's Checked binding SavePassword or similar
Close all the dialogs so you're back at the form
Click anywhere on the background of the form when switch to Events in the property grid, find FormClosing and double click it
Put My.Settings.Save() in the FormClosing event handler
Run the app, write something in the textbox, close the form (by the X, not by stopping debugging), then immediately open the app again (run it)

vb.net backgroundworker CancelAsync not work

I have a stop problem in the backgroundworker, I use the following commands for backgroundworker:
update codes
Private Sub UnpackSystem_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles UnpackSystem.DoWork
Dim worker As System.ComponentModel.BackgroundWorker = DirectCast(sender, System.ComponentModel.BackgroundWorker)
For i As Integer = 1 To 100
If worker.CancellationPending Then
e.Cancel = True
Exit For
End If
worker.ReportProgress(i, i & " iterations complete")
Threading.Thread.Sleep(250)
Dim oProcess As New Process()
Dim oStartInfo As New ProcessStartInfo("cmd.exe", "/c bin\Imgtool\simg2img.exe tmp/system.img tmp/system.img.ext4")
oStartInfo.WindowStyle = ProcessWindowStyle.Hidden
oStartInfo.CreateNoWindow = True
oStartInfo.UseShellExecute = False
oStartInfo.RedirectStandardOutput = True
oProcess.StartInfo = oStartInfo
oProcess.Start()
Dim sOutput As String
Using oStreamReader As System.IO.StreamReader = oProcess.StandardOutput
sOutput = oStreamReader.ReadToEnd()
End Using
TextBox8.Invoke(Sub() TextBox8.AppendText(Environment.NewLine & sOutput))
Next i
End Sub
Private Sub UnpackSystem_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles UnpackSystem.ProgressChanged
Me.ProgressBar5.Value = e.ProgressPercentage
End Sub
Private Sub UnpackSystem_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles UnpackSystem.RunWorkerCompleted
If e.Cancelled = True Then
TextBox8.AppendText(Environment.NewLine & "Canceled!")
ElseIf e.Error IsNot Nothing Then
TextBox8.AppendText(Environment.NewLine & "Error: " & e.Error.Message)
Else
TextBox8.AppendText(Environment.NewLine & "Done!")
End If
End Sub
and, I use the following code to stop backgroundworker proccess ...
Private Sub Button55_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles Button55.Click
If Me.UnpackSystem.IsBusy Then
Me.UnpackSystem.CancelAsync()
End If
Dim cmd() As Process
cmd = Process.GetProcessesByName("cmd")
If cmd.Count > 0 Then
Process.GetProcessesByName("cmd")(0).Kill()
End If
End Sub
But it not be canceled, Where is my problem?
You are only testing whether a cancellation is pending when the DoWork event handler first starts, which of course it will not be at that stage. In order for the background task to be cancelled later on, you would have to actually test whether a cancellation is pending later on.
There's no magic here though. As I said, in order to cancel, you have to actually test whether a cancellation is pending within the DoWork event handler. That test can only come between other lines of code. Once you call that ReadToEnd method, you are going to read the stream to the end, whether the user has requested cancellation or not. You obviously can't test for a pending cancelation until that call returns

VB.Net - Timer Control freezes application

I have added a Timer control to a vb.net application that is used to check if a website is up or down. There are two Timer controls in the app. Both are from System.Windows.Forms.Timer.
There is Timer1 and Timer2. Timer1 is used to perform the website check. Timer2 is simply to display a current date and time in the ToolStrip at the base of the form. The Timer2 runs without issue displaying the time, but when I start the website check that runs Timer1, the application freezes after two checks. Sometimes it runs longer, but eventually freezes.
I have to End Task from within Task Manager in order to shut down the application. I have tested this from within the Debugger and after running the executable. I have also completely removed Timer2 and tested, but the freezing remains. Here is my code. Any assistance would be greatly appreciated.
Imports System
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
lblStatus.Text = ""
Timer1.Stop()
btnStart.Enabled = True
btnStop.Enabled = False
End Sub
Public Function CheckAddress(ByVal URL As String) As Boolean
Try
Dim request As WebRequest = WebRequest.Create(URL)
Dim response As WebResponse = request.GetResponse()
Catch ex As Exception
Return False
End Try
Return True
End Function
Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
Dim startPoint As Integer = -1
If CheckAddress(txtAddress.Text).ToString() = True Then
rtxtResults.AppendText(" -- " & txtAddress.Text & " - Website shows UP at " & tsClock.Text & " - " & vbNewLine)
ElseIf CheckAddress(txtAddress.Text).ToString() = False Then
rtxtResults.AppendText(" -- " & txtAddress.Text & " - Website shows DOWN at " & tsClock.Text & " - " & vbNewLine)
End If
Do
startPoint = rtxtResults.Find("Website shows DOWN at", startPoint + 1, RichTextBoxFinds.None)
If (startPoint >= 0) Then
rtxtResults.SelectionStart = startPoint
rtxtResults.SelectionLength = "Website shows DOWN at".Length
rtxtResults.SelectionColor = Color.Red
End If
Loop Until startPoint < 0
End Sub
Private Sub Timer2_Tick(sender As System.Object, e As System.EventArgs)
tsClock.Text = Now()
End Sub
Private Sub btnStart_Click(sender As System.Object, e As System.EventArgs) Handles btnStart.Click
If txtInterval.Text = "" Then
MsgBox("Must enter a number")
Exit Sub
End If
lblStatus.ForeColor = Color.Green
lblStatus.Text = "Running"
btnStart.Enabled = False
btnStop.Enabled = True
Timer1.Interval = Int(txtInterval.Text) * 1000
Timer1.Start()
End Sub
Private Sub btnStop_Click(sender As System.Object, e As System.EventArgs) Handles btnStop.Click
lblStatus.ForeColor = Color.Red
lblStatus.Text = "Stopped"
btnStop.Enabled = False
btnStart.Enabled = True
Timer1.Stop()
End Sub
End Class
Your application's UI will "freeze" until the Timer1_Tick method completes. Most likely your Timer1_Tick's Do...Loop is not exiting. Try deleting the Do and Loop lines.

VB.NET Webbrowser to textbox

I need help getting all of the text from WebBrowser1 to my textbox1.text
I tried
WebBrowser1.Navigate(TextBox3.Text)
TextBox1.Text = WebBrowser1.DocumentText
textbox3 being my website
and textbox1 being were i want all the text.
You have to handle the DocumentCompleted event of WebBrowser control.
Private Sub WebBrowser1_DocumentCompleted(sender As System.Object,
e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs)
Handles WebBrowser1.DocumentCompleted
TextBox1.Text = WebBrowser1.DocumentText
End Sub
My solution:
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' WebBrowser1
' TextBox1
' TextBox2
'
WebBrowser1.ScriptErrorsSuppressed = True ' we would like to suppress scripts error message
WebBrowser1.Navigate("http://codeguru.com")
End Sub
Private Sub WebBrowser1_DocumentCompleted(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
' 1) Get entire html code and save as .html file
TextBox1.Text = WebBrowser1.DocumentText
' HOWTO retry while error UNTIL ok
' this needs to be done because Body.InnerText returns error when called too soon
' 2) Get Body text and save as .txt file
Dim retry As Boolean = True
Dim body As String = ""
While retry
Try
body = WebBrowser1.Document.Body.InnerText
retry = False
Catch ex As System.IO.IOException
retry = True
Finally
TextBox2.Text = body
End Try
End While
End Sub
End Class