If CbDept_login.Text = "DEPT1" Then
Dim con As New SqlConnection("Data Source=XYZ-PC;Database=DATABASE1;Integrated Security =true")
con.Open()
Dim rs As New SqlCommand("SELECT * FROM TABLE1 WHERE Username=#Username COLLATE SQL_Latin1_General_CP1_CS_AS AND Password=#Password COLLATE SQL_Latin1_General_CP1_CS_AS", con)
Dim UsernameParam As New SqlParameter("#Username", Me.txtUsername.Text)
Dim PasswordParam As New SqlParameter("#Password", Me.txtPassword.Text)
rs.Parameters.Add(UsernameParam)
rs.Parameters.Add(PasswordParam)
Dim sqlRead As SqlDataReader = rs.ExecuteReader
If sqlRead.HasRows Then
If sqlRead.Read = True Then
If sqlRead("UserType") = "Admin" Then
MsgBox("Log in as " + txtUsername.Text, MsgBoxStyle.OkOnly Or MsgBoxStyle.DefaultButton2 Or MsgBoxStyle.Information, "Login Sucess")
frm_Admin.Show()
frm_Admin.LblLogAsAdmin_LCR.Text = txtUsername.Text
Me.Close()
ElseIf sqlRead("UserType") = "Staff" Then
MsgBox("Log in as " + txtUsername.Text, MsgBoxStyle.OkOnly Or MsgBoxStyle.DefaultButton2 Or MsgBoxStyle.Information, "Login Sucess")
frm_User.Show()
frm_User.TblogAsuser.Text = txtUsername.Text
Me.Close()
End If
End If
Else
MsgBox("Please input correct username and password", MsgBoxStyle.OkOnly Or MsgBoxStyle.DefaultButton2 Or MsgBoxStyle.Critical, "Login Failed")
txtPassword.Text = ""
con.Close()
End If
End If
If CbDept_login.Text = "DEPT2" Then
Dim conn As New SqlConnection("Data Source=XYZ-PC;Database=DATABASE2;Integrated Security =true")
conn.Open()
Dim rs As New SqlCommand("SELECT * FROM TABLE2 WHERE Username=#Username COLLATE SQL_Latin1_General_CP1_CS_AS AND Password=#Password COLLATE SQL_Latin1_General_CP1_CS_AS", con)
Dim UsernameParam As New SqlParameter("#Username", Me.txtUsername.Text)
Dim PasswordParam As New SqlParameter("#Password", Me.txtPassword.Text)
rs.Parameters.Add(UsernameParam)
rs.Parameters.Add(PasswordParam)
Dim sqlRead As SqlDataReader = rs.ExecuteReader
If sqlRead.HasRows Then
If sqlRead.Read = True Then
If sqlRead("UserType") = "Admin" Then
MsgBox("Log in as " + txtUsername.Text, MsgBoxStyle.OkOnly Or MsgBoxStyle.DefaultButton2 Or MsgBoxStyle.Information, "Login Sucess")
frm_Admin.Show()
frm_Admin.LblLogAsAdmin_LCR.Text = txtUsername.Text
Me.Close()
ElseIf sqlRead("UserType") = "Staff" Then
MsgBox("Log in as " + txtUsername.Text, MsgBoxStyle.OkOnly Or MsgBoxStyle.DefaultButton2 Or MsgBoxStyle.Information, "Login Sucess")
frm_User.Show()
frm_User.TblogAsuser.Text = txtUsername.Text
Me.Close()
End If
End If
Else
MsgBox("Please input correct username and password", MsgBoxStyle.OkOnly Or MsgBoxStyle.DefaultButton2 Or MsgBoxStyle.Critical, "Login Failed")
txtPassword.Text = ""
conn.Close()
End If
End If
End Sub
Hello, I'm currently facing a problem in my vb project. I'm using visual studio 2012 and SQL server 2012 for my database. I have a login form in which you can access to the different databases just by choosing department name in a combo box and it will check if you input a correct username and password using sqldatareader depends on the username and password value on the database of the department that you choose. Now my problem is when I run it, it will show an error "No source available". maybe my codes are wrong, please help me. thank you in advance. By the way, i put this code on my Login Button.
Related
I'm trying to make a login form.
I've created a database on my server and created the rows username and password.
I then created a root user with root as password.
but I have a problem with the check if the username and password are correct,
I don't know how to give him the 2 rows.
Dim conn = New SqlConnection("Data Source=SRV-SQL;Initial Catalog=prova;User ID=user;Password=user")
Dim sda = New SqlDataAdapter("select count(*) from tblLogin where username ='" + txtUsername.Text + "' and password='" + txtUserPwd.Text + "'", conn)
Dim dt = New DataTable()
sda.Fill(dt)
If (dt.Rows().ToString() = "1") Then
MsgBox("Logged-in successfully")
Else
MessageBox.Show("The username or the password is wrong!", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
Table:
Comments and explanations in-line.
Private Sub VerifyLogin()
'For the Return Value of the command
Dim RetVal As Integer
' A Using...End Using will ensure that you connectionis closed and disposed event
'it there is an error.
Using conn = New SqlConnection("Data Source=SRV-SQL;Initial Catalog=prova;User ID=user;Password=user")
'You don't need a DataAdapter, just a command
'USE PARAMETERS. Yes, I am yelling :-) Even if you are the only user
'it will save you headaches with syntax.
Using cmd = New SqlCommand("select count(*) from tblLogin where username = #UserName and password= #Password;", conn)
cmd.Parameters.Add("#UserName", SqlDbType.VarChar).Value = txtUsername.Text
cmd.Parameters.Add("#Password", SqlDbType.VarChar).Value = txtUserPwd.Text
'You are only returning one row
'ExecuteScalar returns the value in the first column of the
'first row of the the data
conn.Open()
RetVal = CInt(cmd.ExecuteScalar)
End Using
End Using
'No need to convert to a string just compare the Integer
If RetVal = 1 Then
MsgBox("Logged-in successfully")
Else
MessageBox.Show("The username or the password is wrong!", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
End Sub
Private Function CalculateHash(password As String, salt As String) As String
'TODO:
' Suggest pulling the BCrypt from the NuGet gallery for this:
' https://www.nuget.org/packages/BCrypt-Official/
' Just remember that bcyrpt lib encodes salt as part of the password hash, so the function signatures and db table will be different.
End Function
Public Function CheckCredentials(UserName As String, Password As String) As Boolean
Using conn As New SqlConnection("Data Source=SRV-SQL;Initial Catalog=prova;User ID=user;Password=user"), _
' Need to add a "Salt" column to your table, create a new random salt for each user when you create the user
cmd As New SqlCommand("SELECT Salt, PwdHash FROM tblLogin WHERE username = #Username", conn)
'Parameterized queries or NOTHING. String concatention is NOT OKAY here
cmd.Parameters.Add("#UserName", SqlDbType.NVarChar, 50).Value = UserName
conn.Open()
Using rdr As SqlDataReader = cmd.ExecuteReader()
If Not rdr.Read() Then Return False
Dim Salt As String = rdr("Salt")
Dim PwdHash As String = rdr("PwdHash")
'Compare HASHES, not Passwords
Return PwdHash = CalculateHash(Password, Salt As String)
End Using
End Using
End Function
If CheckCredentials(txtUsername.Text, txtUserPwd.Text) Then
MsgBox("Logged-in successfully")
Else
MessageBox.Show("The username or the password is wrong!", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
Use DataReader instead, use this code and just call CheckLogin in login button or somthing else.
Sub CheckLogin()
Dim conn = New SqlConnection("Data Source=SRV-SQL;Initial Catalog=prova;User ID=user;Password=user")
conn.Open()
Try
Dim query As String = "select count(*) from tblLogin where username = #username and password= #password "
Dim cmd = New SqlCommand(query, conn)
cmd.Parameters.AddWithValue("#username", txtUsername.Text)
cmd.Parameters.AddWithValue("#password", txtUserPwd.Text)
Dim DR As SqlDataReader = cmd.ExecuteReader()
If DR.HasRows Then
MsgBox("Logged-in successfully")
Else
MessageBox.Show("The username or the password is wrong!", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
conn.Close()
End Sub
I'm creating a login register with edit information. I'm stuck with the change password form.
Here's what I got - totally lost it, no errors but crashes when tested highlights my reader command
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim sql As String = "Select Username, Password From tblLog Where Username = #Username"
Dim cmd As SqlClient.SqlCommand
cmd = New SqlClient.SqlCommand(sql, con)
cmd.Parameters.Add("#Username", SqlDbType.VarChar).Value = My.Forms.formEdit.tbUser.Text
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim rd As SqlClient.SqlDataReader = cmd.ExecuteReader
Try
If rd.Read = False Then
MessageBox.Show("Incorrect Password")
tbOldPass.Clear()
tbNewPass.Clear()
tbConPass.Clear()
ElseIf tbConPass.Text <> tbNewPass.Text Then
MessageBox.Show("Password does not match")
tbOldPass.Clear()
tbNewPass.Clear()
tbConPass.Clear()
Else
Dim sqry As String = "Update tblLog Set Password = #Password" &
"Where Username = #Username And Password = #OldPassword"
rd.Close()
Dim scmd As New SqlClient.SqlCommand(sqry, con)
scmd.Parameters.AddWithValue("#Password", tbNewPass.Text)
scmd.Parameters.AddWithValue("#Username", My.Forms.formEdit.tbUser.Text)
scmd.Parameters.AddWithValue("#OldPassword", tbOldPass.Text)
scmd.ExecuteNonQuery()
MessageBox.Show("Information Updated")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
con.Close()
End Sub
Edited: Changed the code a bit, it doesn't crash anymore but my database doesn't get updated
Dim sql As String = "Select Username, Password From tblLog Where Username = #Username And Password = #Password"
Dim cmd As New SqlClient.SqlCommand
cmd = New SqlClient.SqlCommand(sql, con)
cmd.Parameters.Add("#Password", SqlDbType.VarChar).Value = My.Forms.formEdit.tbPass.Text
cmd.Parameters.Add("#Username", SqlDbType.VarChar).Value = My.Forms.formEdit.tbUser.Text
If con.State = ConnectionState.Closed Then
con.Open()
End If
cmd.ExecuteNonQuery()
con.Close()
Try
If tbOldPass.Text <> My.Forms.formEdit.tbPass.Text = False Then
MessageBox.Show("Incorrect Password")
tbOldPass.Clear()
tbNewPass.Clear()
tbConPass.Clear()
ElseIf tbConPass.Text <> tbNewPass.Text Then
MessageBox.Show("Password does not match")
tbOldPass.Clear()
tbNewPass.Clear()
tbConPass.Clear()
Else
Dim sqry As String = "Update tblLog Set [Password] = #Pss Where Username = #Use And Password = #OldPassword"
Dim scmd As New SqlClient.SqlCommand(sqry, con)
scmd.Parameters.AddWithValue("#Pss", tbNewPass.Text)
scmd.Parameters.AddWithValue("#Use", My.Forms.formEdit.tbUser.Text)
scmd.Parameters.AddWithValue("#OldPassword", My.Forms.formEdit.tbPass.Text)
If con.State = ConnectionState.Closed Then
con.Open()
End If
scmd.ExecuteNonQuery()
con.Close()
MessageBox.Show("Information Updated")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
Try Adding space before where in query:
Dim sqry As String = "Update tblLog Set Password = #Password" &
" Where Username = #Username And Password = #OldPassword"
After tweaking my code a bit I realized that I was closing the form where the value of my parameters were taken. So I tried to just hide the form not close it, then it worked. Sorry for the troubles.
Edit:
Should I delete this question or just leave it? I can't select my own answer as the correct for 2 more days
I am trying to create a login window with MDI. It is connected to a SQL Server table test. I have changed the datatypes and deleted and recreated the DB. I have 2 columns: usr and pwd of datatype nvarchar.
Dim connetionString As String
Dim cnn As SqlConnection
connetionString = "Data Source=.;Initial Catalog=test;User ID=sa;Password=sasql"
cnn = New SqlConnection(connetionString)
Dim cmd As SqlCommand
Dim myreader As SqlDataReader
Dim query As String
query = "Select usr From users WHERE (usr =" + TextBox1.Text + " and pwd = " + TextBox2.Text + ")"
cmd = New SqlCommand(query, cnn)
cnn.Open()
myreader = cmd.ExecuteReader()
If myreader.Read() Then
Else
MessageBox.Show("Incorrect username/password !", "LOGIN ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
cnn.Close()
Thank you so much.
If you are using Tortuga.Chain, the code would look like this:
Dim ds As New SqlServerDataSource(connetionString)
Dim user = ds.From("users", new With {.usr = TextBox1.Text, .pwd = TextBox2.Text}).ToString.Execute();
If user Is Not Nothing Then
Else
MessageBox.Show("Incorrect username/password !", "LOGIN ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
If you want to stick to raw ADO.NET code, you need to use a parameterized query.
Dim connetionString As String
Dim cnn As SqlConnection
connetionString = "Data Source=.;Initial Catalog=test;User ID=sa;Password=sasql"
cnn = New SqlConnection(connetionString)
Dim cmd As SqlCommand
Dim myreader As SqlDataReader
Dim query As String
query = "Select usr From users WHERE (usr = #user and pwd = #pwd )"
cmd = New SqlCommand(query, cnn)
cmd.Parameters.AddWithValue( "#usr", TextBox1.Text)
cmd.Parameters.AddWithValue( "#pwd", TextBox2.Text)
cnn.Open()
myreader = cmd.ExecuteReader()
If myreader.Read() Then
Else
MessageBox.Show("Incorrect username/password !", "LOGIN ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
cnn.Close()
Remove the spaces from the value of connectionString.
Your query compares textual data, which is invalid unless the user enters ' at the start and end of the textboxes. This would be syntactically correct:
"Select usr From users WHERE (usr ='" + TextBox1.Text + "' and pwd = '" + TextBox2.Text + "')"
but logically flawed, since the user might attempt to inject malicious SQL into your textboxes. Your application is extremely unsafe. You must protect it against SQL injection and you need to encrypt the password of the user as well.
Hello guys am having issues with my login form for multiple users of my software, below is the complete login button code for the admin
Private Sub btnlogin_Click(sender As System.Object, e As System.EventArgs) Handles btnlogin.Click
If cmbusertype.Text = "" Then
MsgBox("Please select the appropriate Account Type!", vbExclamation, "Account Type")
End If
If cmbusertype.Text = "Admin" Then
Dim Strconn As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\phermacy.mdf;Integrated Security=True;User Instance=True"
Dim Selectcmd As String = "select * from tbl_admin where admin_username = '" + txtusername.Text + "' and password = '" + txtpassword.Text + "'"
Dim da As New SqlDataAdapter
Dim ds As New DataSet
Dim sqlcmd As SqlCommand
sqlconn = New SqlConnection(Strconn)
Try
sqlconn.Open()
Catch ex As Exception
MsgBox("Could not connect to DataBase. Application will close now!", vbCritical, "Database Error")
End
End Try
sqlcmd = New SqlCommand(Selectcmd, sqlconn)
da.SelectCommand = sqlcmd
sqlcmd.Dispose()
sqlconn.Close()
da.Fill(ds)
Matching Admin User Name & Password
If ds.Tables(0).Rows.Count > 0 Then
If txtusername.Text = ds.Tables(0).Rows(0).Item(0) And txtpassword.Text = ds.Tables(0).Rows(0).Item(1) Then
MsgBox("Administrator Log-in Successful.", vbInformation, "Admin Log-in")
Me.Hide()
adminform.Show()
Else
ErrorProvider1.SetError(txtusername, "Invalid User Name.")
ErrorProvider1.SetError(txtpassword, "Invalid Password.")
MsgBox("Invalid Administrator Username or Password.", vbCritical, "Admin Log-in")
End If
Else
ErrorProvider1.SetError(txtusername, "Invalid User name or Password.")
ErrorProvider1.SetError(txtpassword, "Invalid User name or Password.")
ErrorProvider1.SetError(cmbusertype, "Please select the appropriate Account Type")
MsgBox("Invalid Administrator Username or Password.", vbCritical, "Admin Log-in")
End If
End If
End Sub
the code line highlighted is the following
If txtusername.Text = ds.Tables(0).Rows(0).Item(0) And txtpassword.Text = ds.Tables(0).Rows(0).Item(1) Then
and the error is "Conversion from string "admin" to type 'Double' is not valid." am actually new to vb trying to create a login for multiple users, the above part as you can see is just for the admin. Please any help here will be appreciated thanks.
Try this...
Private Sub btnlogin_Click(sender As System.Object, e As System.EventArgs) Handles btnlogin.Click
If cmbusertype.Text = "" Then
MsgBox("Please select the appropriate Account Type!", vbExclamation, "Account Type")
End If
If cmbusertype.Text = "Admin" Then
Dim Strconn As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\phermacy.mdf;Integrated Security=True;User Instance=True"
Dim Selectcmd As String = "select * from tbl_admin where admin_username = #usernme and password = #paswd"
Dim da As New SqlDataAdapter
Dim ds As New DataSet
Dim sqlcmd As SqlCommand
sqlconn = New SqlConnection(Strconn)
Try
sqlconn.Open()
Catch ex As Exception
MsgBox("Could not connect to DataBase. Application will close now!", vbCritical, "Database Error")
End
End Try
sqlcmd = New SqlCommand(Selectcmd, sqlconn)
sqlcmd.parameters.addwithValue("#usernme",txtusername.Text)
sqlcmd.parameters.addwithValue("#paswd",txtpassword.Text)
da.SelectCommand = sqlcmd
sqlcmd.Dispose()
sqlconn.Close()
da.Fill(ds)
Okay I have created a log in system on VB.net using a database on access. The problem I am having is that some of the username and password combinations work perfectly, but some of them, although put in correctly, don't work at all. This is the code I have written...
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Check if username or password is empty
If textpassword.Text = "" Or textusername.Text = "" Then
MessageBox.Show("Please complete the required fields..", "Authentication Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
' Both fields were supplied
' Check if user exist in database
' Connect to DB
Dim conn As New System.Data.OleDb.OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\database1.accdb"
'conn.Open()
'MsgBox("Susscess")
Dim sql As String = "SELECT * FROM Accounts WHERE username='" & textusername.Text & "' AND password = '" & textpassword.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
MemberPage.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
textpassword.Text = ""
textusername.Text = ""
'Focus on Username field
textusername.Focus()
End If
End If
End Sub
Do not Concatenate string.Its wide open for SQL injection .Its better to use Parameterized query
Dim sql As String = "SELECT * FROM Accounts WHERE username=? AND password = ?"
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql)
sqlCom.Parameters.AddWithValue("?", textusername.Text);
sqlCom.Parameters.AddWithValue("?", textpassword.Text);
Also you can use HasRows property
If sqlRead.HasRows Then
While sqlRead.Read()
MemberPage.Show()
Me.Hide()
End While
Else
MessageBox.Show("Username and Password do not match..", "Authentication Failure", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) 'Clear all fields
textpassword.Text = ""
textusername.Text = ""
'Focus on Username field
textusername.Focus()
End If
It seems that some mistake is happening at the condition you checking after filling the dataReader. i.e
If sqlRead.Read() Then
try the if condition by following code
If Not sqlRead Is Nothing Then
if it doesnt work then..
I would suggest you to do it using DataAdapter and check whether it returns rows. if the row count is greater than 1 , you must show the MemberPage
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If textpassword.Text = "" Or textusername.Text = "" Then
MessageBox.Show("Please complete the required fields..", "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|\database1.accdb"
Dim sql As String = "SELECT * FROM Accounts WHERE username='" & textusername.Text & "' AND password = '" & textpassword.Text & "'"
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql)
Dim ds As DataSet
sqlCom.Connection = conn
conn.Open()
'Dim sqlRead As System.Data.OleDb.OleDbDataReader = sqlCom.ExecuteReader()
Dim da as New OleDbDataAdapter(sqlCom)
da.Fill(ds)
If ds.Tables(0).Rows.Count > 1 Then
MemberPage.Show()
Me.Hide()
Else
MessageBox.Show("Username and Password do not match..", "Authentication Failure", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
textpassword.Text = ""
textusername.Text = ""
textusername.Focus()
End If
End If
End Sub