This is about forgot password. The error facing is index out of range for this statement " If ds.Tables(0).Rows.Count > 0 Then"
Dim com As New MySqlCommand
Dim dr As MySqlDataReader
conn.Open()
Dim query As String
query = "select Password, CustomerName from userdetail where Email = #Email"
com = New MySqlCommand(query, conn)
com.Parameters.AddWithValue("#Email", Email.Text)
dr = com.ExecuteReader
If dr(0).ToString > 0 Then
Dim Smtp_Server As New SmtpClient
Dim e_mail As New MailMessage()
Smtp_Server.UseDefaultCredentials = False
Smtp_Server.Credentials = New Net.NetworkCredential("xxx", "xxx")
Smtp_Server.Port = 587
Smtp_Server.EnableSsl = True
Smtp_Server.Host = "smtp.gmail.com"
e_mail = New MailMessage()
e_mail.From = New MailAddress("xxx")
e_mail.To.Add(Email.Text)
e_mail.Subject = "Your Password Details"
e_mail.IsBodyHtml = True
e_mail.Body = "Hi, <br/>Please check your Login Detailss<br/><br/>Your Username: " &
Convert.ToString(ds.Tables(0).Rows(0)("CustomerName")) & "<br/><br/>Your Password: " &
Convert.ToString(ds.Tables(0).Rows(0)("Password")) & "<br/><br/>"
Smtp_Server.Send(e_mail)
Else
Label7.Text = "The Email you entered not exists"
End
conn.Close()
My database design:
UserId, Password, CustomerName, Contact, Email, Status
Ok you have changed the question and now you are mixed up between MySqlDataReaders and DataSet
the MySqlDataReader solution should look more like
Using cn As New MySqlConnection("YOURCONNECTIONSTRING")
cn.Open()
Using cmd As New MySqlCommand("select Password, CustomerName from userdetail where Email = #Email", conn)
cmd.Parameters.AddWithValue("#Email", Email.Text)
Dim dr As MySqlDataReader
dr = cmd.ExecuteReader
If dr.Read() Then
'Did find a record to access the fields use = dr("FieldName").ToString()
Else
'didnt find a record
End If
dr.Close()
dr = Nothing
End Using
End Using
Using will take care of disposing the command and connection for you.
However I haven't tested this so emphasis the "look more like" and all this said David's comment is totally correct. Sending passwords in emails is never good.
You need to populate the ds, which I am assuming is a Dataset?..
Dim queryString As String =
"select Password, CustomerName from userdetail where Email = #Email"
Dim cmd As SqlCommand = conn.CreateCommand()
Dim da As New SqlDataAdapter()
cmd.Parameters.AddWithValue("#Email", Email.Text)
cmd.CommandText = queryString
da.SelectCommand = cmd
Dim ds As New DataSet()
conn.Open()
da.Fill(ds)
Then you can check your DataSet for the record. You also need to make sure the following apply:
The Email field is unique
A link sent to the user to enable them to reset the password, and not send clear text.
Related
For my asp.net website I was trying put feature of FB & Google Login. I found tutorial from ASPSNIPPETS. Now in this what I have done is If user click on Facebook Login button then It first authorize the user & get user details in panel. Then I put my code to check whether user already exist in my db or not. If not then it Inserts user & then put login code. My Problem is after executing first line of code it stops executing further so that It is unable to check whether user is logged in or not & so on. I think it may be because of redirect url which stops further codes o execute. How Can I eliminate this problem?
Protected Sub Login(sender As Object, e As EventArgs)
FaceBookConnect.Authorize("user_photos,email", Request.Url.AbsoluteUri.Split("?"c)(0))
If Not String.IsNullOrEmpty(lblId.Text) Then
Dim query As String = "Select ID, email From users where ID=#id"
con.Open()
Dim cmd As New MySqlCommand(query, con)
cmd.Parameters.AddWithValue("#id", lblId.Text)
Dim dr As MySqlDataReader = cmd.ExecuteReader()
If dr.HasRows Then
'Do Login Code here
Try
Dim str As String = "select * from users where ID='" + lblId.Text + "';"
Dim cmd2 As New MySqlCommand(str, con)
Dim da As New MySqlDataAdapter(cmd2)
Response.Cookies("User_Type").Value = "users"
Response.Cookies("chkusername").Value = lblId.Text
Response.Redirect(Request.Url.AbsoluteUri)
welcome.Visible = True
Catch ex As Exception
Response.Write(ex)
End Try
Else
Try
Dim str1 As String = "INSERT INTO users (ID, DP, displayName) values('" + lblId.Text + "', '" + ProfileImage.ImageUrl.ToString + "', '" + lblName.Text + "')"
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
dr.Close()
command.CommandText = str1
command.Connection = con
adapter.SelectCommand = command
command.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex)
End Try
Dim con2 As New MySqlConnection("connectionstring")
con2.Open()
Dim cmd3 As New MySqlCommand("Select ID, email From users where ID=#id", con2)
cmd3.Parameters.AddWithValue("#id", lblId.Text)
Dim dr2 As MySqlDataReader = cmd3.ExecuteReader()
If dr2.HasRows Then
'Do Login Code here
Try
Dim str As String = "select * from users where ID='" + lblId.Text + "';"
Dim cmd2 As New MySqlCommand(str, con2)
con2.Open()
Dim da As New MySqlDataAdapter(cmd3)
Response.Cookies("User_Type").Value = "users"
Response.Cookies("chkusername").Value = lblId.Text
Response.Redirect(Request.Url.AbsoluteUri)
Catch ex As Exception
Response.Write(ex)
con2.Close()
End Try
con.Close()
End If
End If
End If
con.Close()
End Sub
First you can optimise your code :
If Not String.IsNullOrEmpty(lblId.Text) Then
Dim str As String = "select * from users where ID=#id"
con.Open()
Dim cmd2 As New MySqlCommand(str, con)
cmd.Parameters.AddWithValue("#id", lblId.Text)
Dim da As New Common.DataAdapter(cmd2)
Dim ds As New Data.DataSet()
da.Fill(ds)
If ds.Tables(0).Rows.Count > 0 Then
'Do Login Code here
Try
Response.Cookies("User_Type").Value = "users"
Response.Cookies("chkusername").Value = lblId.Text
Response.Redirect(Request.Url.AbsoluteUri)
welcome.Visible = True
Catch ex As Exception
Response.Write(ex)
End Try
Else
Try
Dim str1 As String = "INSERT INTO users (ID, DP, displayName) values(#id, #img,#name)"
Dim cmd As New MySqlCommand
cmd = New SqlCommand(req, con)
cmd.Parameters.Add(New SqlParameter("#id", lblId.Text))
cmd.Parameters.Add(New SqlParameter("#img", ProfileImage.ImageUrl.ToString))
cmd.Parameters.Add(New SqlParameter("#name", lblName.Text))
cmd.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex)
End Try
'After insertion you don't have to select from database just send the parameters to cookies
Response.Cookies("User_Type").Value = "users"
Response.Cookies("chkusername").Value = lblId.Text
Response.Redirect(Request.Url.AbsoluteUri)
End If
con.Close()
End If
I'm trying to create a new user and everything works fine but it enters the same records twice to my db. I have already tried to kept some breakpoints but couldn't find where am I going wrong.
This is my Registration.aspx code:
Protected Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim msg As MailMessage
Dim UserID As String
Dim ActivationUrl As String = String.Empty
Dim emailId As String = String.Empty
UserID = Guid.NewGuid.ToString
'Create ConnectionString and Inser Statement
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim insertSql As String = "INSERT INTO Users (UserID,UserName,Password,Email,Mobile,Address,CreatedDate)" & " values (#UserID,#UserName,#Password,#Email,#Mobile,#Address,#CreatedDate)"
'Create SQL connection
Dim con As New SqlConnection(connectionString)
'Create SQL Command And Sql Parameters
Dim cmd As New SqlCommand(insertSql, con)
Dim usernumber As New SqlParameter()
usernumber.ParameterName = "#UserID"
usernumber.Value = UserID
cmd.Parameters.Add(usernumber)
Dim username As New SqlParameter()
username.ParameterName = "#Username"
username.Value = txtUserName.Text.ToString()
cmd.Parameters.Add(username)
Dim password As New SqlParameter()
password.ParameterName = "#Password"
password.Value = txtPassword.Text.ToString()
cmd.Parameters.Add(password)
Dim email As New SqlParameter()
email.ParameterName = "#Email"
email.Value = txtEmail.Text.ToString()
cmd.Parameters.Add(email)
Dim mobile As New SqlParameter()
mobile.ParameterName = "#Mobile"
mobile.Value = txtMobile.Text.ToString()
cmd.Parameters.Add(mobile)
Dim address As New SqlParameter()
address.ParameterName = "#Address"
address.Value = txtAddress.Text.ToString()
cmd.Parameters.Add(address)
Dim createddate As New SqlParameter()
createddate.ParameterName = "#CreatedDate"
createddate.Value = Date.Now.ToString("MM/dd/yyyy hh:mm:ss tt")
cmd.Parameters.Add(createddate)
Try
con.Open()
cmd.ExecuteNonQuery()
lblMsg.Text = "User Registration successful"
Catch ex As SqlException
Dim errorMessage As String = "Error in registering user"
errorMessage += ex.Message
Throw New Exception(errorMessage)
Finally
con.Close()
End Try
Try
'Sending activation link in the email
msg = New MailMessage()
Dim smtp As New SmtpClient()
emailId = txtEmail.Text.Trim()
'sender email address
msg.From = New MailAddress("voletykiran#gmail.com")
'Receiver email address
msg.[To].Add(emailId)
msg.Subject = "Confirmation email for account activation"
'For testing replace the local host path with your lost host path and while making online replace with your website domain name
ActivationUrl = Server.HtmlEncode("http://localhost:8769/UserRegistration/ActivateAccount.aspx?UserID=" & FetchUserId(emailId) & "&Email=" & emailId)
msg.Body = "Hi " & txtUserName.Text.Trim() & "!" & vbLf & "Thanks for showing interest and registring in <a href='http://www.webcodeexpert.com'> webcodeexpert.com<a> " & " Please <a href='" & ActivationUrl & "'>click here to activate</a> your account and enjoy our services. " & vbLf & "Thanks!"
msg.IsBodyHtml = True
smtp.Credentials = New NetworkCredential("voletykiran#gmail.com", "india#1a")
smtp.Port = 587
smtp.Host = "smtp.gmail.com"
smtp.EnableSsl = True
smtp.Send(msg)
ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Confirmation Link to activate account has been sent to your email address');", True)
Catch ex As Exception
ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Error occured : " & ex.Message.ToString() & "');", True)
Return
Finally
ActivationUrl = String.Empty
emailId = String.Empty
con.Close()
End Try
End Sub
Private Function FetchUserId(emailId As String) As String
Dim cmd As New SqlCommand()
cmd = New SqlCommand("SELECT UserID FROM users WHERE Email=#Email", con)
cmd.Parameters.AddWithValue("#Email", emailId)
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim UserID As String = Convert.ToString(cmd.ExecuteScalar())
con.Close()
cmd.Dispose()
Return UserID
End Function
Private Sub clear_controls()
txtUserName.Text = String.Empty
txtPassword.Text = String.Empty
txtConfirmPassword.Text = String.Empty
txtEmail.Text = String.Empty
txtMobile.Text = String.Empty
txtAddress.Text = String.Empty
txtUserName.Focus()
End Sub
Can anyone say me where am I misleading?
I want to check if the username is already exist or not. this what I've reached but it's not working.
Dim cmdstr As String = "Select count(*) from Registration where username = '" & txtName.Text & "'"
Dim userExist As SqlCommand = New SqlCommand(cmdstr, con)
Dim temp As Integer = Convert.ToInt32(userExist.ExecuteScalar().ToString())
If (temp = 1) Then
Response.Write("user name is already Exist!!")
End If
Your open for SQL-Injection. Don't concatenate strings to a sql-query but use SqlParameters
You haven't opened the connection (i assume)
Here's a full sample:
Public Shared Function GetUserCount(userName As String) As Int32
Const sql = "SELECT COUNT(*) FROM Registration where username = #UserName"
Using con As New SqlConnection(connectionString)
Using cmd = New SqlCommand(sql, con)
cmd.Parameters.AddWithValue("#UserName", userName)
con.Open()
Using reader = cmd.ExecuteReader()
If reader.HasRows
reader.Read()
Dim count As Int32 = reader.GetInt32(0)
Return count
End If
End Using
End Using
End Using
End Function
and use the method in this way:
Dim userCount As Int32 = GetUserCount(txtName.Text.Trim())
If userCount > 0
LblWarning.Text = "User-name already exists!"
End If
I am trying to work out SQL code in VB but I am having problems I have a simple database with the table admin with the columns UserName and Password.
I want to be able to read data from a text box and then input it into a SQL string… the SQL string works (I've tested it) and I can get it to output with a simple SELECT statement but I can't seem to get the SQL to read my Parameter.
Help?
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Call Password_Check(txtTestInput.Text)
End Sub
Public Sub Password_Check(ByVal Answer As String)
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim parameter As New SqlParameter("#Username", Answer)
Try
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("Database1ConnectionString1").ConnectionString
con.Open()
cmd.Connection = con
cmd.CommandText = " SELECT Password FROM Admin WHERE (UserName = #Username)"
cmd.Parameters.Add(parameter)
Dim lrd As SqlDataReader = cmd.ExecuteReader()
While lrd.Read()
Dim sothing As String
sothing = lrd("Password").ToString
If lrd("Password").ToString = txtPassword.Text Then
lblTestData.Text = "passwordSuccess"
ElseIf lrd("Password").ToString <> txtPassword.Text Then
lblTestData.Text = "passwordFail...:("
End If
End While
Catch ex As Exception
lblTestData.Text = "Error while retrieving records on table..." & ex.Message
Finally
con.Close()
End Try
End Sub
in your code above:
--> Dim parameter As New SqlParameter("#Username", Answer)
Can I suggest two options:
Dim parameter As New SqlParameter("#Username", sqldbtype.nvarchar)
parameter.value = Answer
or
cmd.CommandText = string.format("SELECT Password FROM Admin WHERE (UserName = {0})", Answer)
Full Code:
Public Sub Password_Check(ByVal Answer As String)
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim parameter As New SqlParameter("#Username", SqlDbType.NVarChar)
parameter.Value = Answer
Try
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("Database1ConnectionString1").ConnectionString
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT Password FROM Admin WHERE (UserName = #Username)"
cmd.Parameters.Add(parameter)
Dim lrd As SqlDataReader = cmd.ExecuteReader()
While lrd.Read()
Dim sothing As String
sothing = lrd("Password").ToString
If lrd("Password").ToString = txtPassword.Text Then
lblTestData.Text = "passwordSuccess"
ElseIf lrd("Password").ToString <> txtPassword.Text Then
lblTestData.Text = "passwordFail...:("
End If
End While
Catch ex As Exception
lblTestData.Text = "Error while retrieving records on table..." & ex.Message
Finally
con.Close()
End Try
End Sub
Regarding to your Database system it is possible that it does not support parameter names. Have you tried ? Wat DB System you used?
cmd.CommandText = " SELECT Password FROM Admin WHERE (UserName = ?)"
Can anyone tell me from the code what's wrong in the code?
The lbl text should show "Incorrect Username/Password" if the Username and Password do not match.
Code:
Protected Sub btnLogin_Click(sender As Object, e As System.EventArgs) Handles btnLogin.Click
Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Brian\Documents\Visual Studio 2010\WebSites\PetLandia\App_Data\db.mdb")
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [User] where Username=? and Password=?", conn)
cmd.Parameters.AddWithValue("#Username", txtLogin.Text)
cmd.Parameters.AddWithValue("#Password", txtPassword.Text)
If (String.IsNullOrEmpty(txtLogin.Text)) Or (String.IsNullOrEmpty(txtPassword.Text)) Then
lblLoginError.Text = "One or more fields are empty. Please fill in all the fields"
lblLoginError.Visible = True
Else
conn.Open()
Dim read As OleDbDataReader = cmd.ExecuteReader()
Try
If read.HasRows Then
While read.Read()
If txtLogin.Text = read.Item("username").ToString And txtPassword.Text = read.Item("password").ToString Then
Dim tUsername As String = read.Item("Username").ToString
Session("Username") = tUsername
Response.Redirect("Default.aspx")
End If
End While
End If
read.Close()
Catch ex As Exception
Response.Write(ex.Message())
lblLoginError.Text = "Incorrect Username/Password."
lblLoginError.Visible = True
Finally
conn.Close()
End Try
End If
End Sub
Instead of the catch write an Else to the if statements
You can try this code. This code is without Try Catch block.
Protected Sub btnLogin_Click(sender As Object, e As System.EventArgs) Handles btnLogin.Click
If (String.IsNullOrEmpty(txtLogin.Text)) Or (String.IsNullOrEmpty(txtPassword.Text)) Then
lblLoginError.Text = "One or more fields are empty. Please fill in all the fields"
lblLoginError.Visible = True
Else
Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Brian\Documents\Visual Studio 2010\WebSites\PetLandia\App_Data\db.mdb")
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [User] where Username=? and Password=?", conn)
cmd.Parameters.AddWithValue("#Username", txtLogin.Text)
cmd.Parameters.AddWithValue("#Password", txtPassword.Text)
conn.Open()
Dim read As OleDbDataReader = cmd.ExecuteReader()
If read.HasRows Then
read.Read()
Session("Username") = read.Item("Username").ToString
read.Close()
conn.Close() 'Close connection before Redirecting.
Response.Redirect("Default.aspx")
Else
read.Close()
conn.Close()
lblLoginError.Text = "Incorrect Username/Password."
lblLoginError.Visible = True
End If
End If
End Sub
You don't need to return the username and password from the database as you have them already. You just need to count the matching entries. This greatly simplifies it. Also, as jams showed, it's better to do the test for values in the username and password fields before doing anything to do with the database:
If (String.IsNullOrEmpty(txtLogin.Text)) OrElse (String.IsNullOrEmpty(txtPassword.Text)) Then
lblLoginError.Text = "One or more fields are empty. Please fill in all the fields"
lblLoginError.Visible = True
Else
Dim ok As Integer = 0
Using conn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Brian\Documents\Visual Studio 2010\WebSites\PetLandia\App_Data\db.mdb")
Dim cmd As OleDbCommand = New OleDbCommand("SELECT COUNT(*) FROM [User] where Username=? and Password=?", conn)
cmd.Parameters.AddWithValue("#Username", txtLogin.Text)
cmd.Parameters.AddWithValue("#Password", txtPassword.Text)
conn.Open()
ok = CInt(cmd.ExecuteScalar())
conn.Close()
End Using
If ok = 0 Then
' credentials incorrect
Else
' credentials correct
End If
End If
The way you've written it, "Incorrect Username/Password" will only show if an exception is thrown.
if you want to use the code as you've written it, add an ELSE:
If txtLogin.Text = read.Item("username").ToString And txtPassword.Text = read.Item("password").ToString Then
Dim tUsername As String = read.Item("Username").ToString
Session("Username") = tUsername
Response.Redirect("Default.aspx")
else
throw new exception("Incorrect Username/Password")
End If
You decided to roll your own security which led to ...
You appear to be storing passwords in plain text which is a huge security hole and potential source of liability.
If read.HasRows will be false if the passed username and password do not exist in the database. I.e., it will not throw an exception, it will simply return no rows.
You did not call Dispose on the disposable objects.
It would be faster to simply call ExecuteScalar with Select Count(*) to see if the result is greater than zero.
Dim authenticationFailed As Boolean = String.IsNullOrEmpty(txtLogin.Text) _
OrElse String.IsNullOrEmpty(txtPassword.Text)
If Not authenticationFailed Then
Dim connString = "Provider=Microsoft.Jet.OLEDB.4.0..."
Using conn = New OleDbConnection(connString)
Const sql As String = "Select Count(*) From [User] Where Username=? and Password=?"
conn.Open()
Using cmd = New OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#Username", txtLogin.Text)
cmd.Parameters.AddWithValue("#Password", txtPassword.Text)
Try
Dim result = cmd.ExecuteScalar(CommandBehavior.CloseConnection)
Catch generatedExceptionName As SqlException
authenticationFailed = True
End Try
authenticationFailed = authenticationFailed _
OrElse Convert.ToInt32(result) <> 1
If Not authenticationFailed Then
Session("Username") = txtLogin.Text
End If
End Using
conn.Close()
End Using
End If
If authenticationFailed Then
lblLoginError.Text = "Incorrect username and password"
lblLoginError.Visible = True
End If