How to loop through rows in a Datatable? - asp.net

I'm having some trouble getting a loop to see more then just the first row of data. The referenced dataset function gets all the required rows with no problem therefore I'm sure the problem must be with the code.
Dim dtLogin As System.Data.DataTable
Dim userDetails As New dsMembersTableAdapters.mi_membersTableAdapter
Dim rowsLogin As System.Data.DataRow
'Fill datatable using method from dataset
dtLogin = userDetails.GetUserData()
'Find cotrols hidden in Login View
Dim user As String = txtUser.Text
Dim pass As String = txtPass.Text
'Search all users
For Each rowsLogin In dtLogin.Rows
'Find Username Entered
If user = dtLogin.Rows.Item(0).Item(1) Then
'Checks users password matches
If pass = dtLogin.Rows.Item(0).Item(2) Then
If dtLogin.Rows.Item(0).Item(6) = 1 Then
'Log User In
FormsAuthentication.RedirectFromLoginPage(dtLogin.Rows.Item(0).Item(1), True)
Else
'Account Not Active Message
lblValidation.Text = "There is a problem with your account, please contact the website administration"
End If
Else
'Incorrect Password Message
lblValidation.Text = "Incorrect Password"
End If
Else
'No User in DB Message
lblValidation.Text = "No User Found" + dtLogin.Rows.Item(0).Item(1)
End If
Next
If anyone could help at all or point me in the rihgt direct that would be fantastic! Thanks in advance :)

when you use For Each rowsLogin In dtLogin.Rows you are telling the compiler that, for each dtLogin.Rows item, assign it into the variable rowsLogin.
So, every time, inside the loop, you stop using dtLogin.Rows.Item(0).Item(2) like in If pass = dtLogin.Rows.Item(0).Item(2) Then but rather If pass = rowsLogin.Item(0).Item(2) Then

dtLogin.Rows.Item(0).Item(1) - the (0) after Rows.Item refers to the index in the collection of rows, so you're always looking at the first row.
Instead of using dtLogin.Rows.Item(0).Item(1), etc. in your loop, use rowsLogin.Item(1).

dim bUserFound as boolean = false
For Each rowsLogin In dtLogin.Rows
'Find Username Entered
If user = rowsLogin(1) Then
bUserFound = true
'Checks users password matches
If pass = rowsLogin(2) Then
If rowsLogin(6) = 1 Then
'Log User In
FormsAuthentication.RedirectFromLoginPage(rowsLogin(1), True)
Else
'Account Not Active Message
lblValidation.Text = "There is a problem with your account, please contact the website administration"
End If
Else
'Incorrect Password Message
lblValidation.Text = "Incorrect Password"
End If
Else
'No User in DB Message
' lblValidation.Text = "No User Found" + rowsLogin(1)
End If
Next
if not bUserFound then
lblValidation.Text = "No User Found"
end if
For more clear code you should use
rowsLogin("USER_NAME") instead of rowsLogin(1),
rowsLogin("USER_PWD") instead of rowsLogin(2), etc.

Related

ASP application using the saved credentials even after the user cleared the username and password textboxes and hits submit

Could anyone please help, I have an asp application that asks for username and password in the login.aspx page and after logging in with the correct credentials, it prompts me whether to save the credentials. I clicked yes and after some time I logged out, then it takes me to the login.aspx page with the (saved) username and password already filled automatically in the boxes(because I saved previously above). Now my problem is that, now I cleared the username and password that are filled automatically in the boxes and hit submit. Then it should ask for username and password, but now actually it is using the old saved username and password and logging into the application !!!!
*To make it more brief and clear, this is the problem :-
"I am able to login even though I have removed the username and password. I logged out. Erased the content of both fields and then clicked 'Submit'. I was able to get into the Application."
Could anyone help please . Thanks in Advance !!!!
Here's my code for the 'Submit' button 'OnClick' Event :-
Protected Sub SignIn(sender As Object, e As EventArgs)
StatusText.Text = String.Empty
Dim Name As String = UserName.Text
Dim Password As String = UserPassword.Text
If IsValid Then
Try
Dim userStore = New UserStore(Of IdentityUser)()
Dim userManager = New UserManager(Of IdentityUser)(userStore)
userManager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(10)
userManager.MaxFailedAccessAttemptsBeforeLockout = 7
Dim user = userManager.FindByName(Name)
If user IsNot Nothing Then
If userManager.IsLockedOut(user.Id) Then
StatusText.Text = String.Format("Your account is locked. please contact administrator.")
Else
If userManager.CheckPassword(user, Password) Then
userManager.ResetAccessFailedCount(user.Id)
If Not userManager.GetLockoutEnabled(user.Id) Then
userManager.SetLockoutEnabled(user.Id, True)
End If
Dim tkt As FormsAuthenticationTicket
Dim cookiestr As String
Dim ck As HttpCookie
'Add Session to 5 Hours
tkt = New FormsAuthenticationTicket(1, user.UserName, DateTime.Now, DateTime.Now.AddHours(5), RememberMe.Checked, "")
cookiestr = FormsAuthentication.Encrypt(tkt)
ck = New HttpCookie(FormsAuthentication.FormsCookieName, cookiestr)
If RememberMe.Checked Then
ck.Expires = tkt.Expiration
End If
ck.Path = FormsAuthentication.FormsCookiePath
Response.Cookies.Add(ck)
Dim strRedirect As String
strRedirect = Request("ReturnUrl")
If strRedirect Is Nothing Then
strRedirect = "default.aspx"
End If
Response.Cookies.Add(New HttpCookie("adjusterId", New ContextProvider().GetAdjusterId(user.Id)))
Response.RedirectPermanent(strRedirect)
Else
userManager.AccessFailed(user.Id)
If userManager.IsLockedOut(user.Id) Then
StatusText.Text = String.Format("Your account is locked. please contact administrator.")
Else
StatusText.Text = String.Format("Invalid username or password, you have {0} more login attempt(s) left before account is locked out.", (3 - userManager.GetAccessFailedCount(user.Id)))
StatusText.Visible = True
End If
End If
End If
Else
StatusText.Text = String.Format("Invalid username or password.")
StatusText.Visible = True
End If
Catch ex As Exception
StatusText.Text = String.Format("Unable to login, please contact administrator.")
End Try
Else
StatusText.Text = String.Format("Enter username or password.")
End If
End Sub
Likely the authentication cookie is being remembered, after the initial login, and that still exists.
Somehow when you attempt to login with empty fields, it just uses the cookie instead of the empty fields. That would be my guess.
my best guess is that this method is where you will find the culprit code:
userManager.AccessFailed(user.Id)
It could also be a redirect problem. That you simply attempt to redirect the user back to a page on an invalid login, and since the cookie is still set, you are allow to see whatever page you are getting redirected too.
Main problem, your logout function doesn't remove the authentication cookie.
after a lot of banging, I found out a simple change that fulfilled my requirement, I just added the below properties for my 'username' textbox in .aspx as below :-
<asp:TextBox ID="UserName" runat="server" Width="295px" AutoCompleteType="None" EmptyMessage=" "></asp:TextBox>
(added AutoCompleteType and EmptyMessage).
Not sure whether that's the right approach, but that helps !!!! ThankYou.

Redirecting a user to appropriate page is not redirecting correctly. Any ideas?

I understand that there are several resources on how to redirect a user to a specific page based on his or her access level.
My issue is that my has some flaws preventing it from working correctly.
Your assistance is greatly appreciated.
Here is what we are trying to do.
We have employees with grievances. These employees are provided with a link to access and file their grievances.
Once the employee has filed his/her grievance, then the employee's manager would then log in and will be redirected to a page that shows all employees who have filed grievances so they review their grievances and determine whether or not the employees are approved to meet a board to review their cases and this is where I am stuck.
There are two tables that I didn't design. So, I am trying to make the best of what I am handed.
One table, called Employee has employee username (employeeID) and password (ssn).
The other table called Details has employeeID (related to Employee table) and ManagerID also related to Employee table by EmployeeID
Once a user files his/her grievance and submits it, his/her manager's ID (EmployeeID) is saved to the details table as ManagerID.
The idea is that once a manager logs into the system and his/her ID (ManageID) is present in details table, s/he will be redirected to a page called Decision.aspx.
When I attempted coding it, everyone, including Managers are being redirected to the same page called LetterOfIntent.aspx.
Any ideas what I am doing wrong?
Code is below:
StrSQL = "Select Dept, division, divisionManager, EmployeeName,Employee.EmpID, Email, SSN,Category FROM Employee e,Details d Where e.empID = d.managerID OR e.empID = #empid and SSN=#Password"
' Initialize Database Connection
Dim connStr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim conn As New SqlConnection(connStr)
Dim cmd As New SqlCommand(StrSQL, conn)
'We use parametized query to prevent sql injection attack
Dim p1 As New SqlParameter("#enpid", StrUser)
Dim p2 As New SqlParameter("#Password", StrPass)
cmd.Parameters.Add(p1)
cmd.Parameters.Add(p2)
While dr.Read()
If dr("empid") <> "" And dr("ssn") <> "" Then
Session("fullname") = dr("empName")
Session("dept") = dr("Dept")
Session("password") = dr("SSN")
Session("Email") = dr("Email")
Session("division") = dr("division")
Session("empid") = dr("empid")
Session("managerID") = dr("managerId")
Session("Cat") = dr("Category")
BValid = True
Else
End If
End While
' This handles all response per validation
If BValid = True Then
If Session("Cat") = "Pending" Then
Response.Redirect("~/pending.aspx")
ElseIf Session("Cat") = "In Progress" Then
Response.Redirect("~/inprogress.aspx")
ElseIf Session("managerID") <> "" And Session("empid") = Session("managerID") Then '***This is a manager, send him/her to Decision page
Response.Redirect("~/Decision.aspx")
Else '***Ok, this is an employee trying to file grievance, send him to LetterofInternt page.
Response.Redirect("~/LetterOfIntent.aspx?myname= " & Session("empid") & "")
End If
'If all else fails, then reject their athentication attempt and let them know.
ElseIf BValid = False Then
lblMsg.ForeColor = Color.Red
lblMsg.Text = "Login failed. "
End If
I suspect that you need to ToString each of the values you're putting into session, like this:
Session("Cat") = dr("Category").ToString()
You'd need to put some null checking around each one but given the information it seems like its probably you're issue.

ASP.net Coding User Roles into Login Page

I've developed a login page, which functions off of a stored procedure. The login part functions well, however, the website will consist of roles that will determine what page the user is directed to once they are logged into the secure section. The columns I’m focusing on in the database / table are:
Guid -0 column
Login_name -9th column
Login_Pwd -10th column
Role_ID -11th column / Contains a value of 1 or a 2
What I’m trying to do is: get the login page to distinguish between the users with a Role_ID of 1 and those that have a Role_ID of 2. But, currently, when I log into the page, I’m directed to the SecurePage.aspx regardless of what Role ID the user has. Could I please get some direction on this?
This is my Stored Procedure:
ALTER PROCEDURE [dbo].[Check_Users]
#Login_name as varchar(100),
#Login_Pwd as varchar(50)
AS
/* SET NOCOUNT ON */
SELECT * FROM SupplierCompany WHERE Login_name=#Login_name AND Login_Pwd=#Login_Pwd
RETURN
This is the code behind my login button:
Try
Dim con As New SqlConnection(GetConnectionString())
con.Open()
Dim cmd As New SqlCommand("Check_Users", con)
cmd.CommandType = CommandType.StoredProcedure
Dim p1 As New SqlParameter("Login_name", username.Text)
Dim p2 As New SqlParameter("Login_Pwd", password.Text)
cmd.Parameters.Add(p1)
cmd.Parameters.Add(p2)
Dim rd As SqlDataReader = cmd.ExecuteReader()
If rd.HasRows Then
rd.Read()
lblinfo.Text = "You are Authorized."
FormsAuthentication.RedirectFromLoginPage(username.Text, True)
Response.Redirect("securepages/SecurePage.aspx")
Else
lblinfo.Text = "Invalid username or password."
End If
'check the Role of the usre logging in
While (rd.Read())
Session("numrecord") = rd.GetValue(0).ToString()
rd.GetValue(11).ToString()
If rd.GetValue(11).ToString() = 1 Then
Response.Redirect("securepages/SecurePage.aspx")
ElseIf rd.GetValue(11).ToString() = 2 Then
Response.Redirect("securepages/newShipment.aspx")
End If
End While
Catch
Finally
End Try
..Any assistance is greatly appreciated.
Inside your If rd.HasRows Then you redirect to the SecurePage, so I'm guessing it doesn't even reach the while. Try removing the Response.Redirect("securepgaes/SecurePage.aspx") inside this if, and adding the while loop there, like this:
If rd.HasRows Then
rd.Read()
lblinfo.Text = "You are Authorized."
FormsAuthentication.RedirectFromLoginPage(username.Text, True)
'Response.Redirect("securepages/SecurePage.aspx") Remove this line
'check the Role of the user logging in
While (rd.Read())
Session("numrecord") = rd.GetValue(0).ToString()
rd.GetValue(11).ToString()
If rd.GetValue(11).ToString() = 1 Then
Response.Redirect("securepages/SecurePage.aspx")
ElseIf rd.GetValue(11).ToString() = 2 Then
Response.Redirect("securepages/newShipment.aspx")
End If
End While
Else
lblinfo.Text = "Invalid username or password."
End If
Where have you defined the code to redirect the logged in user?
The Login control by default will try and redirect you to a destination page once successful. I would think you should hook in to the OnLoggedIn event and redirect the page before the server has a chance to do it for you.
As an alternative if that doesn't work you could try building your own 'Login Control' - since you are using a stored procedure to validate users anyway, it's not a huge leap to dump a few textboxes on the page and go that way. At least then you don't need to worry about overriding the default behaviour. I believe ASP.NET provides a bunch of SPs you can use which will validate user passwords and such - check it out on the server (they are all like dbo.aspnet_*.

how to allow admin and customer to login in at same place but direct to other page after click button?

i have 2 textbox for name and password and a button
there 2 table, one admin and one customer
after i enter the customer name and password , it verify whether empty or incorrect password , if correct it will go to the customer page
however if i enter admin name and password and after verify it should go to the admin page
i am only able to allow use one table for the login ? so how should i change the code below?
Protected Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
If String.IsNullOrEmpty(txtName.Text) Or String.IsNullOrEmpty(txtPassword.Text) Then
Failure.Text = "Invalid User Name and Password. Try Again."
Exit Sub
End If
Dim connectionString = ConfigurationManager.ConnectionStrings("MYdatabase").ConnectionString
Dim myConn As New SqlConnection(connectionString)
Dim cmd = "Select * From Customer where name = #name"
Dim my As New SqlCommand(cmd, myConn)
my.Parameters.AddWithValue("#name", txtName.Text)
Dim objReader As SqlDataReader
myConn.Open()
objReader = myCmd.ExecuteReader()
FailureText.Text = " "
If objReader.Read() Then
Dim pass As String = objReader.GetString(2)
Dim cusId As Integer = objReader.GetValue(0)
If pass = txtPassword.Text Then
Failure.Text = "Login Successful"
Session("name") = txtName.Text
Session("Password") = txtPassword.Text
Session("customerID") = cusId
my.Dispose()
myConn.Dispose()
Response.Redirect("CustomerHome.aspx")
Else
FailureText.Text = "Invalid Password"
End If
Else
FailureText.Text = "Login Name does not exist"
End If
End Sub
You can repeat the same process that you use to validate if the user is a customer, for validating if it's an administrator.
Where you put: FailureText.Text = "Login Name does not exist" you can repeat the code from above and first validate if the supplied username and password map to an administrator. If so, set the session for an Admin and redirect to the admin page. If not, show the failure text.
To make sure your code stays readable, I would split the validate function into multiple functions that are called from the main function(refactoring). So you would get functions like: IsValidCustomer and IsValidAdministrator that do there checking.

Log-in control if username is not found the label text should answer username not found

got a few question here. As you all know ive created a class wherein ill just instantiate it on my .aspx page.On my .aspx page ive got a logincontrol named login1. Now im getting error when user.UserName = Nothing and stop on this user.UserName = Nothing saying Object reference not set to an instance of an object..Could you help me debug the problem. All i want is that if the username is not on the database the lblmessage should say Error Username is invalid and if it is correct then it will check on the password. Please do help. Thanks and more power guys.
Aspx page
Protected Sub LoginButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim user As New User
Dim userDAL As New UserDAL
user = userDAL.SelectByUsername(Login1.UserName)
If user.UserName = Nothing Then
Login1.FailureText = "Invalid Username"
Else
If Login1.Password <> user.Password Then
Login1.FailureText = "Invalid password"
Else
Login1.FailureText = "success"
End If
End If
End Sub
UserDAL.vb
Public Function SelectByUsername(ByVal userName As String) As User
Try
'select * from User where Username = 'userName'
Dim sqlConn As New SqlConnection(_connString)
sqlConn.Open()
Dim sqlCmd As New SqlCommand("select * from [Users] where Username = '" & userName & "'", sqlConn)
Dim dr As SqlDataReader = sqlCmd.ExecuteReader()
'Create user collection
Dim user As User = Nothing
While dr.Read()
'Create User object
user = New User
user.UserName = dr("UserName").ToString
user.Password = dr("Password").ToString
user.FirstName = dr("FirstName").ToString
user.Surname = dr("Surname").ToString
End While
dr.Close()
Return user
Finally
If _sqlConn IsNot Nothing Then
If _sqlConn.State = Data.ConnectionState.Open Then
_sqlConn.Close()
End If
End If
End Try
Return Nothing
End Function
Instead of comparing with user.Username, first you compare with only user i.e.,
If user Is Nothing Then
Why Bcoz in your SelectByUsername function you are returning Nothing if it is invalid username. Try it and reply.
I would go with the simplest answer on this. Add a validation Summary to your control that returns the required value ("Username Not Valid") and then in your code to validate do a
if(Page.IsValid) (This is C# code but VB should be very close to this)
That should solve your problem.
Here's a quick snippet
<asp:TextBox id="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ErrorMessage="User Name Not Valid" ControlToValidate="TextBox1"></asp:RequiredFieldValidator>
Now of note this error message would display to the right of the text box, however you can style it or even set it to a validation group.
The required field validator or validation group with a validation summary forces client side validation with ASP.NET for postback so when the submit button fires it will run a test and determine if Page.IsValid == true or false;
http://msdn.microsoft.com/en-us/library/aa479013.aspx

Resources