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
Related
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.
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
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.
I've just migrated an old (ASP.NET 2.0) web site to a new server. The application has been maintained for about 8 year (upgraded to ASP.NET 4) and was working fine on the old server. It's also working fine on my development computer.
I've been searching for an answer most of this week, tried a few options but I still cannot figure this one out. Any help/pointer would be appreciated.
Below is the most pertinent snippets of running code.
TIA, Raymond
Shared Function LogMeIn(ByVal p As Page, ByVal sUserName As String, ByVal sPassword As String, ByVal bPersists As Boolean, ByVal lblMessage As Label) As Integer
Try
'get the login dataset
Dim dsLogin As DataSet = GetUserDataSetByUserName(sUserName)
If dsLogin.Tables(0).Rows.Count = 1 Then
FormsAuthentication.Initialize()
Dim sGoodPassword As String = dsLogin.Tables(0).Rows(0).Item("Password").ToString
Dim sRole As String = dsLogin.Tables(0).Rows(0).Item("Roles").ToString
'check password
If sPassword = sGoodPassword Then
Dim ticket As New FormsAuthenticationTicket(1, _
sUserName, _
DateTime.Now, _
DateTime.Now.AddMinutes(60 * 480), _
bPersists, sRole, _
FormsAuthentication.FormsCookiePath)
Dim hash As String = FormsAuthentication.Encrypt(ticket)
Dim cookie As New HttpCookie(FormsAuthentication.FormsCookieName, hash)
If ticket.IsPersistent Then cookie.Expires = DateTime.Now.AddDays(15)
cookie.HttpOnly = True
p.Response.Cookies.Add(cookie)
Dim sReturnUrl As String = "..." 'removed for clarity
p.Response.Redirect(sReturnUrl, True)
Else
lblMessage.Text = "Incorrect Password"
Return 1
End If
Else
'... 'removed for clarity
End If
Catch ex As Exception
'... 'removed for clarity
End Try
End Function
Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
' Fires upon attempting to authenticate the use
If Not (HttpContext.Current.User Is Nothing) Then
Dim gpUser As GenericPrincipal = HttpContext.Current.User
If gpUser.Identity.IsAuthenticated Then
If TypeOf gpUser.Identity Is FormsIdentity Then
Dim fi As FormsIdentity = CType(gpUser.Identity, FormsIdentity)
Dim ticket As FormsAuthenticationTicket = fi.Ticket
Dim sRoles As String()
Dim i As Integer
sRoles = ticket.UserData.Split(",")
For i = 0 To sRoles.Length - 1
sRoles(i) = Trim(sRoles(i))
Next
HttpContext.Current.User = New GenericPrincipal(fi, sRoles)
End If
End If
End If
End Sub
The problem was related to the fact that I'm using an Access database and that the site was originally build on ASP.NET 1.0. The solution was to implement custom Membership and Role providers.
http://www.codeproject.com/Articles/27955/Developing-custom-ASP-NET-Membership-and-Role-prov
I am creating login pages using asp.net with code behind in vb.net, I am newbie:D. My problem is how to pass the login name to another page. First, whenever I login it will identify if it is an administrator shown in a msgbox. The user requirement is that the employee name is displayed as login not the username. Here is my code. Thanks in advance.
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cmd1 As New SqlCommand
Dim rdr As SqlDataReader
cmd1.Connection = cn
cmd1.Connection.Open()
cmd1.CommandText = "SELECT * from UserTable WHERE Username ='" & txt_username.Text & "'"
rdr = cmd1.ExecuteReader
If rdr.HasRows = True Then
rdr.Read()
If txt_username.Text = rdr.Item(0) And txt_password.Text = rdr.Item(3) Then
CurPos = rdr.Item("Type")
CurUser = rdr.Item("Username")
CurName = rdr.Item("EmployeeName")
If rdr.Item(4) = "ADMINISTRATOR" Then
MsgBox("WELCOME! " & rdr.Item(4), MsgBoxStyle.Information)
Main.lbl_name.Text = CurName.ToUpper 'it's not working
POS.lbl_cashier.Text = CurName.ToUpper ' it's not working
Response.Redirect("ACESCHOOLSUPPLIES.aspx")
cmd1.Connection.Close()
'Me.Dispose()
Else
MsgBox("WELCOME! " & rdr.Item(4), MsgBoxStyle.Information)
cmd1.Connection.Close()
Response.Redirect("POS.aspx")
End If
A quick and dirty way to pass a variable is to use a session variable like:
Session("CurName") = CurName
Some other way: https://web.archive.org/web/20210125140826/https://www.4guysfromrolla.com/articles/020205-1.aspx