vb.net // Failed to connect to the database ? Login System Check the user if admin or not - vb.net

Hello guys, I am implementing a login system where there are two users it's either the admin or the superadmin, however it always fail to connect to the database. I'm kinda new to VB.net and I'm trying to figure out on how this make thing work and yep I searched up the web on how to create on but it fails, and btw here's the error log generated after logging in
Failed to Connect to the Database
A first chance exception of type 'System.InvalidOperationException' occurred in System.Data.dll
Imports System.Data.OleDb
Imports System.Data
Public Class LoginFrm
Private Sub LoginBtn_Click_1(sender As Object, e As EventArgs) Handles LoginBtn.Click
If userBox.Text = "" Or passwordBox.Text = "" Then
MessageBox.Show("Username and password are blank", "Authentication Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
Dim conn As New System.Data.OleDb.OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\ResortReservationSystem.accdb"
Dim sql As String = "SELECT * FROM userTable WHERE userName='" & userBox.Text & "' AND passWord = '" & passwordBox.Text & "'"
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql)
sqlCom.Connection = conn
sqlCom.Connection.Open()
Dim sqlRead As System.Data.OleDb.OleDbDataReader = sqlCom.ExecuteReader()
If sqlRead.Item("userType") = "SuperAdmin" Then
welcomeFrm.Show()
Me.Hide()
End If
If sqlRead.Item("userType") = "Admin" Then
manageEmployeeForm.Show()
Else
MessageBox.Show("Username and Password do not match.", "Authentication Failure", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
userBox.Text = ""
passwordBox.Text = ""
userBox.Focus()
End If
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.Close()
End Sub
End Class
Edit: I have fixed some issues and now I am encountering this,
No data exists for the row/column. For what I know, .Item is to get the fetch the data, but it seems like it doesnt work for me.
table name: userTable
fields: userName, passWord, userType
datas: John, Doe, SuperAdmin

The point of a data reader is to read data. If you have done any reading on data readers and their use then you know that you have to call the Read method to actually read a record. You aren't calling Read, hence there's no data in your data reader.

If userBox.Text = "" Or passwordBox.Text = "" Then
Change the Or to OrElse to short circuit the If.
Connections and commands need to be closed and disposed. A Using...End Using block will do this for you even if there is an error.
You can pass the connection string directly to the constructor of the connection. Likewise, pass the command text and connection directly to the constructor of the command.
Never concatenate strings with user input to build sql statements. You risk sql injection which can ruin your database. It also makes the sql statement easier to write because you don't have to use all those single and double quote and ampersands.
You are only using a single piece of data so don't return all the fields. You only need userType.
Always use parameters. Access (OleDb) does not care about the name of the parameter. I just use appropriate names for readability. What is important is the order that the parameter appears in the sql statement must match the order that the parameter is added to the parameters collection. I had to guess at the datatype and field size of the parameters. Check your database for the real values and correct the code accordingly.
Since we are only getting a single piece of data, we can use .ExecuteScalar which returns the first column of the first row of the result set.
The End Using closes and disposes the connection and command so now we can mess with returned data.
Sidenote: Your problem was that a reader does not start reading the returned rows until you call reader.Read. This is no longer relevant since we are not using a reader.
Private Sub LoginBtn_Click_1(sender As Object, e As EventArgs) Handles LoginBtn.Click
Dim AdminType As String
If userBox.Text = "" OrElse passwordBox.Text = "" Then
MessageBox.Show("Username and password must be filled in.", "Authentication Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
Using conn As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\ResortReservationSystem.accdb"),
sqlCom As New OleDbCommand("SELECT userType FROM userTable WHERE userName= #User AND passWord = #Password", conn)
With sqlCom.Parameters
.Add("#User", OleDbType.VarChar, 100).Value = userBox.Text
.Add("#Password", OleDbType.VarChar, 100).Value = passwordBox.Text
End With
conn.Open()
AdminType = sqlCom.ExecuteScalar.ToString
End Using
If String.IsNullOrEmpty(AdminType) Then
MessageBox.Show("Username and Password do not match.", "Authentication Failure", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
userBox.Text = ""
passwordBox.Text = ""
userBox.Focus()
ElseIf AdminType = "SuperAdmin" Then
welcomeFrm.Show()
Me.Hide()
ElseIf AdminType = "Admin" Then
manageEmployeeForm.Show()
End If
End If
End Sub

Related

a beginner in vb.net.. working on a login form

Imports MySql.Data.MySqlClient
Public Class Form1
Dim cmd As New MySqlCommand
Dim da As New MySqlDataAdapter
Dim con As MySqlConnection = JOKENCONN()
Public Function JOKENCONN() As MySqlConnection
Return New MySqlConnection("server=localhost; user id=root; password=; database =studentdb")
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
GroupBox1.Enabled = False
End Sub
Private Sub LBLLOGIN_CLICK(sender As Object, e As EventArgs) Handles lbllogin.Click
lbllogin.Text = "Login"
lbllogin.Text = "Login"
lblname.Text = "Hi, Guest"
If lbllogin.Text = "Login" Then
GroupBox1.Enabled = True
End If
End Sub
Private Sub BTNOK_CLICK(sender As Object, e As EventArgs) Handles btnok.Click
Dim Sql As String
Dim publictable As New DataTable
Try
If txtusername.Text = "" And txtpass.Text = "" Then
MsgBox("Password or username is incorrect!")
Else
Sql = "select ' from tbluseraccount where username='" & txtusername.Text & "' and userpassword='" & txtpass.Text & "'"
With cmd
.Connection = con
End With
da.SelectCommand = cmd
da.Fill(publictable)
If publictable.Rows.Count > 0 Then
Dim user_type As String
user_type = publictable.Rows(0).Item(4)
Name = publictable.Rows(0).Item(1)
If user_type = "Admin" Then
MsgBox("Welcome " & Name & "you login as Administrator")
lbllogin.Text = "logout"
lblname.Text = "Hi, " & Name
GroupBox1.Enabled = False
txtusername.Text = ""
txtpass.Text = ""
ElseIf user_type = "cetakoradi2" Then
MsgBox("Welcome " & Name & "you login as cetakoradi2")
lbllogin.Text = "logout"
lblname.Text = "Hi, " & Name
GroupBox1.Enabled = False
txtusername.Text = ""
txtpass.Text = ""
Else
End If
Else
MsgBox("contact administrator to register")
txtusername.Text = ""
txtpass.Text = ""
End If
da.Dispose()
End If
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub
End Class
this the error i received
ExecuteReader CommandText property has not been properly initialized
i really need help on that. this is the error that i receives. thank you
Assuming that the name of the field represented in publictable.Rows(0).Item(4) is named user_type, then you could use the following:
'Declare the object that will be returned from the command
Dim user_type As String
'Declare the connection object
Dim con As OleDbConnection
'Wrap code in Try/Catch
Try
'Set the connection object to a new instance
con = JOKENCONN()
'Create a new instance of the command object
Using cmd As OleDbCommand = New OleDbCommand("SELECT user_type FROM tbluseraccount WHERE username=#0 AND userpassword=#1;", con)
'Paramterize the query
cmd.Parameters.AddWithValue("#0", txtusername.Text)
cmd.Parameters.AddWithValue("#1", txtpass.Text)
'Open the connection
con.Open()
'Use ExecuteScalar to return a single value
user_type = cmd.ExecuteScalar()
'Close the connection
con.Close()
End Using
Catch ex As Exception
'Display the error
Console.WriteLine(ex.Message)
Finally
'Check if the connection object was initialized
If con IsNot Nothing Then
If con.State = ConnectionState.Open Then
'Close the connection if it was left open(exception thrown)
con.Close()
End If
'Dispose of the connection object
con.Dispose()
End If
End Try
If (String.IsNullOrWhitespace(user_type)) Then
'Failed login
ElseIf (user_type = "Admin") Then
'Admin login
ElseIf (user_type = "cetakoradi2") Then
'cetakoradi2 login
Else
'Not a failed login, but also not an admin or cetakoradi2 either
End If
What this code does is setup a parameterized query to get just the user_type where the username and password match the parameterized values. Since there should only ever be one record that matches those conditions (presumably) then we're able to use ExecuteScalar to return just that single field value.
Just to reinforce the point, MySqlCommand.ExecuteScalar, just like the Microsoft counterparts, "executes the query, and returns the first column of the first row in the result set returned by the query. Extra columns or rows are ignored" and returns " The first column of the first row in the result set, or a null reference if the result set is empty ".
The proposed code by #David checks for this condition using IsNullOrWhitespace.
ExecuteScalar is effective but retrieves only one value at a time.
The other option pursued by the OP is to return a datarow, which is a valid approach if he wants to return several fields at the same time. In his example he retrieves two fields for variables user_type and Name respectively.
Be careful, VB.net like any other programming language has reserved keywords. If you do not take a habit of using good naming conventions you might one day stumble upon on one of those keywords, possibly hit obscure bugs. Name is not a good name for a variable and has the potential for confusion since every object has a name property.
To address the specific issue at hand, the error message ExecuteReader CommandText property has not been properly initialized is self-explanatory. What should have been done is simply:
With cmd
.Connection = con
.CommandText = Sql
End With
You defined a command, but did not tell it what to do. In your code variable Sql is defined but unused. With this missing bit there is a chance the code will work as expected.
Small details:
Not critical, but his condition does not work if you enter whitespace for example:
If txtusername.Text = "" And txtpass.Text = "" Then
An improvement is to simply trim the values from the textboxes:
If txtusername.Text.Trim = "" And txtpass.Text.Trim = "" Then
But I think what you want is not an And but Or. I don't think you want to allow logins without passwords.
Instead of doing multiple If/ElseIf you could have a Select Case

Login Function VB.net using MS Access // two usertypes

Hello, I am trying to create a login system wherein there will be an admin and superadmin to login, I just followed some tutorials over the net and tried it on my own, I am new to vb and I just wanna try it out. However doing the codes below, it is not either logging in. It's always going to the catch part wherein it says it doesn't connect to the database. Here is the code error btw
A first chance exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles LoginBtn.Click
If userBox.Text = "" Or passwordBox.Text = "" Then
MessageBox.Show("Username and password are blank", "Authentication Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
Dim conn As New System.Data.OleDb.OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\ResortReservationSystem.accdb"
Try
Dim sql As String = "SELECT * FROM tbl_user WHERE username='" & userBox.Text & "' AND password = '" & passwordBox.Text & "'"
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql)
sqlCom.Connection = conn
conn.Open()
Dim sqlRead As System.Data.OleDb.OleDbDataReader = sqlCom.ExecuteReader()
If sqlRead.Item("userType") = "Admin" Then
MenuForm.Show()
Me.Hide()
ElseIf sqlRead.Item("userType") = "SuperAdmin" Then
EmployeeForm.Show()
Me.Hide()
Else
MessageBox.Show("Username and Password do not match.", "Authentication Failure", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
userBox.Text = ""
passwordBox.Text = ""
userBox.Focus()
End If
Catch ex As Exception
MessageBox.Show("Failed to connect to Database..", "Database Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End If
End Sub
I changed your Or in the first If statement to an OrElse to short circuit the code from checking the second condition if it finds the first to be True.
Connections are precious objects and need to be closed and disposed. Open as late as possible and closed as soon as possible. Using...End Using blocks ensure this even if there is an error. In this case the command object is also included in the Using.
You can pass the connection string directly to the constructor of the connection. Likewise, pass the command text and the connection to the constructor of the command.
I changed the Select statement to only retrieve UserType because that is all that is used in the method. Don't pull more information than necessary from the database.
Learn to use Parameters. It makes the sql statement easier to write, speeds up the query and protects against sql injection.
Since we are only retrieving a single piece of data we can use .ExecuteScalar which gets the first column of the first row of the result set.
After the connection and command are closed and disposed with the End Using, we can deal with the data retrieved from the database.
Private Sub OpCode()
If userBox.Text = "" OrElse passwordBox.Text = "" Then
MessageBox.Show("Username and/or password are blank", "Authentication Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
End If
Dim AdminType As String
Using conn As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\ResortReservationSystem.accdb"),
sqlComm As New OleDbCommand("SELECT UserType FROM tbl_user WHERE username= #User AND [password] = #Password", conn)
With sqlComm.Parameters
.Add("#User", OleDbType.VarChar, 100).Value = userBox.Text
.Add("#Password", OleDbType.VarChar, 100).Value = passwordBox.Text
End With
conn.Open()
AdminType = sqlComm.ExecuteScalar.ToString
End Using
If String.IsNullOrEmpty(AdminType) Then
MessageBox.Show("Username and Password do not match.", "Authentication Failure", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
userBox.Text = ""
passwordBox.Text = ""
userBox.Focus()
ElseIf AdminType = "Admin" Then
MenuForm.Show()
Me.Hide()
ElseIf AdminType = "SuperAdmin" Then
EmployeeForm.Show()
Me.Hide()
End If
End Sub

Login System VB.net and Access Check if the user is an Admin

I would like my program to check if a user is an admin. I followed a tutorial on the internet on how to do make a login form, and im super new to programming.This is my database in access.
If that box in access is ticked then i would like it to show the "AdminMenu" form to show but if the box isn't ticked i would like it to show the "UserMenu" The code below works fine but like i said i would like to know how i check if that user is an admin or just a normal user
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles LoginButton.Click
' Check if username or password is empty
If TextBox1.Text = "" Or TextBox2.Text = "" Then
MessageBox.Show("Username and password are blank", "Authentication Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
' Both fields was supply
' Check if user exist in database
' Connect to DB
Else
Dim conn As New System.Data.OleDb.OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\-------.ult.org.uk\homestudent\-------\dt_database.accdb"
Try
'conn.Open()
'MsgBox("Susscess")
Dim sql As String = "SELECT * FROM tbl_user WHERE username='" & TextBox1.Text & "' AND password = '" & TextBox2.Text & "'"
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql)
'Open Database Connection
sqlCom.Connection = conn
conn.Open()
Dim sqlRead As System.Data.OleDb.OleDbDataReader = sqlCom.ExecuteReader()
If sqlRead.Read() Then
AdminMenu.Show()
Me.Hide()
Else
' If user enter wrong username and password combination
' Throw an error message
MessageBox.Show("Username and Password do not match.", "Authentication Failure", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
'Clear all fields
TextBox1.Text = ""
TextBox2.Text = ""
'Focus on Username field
TextBox1.Focus()
End If
Catch ex As Exception
MessageBox.Show("Failed to connect to Database..", "Database Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End If
End Sub
Use the DataReader (sqlRead) to check the content of the "admin"-column. Compare it to the state you'd like (-1 is TRUE, 0 is FALSE).
if sqlReader.item("admin") = -1 then
'IsAdmin
else
'IsNotAdmin
end if
Sidenote: do not concatenate querystrings. It's a bad practice and renders the application prone to SQL injection. Use parameterized queries instead.
Based on your schema and the SELECT *. You need to read the actual value of your admin field.
If sqlRead.Read() Then
If Convert.ToBoolean(sqlRead(6)) = True Then 'By ordinal OR
If Convert.ToBoolean(sqlRead("admin")) = True Then 'By field name
'User Is Admin
Else
'User is not admin
End If
AdminMenu.Show()
Me.Hide()
Else

MS Access Update Issue

I've learned from this site the proper way to update an MS Access Database using parameters but now I have another problem. It seems that using Access as Database is not as efficient or user friendly as compared to using SQL Server. This is my code:
Private Sub btnUpdatePass_Click(sender As System.Object, e As System.EventArgs) Handles btnUpdatePass.Click
If MessageBox.Show("Are you sure that " & txtEmpID.Text & " is the Employee ID you want to change password?", "ALERT", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) = Windows.Forms.DialogResult.Yes Then
ChangePassword(Me.txtEmpID.Text, txtChangePass.Text)
End If
End Sub
Public Sub ChangePassword(empID As Object, password As Object)
Try
cnn.Open()
query = "UPDATE Users SET Password = #password WHERE ID = #empID"
cmd = New OleDbCommand(query, cnn)
cmd.Parameters.AddWithValue("#password", password)
cmd.Parameters.AddWithValue("#empID", empID)
cmd.ExecuteNonQuery()
MessageBox.Show("Successfully changed password.", "CHANGE PASSWORD", MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch ex As Exception
GetErrorMessage(ex)
Finally
CloseConnection()
End Try
End Sub
Whenever I press the btnUpdate I get an error saying:
System.Data.OleDB.OleDBException: Syntax Error in Update Statement
I have a table with ID As Number, UserName As Text, Password As Text. I don't know where my error is. Could you show me the way again? Thanks.
Try the following to put double quotes around the parameters.
query = "UPDATE Users SET Password = """#password""" WHERE ID = """#empID""""

How to get a string value from a sql table in visual basic

Basically I have a login system and want to add access rights. In order to do this I want my code to refer to my SQL database, return the value of access and then an if statement which would then direct the user according to their access rights. I believe the issue is when: If access = "Admin", as All I get now is the error message. I can't find out how to refer Admin to Admin in the SQL table.
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
'connection to the database
Dim connection As New SqlClient.SqlConnection
Dim command As New SqlClient.SqlCommand
Dim adaptor As New SqlClient.SqlDataAdapter
Dim dataset As New DataSet
Dim access As String
'data location
connection.ConnectionString = ("Data Source=CHRISTIAN;Initial Catalog=Complete;Integrated Security=True")
'sql statement
command.CommandText = "SELECT Access_Level FROM [User] WHERE Username= '" & txtUsername.Text & "'AND Password='" & txtPassword.Text & ";'"
connection.Open()
command.Connection = connection
adaptor.SelectCommand = command
adaptor.Fill(dataset, "0")
access = CType(command.ExecuteScalar(), String)
Try
If access = "Admin" Then
MenuAdmin.Show()
Me.Hide()
ElseIf access = "User" Then
Menu1.Show()
Me.Hide()
Else
MsgBox("Please try again, wrong username or password entered!")
txtPassword.Clear()
txtUsername.Clear()
'txtUsername.Focus()
End If
Catch ex As Exception
End Try
Thanks for any help
If it is simply a case of connecting to the database to retrieve the value of a column called "access" you will need to look into ADO.NET. Its a rather big subject but there will be plenty of examples if you have a quick Google.
Basic Microsoft ADO.Net example
Using a dataset just to return this one field seems unnecessary if you aren't going to do anything else with the table. Try something like
SqlDataReader reader=command.ExecuteReader();
string access="";
if(reader.HasRows){
reader.Read();
access=reader.IsDBNull(0) ? "" : reader.GetString(0);
}
else{
//Handle unauthorised access
}
reader.Close();
reader.Dispose();