I am trying to create a Login page for asp.net - asp.net

I am trying to reference a database with sql to compare it to the text boxes, I do not know why my code is not working, its probably my IF statement? It could be that I am not writing the SQL statement correctly also.
Protected Sub btnValidate_Click(sender As Object, e As EventArgs) Handles btnValidate.Click
Dim strSQL As String = "SELECT * FROM loginInfo"
If "SELECT UserName, PassCode From loginInfo Where [UserName] [PassCode]" Then
Response.Redirect("gridView.aspx")
End If
End Sub

A couple of things wrong here:
Your query syntax is incorrect.
You don't need to load all the users on page load. Just checking the entered username and password will do.
On a side note, use parameterised queries to avoid SQL Injection.
What you can do is this - in the btnValidate_Click method, get your entered username and password, pass it to the query and if you find a record with username and password matching the user entered text, consider it as a successful login and redirect to the required page. Code would be something like this:
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
Protected Sub btnValidate_Click(sender As Object, e As EventArgs) Handles btnValidate.Click
Dim recordMatch as int
Using con As New OleDbConnection( _
"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + Server.MapPath("DynamicDataBase.mdb")),
con.Open()
Dim strSQL As String = "SELECT COUNT(1) FROM loginInfo WHERE [UserName] = #username AND [PassCode] = #passcode"
Dim cmd As New OleDbCommand(strSQL, con)
cmd.Parameters.Add("#username", SqlDbType.VarChar, 50).Value = yourusernametextbox.Text
cmd.Parameters.Add("#passcode", SqlDbType.VarChar, 50).Value = yourpasscodetextbox.Text
recordMatch = Convert.ToInt32(cmd.ExecuteScalar())
End Using
If recordMatch = 1 Then
Response.Redirect("gridView.aspx")
End If
End Sub

Related

How to search for something in Database using search box in vb.net/asp.net

I am having a library system database. I want to include a search box where I can search for a book name. I am using sql server. I know how to write a sql statement using the LIKE %''% clause, but the thing is I am writing this sql statement in a separate file and include that in the sub method in vb.net. How can I make that statement use the text entered in textbox?
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim str As String = ("Data Source=.\INSTANCE;initial catalog=example;user=sa;password=gariahat")
Dim con As New SqlConnection(str)
Dim cmd As New SqlCommand("select * from item where book_id like '%" + Trim(TextBox1.Text) + "%'", con)
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
If (da.Fill(ds, "item")) Then
ItemDataGridView.DataSource = ds.Tables(0)
MessageBox.Show("match found")
Else
MessageBox.Show("match not found")
End If
End Sub
I know this sub will work if I include the sql statement in the sub itself. But I use squaler to store my sql stored procedures and use those file in my sub, that file does not accept 'textbox.text'.
Example:
Public Shared Sub AccountDeposit(ByVal value As Integer, ByVal AccountNumber As String, ByVal connection As SqlConnection)
Dim cmd As New SqlCommand("AccountDeposit", connection)
cmd.CommandType = Data.CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#AccountNumber", AccountNumber)
cmd.Parameters.AddWithValue("#Value", value)
cmd.ExecuteNonQuery()
End Sub
Here "AccountDeposit" is my stored procedure which i included in my sub.I want to do similar thing here but dont know how to include the text in textbox to sql statement

Login page not working in vb asp.net

I am having an issue with my login page. I am not getting any errors so am not able to know where the problem is?
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Login.Click
'connection string
Dim mysqlconn As MySqlConnection = New MySqlConnection("server=localhost;user id=root;Password=123;database=users;persist security info=False")
Dim cmd As New MySqlCommand
Dim da As New MySqlDataAdapter
Dim mydata As New DataTable
Dim reader As MySqlDataReader
Try
mysqlconn.Open()
Dim query As String
query = "SELECT * FROM login_form where Username = '" & rfvUser.Text & "' and Password='" & rfvPWD.Text & "'"
cmd = New MySqlCommand(query, mysqlconn)
reader = cmd.ExecuteReader
While reader.Read()
If rfvUser.Text = "admin" And rfvPWD.Text = "admin" Then
Me.Session("User") = Me.rfvUser.Text
Server.Transfer("Admin.aspx")
ElseIf (rfvUser.Text = reader("UserName").ToString()) And (rfvPWD.Text = reader("Password").ToString()) Then
Me.Session("User") = Me.rfvUser.Text
Server.Transfer("Ersal_send.aspx")
Else
ClientScript.RegisterStartupScript(Page.[GetType](), "validation", "<script language='javascript'>alert('Invalid Username or Password')</script>")
reader.Close()
End If
End While
Catch ex As Exception
MsgBox(ex.Message)
Finally
mysqlconn.Dispose()
End Try
End Sub
End Class
Have you tried running the query directly via a SQL client? If your query is not returning any rows, then your procedure will simply exit without any errors as it will never enter the While loop.
Another advice: It is never a good idea to pass user input directly into a query. This leads to SQL injection. Use parameterised queries. Google for it.

Format of the initialization string does not conform to specification starting at index 0 Error

I'm writing a simple update-password page (studying purposes). The page consist of two text-box controls that will allow the user to enter their new password, followed by confirming their password by entering it into the second text-box control and finally clicking the submit bottom to update their password in the table stored in a database. My problem is that I receive the following error upon button-click: Format of the initialization string does not conform to specification starting at index 0 Error.
This is the code in behind he button:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
If TextBox2.Text = TextBox3.Text Then
Dim myConnectionString As String
myConnectionString = "myDbIIConnectionString1"
Dim myConnection As New SqlConnection(myConnectionString)
myConnection.Open()
Dim mySQLQuery As String
mySQLQuery = "UPDATE myTb SET password VALUES (#password)"
Dim myCommand As New SqlCommand(mySQLQuery, myConnection)
myCommand.Parameters.AddWithValue("#password", TextBox3.Text)
myCommand.Connection = myConnection
myCommand.ExecuteNonQuery()
myCommand = Nothing
myConnection.Close()
myConnection = Nothing
Label2.Text = "Your Password has been changed"
Else
Label2.Text = "Retype your Password"
End If
Response.Redirect("login.aspx")
End Sub
Could someone assist me as to what I'm missing here? Thank You
There is problem in your update query . Correct it as :
mySQLQuery = "UPDATE myTb SET password=#password"
I figured it out; I should have been using configurationmanager.connectionstrings["the name goes here"]. to access my connection string.

displaying Username using session (ASP.NET)

I am using Visual Studio 2010 as my IDE and creating a simple website using Visual Basic I dunno if it's possible but can I display the Username that has just logged into my LoginForm to the other forms using sessions?
I'm not that good enough to understand it but can anyone tell me, is this the right way to contain the value in a session?, how can I display it to the other form?
Protected Sub ImageButton1_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles ImageButton1.Click
Dim connect As String = "Provider=Microsoft.ACE.OleDb.12.0;" & _
"Data Source=C:\Users\cleanfuel\Documents\Visual Studio 2010\Projects\FinalProject4a2p\FinalProject4a2p\bin\DBFinalProject.accdb"
Dim query As String
query = "Select Count(*) From tblAccount Where Username = ? And UserPass = ?"
Dim result As Integer = 0
Using conn As New OleDbConnection(connect)
Using cmd As New OleDbCommand(query, conn)
cmd.Parameters.AddWithValue("", TxtUser.Text)
cmd.Parameters.AddWithValue("", txtPass.Text)
conn.Open()
result = DirectCast(cmd.ExecuteScalar(), Integer)
End Using
End Using
If result > 0 Then
Response.Redirect("Menus.aspx")
Session("User") = TxtUser.Text
Session("Pass") = txtPass.Text
Else
Response.Write("<td>")
Response.Write("<div align=""center"">")
Response.Write("<font color='white'>")
Response.Write("Unable to Login, Invalid Username or Password! </font>")
Response.Write("</div>")
Response.Write("</td>")
End If
End Sub
Setup a label in your Master Page (if you have one), assign the user name from your session to the label and it will appear in all the pages. If you don't have Master page then can setup a label in the page (you want username to appear) and then set the label Text property to value from the session.
The way you are storing the values in the session is correct, you should redirect to Menu.aspx once the values are stored in the session like:
If result > 0 Then
Session("User") = TxtUser.Text
Session("Pass") = txtPass.Text
Response.Redirect("Menus.aspx")
....
And to access them you can do :
labelUserName.Text = Session("User").ToString()
Use FormsAuthentication, then you can simply put a LoginName control on your form, or get the UserName from HttpContext.Current.User.Identity.Name
The answers that the other users provide can be used also, but I find this one and successfully got the result that I want to have.
here are my codes:
Protected Sub ImageButton1_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles ImageButton1.Click
Dim connect As String = "Provider=Microsoft.ACE.OleDb.12.0;" & _
"Data Source=C:\Users\cleanfuel\Documents\Visual Studio 2010\Projects\FinalProject4a2p\FinalProject4a2p\bin\DBFinalProject.accdb"
Dim query As String
query = "Select Count(*) From tblAccount Where Username = ? And UserPass = ?"
Dim result As Integer = 0
Using conn As New OleDbConnection(connect)
Using cmd As New OleDbCommand(query, conn)
cmd.Parameters.AddWithValue("", TxtUser.Text)
cmd.Parameters.AddWithValue("", txtPass.Text)
conn.Open()
result = DirectCast(cmd.ExecuteScalar(), Integer)
End Using
End Using
If result > 0 Then
Dim myCookie As HttpCookie = New HttpCookie("USER")
myCookie.Value = TxtUser.Text
Response.Cookies.Add(myCookie)
Response.Redirect("Menus.aspx")
Else
Response.Write("<td>")
Response.Write("<div align=""center"">")
Response.Write("<font color='white'>")
Response.Write("Unable to Login, Invalid Username or Password! </font>")
Response.Write("</div>")
Response.Write("</td>")
End If
End Sub
I used HTTPcookie instead of session because I can't satisfy myself because it didn't displayed the value that I want to display and it always shows me the same ERROR over and over again.
here are the codes to display:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Request.Cookies("USER") Is Nothing Then
Label7.Text = "No Account Logged In"
Else
Dim aCookie As HttpCookie = Request.Cookies("USER")
Label7.Text = Convert.ToString(Server.HtmlEncode(aCookie.Value))
End If
End Sub

connect to SQL using asp.net

anyone can help me to connect to SQL server through vb.net using asp.net webform.. I have the database name Users and i want to use the database for the login page.. please help me..
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim ConnectionString As String
ConnectionString = ConfigurationSettings.AppSettings("ConnectionString")
Dim con As New SqlConnection(ConnectionString)
Dim cmd As New SqlCommand("Select UserId, Pwd from Users", con)
con.Open()
Dim myreader As SqlDataReader
myreader = cmd.ExecuteReader()
While myreader.Read()
If TxtUserId.Text = myreader("UserId").ToString().Trim()
AndAlso TxtPwd.Text = myreader("Pwd").ToString().Trim() Then
Session("UserId") = TxtUserId.Text
Response.Redirect("UserMyProfile.aspx")
Else
lblMsg.Visible = True
lblMsg.Text = "Inavalid UserId/Password"
End If
End While
con.Close()
End Sub
There's no shortage of tutorials on the web for this, but a good starting point is here.
EDIT: Based on your comments above, it sounds like you're not importing the Namespace you need for the ADO.NET data objects. Try adding this to the class file:
Imports System.Data.SqlClient

Resources