I am trying to make a program that requires the user to sign in and if the right username and password is entered then open a form for that user. The way I have it done just now is the username is stored in a variable and I was wondering how I can use the text from the variable in the form name for example:
UserName = User1 then
FrmUser1.show
UserName = JohnSmith then
FrmJohnSmith.show
Here is an excerpt from the code I have so far:
Dim Path As String = "Account_File.text "
Dim Read_File() As String = File.ReadAllLines(Path)
Dim NoOfLines As Integer = Read_File.Length
Dim UserName(NoOfLines) As String
Dim Password(NoOfLines) As String
Dim LastNonEmpty As Integer = -1
Dim InputUserName As String = ""
Dim InputPassword As String = ""
If TxtUserName.Text = "" Then
MsgBox("Please enter a username.")
GoTo InvalidDetails
Else
InputUserName = TxtUserName.Text
End If
If TxtPassword.Text = "" Then
MsgBox("Please enter a Password.")
GoTo InvalidDetails
Else
InputPassword = TxtPassword.Text
End If
For i = 0 To NoOfLines
Dim SplitString() As String = Split(Read_File(i))
For j As Integer = 0 To SplitString.Length - 1
If SplitString(j) <> "" Then
LastNonEmpty += 1
SplitString(LastNonEmpty) = SplitString(j)
End If
Next
ReDim Preserve SplitString(LastNonEmpty)
LastNonEmpty = -1
UserName(i) = SplitString(0)
Password(i) = SplitString(1)
Next
For i = 0 To NoOfLines
If UserName(i) = InputUserName And Password(i) = InputPassword Then
frm.show()
Else
MsgBox("Either the username or password is incorrect.")
End If
Next
Some sample code:
Dim formname = "Form" + TxtUserName.Text
Dim typename = Me.GetType().Namespace + "." + formname
Dim type = Me.GetType().Assembly.GetType(typename)
If type IsNot Nothing Then
Dim form = CType(Activator.CreateInstance(type), Form)
form.Show()
End If
Which assumes that all forms live in the same assembly and have the same namespace. Do keep in mind that your customer isn't very likely to be thrilled to have to call you every single time he gets a new employee. Or for that matter is going to like you asking for username + password without providing the kind of security guarantees that a Windows logon already provides. Don't do this.
Related
Do
Do
Console.WriteLine("Create a password. It must be 8 characters in length")
password1 = Console.ReadLine()
Loop Until password1.Length = 8
Console.WriteLine("Please re-enter the password.")
password2 = Console.ReadLine()
Loop Until password2 = password1
password = password1
Console.WriteLine("your password has been created.")
Console.ReadLine()
The below code generates the file
Dim fileName = "C:\Users\emily\Documents\Details.csv"
Dim fileAppend As New System.IO.StreamWriter(fileName, True)
fileAppend.WriteLine(name & ", " & age & ", " & username & ", " & password & ", " & yeargroup)
fileAppend.Close()
So basically I have details about the users stored in a csv file. The columns are arranged as follows: name, age, username, password, yeargroup. I need to be able to input a username and for it to be found in the array/list and then input the password and if the password doesn't match for it to start again.
Nice homework. You should think about storing password. Clear text is obviously risky. With the user file load in a table like this will let you manage all of the user. Add,Remove, Change then just save over the userfile.
Public Class Form1
Dim UserTable As New DataTable("UserTable")
Dim SomeUserName As String = "slims"
Dim SomePassword As String = "abc1234!"
Sub ReadUserFile()
Dim fileName = "C:\dump\test.csv"
Dim fileReader As New System.IO.StreamReader(fileName)
UserTable.Columns.Add("Name")
UserTable.Columns.Add("Age")
UserTable.Columns.Add("Username")
UserTable.Columns.Add("Password")
UserTable.Columns.Add("YearGroup")
Do Until fileReader.EndOfStream = True
Dim OneLine As String = fileReader.ReadLine()
UserTable.Rows.Add(OneLine.Split(","))
Loop
fileReader.Close()
End Sub
Sub WriteUserFile()
Dim fileName = "C:\dump\test.csv"
Dim fileWriter As New System.IO.StreamWriter(fileName)
For Each xRow As DataRow In UserTable.Rows
fileWriter.WriteLine(String.Format("{0},{1},{2},{3},{4}", xRow("Name"), xRow("Age"), xRow("Username"), xRow("Password"), xRow("YearGroup")))
Next
fileWriter.Close()
End Sub
Function CheckUserPassword(UserName As String, Password As String) As Boolean
Dim Found As Boolean = False
For Each xRow As DataRow In UserTable.Rows
If (xRow("Username") = SomeUserName) And (xRow("Password") = SomePassword) Then
Found = True
Exit For
Else
Found = False
End If
Next
Return Found
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ReadUserFile()
If CheckUserPassword(SomeUserName, SomePassword) = True Then
'Good to go
Else
'bad user/pass
End If
WriteUserFile()
End Sub
End Class
You can use IO.File.ReadAllLines(fileName) to read the lines into an array of strings. Then you can use String.Split() on each line to split the fields and pick out the username and password.
dim allLines as String() = IO.File.ReadAllLines(fileName)
for each line as String in allLines
dim lineArray() as string
lineArray = line.Split(New Char() {","c})
username = lineArray(2)
password = lineArray(3)
if username = theUsernameYouWant then
'Found the user. Now check their password
endif
next
I havn't tested this code. Might have syntax errors.
Code for reading and splitting from file:
Public Sub LoadAccount()
currentfilereader = New StreamReader(filename)
Dim Seperator As Char = " "c
For count As Integer = 0 To NumUsers - 1
textstring = currentfilereader.ReadLine
Dim words() As String = currentfilereader.ReadLine.Split(Seperator)
Username = words(0)
Password = words(1)
If words(2) = "1" Then
AccessGranted = True
Else
AccessGranted = False
End If
Users(count, 0) = Username
Users(count, 1) = Password
Users(count, 2) = AccessGranted
Next
currentfilereader.Close()
End Sub
Code for logging in:
Public Sub Login()
Dim InvalidUsername, InvalidPassword As Boolean
InvalidUsername = True
InvalidPassword = True
LoginName = Form1.tbun.Text
LoginPassword = Form1.tbpw.Text
For count As Integer = 0 To NumUsers - 1
If LoginName = Users(count, 0) Then
InvalidUsername = False
If LoginPassword = Users(count, 1) Then
InvalidPassword = False
CurrentUsername = LoginName
CurrentPassword = LoginPassword
CurrentAccessGranted = Users(count, 2)
loggedin = True
Else
MsgBox("Invalid Password")
End If
Else
MsgBox("Invalid Username")
End If
Next
End Sub
Code for calculating number of users:
Public Sub NumberOfUsers()
currentfilereader = New StreamReader(filename)
NumUsers = File.ReadAllLines("Accounts.txt").Length
MsgBox("There are " & NumUsers & " users")
End Sub
I have added a MsgBox to show the number of users to make sure all is working fine which returns the value of 2, since I currently have 2 lines in the text file, "a a 1" and "b b 1".
However when this line runs, Dim words() As String = currentfilereader.ReadLine.Split(Seperator), it returns null.
The purpose of subtracting 1 from the NumUsers in the count is since the count starts at zero along with the array. Meaning that if I didn't it would check 3 times if there is only 2 users in the file. But I just can't seem to figure out what is wrong and why it is returning null.
You call ReadLine twice for each user:
textstring = currentfilereader.ReadLine
Dim words() As String = currentfilereader.ReadLine.Split(Seperator)
This means that for the first user you read both lines, and for the second user you read nothing, leading to the empty split array.
Replace
Dim words() As String = currentfilereader.ReadLine.Split(Seperator)
With
Dim words() As String = textstring.Split(Seperator)
I have been having this problem lately with the code i'm making for a school encryption program, and I have been trying for hours to get around this error but I cant seem to get it working, What do you's thing?
TextBox1.Text = TextBox1.Text.ToLower
Dim input As String = TextBox1.Text
Dim charPos As Integer = 0
Dim Cipher As String = ""
Dim x As Boolean
Dim Random As Boolean
If input = "" Then
MsgBox("Please enter your text for encryption including only characters A-Z")
End If
Select Case Random
Case 0
Random = ComboBox1.SelectedItem.ToString()
Case 1
Random = "selection1"
x = True
Case Else
x = False
End Select
If x = True Then
Dim alphabet As String = "abcdefghij klmnopqrstuvwxyz"
Dim code As String = "kxgtlmpqbwcnderfahjusvi yoz"
For i = 0 To input.Length - 1
Try
charPos = alphabet.IndexOf(input(i))
Cipher = Cipher & code(charPos)
Catch ex As Exception
MsgBox("Please enter your text for encryption including only characters A-Z")
End Try
Next i
TextBox1.Text = (Cipher)
Else
End If
End Sub
The actual error itself in Visual Basic is at
Random = ComboBox1.SelectedItem.ToString()
Sorry if this is hard to understand, I'm new to both Stackoverflow, and VB so if you don't quite understand it comment please :)
Here is an example using your code.
TextBox1.Text = TextBox1.Text.ToLower
Dim input As String = TextBox1.Text
Dim charPos As Integer = 0
Dim Cipher As String = ""
If input = "" Then
MsgBox("Please enter your text for encryption including only characters A-Z")
End If
If ComboBox1.SelectedIndex = 0 Then
Dim alphabet As String = "abcdefghij klmnopqrstuvwxyz"
Dim code As String = "kxgtlmpqbwcnderfahjusvi yoz"
For i = 0 To input.Length - 1
Try
charPos = alphabet.IndexOf(input(i))
Cipher = Cipher & code(charPos)
Catch ex As Exception
MsgBox("Please enter your text for encryption including only characters A-Z")
End Try
Next i
TextBox1.Text = (Cipher)
Else
End If
End Sub
I have been doing A-Level Computing for a couple of months now and I have decided to make a phonebook relevant to the methods used in class. For my exam I am not allowed to use StreamReader etc... However, I can use methods such as FileOpen(1, "FILE NAME", OpenMode.Binary).
I want to store usernames and passwords in a text file (I know its not a good method but it links to my lessons). My .txt file is formatted like:
Username, Password.
Username2, Password2.
What would i be able to do to make it store each Username and Password in a list?
Here's what I've got... (don't know why it doesn't work)
Private Sub CheckAccount()
Dim Username_File As New ArrayList
Dim Username_Temp As String = ""
Dim Password_File As New ArrayList
Dim Password_Temp As String = ""
FileOpen(1, "Users.txt", OpenMode.Binary)
Do While Not EOF(1)
Dim PosCount_Start As Integer = 0
Dim PosCount_End As Integer = 0
Dim TempChar As Char = ""
Do
FileGet(1, TempChar)
If TempChar = "," Then Exit Do
Username_Temp = Username_Temp + TempChar
PosCount_End = PosCount_End + 1
Loop
Username_Temp = Username_Temp.Substring(PosCount_Start, (PosCount_End - PosCount_Start))
Username_File.Add(Username_Temp)
PosCount_End = 0
Do
FileGet(1, TempChar)
If TempChar = "." Then Exit Do
Password_Temp = Password_Temp + TempChar
PosCount_End = PosCount_End + 1
Loop
Password_Temp = Password_Temp.Substring(0, PosCount_End)
Password_Temp = Password_Temp.Trim
Password_File.Add(Password_Temp)
PosCount_End = 0
Loop
FileClose(1)
For i = 0 To Username_File.Count - 1
Dim Temp As String
Temp = Username_File(i)
If Temp.ToLower = Username.ToLower Then
If Password = Password_File(i) Then
LoggedIn = True
End If
End If
Next
End Sub
This is killing me because I know why it's doing it but I don't know how to stop it. I am reading from a text file where I have 2 users on 2 lines: bill|777 & john|333.
My conditional statement satisfies both conditions because when it loops thru, it declines one user and accepts the other causing it to do the if and the else. Please tell me how to do this one at a time. Loop thru the text, get the proper user and then go thru the conditions.
Dim MyReader As New StreamReader("login.txt")
While Not MyReader.EndOfStream
Dim user As String = UsernameTextBox.Text + "|" + PasswordTextBox.Text
Dim names() As String = MyReader.ReadLine().Split()
For Each myName In names
If user = myName Then
Me.Hide()
OrderForm.Show()
Else
MsgBox("Wrong username and password")
End If
Next
End While
MyReader.Close()
Something like this should work:
Using MyReader As New StreamReader("login.txt")
Dim GoodUser As Boolean = False
Dim user As String = UsernameTextBox.Text + "|" + PasswordTextBox.Text
While Not MyReader.EndOfStream
Dim user As String = UsernameTextBox.Text + "|" + PasswordTextBox.Text
Dim names() As String = MyReader.ReadLine().Split()
If Not names Is Nothing Then
For Each myName In names
If user = myName Then
GoodUser = True
Me.Hide()
OrderForm.Show()
Exit While
End If
Next
End If
End While
If Not GoodUser Then
MsgBox("Wrong username and password")
End If
End Using
The using block automatically disposes of the streamreader. A boolean to signify a good login can set the condition when the While loop exits. The Exit While will break out of the loop when the proper user is found. It's usually a good idea to set a conditional to check for empty lines
One thing to watch for. If a user name includes a space your code won't work. You'll have to either restrict the user names or use a different delimiter like ~.
Try this code:
Using r As StreamReader = New StreamReader("login.txt")
Dim line As String = r.ReadLine
Dim user As String = UsernameTextBox.Text + "|" + PasswordTextBox.Text
Dim found As Boolean = False
Do While (Not line Is Nothing)
If (line = user) Then
found = True
break
End If
line = r.ReadLine
Loop
If (Not found) Then
MessageBox.Show("Wrong username and password")
End If
End Using