user login in vb.net Windows Form - vb.net

I'm sorry for disturbing you guys, but I had a question to ask. I'm currently doing a program where user which are in the access database can log in, the code is working but the problem is that when I debug I can only login using 1 user, when I try logging in using another user account it shows Login Invalid and I'm not sure why. I hope someone could pin point what am I doing wrong;
Here's my code;
Imports System.Data.OleDb 'provides classes to connect to the database
Imports System.Data
Imports System.IO
Public Class Login
Dim conn As New OleDbConnection
Dim cmd As New OleDbCommand
Function getcount() As Integer
Using conn As New OleDb.OleDbConnection _
("Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " & Application.StartupPath & "\User.mdb")
'provider to be used when working with access database
conn.Open()
Dim cmd As New OleDb.OleDbCommand("Select COUNT(*) FROM UserProf_table", conn)
Return cmd.ExecuteScalar()
End Using
End Function
Private Sub Login_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
conn = New OleDbConnection
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " & Application.StartupPath & "\User.mdb"
conn.Open()
If getcount() = 1 Then
btnReg.Visible = False
Else
btnReg.Visible = True
End If
MsgBox(conn.State.ToString()) 'to check connection
End Sub
Private Sub btnSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
Dim idbx As String ' noted that ID is numbers
Dim pwd As String
idbx = idbox.Text
pwd = pwdbox.Text
With cmd
'Open Connection for executereader
If Not conn.State = ConnectionState.Open Then
conn.Open()
End If
'initialized database connection
.Connection = conn
.CommandText = "SELECT UserID, UserPwd FROM UserProf_table WHERE UserID = '" & idbox.Text & "' AND UserPwd = '" & pwdbox.Text & "'"
Dim dr As OleDbDataReader
dr = cmd.ExecuteReader
If dr.HasRows Then
dr.Read()
If idbx = dr.Item("UserID") And pwd = dr.Item("UserPwd") Then
idbx = SystemInformation.UserName
mainForm.Show()
Me.Hide()
Else
MsgBox("Password or username is incorrect")
idbox.Clear()
pwdbox.Clear()
End If
dr.Close()
End If
End With
'close connection
conn.Close()
End Sub
Private Sub btnReg_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReg.Click
registerForm.Show() ' Register form
Me.Hide()
End Sub
End Class
Here's my database:
I login using the UserID and UserPwd. And is there a way for me to save the UserID do that I can use it in different form? Thank you in advance

You are always reading the whole username/password list!
You have forgotten a WHERE clause in :
SELECT UserID, UserPwd FROM UserProf_table
WHERE UserId = ???
You can login as the first user because it's the first row returned!
[Also: please don't store passwords as plain text]

You should change your sql command to retrieve only 1 record:
.CommandText = "SELECT UserID,UserPwd FROM UserProf_table WHERE UserId =" + idbx.trim()
Moreover, if you are using Visual Studio, you can use "Watch and QuickWatch Windows" in debug mode to show your variables and make sure they return expected values.
https://msdn.microsoft.com/en-us/library/0taedcee.aspx

Related

How do I make it so everyone has a separate account when they login

I am trying to create a login system for a revision app. However, I was wondering if there was a way where everyone can have separate accounts.
Private Sub Btnlogin_Click(sender As Object, e As EventArgs) Handles Btnlogin.Click
Dim sqlstring As String
sqlstring = "select * FROM login where username = '" & txtusername.Text & "'"
connection.Open()
dataadapter = New OleDb.OleDbDataAdapter(sqlstring, connection)
dt.Clear()
dataadapter.Fill(dt)
connection.Close()
If dt.Rows.Count = 0 Then
MsgBox("no such user")
Exit Sub
End If
If dt.Rows(0)(2) = Txtpassword.Text Then
Flashcard.Show()
Else
Txtpassword.Text = ""
txtusername.Text = ""
MsgBox("Invalid username and password combination")
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Register.Show()
End Sub
That's the code I have if a user already has an account.
Imports System.Data.OleDb
Public Class Register
Dim pro As String
Dim connstring As String
Dim command As String
Dim myconnection As OleDbConnection = New oledbconnection
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
pro = "provider=microsoft.ACE.OLEDB.12.0;Data Source=flashcard login.accdb"
connstring = pro
myconnection.ConnectionString = connstring
myconnection.Open()
command = " insert into login ([username],[password]) values ('" & TextBox1.Text & "','" & TextBox2.Text & "')"
Dim cmd As OleDbCommand = New OleDbCommand(command, myconnection)
cmd.Parameters.Add(New OleDbParameter("username", CType(TextBox1.Text, String)))
cmd.Parameters.Add(New OleDbParameter("password", CType(TextBox1.Text, String)))
MsgBox("You have successfully signed up!")
Form1.Show()
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myconnection.Close()
TextBox1.Clear()
TextBox2.Clear()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
That's the code if the user presses the register button (does not have an account).
This code works where the user can succesfully login or register, but the problem is that everyone will have the same windows form. So, I was wondering if there was a way to make each windows form unique to each user?
You can declare and initialize a variable on the same line. The only information you need is if the userName and password exist in the database. Don't pull down data your don't need. You can get this with Count.
Always declare and dispose the connection and command it the method where they are used. Both of these objects need to be disposed so that their unmanaged resources can be released. Using... End Using blocks handle this.
Always use parameters to avoid sql injection. In OleDb the order that the parameters appear in the sql string must match the order that they are added to the parameters collection.
Don't open the connection until directly before the .Execute...
Private ConStr As String = "provider=microsoft.ACE.OLEDB.12.0;Data Source=flashcard login.accdb" '"Your connection string"
Private Sub Btnlogin_Click(sender As Object, e As EventArgs) Handles Btnlogin.Click
Dim rowCount As Integer
Dim sqlstring = "select Count(*) FROM login where [username] = #UserName ANd [password] = #password;"
Using connection As New OleDbConnection(ConStr),
cmd As New OleDbCommand(sqlstring, connection)
cmd.Parameters.Add("#UserName", OleDbType.VarChar).Value = txtusername.Text
connection.Open()
rowCount = CInt(cmd.ExecuteScalar)
End Using
If rowCount = 0 Then
MsgBox("no such user")
Else
Flashcard.Show()
End If
End Sub
Same ideas for the insert. A text box's Text property is always a String so you don't have to convert it.
You are not doing the parameters correctly. You are not using these parameters because the don't appear in the CommandText
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Command = " insert into login ([username],[password]) values (#UserName, #Password);"
Try
Using myconnection As New OleDbConnection(ConStr),
cmd As OleDbCommand = New OleDbCommand(Command, myconnection)
cmd.Parameters.Add("#UserName", OleDbType.VarChar).Value = TextBox1.Text
cmd.Parameters.Add("#Password", OleDbType.VarChar).Value = TextBox2.Text
myconnection.Open()
cmd.ExecuteNonQuery()
End Using
Catch ex As Exception
MsgBox(ex.Message)
Exit Sub
End Try
MsgBox("You have successfully signed up!")
Form1.Show()
TextBox1.Clear()
TextBox2.Clear()
End Sub
Finally, and very important. You should never store passwords as plain text. Look into salting and encrypting.

An exception of type 'System.InvalidOperationException' occurred in System.Data.dll

This is my code. help me to solve it thanks!
An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code Additional information: ExecuteReader requires an open and available Connection. The connection's current state is closed
Imports System.Data.SqlClient
Partial Class Staff
Inherits System.Web.UI.Page
' Dim conn As New SqlConnection("Data Source=USER-PC\SQLEXPRESS;Initial Catalog=carrental;Integrated Security=True;Pooling=False")
Dim con As New Data.SqlClient.SqlConnection
Dim cmd As New Data.SqlClient.SqlCommand
Dim dr As Data.SqlClient.SqlDataReader
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
con.ConnectionString = ("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\user\Desktop\oh manisku\PROJECT ABIS\project baru\project baru\App_Data\order.mdf;Integrated Security=True;Connect Timeout=30")
con.Open()
Catch ex As Exception
' MsgBox(ex.Message)
End Try
End Sub
Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
cmd.CommandText = ("Select Username, Password from Admin WHERE Username ='" & txtusername.Text & "' and Password = '" & txtPass.Text) & "' "
cmd.Connection = con
dr = cmd.ExecuteReader
con.Close()
If dr.HasRows Then
MsgBox("Succesfully Login")
Response.Redirect("recalled.aspx")
Else
MsgBox("Invalid Username and Password")
End If
End Sub
Private Sub btnReset_Click(sender As Object, e As EventArgs) Handles btnReset.Click
End Sub
Protected Sub SqlDataSource1_Selecting(sender As Object, e As SqlDataSourceSelectingEventArgs) Handles SqlDataSource1.Selecting
End Sub
End Class
As I said in my comment, you're closing the connection before reading the data. You should move the connection close to after you finished with the data reader.
Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
Dim con As New Data.SqlClient.SqlConnection
con.ConnectionString = ("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\user\Desktop\oh manisku\PROJECT ABIS\project baru\project baru\App_Data\order.mdf;Integrated Security=True;Connect Timeout=30")
con.Open()
cmd.CommandText = ("Select Username, Password from Admin WHERE Username ='" & txtusername.Text & "' and Password = '" & txtPass.Text) & "' "
cmd.Connection = con
dr = cmd.ExecuteReader
If dr.HasRows Then
MsgBox("Succesfully Login")
Response.Redirect("recalled.aspx")
Else
MsgBox("Invalid Username and Password")
End If
dr.Close() ' close the datareader
con.Close() ' close the connection
End Sub
Private Sub btnReset_Click(sender As Object, e As EventArgs) Handles btnReset.Click
End Sub
Calling ExecuteReader simply opens the stream. If you close the connection, you close the stream. To use a telephone analogy: it's like hanging up on someone, and then trying to have a conversation.
Please also switch to using parameterized queries since, as it stands, I could enter my username as ' OR 1 = 1 ; -- and I'd gain full access to the first account in your system.
Also, please look into ways to securely store passwords. You should never store passwords in your database in plain text, and you should never store passwords in a way that allows you to reverse them to the original user input. Passwords should be hashed with a salt. see here.

How to read and move read content via SQL into variables within VB.net and use a connectionstring from a module in forms?

This is my first question, by the way - and I'm not sure exactly how to ask, or say what's wrong. There's 3 things I can't sort so any help would be appreciated.
Module:
This and the first (login) form work as they are but I couldn't get either Form to reference con.connectionstring for them to use without having to re-use the string contained in "" (as they do below) - my attempts ended up with errors including saying that the state couldn't be changed as the connection was already open, but I'd like the same one string to be referenced from the Forms.
Module ConnectionModule
Public con As OleDb.OleDbConnection = New OleDb.OleDbConnection
Public da As OleDb.OleDbDataAdapter
Public ds As DataSet = New DataSet
Public Path As String = Application.StartupPath
Public Sub OpenDb()
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=F:\Computing A2\CG4 Coursework\Greener Cleaning\dbCoursework.accdb"
con.Open()
If con.State = ConnectionState.Closed Then
MsgBox("Connection to db not made.")
End If
End Sub
Public CurrentUser As String = Nothing
End Module
The First Form:
Public Class LoginForm
Private Sub LoginForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
OpenDb()
con.Close()
End Sub
Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
Dim ID As String = txtID.Text
Dim Pass As String = txtPassword.Text
If IsNumeric(ID) = False Or ID.Length > 4 Or Pass = Nothing Then
MsgBox("Staff ID is a 4-digit number and Password must not be blank.")
Else
Dim con As New System.Data.OleDb.OleDbConnection()
OpenDb()
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=F:\Computing A2\CG4 Coursework\Greener Cleaning\dbCoursework.accdb"
Try
Dim sql As String = "SELECT * FROM tblStaff WHERE [StaffID]='" & ID & "' AND [Pword] = '" & Pass & "'"
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql)
'Open Database Connection
sqlCom.Connection = con
con.Open()
Dim sqlRead As System.Data.OleDb.OleDbDataReader = sqlCom.ExecuteReader()
If sqlRead.Read() Then 'Correct:
MenuForm.Show()
Me.Hide()
CurrentUser = ID
Else 'Incorrect:
MsgBox("Staff ID or Password incorrect.")
txtPassword.Text = ""
txtID.Text = ""
txtID.Focus()
End If
Catch ex As Exception
MsgBox("Database Connection Error.")
End Try
con.Close()
End If
End Sub
End Class
A form to change the password:
The problem here is that lblUser (A clarification for the user to tell them which password will be changed) only outputs the data already within the program as a variable: CurrentUser (as assigned upon successful login). No error is produced but the full name of the user isn't shown (or possibly read from the database).
I'm also unsure how the UPDATE SQL command should be contained within the second procedure, btnAccept_click, here. What the syntax is, basically. I haven't found a clear example to look at.
Imports System.Data.OleDb
Public Class PasswordForm
Private Sub PasswordForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
con = New System.Data.OleDb.OleDbConnection()
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=F:\Computing A2\CG4 Coursework\Greener Cleaning\dbCoursework.accdb"
Dim Returned(2) As String
CurrentUser = CurrentUser
Dim cmd As OleDbCommand = New OleDbCommand("SELECT [Title], [Forename], [Surname] FROM tblStaff WHERE [StaffID]='" & CurrentUser & "'", con)
Try
con.Open()
Dim reader As OleDbDataReader = cmd.ExecuteReader()
If reader.HasRows Then
reader.Read()
'Makes db contents variables
Returned(0) = reader.Item("[Title]").ToString
Returned(1) = reader.Item("[Forename]").ToString
Returned(2) = reader.Item("[Surname]").ToString
End If
reader.Close()
Catch ex As Exception
Me.Hide()
MsgBox("Database Connection Error.")
Finally
con.Close()
End Try
lblUser.Text = "Current User: " & CurrentUser & Returned(0) & Returned(1) & Returned(2)
''Only outputs CurrentUser
End Sub
Private Sub btnAccept_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAccept.Click
Dim Current As String = txtCurrent.text
Dim NewPass As String = txtNew.Text
'Verification
If txtNew.Text = txtConfirm.Text And NewPass.Length <= 20 Then
Dim cmd As OleDbCommand = New OleDbCommand("UPDATE tblStaff SET [Pword]='" & NewPass & "' WHERE [StaffID]='" & CurrentUser & "'", con)
End If
End Sub
End Class
Thank you, again, for anyone with ideas (especially exact code).
Oh and throughout what's here there are no errors thrown. Just missing content.
you are opening the connection in openDB() and you are trying to open it again in form1, this will throw the error you are getting. So comment all the con related lines in your form. Same comment for your passowrd form also.
'Dim con As New System.Data.OleDb.OleDbConnection()
OpenDb()
'con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=F:\Computing A2\CG4 Coursework\Greener Cleaning\dbCoursework.accdb"
Try
Dim sql As String = "SELECT * FROM tblStaff WHERE [StaffID]='" & ID & "' AND [Pword] = '" & Pass & "'"
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql)
'Open Database Connection
sqlCom.Connection = con
'con.Open()
...
end try

.executenonquery() error No value given for one or more required parameters

Imports System.Data.OleDb
Public Class LoginForm
Dim connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\User\Desktop\thesis\YBIM.accdb"
Dim conn As New OleDbConnection
' TODO: Insert code to perform custom authentication using the provided username and password
' (See http://go.microsoft.com/fwlink/?LinkId=35339).
' The custom principal can then be attached to the current thread's principal as follows:
' My.User.CurrentPrincipal = CustomPrincipal
' where CustomPrincipal is the IPrincipal implementation used to perform authentication.
' Subsequently, My.User will return identity information encapsulated in the CustomPrincipal object
' such as the username, display name, etc.
Private Sub LoginForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
conn.ConnectionString = connstring
If conn.State = ConnectionState.Closed Then
conn.Open()
MsgBox("welcome")
Else
MsgBox("Cannot connect to database")
End If
End Sub
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
Dim SqlQuery As String = ("SELECT * FROM tablelogin WHERE Username= #field1 AND Password=#field2")
Dim SqlCommand As New OleDbCommand
Dim Sqlrdr As OleDbDataReader
With SqlCommand
.CommandText = SqlQuery
.Connection = conn
.Parameters.AddWithValue("#field1", UsernameTextBox.Text)
.Parameters.AddWithValue("#field2", PasswordTextBox.Text)
.ExecuteNonQuery()
End With
Sqlrdr = SqlCommand.ExecuteReader()
If (Sqlrdr.Read() = True) Then
home.ShowDialog()
Me.Hide()
Else
MsgBox("wong input")
End If
End Sub
End Class
There are two things of note in your code which you can remedy.
1* You are naming your parameters incorrectly.
This:
.Parameters.AddWithValue("#field1", UsernameTextBox.Text)
.Parameters.AddWithValue("#field2", PasswordTextBox.Text)
Should be this:
.Parameters.AddWithValue("field1", UsernameTextBox.Text)
.Parameters.AddWithValue("field2", PasswordTextBox.Text)
2* You are executing the command twice. Remove .ExecuteNonQuery() from the With statement,
and change:
Sqlrdr = SqlCommand.ExecuteReader()
to
Dim ret As Integer
ret = SqlCommand.ExecuteNonQuery()
And instead of using Sqlrdr.Read(), simply check if ret > 0 (ExecuteNonQuery returns the amount of rows affected by the command).

Problems passing values from one form to another

I'm new to VB.net. So here is what I want to do which I am having some serious problem
Using the "Get_Computer_Name form" will post the username and account type into another form. The Get_Computer_Name also gets the computer name where it will be sent to a module and that module will work as the main connection. Now I have tried to separate the login form and form that gets the computer name but that didn't work (I also want to try that method).
The problem with my current method is that it can only perform one thing at a time. It fails to post the username and account type and it fails to send the computer name to the module. Now strangely there is a way around. If I comment out the post username and account type, the computer name will be sent to the module and the module will work and connect to the database. Now if I choose not to comment out the code that post the username and account to the other form, the computer name won't be sent to the module that handles the connection thus failing to connect to the database.
I am open to other suggestions rather than doing it this way.
Thank you
'Here is my code for "Get_Computer_Name form"
Imports System.Data.SqlClient
Public Class Get_Computer_Name
Public Sub Get_Computer_Name_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
cmbcomputername.Text = My.Computer.Name
connect()
End Sub
Private Sub cmbcomputername_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles cmbcomputername.SelectedIndexChanged, cmbcomputername.TextChanged
cmbcomputername.Text = My.Computer.Name
End Sub
Public Sub btnlogin_Click(sender As System.Object, e As System.EventArgs) Handles btnlogin.Click
datasource = cmbcomputername.Text
If connection.State = ConnectionState.Closed Then
connection.Open()
End If
Dim reader As SqlDataReader
Dim sqlstatement As SqlCommand = New SqlCommand
sqlstatement.Connection = connection
Try
sqlstatement.CommandText = "Select account_username, account_password, account_type " &
"from account_login where account_username='" & txtusername.Text & "' and account_password='" & txtpassword.Text & "'"
reader = sqlstatement.ExecuteReader()
If (reader.Read()) Then
Dim application_form As application_form
application_form = New application_form
application_form.Show()
application_form = Nothing
Me.Visible = False
'This is the code that post the username and account type to the other form (application form). If I comment this code out, the system successfully connects to the database
application_form.lblusername.Text = (reader("account_username").ToString)
application_form.lblaccount_type.Text = (reader("account_type").ToString)
sqlstatement.Dispose()
reader.Close()
connection.Close()
Else
connection.Close()
MsgBox("Invalid")
End If
reader.Close()
Catch ex As Exception
End Try
End Sub
End Class
'This is the code for the module that holds the main connection string
Public connection As SqlConnection = New SqlConnection
Public datasource As String
Public database As String = "bpmi"
Public sqlmainconnector As String
Public Sub connect()
sqlmainconnector = "Data Source=" & datasource & ";Initial Catalog=bpmi;Integrated Security=True"
connection.ConnectionString = sqlmainconnector
Try
If connection.State = ConnectionState.Closed Then
connection.Open()
Else
connection.Close()
End If
Catch ex As Exception
End Try
End Sub
'And this code is the form where the username and account type will be posted
Imports System.Data.SqlClient
Public Class application_form
Dim sqlcommand As SqlCommand
Dim da As SqlDataAdapter
Dim table As New DataTable
Dim dategrabberapp As String
Dim dategrabberben As String
Dim benidgrabber As String
Private Sub Form1_Load(sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
connect()
filldatagrid(updateappdatagrid, updatebendatagrid)
fillcomboboxstatus(cmbstatus)
fillcomboboxposition(cmbappworkposition)
fillcomboboxrelationship(cmbrelation)
fillcomboboxrelationshipupdate(cmbrelationbenupdate)
fillcomboboxstatusupdate(cmbappstatusupdate)
fillcomboboxpositionupdate(cmbappworkposupdate)
'this is where the account type will got to
If lblaccount_type.Text <> "Administrator" Then
Me.TabControl1.TabPages(1).Enabled = False
Me.TabControl1.TabPages(2).Enabled = False
MsgBox("As a 'Staff', you are not permitted to do any updates")
updateappdatagrid.Hide()
updatebendatagrid.Hide()
End If
End Sub
End Class