vb.net auto login using webbrowser1 - vb.net

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

Related

How to split a procedure in few logic parts?

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

Why is this variable constantly resetting?

I'm working on a program in VB.net that uses the form load event to prompt for password. I have this working, but I am supposed to be showing the attempt number you are at if you fail. However, my code is always returning "Attempt #1" and never increasing to #2, #3, etc, and I am unsure why it is constantly being reset.
Private Function checkPassword(passwordGuess As String)
Dim isValid As Boolean = False
Dim password As String = "941206"
Dim attemptCounter As Integer
If isValid = False Then
If password <> txtPassword.Text Then
attemptCounter += 1
MessageBox.Show("Login Unsuccesful.",
"Attempt #" & attemptCounter)
Else
isValid = True
MessageBox.Show("Login Successful.",
"Attempt #" & attemptCounter)
Me.Text = "Attempt #" & attemptCounter
End If
End If
End Function
Private Sub btnConfirm_Click(sender As Object, e As EventArgs) Handles btnConfirm.Click
Dim password As String
password = txtPassword.Text
checkPassword(password)
End Sub
You could create a class to store information about attempts that persists across function calls:
Public Class attempt
Public Shared counter As Integer = 0
End Class
Private Function checkPassword(passwordGuess As String)
Dim isValid As Boolean = False
Dim password As String = "941206"
If isValid = False Then
If password <> txtPassword.Text Then
attempt.counter += 1
MessageBox.Show("Login Unsuccesful.",
"Attempt #" & attempt.counter)
Else
isValid = True
MessageBox.Show("Login Successful.",
"Attempt #" & attempt.counter)
Me.Text = "Attempt #" & attempt.counter
End If
End If
End Function
Private Sub btnConfirm_Click(sender As Object, e As EventArgs) Handles btnConfirm.Click
Dim password As String
password = txtPassword.Text
checkPassword(password)
End Sub

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 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

LDAP Query Handle empty attitributes

I am running a vb.net query into LDAP. I pull back the homedirectory. How can i write an IF statement to popup a msgbox if the homedirectory is empty versus the error "Object reference not set to an instance of an object."
code is below:
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
If TextBox2.Text = "" Then
MsgBox("Please enter a Network ID")
TextBox2.Focus()
Exit Sub
End If
Dim yourUserName As String = TextBox2.Text
Dim ADSearch As New DirectorySearcher()
Dim de As DirectoryEntry = GetDirectoryEntry()
ADSearch.SearchRoot = de
ADSearch.Filter = "(sAMAccountName=" & yourUserName & ")"
'ADSearch.PropertiesToLoad.Add("homedirectory")
Dim ADResult As SearchResult = ADSearch.FindOne()
If ADResult Is Nothing Then
MsgBox("User not found, please try again", MsgBoxStyle.OkOnly, "Not Found")
TextBox2.Text = ""
TextBox2.Focus()
Exit Sub
Else
Dim ADEntry As DirectoryEntry = New DirectoryEntry(ADResult.Path)
TextBox1.Text = (ADEntry.Properties("homeDirectory").Value.ToString)
End If
End Sub
You need to perform very basic null checking!
' if the "homeDirectory" hasn't been set -> then it will not show up in the SearchResult
If ADEntry.Properties("homeDirectory") Is Nothing Then
' do something
Else
If ADEntry.Properties("homeDirectory").Value Is Nothing Then
' do something
Else
' access your property here
TextBox1.Text = (ADEntry.Properties("homeDirectory").Value.ToString)
End If
End If