ASP.NET Login to grant access to specific type of group of people - asp.net

Have a asp.net(vb.net) login page that I need set up to grant access to users base on EmployeeTypeID. The following code needs to be converted into vb.net from Access vb6 or written in vb.net
If rs!EmployeeTypeID = 2 Then
rs.Close
Me.LoginLabel.Visible = False
DoCmd.OpenForm "DetectIdleTIme", , , , , acHidden
DoCmd.OpenForm "frmProcessTimer", , , , , acHidden
DoCmd.OpenForm "frmCRMControlCenter"
DoCmd.Close acForm, Me.Name
Exit Sub
End If
If rs!EmployeeTypeID = 3 Then
Dim prop As Property
On Error GoTo SetProperty
If MsgBox("Would you like to turn on the ByPass Key?", vbYesNo, "Allow Bypass?") = vbYes Then
CurrentDb.Properties("AllowBypassKey") = True
Else
CurrentDb.Properties("AllowBypassKey") = False
End If
rs.Close
Me.LoginLabel.Visible = False
DoCmd.OpenForm "DetectIdleTIme", , , , , acHidden
DoCmd.OpenForm "frmProcessTimer", , , , , acHidden
DoCmd.OpenForm "frmCRMControlCenter"
DoCmd.Close acForm, Me.Name
Exit Sub

This should help :)
Protected Sub UserLogin()
Dim Username As String = Me.txtUserName.Text
Dim Password As String = Me.txtPassword.Text
Dim Connstr As String = "SERVER:BLAHBALHUID" ' Your connection string <<<<
Dim con As SqlConnection = New SqlConnection(Connstr)
'Query string - using paramters (#User and #Pwd to set the username and password criteria)
Dim qry As String = "SELECT Username, Password, EmployeeTypeID FROM Employees WHERE Username =#User AND Password=#Pwd"
Dim cmd As SqlCommand = New SqlCommand(qry, con)
'Using cmd.paramters means that you wont get any SQL injections
'- definately google SQL injections and check out some of the Youtubes!! :)
cmd.Parameters.Add("#User", SqlDbType.VarChar).Value = Username
cmd.Parameters.Add("#Pwd", SqlDbType.VarChar).Value = Password
con.Open()
Dim rdr As SqlDataReader = cmd.ExecuteReader
Dim Found_A_Record As Boolean = False
Dim EmployeeType As String = Nothing
While rdr.Read
'if there is a row - then we have found the username and password that matches
'Therefore - this must be a user with the username and matching password
Found_A_Record = True
EmployeeType = rdr("EmployeeTypeID")
End While
cmd.Dispose()
con.Close()
If Not Found_A_Record Then
'No records found - exit? or do whatever would be for not correct details
End If
Select Case EmployeeType
Case "1"
Response.Redirect("~/CustomerRelationshipManagement.aspx")
Case "2"
Response.Redirect("~/CRMControlCenter.aspx")
Case "3"
Response.Redirect("~/CRMControlCenter.aspx")
Case Else
Response.Write("<script>alert('Incorrect Username or Password.', 'Login Failed')</script>")
End Select
End Sub

Related

ASP.Net Login Page with MySQL

Can anyone spot the error in this? I'm trying to create a simple login page (asp.net vb) that does a count on a mysql table. When i type anything in it logs me in even if the details do not match. I believe it'll be the case statement that's wrong but any help would be appreciated!
Protected Sub ValidateUser(sender As Object, e As EventArgs)
Dim userId As Integer = -1
Dim constr As String = ConfigurationManager.ConnectionStrings("conn").ConnectionString
Using con As New MySqlConnection(constr)
Using uscmd As New MySqlCommand("SELECT COUNT(*) FROM tblUser WHERE UName = ?#Username AND Pword = ?#Password", con)
uscmd.Parameters.AddWithValue("#Username", Login1.UserName)
uscmd.Parameters.AddWithValue("#Password", Login1.Password)
Using uuda As New MySqlDataAdapter(uscmd)
Dim ds As New DataSet()
uuda.Fill(ds)
userId = ds.Tables(0).Rows.Count.ToString()
End Using
End Using
Select Case userId
Case -1
Login1.FailureText = "Username and/or password is incorrect."
Exit Select
Case -2
Login1.FailureText = "Account has not been activated."
Exit Select
Case Else
FormsAuthentication.RedirectFromLoginPage(Login1.UserName, Login1.RememberMeSet)
Exit Select
End Select
End Using
End Sub
Your query "SELECT COUNT()..." will always return 1 record. After execute the query, you make an assignment
userId = ds.Tables(0).Rows.Count.ToString()
So the value of userId will be always 1. So it always run into CASE ELSE of the CASE statement. That's why whatever you type, it logs you in even if the details do not match.
To check the username and password have been registered or not, you could update your code like following
Protected Sub ValidateUser(sender As Object, e As EventArgs)
Dim userCount As Integer = -1
Dim constr As String = ConfigurationManager.ConnectionStrings("conn").ConnectionString
Using con As New MySqlConnection(constr)
Using uscmd As New MySqlCommand("SELECT COUNT(*) FROM tblUser WHERE UName = ?#Username AND Pword = ?#Password", con)
uscmd.Parameters.AddWithValue("#Username", Login1.UserName)
uscmd.Parameters.AddWithValue("#Password", Login1.Password)
Using uuda As New MySqlDataAdapter(uscmd)
Dim ds As New DataSet()
uuda.Fill(ds)
Integer.TryParse(ds.Tables(0).Rows(0)(0), userCount)
End Using
End Using
If userCount > 0 Then
FormsAuthentication.RedirectFromLoginPage(Login1.UserName, Login1.RememberMeSet)
Else
Login1.FailureText = "Username and/or password is incorrect."
End If
End Using
End Sub

Check if Record Exists IN DB Using ASP VB

I am trying to check whether an email exists in my sql database from an an asp code behind
Basically a user will fill in a form and submit, I need to check wther that email exists first before inserting
Protected Sub btnSignup_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSignup.Click
Response.Cookies("survey")("fullname") = TextBoxFullName.Text
Response.Cookies("survey")("surname") = TextBoxSurname.Text
Response.Cookies("survey")("lastVisit") = DateTime.Now.ToString()
Response.Cookies("survey")("contactnumber") = TextBoxPhone.Text
Response.Cookies("survey")("email") = TextBoxEmail.Text
Response.Cookies("survey").Expires = DateTime.Now.AddDays(365)
'InsertCommand="INSERT INTO [Comp_20140409_Broadband] ([SignupName], [SignupGender], [SignupIDNo], [SignupEmailAddress], [CurrentProvider], [CurrentSpeed], [CurrentUsage]) VALUES (#SignupName, #SignupGender, #SignupIDNo, #SignupEmailAddress, #CurrentProvider, #CurrentSpeed, #CurrentUsage)"
If Not Page.IsValid Then Exit Sub
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim updateSql3 As String = "Select [PersonId] FROM [Users] WHERE [Email] = #Email"
Dim PersonId As Integer
Using myConnection As New SqlConnection(connectionString)
myConnection.Open()
Dim myCommand As New SqlCommand(updateSql3, myConnection)
myCommand.Parameters.AddWithValue("#Email", TextBoxEmail.Text)
PersonId = myCommand.ExecuteScalar()
myConnection.Close()
End Using
Dim updateSql2 As String = " INSERT INTO [Survey_Legal] ([LegalInsurance],[ThirdParty], [LegalIssues], [RequestLegal], [PersonId], [Category_Type]) VALUES (#LegalInsurance, #ThirdParty, #LegalIssues, #RequestLegal, #PersonId, #Type )"
Using myConnection2 As New SqlConnection(connectionString)
myConnection2.Open()
Dim myCommand2 As New SqlCommand(updateSql2, myConnection2)
myCommand2.Parameters.AddWithValue("#LegalInsurance", DDLLegal1.SelectedValue)
myCommand2.Parameters.AddWithValue("#ThirdParty", DDLLegal2.SelectedValue)
myCommand2.Parameters.AddWithValue("#LegalIssues", DDLLegal3.SelectedValue)
myCommand2.Parameters.AddWithValue("#RequestLegal", DDLLegal4.SelectedValue)
myCommand2.Parameters.AddWithValue("#PersonId", PersonId)
myCommand2.Parameters.AddWithValue("#Type", "Legal-Insurance")
myCommand2.ExecuteNonQuery()
myConnection2.Close()
End Using
This is how I do this. I check for a duplicate email address in my stored procedure with an output parameter.
CREATE Procedure sp_AddSubscriber
#Name as nvarchar(50),
#Email as nvarchar(50),
#AddSubscriber bit OUTPUT
AS
IF (SELECT COUNT(Email)
FROM TSubscribers
WHERE Email = #Email) = 0
BEGIN
INSERT TSubscribers (Name, Email)
VALUES (#Name, #Email)
SET #AddSubscriber = False
END
ELSE
SET #AddSubscriber = True
GO

Activation Email/Link Not Working

I'm trying to send an activation email and have the user activate their account by clicking on the link provided. I have been tweaking it based on open source code I've been looking at online, however it has recently stopped sending the email without giving any errors. Here is the sign up form with the send email function:
Imports System.Data.SqlClient
Imports System.Data.Sql
Imports System.Data.SqlTypes
Imports System.Data
Imports System.Configuration
Imports System.Net.Mail
Imports System.Net
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Public Class WebForm1
Inherits System.Web.UI.Page
Dim boolCar As Object
Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
If txtEmailAddress.Text.Trim.EndsWith("#umary.edu") Or txtPassword.Text.Trim = txtRetypePassword.Text.Trim Then
Dim con As New SqlConnection
Dim cmdEmail As New SqlCommand
Dim cmdRegistration As New SqlCommand
Dim EmailCount As Integer = 0
Try
con.ConnectionString = "Data Source=SERVERNAME;Initial Catalog=StudentGov;User ID=sa;Password=Password1"
con.Open()
cmdEmail = New SqlCommand("SELECT COUNT(UMaryEmail) As EmailCount FROM RegisteredUsers WHERE UMaryEmail='" & txtEmailAddress.Text.Trim & "'", con)
EmailCount = cmdEmail.ExecuteScalar()
If EmailCount = 0 Then
' Declare database input variables
Dim userId As Integer = 0
Dim firstName As String = txtFirstName.Text
Dim lastName As String = txtLastName.Text
Dim hometown1 As String = txtHometown1.Text
Dim state1 As String = txtState1.Text
Dim zip1 As String = txtZipCode1.Text
Dim hometown2 As String = txtHometown2.Text
Dim state2 As String = txtState2.Text
Dim zip2 As String = txtZipCode2.Text
Dim phoneNum As String = txtPhoneNumber.Text
Dim emailAddress As String = txtEmailAddress.Text
Dim password As String = txtPassword.Text
Dim boolCar As Boolean = False
Dim boolUmary As Boolean = False
If radYesNo.SelectedIndex = 0 Then
boolCar = True
Else
boolCar = False
End If
' Define the command using parameterized query
cmdRegistration = New SqlCommand("INSERT INTO RegisteredUsers(FirstName, LastName, Hometown1, State1, ZIP1, Hometown2, State2, ZIP2, PhoneNum, UMaryEmail, Password, Car) VALUES (#txtFirstName, #txtLastName, #txtHometown1, #txtState1, #txtZipCode1, #txtHometown2, #txtState2, #txtZipCode2, #txtPhoneNumber, #txtEmailAddress, #txtPassword, #RadYesNo)", con)
' Define the SQL parameter '
cmdRegistration.Parameters.AddWithValue("#txtFirstName", txtFirstName.Text)
cmdRegistration.Parameters.AddWithValue("#txtLastName", txtLastName.Text)
cmdRegistration.Parameters.AddWithValue("#txtHometown1", txtHometown1.Text)
cmdRegistration.Parameters.AddWithValue("#txtState1", txtState1.Text)
cmdRegistration.Parameters.AddWithValue("#txtZipCode1", txtZipCode1.Text)
cmdRegistration.Parameters.AddWithValue("#txtHometown2", txtHometown2.Text)
cmdRegistration.Parameters.AddWithValue("#txtState2", txtState2.Text)
cmdRegistration.Parameters.AddWithValue("#txtZipCode2", txtZipCode2.Text)
cmdRegistration.Parameters.AddWithValue("#txtPhoneNumber", txtPhoneNumber.Text)
cmdRegistration.Parameters.AddWithValue("#txtEmailAddress", txtEmailAddress.Text)
cmdRegistration.Parameters.AddWithValue("#txtPassword", txtPassword.Text)
cmdRegistration.Parameters.AddWithValue("#RadYesNo", boolCar)
cmdRegistration.ExecuteNonQuery()
SendActivationEmail(userId)
Response.Redirect("RegistrationSuccess.aspx")
Else
' Duplicate Email Exist Error Message
MsgBox("Email address already supplied.")
End If
' Catch ex As Exception (Not needed)
' Error Executing One Of The SQL Statements
Finally
con.close()
End Try
Else
' Throw Error Message
MsgBox("Email input error")
End If
End Sub
Private Sub SendActivationEmail(userId As Integer)
Dim sqlString As String = "Server=SERVERNAME;Database=StudentGov;UId=sa;Password=Password1;"
Dim ActivationCode As String = Guid.NewGuid().ToString()
Dim ActivationUrl As String = Server.HtmlEncode("http://localhost:63774/ActivateAccount.aspx?userId=" & FetchUserId(txtEmailAddress.ToString) & "&txtEmailAddress=" & txtEmailAddress.ToString & "&ActivationCode=" & ActivationCode.ToString)
Using con As New SqlConnection(sqlString)
Using sqlCmd As New SqlCommand("UPDATE RegisteredUsers SET UserId = '" + userId.ToString + "', ActivationCode = '" + ActivationCode.ToString + "' WHERE UMaryEmail='" + txtEmailAddress.Text + "';")
Using sda As New SqlDataAdapter()
sqlCmd.CommandType = CommandType.Text
sqlCmd.Parameters.AddWithValue("#UserId", userId)
sqlCmd.Parameters.AddWithValue("#ActivationCode", ActivationCode)
sqlCmd.Connection = con
con.Open()
sqlCmd.ExecuteNonQuery()
con.Close()
End Using
End Using
End Using
Using mm As New MailMessage("****#outlook.com", txtEmailAddress.Text)
mm.Subject = "Account Activation"
Dim body As String = "Hello " + txtFirstName.Text.Trim() + ","
body += "<br /><br />Please click the following link to activate your account"
body += "<br /><a href='" & ActivationUrl & "'>Click here to activate your account.</a>"
body += "<br /><br />Thanks"
mm.Body = body
mm.IsBodyHtml = True
Dim smtp As New SmtpClient()
smtp.Host = "smtp.live.com"
smtp.EnableSsl = True
Dim NetworkCred As New NetworkCredential("****#outlook.com", "****")
smtp.UseDefaultCredentials = True
smtp.Credentials = NetworkCred
smtp.Port = 587
Try
smtp.Send(mm)
Catch ex As Exception
MsgBox("Email was not sent")
End Try
End Using
End Sub
Private Function FetchUserId(emailAddress As String) As String
Dim cmd As New SqlCommand()
Dim con As New SqlConnection("Data Source=SERVERNAME;Initial Catalog=StudentGov;User ID=sa;Password=Password1")
cmd = New SqlCommand("SELECT UserId FROM RegisteredUsers WHERE UMaryEmail=#txtEmailAddress", con)
cmd.Parameters.AddWithValue("#txtEmailAddress", emailAddress)
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
End Class
And here is the AccountActivation page:
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Public Class ActivateAccount
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
ActivateMyAccount()
End If
End Sub
Private Sub ActivateMyAccount()
Dim con As New SqlConnection()
Dim cmd As New SqlCommand()
Try
con.ConnectionString = "Data Source=CISWEB\UMCISSQL2008;Initial Catalog=StudentGov;User ID=sa;Password=Password1"
If (Not String.IsNullOrEmpty(Request.QueryString("UserId"))) And (Not String.IsNullOrEmpty(Request.QueryString("UMaryEmail"))) Then
'approve account by setting Is_Approved to 1 i.e. True in the sql server table
cmd = New SqlCommand("UPDATE RegisteredUsers SET AccountActivated=1 WHERE UserId=#UserId AND UMaryEmail=#txtEmailAddress", con)
cmd.Parameters.AddWithValue("#UserId", Request.QueryString("UserId"))
cmd.Parameters.AddWithValue("#txtEmailAddress", Request.QueryString("UMaryEmail"))
If con.State = ConnectionState.Closed Then
con.Open()
End If
cmd.ExecuteNonQuery()
Response.Write("You account has been activated. You can <a href='SignIn.aspx'>Sign in</a> now! ")
End If
Catch ex As Exception
ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Error occured : " & ex.Message.ToString() & "');", True)
Return
Finally
con.Close()
cmd.Dispose()
End Try
End Sub
End Class
As you may be able to tell already, I am flummoxed. With no error messages I'm receiving, I don't know why the SendActivationEmail function is no longer working. Someone help please! :(
Hi FlummoxedUser are you sure that have you checked your code as well ????
Take a look here :
Dim ActivationUrl As String = Server.HtmlEncode("http://localhost:63774/ActivateAccount.aspx?userId=" & FetchUserId(txtEmailAddress.ToString) & "&txtEmailAddress=" & txtEmailAddress.ToString & "&ActivationCode=" & ActivationCode.ToString)
I think is better use httputility.urlEncode/Decode for this stuff where it use it to filter only the result of each function or single variable.
Second one take care at your code above
this is in your page :
If (Not String.IsNullOrEmpty(Request.QueryString("UserId"))) And (Not String.IsNullOrEmpty(Request.QueryString("UMaryEmail")))
where have you found "UmaryEmail" key in your querystring parameters?????
Check it and you will solve your issue but check also in cmd and so on in activation page or you will make some issues :)
I hope it help you and if it solves your issue mark this as answer.
UPDATE :
> Dim ActivationUrl As String = Server.HtmlEncode("http://localhost:63774/ActivateAccount.aspx?userId=" & FetchUserId(txtEmailAddress.ToString) & "&txtEmailAddress=" & txtEmailAddress.ToString & "&ActivationCode=" & ActivationCode.ToString)
with this task you create yout activation link which will be something like
http://localhost:63774/ActivateAccount.aspx?userId=1&txtEmailAddress=email#pippo&ActivationCode=123456
Now what's append when click on that link server handle request and create a collection data which include all the keys within your querystring
In effect you can use request.QueryString to check/retrieve values from each keys. So you can use as you did request.Querystring("keyname") to get the value for that particular parameter BUT in your case you check for a key which are not passed into the link. Pay attention that you have setup only 3 keys which are
UserID
txtEmailAddress
ActivationCode
there's no "UMaryEmail" key in request query string
Also another important stuff NEVER PASS IN QUERY STRING DATABASE FIELD :) use fantasy name or shortname which not reflect database field
example :
UserID => uid
ActivatioCode = token,acd,cd or anything you want
txtEmailAddress= email, em or any other name
Now activation page issue when you try to check your value use an if statement where check for userid key and UMaryEmail where userid could be matched coz it exist in query string but UmaryEmail is not into the request.querystring you have not provided it so if fails and nothing has been shown in page.
Here your Activation Sub revisited with some comments to better understand :
Private Sub ActivateMyAccount()
'Checking you keys in querystring
If Request.QueryString.AllKeys.Contains("Userid") AndAlso Request.QueryString.AllKeys.Contains("txtEmailAddress") Then
'here we assume that keys exist and so we can proceed with rest
If (Not String.IsNullOrEmpty(Request.QueryString("UserId"))) And (Not String.IsNullOrEmpty(Request.QueryString("txtEmailAddress"))) Then
'no we can proceed to make other stuff
'Another stuff place you connection string within connection string section in webconfig in order to make a simple request like this one :
'classic example for create a connection with web config file
' Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("yourconnectionstringname").ToString)
Using con As New SqlConnection("Data Source=CISWEB\UMCISSQL2008;Initial Catalog=StudentGov;User ID=sa;Password=Password1")
If con.State = ConnectionState.Closed Then con.Open()
Dim sqlQuery As String = "UPDATE RegisteredUsers SET AccountActivated=1 WHERE UserId=#UserId AND UMaryEmail=#txtEmailAddress"
Using cmd As New SqlCommand(sqlQuery, con)
Try
With cmd
.Parameters.AddWithValue("#UserId", Request.QueryString("UserId"))
.Parameters.AddWithValue("#txtEmailAddress", Request.QueryString("txtEmailAddress"))
.ExecuteNonQuery()
Response.Write("You account has been activated. You can <a href='SignIn.aspx'>Sign in</a> now! ")
End With
Catch ex As Exception
ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('We apologize but something is gone wrong;our techs are checking the issue.Best regards etc etc etc');", True)
End Try
End Using
End Using
Else
Response.Write("<h1>invalid activation links!!</h1>")
End If
Else
Response.Write("<h1>invalid activation links!!</h1>")
End If
End Sub
If your query is right it should work at first shot :)
Take a try and let me know and if it solve your issue please mark it as answer
UPDATE 2:
Your actual code is :
Dim ActivationUrl As String = Server.HtmlEncode("localhost:63774/ActivateAccount.aspx?userId=" & HttpUtility.UrlEncode(FetchUserId(txtEmailAddress.ToString)) & "&txtEmailAddress=" & HttpUtility.UrlEncode(txtEmailAddress.ToString) & "&ActivationCode=" & HttpUtility.UrlEncode(ActivationCode.ToString))
But is all wrong let me explain:
Declar your variable : Dim ActivationUrl as string it is ok
Then built url so :
="http://localhost:63774/ActivateAccount.aspx?userId=" & HttpUtility.UrlEncode(FetchUserId(txtEmailAddress.text.tostring)) & "&txtEmailAddress=" & HttpUtility.UrlEncode(txtEmailAddress.text.tostring) & "&ActivationCode=" & HttpUtility.UrlEncode(ActivationCode.ToString))
Where take a look to piece of code which is your : 'HttpUtility.UrlEncode(txtEmailAddress.ToString)' in this manner you are passing a value system type object which is a textbox to pass textbox value you need to access to its .Text property like txtEmailAddress .Text
Change as per my code above and it will work (if your procedure is right)
**UPDATE CODE 3 **
Change your code with this.§be carefull don't change anything copy and paste all ActivateMyAccount Sub and delete your old one
Private Sub ActivateMyAccount()
'Checking you keys in querystring
If Request.QueryString.AllKeys.Contains("userId") And Request.QueryString.AllKeys.Contains("txtEmailAddress") Then
'here we assume that keys exist and so we can proceed with rest
If (Not String.IsNullOrEmpty(Request.QueryString("userId"))) And (Not String.IsNullOrEmpty(Request.QueryString("txtEmailAddress"))) Then
'no we can proceed to make other stuff
'Another stuff place you connection string within connection string section in webconfig in order to make a simple request like this one :
'classic example for create a connection with web config file
' Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("yourconnectionstringname").ToString)
Using con As New SqlConnection("Data Source=CISWEB\UMCISSQL2008;Initial Catalog=StudentGov;User ID=sa;Password=Password1")
If con.State = ConnectionState.Closed Then con.Open()
Dim sqlQuery As String = "UPDATE RegisteredUsers SET AccountActivated=1 WHERE UserId=#UserId AND UMaryEmail=#txtEmailAddress"
Using cmd As New SqlCommand(sqlQuery, con)
Try
With cmd
cmd.Parameters.AddWithValue("#UserId", Request.QueryString("userId"))
cmd.Parameters.AddWithValue("#txtEmailAddress", Request.QueryString("txtEmailAddress"))
cmd.ExecuteNonQuery()
Response.Write("You account has been activated. You can <a href='SignIn.aspx'>Sign in</a> now! ")
End With
Catch ex As Exception
ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('We apologize but something is gone wrong;our techs are checking the issue.Best regards etc etc etc');", True)
End Try
End Using
End Using
Else
Response.Write("<h1>invalid activation links!! bad query string</h1>")
End If
Else
Response.Write("<h1>invalid activation links!! bad not string</h1>")
End If
End Sub

How to check if mysql query returns nothing?

I'm writing a project and at the some point i have to check if there is an entry in database which matches the content of id-textbox and password-textbox. But I don't know how to indicate in my backend code(VB) that the query returns nothing.
This is the code I am using. But it doesn't work somehow. Error messages Are not being prompt:
Try
myconn.Open()
Dim stquery As String = "SELECT * from accountstbl WHERE user_ID = " & IdNumb.Text
Dim smd As MySqlCommand
Dim myreader As MySqlDataReader
smd = New MySqlCommand(stquery, myconn)
myreader = smd.ExecuteReader()
If myreader.Read() = True Then
If myreader.Item("user_ID") = IdNumb.Text Then
If myreader.Item("password") = CurrPass.Text Then
'some code if the user input is valid
Else
errorPassID.Visible = True
End If
Else
errorPassC.Visible = True
End If
End If
myconn.Close()
Catch ex As Exception
Dim ErrorMessage As String = "alert('" & ex.Message.ToString() & "');"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "ErrorAlert", ErrorMessage, True) myconn.Close()
End Try
Will appreciate any help or suggestion.
I will try to check if the reader return rows and if not, emit an error message.
Also, do not use string concatenation to build queries, use always parametrized queries
myconn.Open()
Dim stquery As String = "SELECT * from accountstbl WHERE user_ID = #id"
Dim smd = New MySqlCommand(stquery, myconn)
smd.Parameters.AddWithValue("#id", Convert.ToInt32(IdNumb.Text))
Dim myreader = smd.ExecuteReader()
if Not myreader.HasRows Then
Dim ErrorMessage As String = "alert('No user found');"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "ErrorAlert", ErrorMessage, True)
myconn.Close()
return
else
myreder.Read()
' no need to check if id is equal, you pass it as parameter to a where clause'
If myreader.Item("password") = CurrPass.Text Then
'some code if the user input is valid '
Else
errorPassID.Visible = True
' or error message '
End If
End If
myconn.Close()
Catch ex As Exception
Dim ErrorMessage As String = "alert('" & ex.Message.ToString() & "');"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "ErrorAlert", ErrorMessage, True)
myconn.Close()
End Try
Note also that passing a clear text password along the wire is a serious security hole. I hope you have stored an hash of the password and check on that instead.
By the way, why don't pass also the password hash in the query? Somthing like this:
Dim stquery As String = "SELECT * from accountstbl WHERE user_ID = #id AND password = #pwd"
In this way, if you have a record returned the user is validated and your client side code will be simple

How can I update a database table programmatically?

I have a button which when pressed, sets the user's rights in the db. (If Administrator UserTypeID is set to '2' and if Customer it is set to '1'). However when I run the below code, everything remains the same. I think it's from the SQL statement but I;m not sure. Can anyone help please?
Protected Sub btnSetUser_Click(sender As Object, e As System.EventArgs) _
Handles btnSetUser.Click
Dim conn As New OleDbConnection( _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\...\WebSite3\db.mdb;")
Dim cmd As OleDbCommand = _
New OleDbCommand("UPDATE [User] SET [UserTypeID] WHERE Username=?", conn)
conn.Open()
cmd.Parameters.AddWithValue("#Username", txtUser.Text)
If ddUserType.SelectedItem.Text = "Administrator" Then
cmd.Parameters.AddWithValue("#UserTypeID", "2")
cmd.ExecuteNonQuery()
lblSetUser.Text = txtUser.Text + "was set to Administrator."
ElseIf ddUserType.SelectedItem.Text = "Customer" Then
cmd.Parameters.AddWithValue("#UserTypeID", "1")
cmd.ExecuteNonQuery()
lblSetUser.Text = txtUser.Text + "was set to Customer."
End If
conn.Close()
End Sub
End Class
If you add a parameter #Username your command should have such a parameter
SELECT [UserTypeID] FROM [User] WHERE Username = #Username
Also, you add an additional parameter later, which does not occur at all in your query! You call cmd.ExecuteNonQuery(), which works only for INSERT, UPDATE and DELETE queries.
Your query should probably look like this
UPDATE [User]
SET UserTypeID = #UserTypeID
WHERE Username = #Username
Dim cmd As OleDbCommand = New OleDbCommand( _
"UPDATE [User] SET UserTypeID = #UserTypeID WHERE Username = #Username", conn)
Dim userType As String = ddUserType.SelectedItem.Text
Dim userTypeId As Integer = If(userType = "Administrator", 2, 1)
cmd.Parameters.AddWithValue("#UserTypeID", userTypeId)
cmd.Parameters.AddWithValue("#Username", txtUser.Text)
conn.Open()
cmd.ExecuteNonQuery()
lblSetUser.Text = txtUser.Text + "was set to " & userType
UPDATE (some clarifications)
In "UDATE [User] SET UserTypeID = #UserTypeID WHERE Username = #Username"
[User] is the name of the table
UserTypeID is the name of the user type id column
#UserTypeID is the name of the user type id parameter (the new value)
Username is the name of the user name column
#Username is the name of the user name parameter
You might have to change these names in order to match your actual situation.
You are only performing a Select Query - which will not modify any data at all.
You will want to use an Update Query, supplying parameters for both the username and the user rights number.
You're doing a SELECT instead of an UPDATE...
New OleDbCommand("SELECT [UserTypeID] FROM [User] WHERE Username=?", conn)
should be
New OleDbCommand("UPDATE [User] SET [UserTypeID] = #UserTypeID WHERE Username = #Username", conn)

Resources