wait for webbrowser to load, then execute code - vb.net

I have a code that constantly claims a username on a website, so that when the social medium decides to release these usernames I will be the first in line to get it. Now, it does timeout which is a huge problem. So to fix it, I have tried to make it sign out of the account then sign back in.
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
If number_of_ticks > NumericUpDown1.Value Then
WebBrowser1.Navigate("https://live.xbox.com/Account/Signout")
While Not WebBrowser1.ReadyState = WebBrowserReadyState.Complete
Application.DoEvents()
End While
WebBrowser1.Navigate("https://live.xbox.com/en-US/ChangeGamertag")
WebBrowser1.Document.GetElementById("login").SetAttribute("value", txtUsername.Text)
WebBrowser1.Document.GetElementById("passwd").SetAttribute("value", txtPassword.Text)
WebBrowser1.Document.GetElementById("SI").InvokeMember("Click")
number_of_ticks = 0
End If
If WebBrowser1.Url.ToString = "https://live.xbox.com/en-US/ChangeGamertag" Then
WebBrowser1.Document.GetElementById("NewGamertag").SetAttribute("value", txtTurbo.Text)
WebBrowser1.Document.GetElementById("claimIt").InvokeMember("Click")
number_of_ticks += 1
Else
End If
End Sub
As you can see, after number_of_ticks reaches a certain number I want it to navigate to the log out page, and then once the web page is fully loaded, navigate to the other page where it puts the info in again to log in. Unfortunately, this doesn't work, and all I get are errors when I try to run this. The code:
While Not WebBrowser1.ReadyState = WebBrowserReadyState.Complete
Application.DoEvents()
End While
seems to not work at all, and especially the other codes such as the WaitForPageLoad.
I have looked for solutions and haven't found ANYTHING.

Related

Running a BackGroundWorker more than once

I wonder if you can help?, please bear in mid I’m an absolute novice.
I trying to update a program I made a few years ago for booking in serial numbers into a CRM application.
Currently it runs the following command for each of the 100 textboxes and has worked a treat booking in more than 81000 serial numbers.
If TextBox1.Text.Length > 1 Then
Clipboard.SetText(TextBox1.Text)
RetBat1 = Shell("C:\Windows\BookIN.exe", , True)
Endif
The new version of the app I’ve added a listbox1 with the serial numbers in, I’m then running the below For Each loop.
The For Each loop copies each Item into the clipboard and the BookIN.exe tabs to the right location in the CRM and pastes the information, then clicks a button in the CRM for a new Line and then runs again. This works fine, but I want to add a stop button or a stop checkbox.
For Each items In ListBox1.Items
Clipboard.SetText(items)
RetBat1 = Shell("C:\Windows\BookIN.exe", , True)
Next
I have tried adding the Retbat1 to a backgroundworker, which checks if Checkbox1.checked then exit the for each loop.
The first serial number works, but when the backgroundworker runs more than once I get the following error.
If CheckBox1.Checked = True Then
BackgroundWorker1.CancelAsync()
Else
Dim RetBat1 As String
RetBat1 = Shell("C:\Windows\BookIN.exe", , True)
End If
System.InvalidOperationException: 'This BackgroundWorker is currently busy and cannot run multiple tasks concurrently.'
Sorry if this makes not sense, thanks James
The way it would go is that you would run the BackgroundWorker and have your loop in the DoWork event handler and check whether a cancellation has been requested within that loop. As you've described it, you would then handle the CheckedChanged even of your CheckBox and request the cancellation when the event is raised. I would not use a CheckBox though, because that implies that you can uncheck it to uncancel the work. I would suggest using a Button and handling its Click event, e.g.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'We must get the data from the UI here and pass it into the background thread.
Dim items = ListBox1.Items.Cast(Of String)().ToArray()
'Start the background work and pass in the data.
BackgroundWorker1.RunWorkerAsync(items)
'Enable the Cancel button.
Button2.Enabled = True
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'Disable the Cancel button so it cannot used again.
Button2.Enabled = False
'Request that background processing be cancelled.
BackgroundWorker1.CancelAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
'Get the data that was passed in.
Dim items = DirectCast(e.Argument, String())
'Process each item.
For Each item In items
'Check whether processing has been cancelled.
If BackgroundWorker1.CancellationPending Then
'Cancel processing.
e.Cancel = True
Exit For
End If
'Process the current item here.
Next
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
If e.Cancelled Then
MessageBox.Show("The background operation was cancelled")
Else
'Disable the Cancel button.
Button2.Enabled = False
MessageBox.Show("The background operation completed successfully")
End If
End Sub
The Cancel Button should be disabled by default and notice that this code ensures that it is only enabled when background processing is in progress. Note that the other Button probably ought to be disabled while the processing is in progress too. If you don't do that, at least check IsBusy on the BackgroundWorker. The visual feedback to the user is better though.

Process.Start open too many multiple windows

I started to program a couple of months ago and I'm having hard time with Process.Start command.
In the first form I've made a timer that can set a time and opens the program, that i defined it location in my TextBox box (another vb app that i built),
according to the time one enters and presses the "Set" button, when its time it opens the file that you choose.
For some reason it opens 10 multiple windows and on browsing for JPG file, it opens it only once, the multiple windows issues occurs only with .exe files.
Does anyone know the reason?
Here is my code so far:
Public Class startup
Dim iSetTime As Date
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
If txtTMinute.Text <> String.Empty Then
Clipboard.SetText(txtTMinute.Text)
Else
Clipboard.Clear()
End If
txtTSecond.Clear()
txtTSecond.Paste()
If (Timer1.Enabled = True) Then
Timer1.Enabled = False
End If
iSetTime = txtTHour.Text + ":" + txtTMinute.Text + ":" + txtTSecond.Text
Timer1.Enabled = True
Label6.Text = "Timer not activated."
Me.Refresh()
System.Threading.Thread.Sleep(1000)
'MessageBox.Show("Activated Succesfully")
Label6.Text = "Timer Activated!"
Label6.ForeColor = Color.Green
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
If (TimeOfDay = iSetTime) Then
Process.Start(TextBox1.Text)
End If
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Using ofd As New OpenFileDialog
ofd.Filter = "All files (*.*)|*.*"
ofd.Title = "Select File"
If ofd.ShowDialog() = Windows.Forms.DialogResult.OK Then
Me.TextBox1.Text = ofd.FileName
End If
End Using
End Sub
End Class
You don't use enabled = true or false , you use timer.start or timer.stop , i don't know why are you even using a timer to do this? Anywho what's happening is the timer is continously looping through the code after little intervals because IT IS A TIMER and that's what it does until you stop it. If you really want to use a timer for this task then after this line Process.Start(TextBox1.Text) use this code: Timer1.Stop
By the way if you haven't changed the default interval of the timer then it would be set to 100 which is in milliseconds. it is equal to the same time as System.Threading.Thread.Sleep(100) and if you are stopping your timer after System.Threading.Thread.Sleep(1000) then it would've already looped the code: Process.Start(TextBox1.Text) 10 times because 1000/100 = 10
"When im browsing for JPG file, it opens it only once, only with exe
it multiple it."
I'm going to guess that it's trying to open anything you tell it to 10 times, the difference is that when you open an image, it is getting displayed in a single-instance program (like Preview, or Windows Image Viewer, or whatever it happens to be called), and then "reopened" in the same viewer instance 9 more times.
Set a breakpoint at this line:
Process.Start(TextBox1.Text)
When the breakpoint is encountered after running your application in the debugger, mouseover the two variables in the previous line, TimeOfDay and iSetTime in the IDE, and compare their values. I'd be willing to bet you're getting multiple True cases because of the implicit conversion between TimeOfDay's TimeSpan data format, and iSetTime as a Date.

VB.NET Upload to FTP with progressbar

I relise there is so many other questions out there regarding the progressbar, though I've looked through them "all" and can not find one that works.
I am trying to upload c:\screenshot.png to my ftp with a progress bar and a msgbox once finished.
Could someone provide a working example for me?
Thankyou
Edit heres the code I tried. Uploading works, though the progress bar dosent.
Sub UpdateProgressBar(ByVal sender As Object, ByVal e As UploadProgressChangedEventArgs)
If ProgressBar1.InvokeRequired Then
ProgressBar1.Invoke(New UploadProgressChangedEventHandler(AddressOf UpdateProgressBar), sender, e)
Exit Sub
End If
ProgressBar1.Value = CInt(ProgressBar1.Minimum + _
((ProgressBar1.Maximum - ProgressBar1.Minimum) * _
e.ProgressPercentage) / 100)
End Sub
Private Sub btnUpload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button8.Click
Label16.Text = "Uploading now..."
Label16.Update()
Dim client As New System.Net.WebClient()
AddHandler client.UploadProgressChanged, AddressOf UpdateProgressBar
With client
.Credentials = New NetworkCredential( _
"damon#slimar.eu", "mine123!")
.UploadFile("ftp://slimar.eu/screenshot.png", "C:\screenshot.png")
End With
Label16.Text = "Done!"
Label16.Update()
End Sub
Progress bar has minValue,Max value, StepValue which is used to perform a step and Value to setup arbitray value.When you uploading a file or downloading you should be able to see via e paramenter total byte and actual byte trasmission.So you can setup Progress bar value and max value.
Also personally i invite you to use backgroundworker which :
Not Freeze GUI
Give you much controll on thread with no issue and no invoke needs
Make it more simple :)

Function call only works when MessageBox.Show() is included?

In my current project I have a self-made audioplayer which is operated trough my musictimer() function. Below is a sub which orders the audioplayer to go to the next song when someone has clicked on a picture. This works perfectly.
Private Sub PictureBox4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox4.Click
If (ListBox1.Items.Count - 1 > songBeingPlayed) Then
musictimer("next")
Else
musictimer("stop")
End If
End Sub
Below there is a sub which orders the player to play the next song when a song is finished playing. This sub also works but only when I have the MessageBox.Show("blabla") line in there. Otherwise it simply ignores the musictimer("next"). Obviously its quite annoying to have popup messages the entire times so I want it gone. Does anyone know whats going on? Im clueless.
Private Sub AxWindowsMediaPlayer1_PlayStateChange(ByVal sender As System.Object, ByVal e As AxWMPLib._WMPOCXEvents_PlayStateChangeEvent) Handles AxWindowsMediaPlayer1.PlayStateChange
If AxWindowsMediaPlayer1.playState = WMPLib.WMPPlayState.wmppsStopped Then
musictimer("next")
MessageBox.Show("blabla")
End If
End Sub
My very messy musictimer function.
Function musictimer(ByVal action)
If action Is "initial" Then
TextBox1.Text = "0:00"
Timer1.Stop()
secondsCounter = 1
doubledigitsecondCounter = 0
minuteCounter = 0
End If
If action Is "reset" Then
TextBox1.Text = "0:00"
Timer1.Stop()
secondsCounter = 1
doubledigitsecondCounter = 0
minuteCounter = 0
Me.AxWindowsMediaPlayer1.URL = ""
changePlayButton("play")
End If
If action Is "start" Then
If (ListBox1.Items.Count > 0) Then
Me.AxWindowsMediaPlayer1.URL = directoryPath + listboxpl(songBeingPlayed)
AxWindowsMediaPlayer1.Ctlcontrols.play()
Timer1.Start()
changePlayButton("pause")
End If
End If
If action Is "pause" Then
Timer1.Stop()
AxWindowsMediaPlayer1.Ctlcontrols.pause()
changePlayButton("play")
End If
If action Is "next" Then
If (ListBox1.Items.Count - 1 > songBeingPlayed) Then
songBeingPlayed += 1
musictimer("reset")
musictimer("start")
changePlayButton("pause")
Else
musictimer("pause")
End If
End If
If action Is "previous" Then
If (songBeingPlayed > 0) Then
songBeingPlayed -= 1
musictimer("reset")
musictimer("start")
End If
End If
End Function
The PlayStateChanged event is quite notorious. It was really meant to just update a UI element that shows the state. Doing anything with the player in that event is very troublesome. A call to MessagBox can have an affect because it pumps a message loop, always a big deal for ActiveX controls.
The best way to stay out of trouble is by delaying your code, making it run after the event was fired and the player is back into a quiescent state. Elegantly done by using the Control.BeginInvoke() method. Like this:
Private Sub AxWindowsMediaPlayer1_PlayStateChange(ByVal sender As System.Object, ByVal e As AxWMPLib._WMPOCXEvents_PlayStateChangeEvent) Handles AxWindowsMediaPlayer1.PlayStateChange
If e.newState = WMPLib.WMPPlayState.wmppsStopped Then
Me.BeginInvoke(New Action(AddressOf NextSong))
End If
End Sub
Private Sub NextSong()
musictimer("next")
End Sub

VB - Using DownloadFileASync (WebClient) for multiple downloads

I'm trying to download multiple files based on what a user has selected on a form.
I have multiple checkboxes in place, so If a user would select Checkboxes 1,3,4 I would want the webclient to download files 1.txt, 3.txt, 4.txt.
The WebClient method is causing a "WebClient does not support concurrent I/O operations." error.
If chk1.Checked Then
WC.DownloadFileAsync(New Uri("http://www.google.com/1.txt), Path.Combine(DataSource & strDirectory, "1.txt"))
End If
If chk2.Checked Then
WC.DownloadFileAsync(New Uri("http://www.google.com/2.txt), Path.Combine(DataSource & strDirectory, "2.txt"))
End If
If chk3.Checked Then
WC.DownloadFileAsync(New Uri("http://www.google.com/3.txt), Path.Combine(DataSource & strDirectory, "3.txt"))
End If
If chk4.Checked Then
WC.DownloadFileAsync(New Uri("http://www.google.com/4.txt), Path.Combine(DataSource & strDirectory, "4.txt"))
End If
I do have a progress bar that tracks the download, as well as a completed event that calls a messagebox.
Private Sub WC_DownloadProgressChanged(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs) Handles WC.DownloadProgressChanged
ProgressBar1.Value = e.ProgressPercentage
End Sub
Private Sub WC_DownloadFileCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.AsyncCompletedEventArgs) Handles WC.DownloadFileCompleted
MessageBox.Show("Download complete", "Download", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub
How could I go about programming this to download all files checked?
I don't mind if the user only sees that progress bar showing total files downloaded or time remaining, but I do need something to show when all downloads are completed.
Any Suggestions?
I think is because of you using single WebClient instance to execute several HTTP requests at the same time. Try to use several instances.