Why is this variable constantly resetting? - vb.net

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

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

I am looking to use textfiles to validate a username and password login

I am looking to use textfiles to validate a username and password in VB.NET.
I have the username validated but I can not validate the passsword and anything entered in txtpassowrd.text will result in a login.
The code I used is this:
Imports System.IO
Public Class frmReceptionist
Function IsInFile(ByVal person As String) As Boolean
If File.Exists("receptionistUser.txt") And File.Exists("receptionistPassword.txt") Then
Dim sr As StreamReader = File.OpenText("receptionistUser.txt")
Dim individual As String
Do Until sr.EndOfStream
individual = sr.ReadLine
If individual = person Then
sr.Close()
Return True
End If
Loop
sr.Close()
End If
Return False
End Function
Private Sub btnConfirm_Click(sender As Object, e As EventArgs) Handles btnConfirm.Click
'Determine if a person is in the file
Dim person As String = txtUsername.Text
If person <> "" Then
If IsInFile(person) Then
MessageBox.Show(person & " Welcome Receptionist", "Bia Duitse")
Me.Hide()
frmBiaDuitse.Show()
Else
MessageBox.Show(person & " Incorrect Login", "No")
End If
Else
MessageBox.Show("You must enter Details", "Information")
End If
txtUsername.Clear()
txtUsername.Focus()
End Sub
Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
Me.Hide()
frmSelectJob.Show()
End Sub
End Class
This is definitely not the way you should be doing this.
For learning purposes, you could load up your files into a Dictionary() like this:
Private Credentials As Dictionary(Of String, String)
Private Sub LoadCredentials()
If IsNothing(Credentials) Then
Credentials = New Dictionary(Of String, String)()
If File.Exists("receptionistUser.txt") And File.Exists("receptionistPassword.txt") Then
Dim users() As String = File.ReadAllLines("receptionistUser.txt")
Dim passwords() As String = File.ReadAllLines("receptionistPassword.txt")
If users.Length = passwords.Length Then
For i As Integer = 0 To users.Length - 1
Credentials.Add(users(i), passwords(i))
Next
End If
End If
End If
End Sub
Function IsInFile(ByVal person As String) As Boolean
LoadCredentials()
If Not IsNothing(Credentials) Then
Return Credentials.ContainsKey(person)
End If
Return False
End Function
Function Checkpassword(ByVal person As String, ByVal password As String) As Boolean
LoadCredentials()
If Not IsNothing(Credentials) Then
Return Credentials.ContainsKey(person) AndAlso password = Credentials(person)
End If
Return False
End Function

(VB.NET) Object reference not set to an instance of an object

This program works like this: User enters building name and number of floors, that gets validated and accepted. Then user enters rates for each floor until it goes through all floors, that data gets added to a listbox, then user enters a desired floor and it adds the rent and other info to another listbox lower down. As soon as I enter my number of floors and click on the button to save the info, the program runs into an error under btnEnterBuilding Click event where it says dblRates(intHowMany) = dblRent. The error is
"An unhandled exception of type 'System.NullReferenceException' occurred in WindowsApplication5.exe
Additional information: Object reference not set to an instance of an object."
Any help would be greatly appreciated, thanks!
Option Explicit On
Option Strict On
Option Infer Off
Public Class Form1
Dim dblRates() As Double
Dim intHowMany As Integer = 0 'points to the next avail entry in the array
Private Function ValidateString(ByVal strText As String, strInput As String, strValue As String) As Boolean
If strText = Nothing Then
MessageBox.Show(strText & " Must Be Supplied", "Error")
Return False
Else
Return True
End If
End Function
Private Function ValidateInteger(ByVal strText As String,
ByVal strIn As String,
ByRef intValue As Integer,
ByVal intMinValue As Integer,
ByVal intMaxValue As Integer) As Boolean
If strIn = Nothing Then
MessageBox.Show(strText & " Must Be Supplied", "Error")
Return False
Else
If Integer.TryParse(strIn, intValue) = False Then
MessageBox.Show(strText & " Must Be A Whole Number", "Error")
Return False
Else
If intValue < intMinValue Or intValue > intMaxValue Then
MessageBox.Show("Outside of Number of " & strText & " Limits", "Error")
Return False
Else
Return True
End If
End If
End If
End Function
Private Function ValidateDouble(ByVal strText As String,
ByVal strDbl As String,
ByRef dblValue As Double,
ByVal dblMinValue As Double,
ByVal dblMaxValue As Double) As Boolean
If strDbl = Nothing Then
MessageBox.Show(strText & " Must Be Supplied", "Error")
Return False
Else
If Double.TryParse(strDbl, dblValue) = False Then
MessageBox.Show(strText & " Must Be A Whole Number", "Error")
Return False
Else
If dblValue < dblMinValue Or dblValue > dblMaxValue Then
MessageBox.Show("Outside of Number of " & strText & " Limits", "Error")
Return False
Else
Return True
End If
End If
End If
End Function
Private Sub Form1_Load(sender As Object,
e As EventArgs) Handles Me.Load
Me.grpBuilding.Enabled = True
Me.grpRents.Enabled = False
Me.grpDesiredFloor.Enabled = False
End Sub
Private Sub btnRents_Click(sender As Object,
e As EventArgs) _
Handles btnRents.Click
Dim strName, strFloors As String
Dim intFloors As Integer
strName = txtName.Text
strFloors = txtFloors.Text
intFloors = CInt(strFloors)
If ValidateString("Building name", Me.txtName.Text, strName) = True Then
If ValidateInteger("Number of floors", Me.txtFloors.Text, intFloors, 3, 20) = True Then
Me.grpBuilding.Enabled = False
Me.grpRents.Enabled = True
Me.grpDesiredFloor.Enabled = False
End If
End If
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Close()
End Sub
Private Sub btnEnterBuilding_Click(sender As Object,
e As EventArgs) _
Handles btnEnterBuilding.Click
Dim intFloors As Integer
Dim dblRent As Double
Dim strRent As String
strRent = txtRent.Text
dblRent = CDbl(strRent)
If ValidateDouble("Rent", Me.txtRent.Text, dblRent, 1000.0, 2500.0) = True Then
dblRates(intHowMany) = dblRent
Me.txtRent.Focus()
Me.txtRent.SelectAll()
Me.ListBox1.Items.Add("Floor No. " & intHowMany.ToString("N0") &
" -- Rent Is: " & dblRent.ToString("N$"))
If intHowMany < intFloors Then
intHowMany += 1
Else
Me.grpBuilding.Enabled = False
Me.grpRents.Enabled = False
Me.grpDesiredFloor.Enabled = True
End If
Else
Me.txtRent.Focus()
Me.txtRent.SelectAll()
End If
End Sub
Private Sub btnCompute_Click(sender As Object, e As EventArgs) Handles btnCompute.Click
Dim intFloors, intFloor As Integer
Dim strName, strFloors As String
strName = txtName.Text
strFloors = txtFloors.Text
intFloors = CInt(strFloors)
If ValidateInteger("Desired Floor", Me.txtFloor.Text, intFloor, 3, 20) = False Then
MessageBox.Show("Please enter a valid floor number", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
Me.lstDisplay.Items.Add("Building Name: " & strName & " # of Floors: " & intFloors.ToString)
Me.lstDisplay.Items.Add("Desired Floor: " & intFloor.ToString)
Me.lstDisplay.Items.Add(" Rent: " & intFloors.ToString)
End If
End Sub
End Class
You can't dim dblRates() as double like this without giving it initial values. You will need to dim dblRates(<some amount>) as Double and then redim it if necessary to add more values to it. Or you could Dim dblRates() as double = {0} but if you still want to add more values to the array, you will still need to redim it as the second options would just create an array of 1 element.

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