How to Use a parameter within SQL in Vb 2010 (web developer) - asp.net

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 = ?)"

Related

VB.Net Code not executing when value is not nullorempty

I'm trying to make fb login for my website. So I put condition if user already exist then it will do login & if not then it perform insert user data.
In following code if string is Not Null Or Empty then I am trying to execute code but by putting breakpoint on my statement I see that if string has value then rest code not executing. What could be the reason? Is I am doing something wrong? My first block of code is working fine(users data fetching from facebook). Problem is in second block where I am checking condition.
Private Sub login_Load(sender As Object, e As EventArgs) Handles Me.Load
FaceBookConnect.API_Key = "XXXXXXX"
FaceBookConnect.API_Secret = "XXXXXXX"
If Not IsPostBack Then
If Request.QueryString("error") = "access_denied" Then
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('User has denied access.')", True)
Return
End If
Dim code As String = Request.QueryString("code")
If Not String.IsNullOrEmpty(code) Then
Dim data As String = FaceBookConnect.Fetch(code, "me")
Dim faceBookUser As FaceBookUser = New JavaScriptSerializer().Deserialize(Of FaceBookUser)(data)
faceBookUser.PictureUrl = String.Format("https://graph.facebook.com/{0}/picture", faceBookUser.Id)
pnlFaceBookUser.Visible = True
lblId.Text = faceBookUser.Id
lblUserName.Text = faceBookUser.UserName
lblName.Text = faceBookUser.Name
lblEmail.Text = faceBookUser.Email
ProfileImage.ImageUrl = faceBookUser.PictureUrl
btnLogin.Enabled = False
End If
End If
If IsPostBack Then
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.CommandTimeout = 50000
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)
Response.Write("User Already Exist")
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()
Response.Write("User Added")
Catch ex As Exception
Response.Write(ex)
End Try
End If
con.Close()
End If
End If
End Sub
End Class

Facebook & Google Login for asp.net website

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

Asp.net (SQL) Simple Login Form

I'm kinda new to asp.net but I'm learning fast, tho I cant find any good web forms tutorial for login page written in vb, I'm using the offline application tutorials to learn and I just change the commands,
So i've come to a simple error for you guys, the problem is with the dsc.sqlclient, probably there's not such command, but what should I use?
Thanks a lot anyway!
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
If Page.IsValid Then
' check for username & password in the database
Dim conn As New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=LoginDB;Integrated Security=True")
' Get the row corresponding the given username and password
Dim strSQL As String = "Select * From Users Where Username='" + txtUname.Text + "' and Password = '" + txtPassword.Text + "'"
Dim dsc As New SqlClient.SqlCommand(strSQL, conn)
' Fill the dataset
Dim ds As New DataSet()
dsc.sqlclient.sqlcommand(ds, "Users")
' if there no entry then the user is invalid
If ds.Tables("Users").Rows.Count = 0 Then
Response.Redirect("Default.aspx")
Else
Response.Redirect("login.aspx")
End If
End If
End Sub
Thanks a lot guys, this is the correct answer tho, kbworkshop helped me a lot!
For anyone wanna know this is the code
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
If Page.IsValid Then
' check for username & password in the database
Dim conn As New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=LoginDB;Integrated Security=True")
' Get the row corresponding the given username and password
Dim strSQL As String = "Select * From Users Where Username='" + txtUname.Text + "' and Password = '" + txtPassword.Text + "'"
'I recommend not to use * in querys
Dim dsc As New SqlClient.SqlCommand(strSQL, conn)
conn.Open()
Dim dr As SqlDataReader
dr = dsc.ExecuteReader()
If dr.HasRows = True Then
Response.Redirect("Default.aspx")
Else
Response.Redirect("login.aspx")
End If
conn.Close()
End If
End Sub
Your code should be something like this:
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
If Page.IsValid Then
' check for username & password in the database
Dim conn As New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=LoginDB;Integrated Security=True")
' Get the row corresponding the given username and password
Dim strSQL As String = "Select * From Users Where Username='" + txtUname.Text + "' and Password = '" + txtPassword.Text + "'"
objConn.Open()
' Fill the dataset
Dim ds As New DataSet("Users")
Dim daExample As New SqlDataAdapter(strSQL, objConn)
daExample.Fill(ds, "Users2")
' if there no entry then the user is invalid
If ds.Tables("Users").Rows.Count = 0 Then
Response.Redirect("Default.aspx")
Else
Response.Redirect("login.aspx")
End If
objConn.close()
End If
End Sub
but you can also take this:
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
If Page.IsValid Then
' check for username & password in the database
Dim conn As New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=LoginDB;Integrated Security=True")
' Get the row corresponding the given username and password
Dim strSQL As String = "Select * From Users Where Username='" + txtUname.Text + "' and Password = '" + txtPassword.Text + "'"
'I recommend not to use * in querys
Dim dsc As New SqlClient.SqlCommand(strSQL, conn)
Dim dr As SqlDataReader
dr = dsc.ExecuteReader()
If dr.HasRows = True Then
Response.Redirect("Default.aspx")
Else
Response.Redirect("login.aspx")
End If
End If
End Sub
PLEASE don't create your SELECT statement by pasting text together.
Ugh.
Never do that.
You just allow anyone to use "SQL Injection" to log in (and worse) without a
password.
Imports System.Data
Imports System.Data.SqlClient
Partial Class log
Inherits System.Web.UI.Page
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cn As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=F:\WebSite1\App_Data\Database.mdf;Integrated Security=True;User Instance=True")
Dim log As String = "SELECT * FROM login WHERE userid='" & TextBox1.Text & "' AND password='" & TextBox2.Text & "'"
Session("user") = TextBox1.Text
Dim cmd As New SqlCommand(log, cn)
Dim dr As SqlDataReader
cn.Open()
dr = cmd.ExecuteReader()
If dr.HasRows = True Then
Response.Redirect("showdata.aspx")
Else
Response.Redirect("log.aspx")
End If
End Sub
End Class
You can use SqlDataAdapter class to fill your dataset:
SqlConnection conn = new SqlConnection("My ConnectionString");
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = SQL;
da.SelectCommand = cmd;
DataSet ds = new DataSet();
conn.Open();
da.Fill(ds);
conn.Close();
VB.Net:
Dim conn As New SqlConnection("My ConnectionString")
Dim da As New SqlDataAdapter()
Dim cmd As SqlCommand = conn.CreateCommand()
cmd.CommandText = SQL
da.SelectCommand = cmd
Dim ds As New DataSet()
conn.Open()
da.Fill(ds)
conn.Close()

query string is throwing exception for being null when its not

Here is whats happening , If the user is logged in - this is called directly from Page_Load
Protected Sub EnterNewTransInDb()
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("connstring").ConnectionString)
Dim comm As New SqlCommand("INSERT INTO tblRegisterRedirect (RegID , UserID, EventID, TimeStamp) VALUES (#RegID, #UserID, #EventID , getdate()) ;", conn)
Dim RegID As Guid
RegID = Guid.NewGuid()
Dim GIUDuserid As Guid
GIUDuserid = New Guid(HttpContext.Current.Request.Cookies("UserID").Value.ToString())
Dim GIUDevnetid As New Guid(HttpContext.Current.Request.QueryString("id").ToString())
comm.Parameters.AddWithValue("#RegID", RegID)
comm.Parameters.AddWithValue("#UserID", GIUDuserid)
comm.Parameters.AddWithValue("#EventID", GIUDevnetid)
Try
conn.Open()
Dim i As Integer = comm.ExecuteNonQuery()
conn.Close()
Catch ex As Exception
Dim errors As String = ex.ToString()
End Try
Dim URL As String = Request.QueryString("url").ToString()
Response.Redirect(URL + "?aid=854&rid=" + RegID.ToString())
End Sub
This works great, but if their not logged in , then they enter their log-in credentials - this happens on Button_Click event, in the click event I call this function EnterNewTransInDb() , When I run it this time , after logging in - SAME CODE , it throws an exception - Object reference is null - referring to the querystring
Protected Sub btnLogin_Click(sender As Object, e As System.EventArgs) Handles btnLogin.Click
'took out code SqlConnection onnection and SqlDataReader Code
dbCon.Open()
'If Email and PW are found
If dr.Read Then
Dim appCookie As New HttpCookie("UserID")
appCookie.Value = dr("GUID").ToString()
appCookie.Expires = DateTime.Now.AddDays(30)
HttpContext.Current.Response.Cookies.Add(appCookie)
Dim appCookie1 As New HttpCookie("UserName")
appCookie1.Value = dr("UserName").ToString
appCookie1.Expires = DateTime.Now.AddDays(30)
HttpContext.Current.Response.Cookies.Add(appCookie1)
Dim appCookie2 As New HttpCookie("UserEmail")
appCookie2.Value = txtEmail.Text.ToLower()
appCookie2.Expires = DateTime.Now.AddDays(30)
HttpContext.Current.Response.Cookies.Add(appCookie2)
Dim appCookie3 As New HttpCookie("Lat")
appCookie3.Value = dr("GeoLat").ToString()
appCookie3.Expires = DateTime.Now.AddDays(30)
HttpContext.Current.Response.Cookies.Add(appCookie3)
Dim appCookie4 As New HttpCookie("Long")
appCookie4.Value = dr("GeoLong").ToString()
appCookie4.Expires = DateTime.Now.AddDays(30)
HttpContext.Current.Response.Cookies.Add(appCookie4)
Dim appCookie5 As New HttpCookie("City")
appCookie5.Value = dr("City").ToString()
appCookie5.Expires = DateTime.Now.AddDays(30)
HttpContext.Current.Response.Cookies.Add(appCookie5)
Dim appCookie6 As New HttpCookie("State")
appCookie6.Value = dr("State").ToString
appCookie6.Expires = DateTime.Now.AddDays(30)
HttpContext.Current.Response.Cookies.Add(appCookie6)
HttpContext.Current.Response.Cookies("EO_Login").Expires = Now.AddDays(30)
HttpContext.Current.Response.Cookies("EO_Login")("EMail") = txtEmail.Text.ToLower()
Dim sUserData As String = HttpContext.Current.Server.HtmlEncode(HttpContext.Current.Request.Cookies("UserID").Value) & "|" & HttpContext.Current.Server.HtmlEncode(HttpContext.Current.Request.Cookies("UserName").Value) & "|" & HttpContext.Current.Server.HtmlEncode(HttpContext.Current.Request.Cookies("UserEmail").Value)
' Dim sUserData As String = "dbcf586f-82ac-4aef-8cd0-0809d20c70db|scott selby|scottselby#live.com"
Dim fat As FormsAuthenticationTicket = New FormsAuthenticationTicket(1, _
dr("UserName").ToString, DateTime.Now, _
DateTime.Now.AddDays(6), True, sUserData, _
FormsAuthentication.FormsCookiePath)
Dim encTicket As String = FormsAuthentication.Encrypt(fat)
HttpContext.Current.Response.Cookies.Add(New HttpCookie(FormsAuthentication.FormsCookieName, encTicket))
'If Email and Pw are not found
Else
dr.Close()
dbCon.Close()
End If
'Always do this
dr.Close()
sSql = "UPDATE eo_Users SET LastLogin=GETUTCDATE() WHERE GUID=#GUID; "
cmd = New SqlCommand(sSql, dbCon)
cmd.Parameters.AddWithValue("#GUID", HttpContext.Current.Session("UserID"))
cmd.ExecuteNonQuery()
dbCon.Close()
EnterNewTransInDb()
'Dim URL As String = Request.QueryString("url").ToString()
'Response.Redirect(URL + "?aid=854&rid=" + RegID.ToString())
End Sub
Assuming you only want this code to run if there is a valid QueryString, you could put a guard clause at the beginning of the method to simply check if QueryString is null and then perform some other action if this page is called without a QueryString.
Try setting the breakpoints before the call and make sure the variables are assigned values.
Have you tried putting a breakpoint on Dim URL As String = Request.QueryString("url").ToString() line in your code? Maybe you just need to evaluate first the querystring for the 'url' parameter, if it exists; before converting it to a string.

VB.NET - ASP.NET - Incorrect Username/Password (Validation)

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

Resources