I am having trouble validating a username and password when someone clicks a button. I have two text boxes named user_logon_id and user_password.
I have a table called MyUsers that I suppose to verify that both the username (user_logon_id) and password (user_password) are in the same row. If they do not match, it's supposed to notify the user. If it does match then direct them to userAdmin.aspx.
I am using Microsoft Visual Studio 2008. I am really new to this and would really like to get a grasp on this. I do not need to worry about encrypting the password.
Can you run this in the debugger and verify that the query is returning a row?
Some suggestions:
Consider parameterizing your query like this:
Dim conn As New SqlConnection(_connectionString)
conn.Open()
Dim s As String = "SELECT user_password FROM MyUsers WHERE user_logon_id = #user_login_id"
Dim cmd As New SqlCommand(s)
cmd.Parameters.Add("#user_login_id", Me.user_logon_id.Text)
Dim reader As SqlDataReader = cmd.ExecuteReader()
Hash the password in some way
Consider selecting from the database table where the username and password match. If the result is one record the login succeeded.
Dim s As String = "SELECT userid FROM MyUsers WHERE user_logon_id = #user_login_id and user_password=#user_password"
Full code
Protected Sub butSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles butSubmit.Click
Dim myReader As Data.SqlClient.SqlDataReader
Dim mySqlConnection As Data.SqlClient.SqlConnection
Dim mySqlCommand As Data.SqlClient.SqlCommand
'Establish the SqlConnection by using the configuration manager to get the connection string in our web.config file.
mySqlConnection = New Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString1").ToString())
Dim sql As String = "SELECT userid FROM MyUsers WHERE user_logon_id = #user_login_id and user_password=#user_password"
mySqlCommand = New Data.SqlClient.SqlCommand(sql, mySqlConnection)
cmd.Parameters.Add("#user_login_id", Me.user_logon_id.Text)
cmd.Parameters.Add("#user_password", Me.user_password.Text)
Try
mySqlConnection.Open()
myReader = mySqlCommand.ExecuteReader()
If (myReader.HasRows) Then
'Open page with users and roles
Dim message As String = "Correct password"
Dim style As MsgBoxStyle = MsgBoxStyle.OkOnly
Dim title As String = "Authenticated"
MsgBox(message, style, title)
End If
Catch ex As Exception
Console.WriteLine(ex.ToString())
Finally
If Not (myReader Is Nothing) Then
myReader.Close()
End If
If (mySqlConnection.State = Data.ConnectionState.Open) Then
mySqlConnection.Close()
End If
End Try
End Sub
Related
I have a user registration form for multiple users. This works fine except the code is unable to identify if there is already username exist. I know there is mistake in my code but I am unable to rectify that one.
Code is below can anyone help me sort this, how to write modify code for reader
Private Sub OK_Click(sender As Object, e As EventArgs) Handles OK.Click
Dim user, pass As String
user = UsernameTextBox.Text
pass = PasswordTextBox.Text
Dim connection1 As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=Credentials.mdb;")
Dim command As New OleDbCommand("SELECT [ID] FROM [Staff] WHERE [usernameField] = username AND [passwordField] = password", connection1)
Dim usernameParam As New OleDbParameter("username", Me.UsernameTextBox.Text)
Dim passwordParam As New OleDbParameter("password", Me.PasswordTextBox.Text)
command.Parameters.Add(usernameParam)
command.Parameters.Add(passwordParam)
command.Connection.Open()
Dim reader As OleDbDataReader = command.ExecuteReader()
If reader.HasRows Then
MessageBox.Show("User Exist")
MyPlayer.SoundLocation = path & LogOnsound
PasswordTextBox.Text = ""
UsernameTextBox.Text = ""
ElseIf user = "" Or pass = "" Then
MsgBox("Please Fill The Boxs", , "Error")
Else
Dim connection As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Credentials.mdb;"
Using myconnection As New OleDbConnection(connection)
myconnection.Open()
Dim sqlq As String = "INSERT INTO [staff] ([username], [password]) VALUES (#user, #pass)"
Using cmd As New OleDbCommand(sqlq, myconnection)
cmd.Parameters.AddWithValue("#usernme", user)
cmd.Parameters.AddWithValue("#passwrd", pass)
cmd.ExecuteNonQuery()
MsgBox("User Registered!", , "register")
user = ""
pass = ""
End Using
End Using
End If
command.Connection.Close()
End Sub
It looks like you have multiple things wrong:
You should be specifying #username instead of just username in your SELECT statement so that it will be recognized as a parameter.
Why are you checking for a match on password also? If you do that, people can have the same username with just a different password...do you want that?
In your SELECT, you have usernameField as the column name in your Staff table, but in your INSERT, you have username as the column name. Which is it?
In your INSERT, you specify the parameter #user, but in your cmd.Parameters.AddWithValue statement, you have #usernme.
In short, I am working on a program that will add/edit entries to an SQL database.
One of the features for this program is that it, if given the account ID number, will look up the name under that account with that given ID. This is what I am having trouble with.
General Format:
Objective: SQL Query that will return string to textbox
AcctID => field in table with account number
AcctName => field in table with account name
txtbx_accountName => textbox I need the name returned to
NOTE:
This is all nested in a generic Try-Catch statement with error
handling.
This is all inside a Click event handler for a button.
This is all done in Visual Studio 2015
Dim myConn As New SqlConnection
Dim myCmd As New SqlCommand
myConn.ConnectionString = ""
myConn.Open() ' Open the connection
myCmd = myConn.CreateCommand()
' Build the query with the account number as paramter
myCmd.CommandText = "SELECT AcctName FROM DataSetTable WHERE (AcctID = #incomingAcctID)"
' Add the parameter so the SqlCommand can build the final query
myCmd.Parameters.Add(New SqlParameter("#incomingAcctID", (CInt(txtbx_accountNum.Text))))
' run the query and obtain a reader to get the results
Dim reader As SqlDataReader = myCmd.ExecuteReader()
' check if there are results
If (reader.Read()) Then
' populate the values of the controls
txtbx_accountName.Text = reader(0)
End If
' Close all connections
myCmd.Dispose()
myConn.Close() ' Close connection
myConn.Dispose()
i am not pro but i do like this,sorry if this not helped you:
if your Stored procedure is created to add and edit than write this and call it where you want to add:
private sub NAME(ByVAL Parameter1 name as integer,
ByVAL Parameter2 name as string,
ByVAL Parameter3 name as boolean)
Dim strConn As String = ConfigurationManager.ConnectionStrings("databaseXYZ").ConnectionString
Dim myConn As New SqlConnection(strConn)
Dim myCmd As SqlCommand
try
myConn.Open()
sqlCommand = New SqlCommand("PRCEDURE_NAME", myConn )
sqlCommand.CommandType = CommandType.StoredProcedure
dim param as new System.Data.SqlClient.SqlParameter
param.parameterName="#send_parameter1"
param.Direction = ParameterDirection.Input
param.Value = send_parameter1
dim param1 as new System.Data.SqlClient.SqlParameter
param1.parameterName="#send_parameter2"
param1.Direction = ParameterDirection.Input
param1.Value = send_parameter2
sqlCommand.Parameters.Add(Param)
sqlCommand.Parameters.Add(Param1)
sqlCommand.ExecuteNonQuery()
catch ex as exception
throw
End Try
myConn.Close()
myConn = Nothing
end sub
I'm a dummy!!!
Here is the solution, for all interested parties.
Click Event Handler (w/ nested Try-Catch):
txtbx_accountName.Text = DataSetTableAdapter.SearchNameQuery(CInt(txtbx_accountNum.Text)).ToString
SearchNameQuery:
SELECT AcctName FROM DataSetTable WHERE AcctID = #incomingAcctID
More notes on this:
- The dataset is already included in the project
I am encountering an error where it is stating:
authentication to host '' for user '' using method 'mysql_native_password' failed with message: access denied for user ''#'localhost' (using password: no)
Now I read online about checking my passwords, my connection strings, and IP address. I have checked them all. I even checked the user privileges on my database and I have all access and every ability to modify, delete, update, and insert the database.
What is weird is that, it is only this set of code that it will not execute (This code should run when I add a new record):
Private Sub PolicyEnableFields()
'Automate Last Modified By textbox
Dim sqlAdapter As New MySqlDataAdapter
Dim sqlCommand As New MySqlCommand
Dim sqlTable As New DataTable
Dim sqlText As String = "select full_name from user_privileges where user_name='" & Login.UserIDTextBox.Text & "'"
With sqlCommand
.CommandText = sqlText
.Connection = sConnection
End With
With sqlAdapter
.SelectCommand = sqlCommand
.Fill(sqlTable)
End With
For i = 0 To sqlTable.Rows.Count - 1
Me.PolicyModifiedTextBox.Text = (sqlTable.Rows(i)("full_name"))
Next
sqlTable.Dispose()
sqlCommand.Dispose()
sqlAdapter.Dispose()
End Sub
But when I run the exact some piece of code in a different SUB it works perfectly fine (This code runs when I edit a existing record):
Private Sub PolicyEditButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PolicyEditButton.Click
'Automate Last Modified By textbox
Dim sqlAdapter As New MySqlDataAdapter
Dim sqlCommand As New MySqlCommand
Dim sqlTable As New DataTable
Dim sqlText As String = "select full_name from user_privileges where user_name='" & Login.UserIDTextBox.Text & "'"
With sqlCommand
.CommandText = sqlText
.Connection = sConnection
End With
With sqlAdapter
.SelectCommand = sqlCommand
.Fill(sqlTable)
End With
For i = 0 To sqlTable.Rows.Count - 1
Me.PolicyModifiedTextBox.Text = (sqlTable.Rows(i)("full_name"))
Next
sqlTable.Dispose()
sqlCommand.Dispose()
sqlAdapter.Dispose()
End Sub
HERE is my connection STRING (of course I will not show my PW):
Public sqlConnect As String = "server=10.0.7.30; userid=Alliance; password=*******; database=mydb; convert zero datetime=True"
Can anyone help?
Check the sConnection, and make sure it is initialized with the proper connection string. The error message mentions localhost, but the connection string you show is 10.0.7.30.
I am doing a form where the user is writing his username and choose from a button list. Before the insert i need to check if the username is already existed or not. The server side code is:
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
'Duplicate username
Dim username As String = tbUsername.Text.Trim()
Dim tempUser As Byte = CByte(rblDept.SelectedIndex)
Dim query1 As String = "Select cUserName FROM Intranet.dbo.Gn_ISCoordinators WHERE cUserName = #cUserName"
Dim haha As DataTable = New DataTable()
Using adapter = New SqlDataAdapter(query1, ConfigurationManager.ConnectionStrings("IntranetConnectionString").ConnectionString)
adapter.Fill(haha)
If haha.Rows.Count <> 0 Then
lblmessage.Text = "Error! user name is already exist"
Return
End If
End Using
'Insert new user
Dim query As String = "Insert into Intranet.dbo.Gn_ISCoordinators (cUserName,lDeptUser) Values ('" & username & "'," & tempUser & ")"
Dim hehe As DataTable = New DataTable()
Using adapter1 = New SqlDataAdapter(query, ConfigurationManager.ConnectionStrings("IntranetConnectionString").ConnectionString)
adapter1.Fill(hehe)
lblmessage.Text = "User has been added"
End Using
End Sub
So when the user press the button it first check the duplicate username if everything is ok, then it inserts the row.
Btw the error is occur when i press on submit button and it gave me this Must declare the scalar variable "#cUserName". on adapter.Fill(haha) line.
Please i want to know what is wrong with my code. Help me
Thanks in advance.
Error message shows everything you need to know to solve that issue. You're using parameter #cUserName in your query, but it is never set.
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("IntranetConnectionString").ConnectionString)
conn.Open()
Dim query1 As String = "Select cUserName FROM Intranet.dbo.Gn_ISCoordinators WHERE cUserName = #cUserName"
Dim command As New SqlCommand(query1, conn )
Dim param As New SqlParameter()
param.ParameterName = "#cUserName"
param.Value = username
command.Parameters.Add(param)
Using adapter = New SqlDataAdapter(command)
You are using a Parameter #cUserName but you did not initialize it or pass values to it.
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("IntranetConnectionString").ConnectionString)
conn.Open()
Dim query1 As String = "Select cUserName FROM Intranet.dbo.Gn_ISCoordinators WHERE cUserName = #cUserName"
Dim command As New SqlCommand(query1, conn)
command.Parameters.AddWithValue("#cUserName",username)
Using adapter = New SqlDataAdapter(command)
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Checking for an SQL result in VB.NET
I have login form which is redirect user for their levels but before to that if there is no any user on the data table I would like to redirect to create admin form. I have all the forms but I didn't manage to redirect them because I don't know how to create statement. Could you please help me about solution.
Dim con As SqlCeConnection
Dim command As SqlCeCommand
con = New SqlCeConnection("Persist Security Info=False;Data Source=.\database.sdf;Password=********;File Mode=shared read")
con.Open()
command = New SqlCeCommand("select * from users where Name=? and Password=?", con)
Dim param1, param2 As SqlCeParameter
param1 = New SqlCeParameter("Name", uname.Text)
param2 = New SqlCeParameter("Password", pwd.Text)
command.Parameters.Add(param1)
command.Parameters.Add(param2)
Dim reader As SqlCeDataReader = command.ExecuteReader
If (reader.Read = True) Then
role = reader.GetString(1)
Else
MsgBox("Invalid Login")
End If
I have this code is working. What to write for
Private Sub frmlogin_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
I would recommend trying the DataReader's HasRows property to determine if one or more rows was returned to the DataReader object.
if (reader.HasRows)
{
reader.Read();
role = reader.GetString(1)
}
else
{
// invalid login
}
Not sure I completely understand your question, but if the table is empty then reader.Read() would evaluate to False.
I think what you want is a SQL Statement checking the Count of the users table.
Something like
command = New SqlCeCommand("SELECT COUNT(Name) as NameCount FROM Users", con)
Then you would evaluate the count by doing something like
Dim reader as SqlCeDataReader = command.ExecuteReader()
While(reader.Read())
if reader("NameCount") = 0 then
'Redirect to Admin Form
else
'Run all your current logic here to find the user from the DB
end if
End While