How to split a procedure in few logic parts? - vb.net

Hi, I'm creating a downloader by halving it in steps so that each part works logically.
The code is divided into:
public class Form1
Public Shared link As String 'I'm sharing data with another form
I insert a url to download in the textchanged event of textbox:
If (My.Settings.Cartellasalvataggio = "") Then
Label2.Text = "Download folder is missing"
' MsgBox("manca destinazione")
Else
If Clipboard.GetText.Contains("youtube") = False Then
Label2.Text = "not a valid youtube link"
Else
If TextBox1.Text = Clipboard.GetText Then
Label2.Text = "you already use it"
Else
TextBox1.Text = Clipboard.GetText
WebBrowser1.Navigate("https://www.320youtube.com/v8/watch?v=" +
_TextBox1.Text.Replace("https://www.youtube.com/watch?v=", ""))
End If
End If
End If
Then, in the document completed event I extract the download link:
Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
Dim collection As HtmlElementCollection = WebBrowser1.Document.All
Dim a As String
For Each element As HtmlElement In collection
If element.TagName = "A" Then
a = element.GetAttribute("HREF")
If a.Length > 70 Then
a.ToString.Replace(" - YouTube", "")
link = a
If link IsNot Nothing Then
Title()
End If
End If
End If
Next
End Sub
If the link variable is not empty then I activate the sub title:
Private Sub Title()
Dim wctitolo As New WebClient()
wctitolo.Encoding = Encoding.UTF8
Dim source As String = wctitolo.DownloadString(TextBox1.Text.Replace(" - YouTube", ""))
Dim title As String = Regex.Match(source, "\<title\b[^>]*\>\s*(?<Title>[\s\S]*?)\</title\>", RegexOptions.IgnoreCase).Groups("Title").Value
Dim a As String = title.Replace(" - YouTube", "")
Dim webdecode As String = WebUtility.HtmlDecode(a)
My.Settings.Titolo = String.Join("-", webdecode.Split(IO.Path.GetInvalidFileNameChars))
Label2.Text = "Getting title..- Step 3/4"
Label1.Text = My.Settings.Titolo
RichTextBox1.AppendText(vbLf + My.Settings.Titolo + Environment.NewLine)
formcs.BetterListBox1.Items.Add(My.Settings.Titolo)
My.Settings.Save()
If Fileexist() Then
Else
If My.Settings.Titolo IsNot Nothing Then
Download()
End If
End If
and sub FileExists () which returns true if the file exists and false if it does not exist. If it does not exist then, as dictated in private sub Title (), I activate the private sub Download ().
Public Function Fileexist() As Boolean
Label3.Text = Label3.Text + "Fileesiste+ "
Dim result As Boolean
Dim cartella = My.Settings.Cartellasalvataggio
Dim filedidestinazione = Directory.GetFiles(cartella,
My.Settings.Titolo + ".mp3",
SearchOption.AllDirectories).FirstOrDefault()
If filedidestinazione IsNot Nothing Then
Dim answer As String
answer = CType(MsgBox("File exist in" + vbLf + My.Settings.Cartellasalvataggio + "\" + My.Settings.Titolo + ".mp3" + vbLf + "Would you like to open the folder?", vbYesNo), String)
If CType(answer, Global.Microsoft.VisualBasic.MsgBoxResult) = vbYes Then
Process.Start("explorer.exe", "/select," & filedidestinazione)
result = True
Else
result = False
answer = CType(vbNo, String)
Label2.Text = "File exist"
End If
End If
Return result
End Function
and at the end, the Download sub:
Public WithEvents mclient As New WebClient
Private Sub mClient_DownloadProgressChanged(sender As Object, e As DownloadProgressChangedEventArgs) Handles mclient.DownloadProgressChanged
Try
Label4.Text = (Val(e.BytesReceived) / 1048576).ToString("0.00") & "MB Scaricati"
Label2.Text = "Download di " + My.Settings.Titolo + " in corso.."
Catch ex As Exception
End Try
End Sub
Private Sub Download()
Label3.Text = Label3.Text + "Download+ "
Dim filepath As String = (My.Settings.Cartellasalvataggio + "\" + Label1.Text + ".mp3")
mclient.Encoding = Encoding.UTF8
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
mclient.Headers.Add(HttpRequestHeader.UserAgent, "")
mclient.DownloadFileAsync(New Uri(link), filepath)
End Sub
I thought everything was fine, but at runtime I get an error for stackoverflow ..
The "Settings.Designer.vb" tab opens with the error
System.StackOverflowException in
<Global.System.Configuration.UserScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("")> _
Public Property Titolo() As String
Get
Return CType(Me("Titolo"),String)
End Get
Set
Me("Titolo") = value
End Set
End Property
is there an easy way I can concatenate these pieces of code in such a way that they work in a logical step by step without modifying to much the code?
Thank you

Related

vb.net auto login using webbrowser1

Trying to autologin to a web site using a vb.net form application. I do not receive any exceptions or errors. I Navigate to my page, set the email and password attributes and then click the 'cmd' button on the webpage. Using Debug statements I have verified the attributes are set.
After I click the 'cmd' button on the webpage I get back the same page I started with and cannot find anything that tells me there was an exception or error.
I am able to login to the webpage using chrome or IE using the same email/password combination.
Here is my code.
Private mPageReady As Boolean = False
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
AddHandler Me.WebBrowser1.DocumentCompleted, New WebBrowserDocumentCompletedEventHandler(AddressOf PageWaiter)
End Sub
Public Function LoginUser(pEmailAddress As String, pPassword As String) As Boolean
Dim IsOkay As Boolean = False
Dim myURL As String = "https://login.wlpc.com/index.php/"
Me.WebBrowser1.Navigate(myURL)
WaitForPageLoad()
Debug.WriteLine("After Navigate: " & Me.WebBrowser1.DocumentText)
Try
Me.WebBrowser1.Document.GetElementById("email").SetAttribute("value", pEmailAddress)
Debug.WriteLine("After assignment of email: " & Me.WebBrowser1.Document.GetElementById("email").GetAttribute("value"))
Me.WebBrowser1.Document.GetElementById("password").SetAttribute("value", pPassword)
Debug.WriteLine("After assignment of password: " & Me.WebBrowser1.Document.GetElementById("password").GetAttribute("value"))
Dim myDoc As HtmlDocument = Me.WebBrowser1.Document
Dim myCmd As HtmlElement = myDoc.All("cmd")
myCmd.InvokeMember("click")
WaitForPageLoad()
Debug.WriteLine("After click: " & Me.WebBrowser1.DocumentText)
IsOkay = True
Catch ex As Exception
IsOkay = False
End Try
Return IsOkay
End Function
Public Function GetPage(URL As String) As String
Debug.WriteLine(String.Format("Accessing {0}", URL))
Me.WebBrowser1.Navigate(URL)
WaitForPageLoad()
Dim pagedata As String = Me.WebBrowser1.DocumentText
Return pagedata
End Function
Public Sub WaitForPageLoad()
While Not mPageReady
Application.DoEvents()
End While
mPageReady = False
End Sub
Private Sub PageWaiter(ByVal sender As Object, ByVal e As WebBrowserDocumentCompletedEventArgs)
If Me.WebBrowser1.ReadyState = WebBrowserReadyState.Complete Then
mPageReady = True
End If
End Sub
Private Sub BtnSignin_Click(sender As Object, e As EventArgs) Handles BtnSignin.Click
LoginUser(mEmailAddress, mPassword)
End Sub
After further testing and a correction to my new code, I was able to complete the login process. Here is the code with a bunch of 'debug.writeline' statements.
Private Sub BtnSignIn_Click(sender As Object, e As EventArgs) Handles BtnSignIn.Click
Dim myURL As String = "https://login.wlpc.com/index.php/"
AddHandler Me.WebBrowser1.DocumentCompleted, New WebBrowserDocumentCompletedEventHandler(AddressOf WebBrowserDocumentCompleted)
Me.WebBrowser1.Navigate(myURL)
End Sub
Private Sub WebBrowserDocumentCompleted(ByVal sender As Object, ByVal e As WebBrowserDocumentCompletedEventArgs)
If Me.WebBrowser1.ReadyState <> WebBrowserReadyState.Complete Then
Debug.WriteLine(Me.WebBrowser1.ReadyState.ToString)
Return
End If
Try
Const lEmailAddress As String = "TestEmail#somewhere.com"
Const lThisPassword As String = "SimplePassword"
' get the form: <form action="/index.php" method="POST" name="login">
Dim lFormHtmlElement As HtmlElement = Nothing ' the form element
Dim lFormFound As Boolean ' can we find the form?
For Each lFormHtmlElement In WebBrowser1.Document.Forms()
If lFormHtmlElement.Name = "login" Then
lFormFound = True
Exit For
End If
Next
If Not lFormFound Then
Debug.WriteLine("Can't find form")
Exit Sub
End If
'<input type="email" name="email" value="" tabindex="1" placeholder="name#example.com">
Dim lEmail As HtmlElement = lFormHtmlElement.Document.GetElementById("email")
If IsNothing(lEmail) Then
Debug.WriteLine("lEmail element is nothing")
Exit Sub
Else
Debug.WriteLine("lEmail element was found")
End If
If IsNothing(lEmail.GetAttribute("value")) Then
Debug.WriteLine("lEmail attribute value is nothing before set")
Else
Debug.WriteLine("lEmail attribute value is contains '" & lEmail.GetAttribute("value") & "' before set")
End If
lEmail.SetAttribute("value", lEmailAddress)
If IsNothing(lEmail.GetAttribute("value")) Then
Debug.WriteLine("lEmail value is nothing after set")
ElseIf lEmail.GetAttribute("value") = lEmailAddress Then
Debug.WriteLine("lEmail set to: '" & lEmail.GetAttribute("value") & "'")
End If
'<input type="password" name="password" id="password1" size="25" tabindex="2">
Dim lPassword As HtmlElement = lFormHtmlElement.Document.GetElementById("password")
Dim lPassword1 As HtmlElement = lFormHtmlElement.Document.GetElementById("password1")
If IsNothing(lPassword) Then
Debug.WriteLine("lPassword element is nothing")
Exit Sub
Else
Debug.WriteLine("lPassword element was found")
End If
If IsNothing(lPassword1) Then
Debug.WriteLine("lPassword1 element is nothing")
Exit Sub
Else
Debug.WriteLine("lPassword1 element was found")
End If
If lPassword.Document.Body.InnerText = lPassword1.Document.Body.InnerText Then
Debug.WriteLine("lPassword and lPassword1 same body innertext")
Else
Debug.WriteLine("lPassword and lPassword1 have different body innertext")
End If
If IsNothing(lPassword.GetAttribute("value")) Then
Debug.WriteLine("lPassword attribute value is nothing before set")
Else
Debug.WriteLine("lPassword attribute value is contains '" & lPassword.GetAttribute("value") & "' before set")
End If
If IsNothing(lPassword1.GetAttribute("value")) Then
Debug.WriteLine("lPassword1 attribute value is nothing before set")
Else
Debug.WriteLine("lPassword1 attribute value is contains '" & lPassword1.GetAttribute("value") & "' before set")
End If
lPassword.SetAttribute("value", lThisPassword)
If IsNothing(lPassword.GetAttribute("value")) Then
Debug.WriteLine("lPassword attribute value is nothing after set")
Exit Sub
ElseIf lPassword.GetAttribute("value") = lThisPassword Then
Debug.WriteLine("lPassword set to: '" & lPassword.GetAttribute("value") & "'")
End If
If IsNothing(lPassword1.GetAttribute("value")) Then
Debug.WriteLine("lPassword1 is nothing")
ElseIf lPassword1.GetAttribute("value") = lThisPassword Then
Debug.WriteLine("lPassword1 attribute value is same password value as lPassword attribute value")
End If
'<button type="submit" name="cmd" value="cred_set" tabindex="3">
Dim lCmdButton As HtmlElement = lFormHtmlElement.Document.GetElementById("cmd")
If IsNothing(lCmdButton) Then
Debug.WriteLine("lCmdButton element is nothing")
Else
Debug.WriteLine("lCmdButton element was found")
' found the 'cmd' button so click it
lCmdButton.InvokeMember("click")
End If
Catch ex As Exception
Debug.WriteLine("exception: " & ex.Message)
Finally
RemoveHandler Me.WebBrowser1.DocumentCompleted, AddressOf WebBrowserDocumentCompleted
End Try
End Sub

How to use few subs in order to split the code procedure

I'm creating a downloader by halving it in steps so that each part works logically.
The code is divided into:
public class Form1
Public Shared link As String 'I'm sharing data with another form
I insert a url to download in the textchanged event of textbox:
If (My.Settings.Cartellasalvataggio = "") Then
Label2.Text = "Download folder is missing"
' MsgBox("manca destinazione")
Else
If Clipboard.GetText.Contains("youtube") = False Then
Label2.Text = "not a valid youtube link"
Else
If TextBox1.Text = Clipboard.GetText Then
Label2.Text = "you already use it"
Else
TextBox1.Text = Clipboard.GetText
WebBrowser1.Navigate("https://www.320youtube.com/v8/watch?v=" +
_TextBox1.Text.Replace("https://www.youtube.com/watch?v=", ""))
End If
End If
End If
Then, in the document completed event I extract the download link:
Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
label3.text=label3.text+"link download"
Dim collection As HtmlElementCollection = WebBrowser1.Document.All
Dim a As String
For Each element As HtmlElement In collection
If element.TagName = "A" Then
a = element.GetAttribute("HREF")
If a.Length > 70 Then
a.ToString.Replace(" - YouTube", "")
link = a
If link IsNot Nothing Then
Title()
End If
End If
End If
Next
End Sub
If the link variable is not empty then I activate the sub title:
Private Sub Title()
label3.text=label3.text+"title+ "
Dim wctitolo As New WebClient()
wctitolo.Encoding = Encoding.UTF8
Dim source As String = wctitolo.DownloadString(TextBox1.Text.Replace(" - YouTube", ""))
Dim title As String = Regex.Match(source, "\<title\b[^>]*\>\s*(?<Title>[\s\S]*?)\</title\>", RegexOptions.IgnoreCase).Groups("Title").Value
Dim a As String = title.Replace(" - YouTube", "")
Dim webdecode As String = WebUtility.HtmlDecode(a)
My.Settings.Titolo = String.Join("-", webdecode.Split(IO.Path.GetInvalidFileNameChars))
Label2.Text = "Getting title..- Step 3/4"
Label1.Text = My.Settings.Titolo
RichTextBox1.AppendText(vbLf + My.Settings.Titolo + Environment.NewLine)
formcs.BetterListBox1.Items.Add(My.Settings.Titolo)
My.Settings.Save()
If Fileexist() Then
Else
If My.Settings.Titolo IsNot Nothing Then
Download()
End If
End If
and sub FileExists () which returns true if the file exists and false if it does not exist. If it does not exist then, as dictated in private sub Title (), I activate the private sub Download ().
Public Function Fileexist() As Boolean
Label3.Text = Label3.Text + "Checking if file exist+ "
Dim result As Boolean
Dim cartella = My.Settings.Cartellasalvataggio
Dim filedidestinazione = Directory.GetFiles(cartella,
My.Settings.Titolo + ".mp3",
SearchOption.AllDirectories).FirstOrDefault()
If filedidestinazione IsNot Nothing Then
Dim answer As String
answer = CType(MsgBox("File exist in" + vbLf + My.Settings.Cartellasalvataggio + "\" + My.Settings.Titolo + ".mp3" + vbLf + "Would you like to open the folder?", vbYesNo), String)
If CType(answer, Global.Microsoft.VisualBasic.MsgBoxResult) = vbYes Then
Process.Start("explorer.exe", "/select," & filedidestinazione)
result = True
Else
result = False
answer = CType(vbNo, String)
Label2.Text = "File exist"
End If
End If
Return result
End Function
and at the end, the Download sub:
Public WithEvents mclient As New WebClient
Private Sub mClient_DownloadProgressChanged(sender As Object, e As DownloadProgressChangedEventArgs) Handles mclient.DownloadProgressChanged
Try
Label4.Text = (Val(e.BytesReceived) / 1048576).ToString("0.00") & "MB Scaricati"
Label2.Text = "Download di " + My.Settings.Titolo + " in corso.."
Catch ex As Exception
End Try
End Sub
Private Sub Download()
Label3.Text = Label3.Text + "Download+ "
Dim filepath As String = (My.Settings.Cartellasalvataggio + "\" + Label1.Text + ".mp3")
mclient.Encoding = Encoding.UTF8
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
mclient.Headers.Add(HttpRequestHeader.UserAgent, "")
mclient.DownloadFileAsync(New Uri(link), filepath)
End Sub
I thought It was ok but, Look at this gif Gif example
is there an easy way I can concatenate these pieces of code in such a way that they work in a logical step by step without modifying to much the code?
Thank you
Private Sub Title()
label3.text=label3.text & "title+ "
Public Function Fileexist() As Boolean
Label3.Text = Label3.Text & "Checking if file exist+ "
Private Sub Download()
Label3.Text = Label3.Text & "Download+ "
The label is updating one after the other; it is just happening so fast that you can't see it. To prove it to yourself, put a breakpoint somewhere after the label code in each method and you will see the label text building. BTW, the ampersand is the usual vb concatenation symbol. Any + sign inside a string is not considered a concatenation character. "title+" for example.
I think you will find that your code is more readable if you can start using interpolated strings.

multi-threaded code to check proxies

I'm suffering with this VB.Net 2017 code which is supposed to check if Proxies working or not. Sometimes it reach to an end successfully, and sometimes the program never reach and end or take lots of time to do so, although I have specified the timeout for every webrequest to be 11000... Also, the list of working proxies always has duplicates! I don't know how that happens, althoug the original (raw) list is unique!
Could you please help? This is supposed to wait till the 99 threads finished then another 99 (or the remaining threads) kick-started.
P.S. MYWEBSITE.com works for me only and it displays the IP address of the visitor, i.e. to double check if the proxy has worked fine
Imports System.Net
Imports System.IO
Imports System
Imports System.Text.RegularExpressions
Imports System.Threading
Public Class frmMain
Dim FinalWorkingProxies As New List(Of String)()
Private Sub btnBrowse_Click(sender As Object, e As EventArgs) Handles btnBrowse.Click
Control.CheckForIllegalCrossThreadCalls = False
PB.Maximum = txtRawIP.Lines.Count
PB.Value = 0
StartCheckingIP(0)
End Sub
Function StartCheckingIP(ByVal num As Integer)
For I As Integer = num To txtRawIP.Lines.Count - 1
Dim StrIPOnly As String = txtRawIP.Lines(I)
StrIPOnly = Trim(StrIPOnly.TrimStart("0"c)) 'remove any leading zeros
Try
Dim clsThreads As New System.Threading.Thread(AddressOf CheckIP)
clsThreads.Start(StrIPOnly)
Catch ex As Exception
MsgBox(I)
End Try
If (I > 0 And (I Mod 99 = 0)) Then Exit For
Next
Return True
End Function
Private Function CheckIP(ByVal Prox As String) As Boolean
'txtHTML.Text += vbCrLf & Prox
'txtHTML.Refresh()
Dim txtWebResult As String = ""
Dim OriginalFullProx As String = Trim(Prox)
Dim proxyObject As WebProxy = New WebProxy("http://" & OriginalFullProx & "/")
proxyObject.BypassProxyOnLocal = True
Prox = Prox.Substring(0, Prox.IndexOf(":"))
Dim sURL As String
sURL = "http://MYWEBSITE.com/testip.php"
Dim wrGETURL As WebRequest
wrGETURL = WebRequest.Create(sURL)
wrGETURL.Proxy = proxyObject
wrGETURL.Timeout = 6000
txtWebResult = "Dosn't work"
Try
Dim objStream As Stream
objStream = wrGETURL.GetResponse.GetResponseStream
Dim objReader As New StreamReader(objStream)
Dim sLine As String = ""
sLine = objReader.ReadLine
If Not sLine Is Nothing Then
txtWebResult = sLine
End If
txtWebResult = Regex.Replace(txtWebResult, “^\s+$[\r\n]*”, “”, RegexOptions.Multiline)
If (Trim(Prox) = Trim(txtWebResult)) Then
FinalWorkingProxies.Add(OriginalFullProx)
End If
Catch ex As Exception
txtWebResult = "Dosn't work"
End Try
If (PB.Value < PB.Maximum) Then PB.Value += 1
PB.Refresh()
If (PB.Value = PB.Maximum) Then
txtFilteredIP.Clear()
Randomize()
Dim RRR As Integer = CInt(Math.Ceiling(Rnd() * 1000)) + 1
Thread.Sleep(RRR)
If (txtFilteredIP.Text <> "") Then Return False
Dim str As String
For Each str In FinalWorkingProxies
txtFilteredIP.Text += str & vbCrLf
Next
ElseIf ((PB.Value - 1) > 0 And ((PB.Value - 1) Mod 99 = 0)) Then
StartCheckingIP(PB.Value)
End If
Return True
End Function
Private Sub txtRawIP_TextChanged(sender As Object, e As EventArgs) Handles txtRawIP.TextChanged
lblRawIPTotal.Text = "Total: " & txtRawIP.Lines.Count
End Sub
Private Sub txtFilteredIP_TextChanged(sender As Object, e As EventArgs) Handles txtFilteredIP.TextChanged
lblFilteredIPTotal.Text = "Total: " & txtFilteredIP.Lines.Count
End Sub
End Class
Here is the modified code, but it stills takes long of time to finalize long list of proxies, although I sat max concurrent connection to 2000 and timeout to 8sec. Please help. Thanks.
Public Class frmMain
Dim FinalWorkingProxies As New List(Of String)()
Private Sub btnBrowse_Click(sender As Object, e As EventArgs) Handles btnBrowse.Click
'Control.CheckForIllegalCrossThreadCalls = False
ServicePointManager.Expect100Continue = False
ServicePointManager.DefaultConnectionLimit = 2000
'ServicePointManager.Expect100Continue = True
FinalWorkingProxies.Clear()
PB.Maximum = txtRawIP.Lines.Count
PB.Value = 0
StartCheckingIP(0)
End Sub
Function StartCheckingIP(ByVal num As Integer)
For I As Integer = num To txtRawIP.Lines.Count - 1
Dim StrIPOnly As String = txtRawIP.Lines(I)
StrIPOnly = Trim(StrIPOnly.TrimStart("0"c)) 'remove any leading zeros
Try
Dim clsThreads As New System.Threading.Thread(AddressOf CheckIP)
clsThreads.Start(StrIPOnly)
Catch ex As Exception
MsgBox(I)
End Try
If (I > 0 And (I Mod 333 = 0)) Then Exit For
Next
Return True
End Function
Private Function CheckIP(ByVal Prox As String) As Boolean
'txtHTML.Text += vbCrLf & Prox
'txtHTML.Refresh()
Dim txtWebResult As String = ""
Dim OriginalFullProx As String = Trim(Prox)
Dim proxyObject As WebProxy = New WebProxy("http://" & OriginalFullProx & "/")
proxyObject.BypassProxyOnLocal = True
Prox = Prox.Substring(0, Prox.IndexOf(":"))
Dim sURL As String
sURL = "http://MYWEBSITE.com/testip.php"
Dim wrGETURL As WebRequest
wrGETURL = WebRequest.Create(sURL)
wrGETURL.Proxy = proxyObject
wrGETURL.Timeout = 8000
txtWebResult = "Dosn't work"
Try
Dim objStream As Stream
objStream = wrGETURL.GetResponse.GetResponseStream
Dim objReader As New StreamReader(objStream)
Dim sLine As String = ""
sLine = objReader.ReadLine
If Not sLine Is Nothing Then
txtWebResult = sLine
End If
txtWebResult = Regex.Replace(txtWebResult, “^\s+$[\r\n]*”, “”, RegexOptions.Multiline)
If (Trim(Prox) = Trim(txtWebResult)) Then
'Now know exact country
sURL = "http://ip-api.com/xml/" & Prox
wrGETURL = WebRequest.Create(sURL)
wrGETURL.Proxy = proxyObject
wrGETURL.Timeout = 8000
objStream = wrGETURL.GetResponse.GetResponseStream
Dim objReader2 As New StreamReader(objStream)
Dim FullCODEOFAPI As String = objReader2.ReadToEnd()
Dim XMLR As XmlReader
XMLR = XmlReader.Create(New StringReader(FullCODEOFAPI))
XMLR.ReadToFollowing("country")
XMLR.Read()
OriginalFullProx += "-" + XMLR.Value
FinalWorkingProxies.Add(OriginalFullProx)
End If
Catch ex As Exception
txtWebResult = "Dosn't work"
End Try
If (PB.Value < PB.Maximum) Then UpdatePB(1)
If (PB.Value = PB.Maximum) Then
UpdateFilteredList(1)
ElseIf ((PB.Value - 1) > 0 And ((PB.Value - 1) Mod 333 = 0)) Then
StartCheckingIP(PB.Value)
End If
Return True
End Function
Private Delegate Sub UpdatePBDelegate(ByVal PBVal As Integer)
Private Sub UpdatePB(ByVal PBVal As Integer)
If PB.InvokeRequired Then
PB.Invoke(New UpdatePBDelegate(AddressOf UpdatePB), New Object() {PBVal})
Else
PB.Value += PBVal
PB.Refresh()
End If
End Sub
Private Delegate Sub UpdateFilteredListDelegate()
Private Sub UpdateFilteredList(ByVal TMP As Integer)
If txtFilteredIP.InvokeRequired Then
txtFilteredIP.Invoke(New UpdatePBDelegate(AddressOf UpdateFilteredList), New Object() {TMP})
Else
txtFilteredIP.Clear()
Dim str As String
For Each str In FinalWorkingProxies
txtFilteredIP.Text += str & vbCrLf
Next
End If
End Sub
Private Sub txtRawIP_TextChanged(sender As Object, e As EventArgs) Handles txtRawIP.TextChanged
lblRawIPTotal.Text = "Total: " & txtRawIP.Lines.Count
End Sub
Private Sub txtFilteredIP_TextChanged(sender As Object, e As EventArgs) Handles txtFilteredIP.TextChanged
lblFilteredIPTotal.Text = "Total: " & txtFilteredIP.Lines.Count
End Sub
Private Sub btnLoadList_Click(sender As Object, e As EventArgs) Handles btnLoadList.Click
OFD.ShowDialog()
If (OFD.FileName <> "") Then
txtRawIP.Text = File.ReadAllText(OFD.FileName)
End If
End Sub
End Class

Form.show() in VB.NET returning InvalidOperationException

For some reason while I call a specific form in my program it comes up with
An unhandled exception of type 'System.InvalidOperationException' occurred in CinemaBooking2.exe
Additional information: An error occurred creating the form. See Exception.InnerException for details. The error is: Conversion from string "" to type 'Integer' is not valid.
But I'm not sure why. This only suddenly started happening and I'm not sure if it's visual studio messing up or me.
This is the form it is trying to load:
Imports System.IO
Public Class MainMenu2
Dim intChildren As Integer = 0
Dim intStandard As Integer = 0
Dim intOAP As Integer = 0
Public intTotal As Integer = 0
Dim Reader As StreamReader
Dim Writer As StreamWriter
Dim booAdmin As Boolean
Private Sub BtnComingSoon_Click(sender As Object, e As EventArgs) Handles BtnComingSoon.Click
Me.Visible = False
frmComingSoon.Visible = True
End Sub
Private Sub BtnEdit_Click(sender As Object, e As EventArgs)
Me.Hide()
FrmNowShowing.Show()
End Sub
Private Sub FrmMenu_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Reader = New StreamReader("NowShowing.txt")
LblShowing1.Text = ("Now showing: " & Reader.ReadLine)
LblShowing2.Text = ("Now showing: " & Reader.ReadLine)
Reader.Close()
Reader = New StreamReader("Settings.txt")
booAdmin = Reader.ReadLine
Reader.Close()
If booAdmin = False Then
BtnRefresh.Hide()
BtnEdit.Hide()
End If
End Sub
Private Sub BtnBook_Click(sender As Object, e As EventArgs) Handles BtnBook.Click
Me.Hide()
FrmBookings.Show()
End Sub
Private Sub CmbChildren_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CmbChildren.SelectedIndexChanged
intStandard = CInt(CmbStandard.Text) 'Code for standard combo box
intTotal = intChildren + intStandard + intOAP
LblTotal.Text = ("Total: £" & (intChildren * 3.5) + (intStandard * 5.95) + (intOAP * 4.95) & " for " & intTotal & " People.")
Reader.Close()
If intTotal > 0 And intTotal <= 100 Then
BtnBook.Enabled = True
Else
BtnBook.Enabled = False
End If
Reader = New StreamReader("Settings.txt")
booAdmin = Reader.ReadLine
Reader.Close()
Writer = New StreamWriter("Settings.txt")
Writer.WriteLine(booAdmin)
Writer.WriteLine(intTotal)
Writer.Close()
End Sub
Private Sub CmbStandard_SelectedIndexChanged_1(sender As Object, e As EventArgs) Handles CmbStandard.SelectedIndexChanged
intStandard = CInt(CmbStandard.Text) 'Code for standard combo box
intTotal = intChildren + intStandard + intOAP
LblTotal.Text = ("Total: £" & (intChildren * 3.5) + (intStandard * 5.95) + (intOAP * 4.95) & " for " & intTotal & " People.")
Reader.Close()
If intTotal > 0 And intTotal <= 100 Then
BtnBook.Enabled = True
Else
BtnBook.Enabled = False
End If
Reader = New StreamReader("Settings.txt")
booAdmin = Reader.ReadLine
Reader.Close()
Writer = New StreamWriter("Settings.txt")
Writer.WriteLine(booAdmin)
Writer.WriteLine(intTotal)
Writer.Close()
End Sub
Private Sub CmbOAP_SelectedIndexChanged_1(sender As Object, e As EventArgs) Handles CmbOAP.SelectedIndexChanged
intOAP = CInt(CmbOAP.Text) 'Code for OAP combo box
intTotal = intChildren + intStandard + intOAP
LblTotal.Text = ("Total: £" & (intChildren * 3.5) + (intStandard * 5.95) + (intOAP * 4.95) & " for " & intTotal & " People.")
Reader.Close()
If intTotal > 0 And intTotal <= 100 Then
BtnBook.Enabled = True
Else
BtnBook.Enabled = False
End If
Reader = New StreamReader("Settings.txt")
booAdmin = Reader.ReadLine
Reader.Close()
Writer = New StreamWriter("Settings.txt")
Writer.WriteLine(booAdmin)
Writer.WriteLine(intTotal)
Writer.Close()
End Sub
End Class
This error only appears for this form and no others, so I am unsure of if it is something to do with the form, or if the form has corrupted in some way.
Reader.ReadLine returns strings. I see several places in your code where you are trying to directly assign string values to variables that are not strings. for example:
booAdmin = Reader.ReadLine
This should probably be:
booAdmin = Boolean.Parse(Reader.ReadLine)
Any place where you are trying to read an integer should be:
someIntegerVariable = Integer.Parse(Reader.Readline)
If you want to be even more same, use TryParse instead of Parse, but that will have slightly different semantics.

How to open new form once process in command line is complete

I have been trying to figure this out for the best part of a day now and I cannot wrap my head around this issue.
I do not have much prior code knowledge but I try to research before I attempt to code anything. I have a basic understanding of how VB.net works but need some help with my code
Public Class Form1
Dim CopyFrom As String
Dim CopyTo As String
Dim RoboCopyVariables As String
Dim CopyS As String
Dim CopyE As String
Dim WaittimeTXT As String
Dim WaitTime As String
Dim RetryAttemptsTXT As String
Dim RetryAttempts As String
Dim pProcess() As Process = System.Diagnostics.Process.GetProcessesByName("CMD")
Private Sub RunBTN_Click(sender As Object, e As EventArgs) Handles RunBTN.Click
CopyFrom = CopyFromTXT.Text
CopyTo = CopyToTXT.Text
'All of the selections for if CopyS has been checked
If CopySFoldersCB.Checked = True Then
CopyS = " /s"
ElseIf CopySFoldersCB.Checked = False Then
CopyS = ""
End If
If CopyEFoldersCB.Checked = True Then
CopyE = " /e"
ElseIf CopyEFoldersCB.Checked = False Then
CopyE = ""
End If
If WaitTimeCB.Checked = True Then
WaittimeTXT = WaitTimeTXT1.Text
WaitTime = " /w:" & WaittimeTXT
ElseIf WaitTimeCB.Checked = False Then
WaitTime = ""
End If
If RetryAttemptsCB.Checked = True Then
RetryAttemptsTXT = RetryAttempts1.Text
RetryAttempts = " /r:" & RetryAttemptsTXT
ElseIf RetryAttemptsCB.Checked = False Then
RetryAttempts = ""
End If
RoboCopyVariables = CopyS + CopyE + WaitTime + RetryAttempts
'CommandTest.Text = "/k robocopy " + CopyFrom + " " + CopyTo + "" + RoboCopyVariables
Process.Start("CMD", "/k robocopy " + CopyFrom + " " + CopyTo + "" + RoboCopyVariables)
For Each p As Process In pProcess
p.Kill()
Next
Form2.Show()
Me.Hide()
End Sub
Private Sub CancelButton_Click(sender As Object, e As EventArgs) Handles CancelButton.Click
Me.Close()
Form2.Close
End Sub
End Class
Thank you for all the help I recieve
Firstly, since RoboCopy is a command-line interface application (things badly known as "external command" in Batch) then you should call it directly, because there is no need to call the Windows command-line just only to "host" another app.
Secondly, to solve the main problem that you are having, you can use the Process.WaitForExit method, this will block the current thread until the process has exited.
Dim p As New Process
p.StartInfo.FileName = "Robocopy.exe"
p.StartInfo.Arguments = String.Format("""{0}"" ""{1}"" {2}",
CopyFrom, CopyTo, RoboCopyVariables)
p.Start()
p.WaitForExit(-1)
Another solution is to to enable the process to raise events then subscribe to the Process.Exited event, this will result in a non-thread-blocking mechanism good for asynchronous scenarios.
Public Class yourClassName
Friend WithEvents P As New Process
' Call "Test" method somewhere...
Sub Test()
Dim copyFrom As String = ...
Dim copyTo As String = ...
Dim roboCopyVariables As String = ...
Me.P.EnableRaisingEvents = True
Me.P.StartInfo.FileName = "Robocopy.exe"
Me.P.StartInfo.Arguments = String.Format("""{0}"" ""{1}"" {2}",
copyFrom, copyTo, roboCopyVariables)
Me.P.Start()
' Can do any thing here while asynchronouslly we wait for the process to exit...
End Sub
Private Sub P_Exited(ByVal sender As Object, ByVal e As EventArgs) _
Handles P.Exited
' Show the form here...
Form2.Show()
Me.Hide()
End Sub
End Class