How to check and change labels and textboxes in ASP.net - asp.net

I am trying to make a website using asp.net. First you must log in. This textbox is called Username, and there is a textbox called Password.
If Username = Hello and Password = 123, then I want the page to redirect. If it doesn't match then I want a pre-existing label called ErrorMessage to display a message saying: Please check Username and password.
Here is my current code in the button click event.
Nothing works so far.
If (Username.Text.Contains("Hello")) & (Password.Text.Contains("123")) Then
Response.Redirect("MemberContactInfo.aspx")
Else
ErrorMessage.Text = "Please check username and password"
End If

You're using the wrong operator in your If statement. When you want two conditions to be true, you should use the And operator, not the & operator (which performs string concatenation).
Modify your code as follows:
If (Username.Text.Contains("Hello")) And (Password.Text.Contains("123")) Then
Response.Redirect("MemberContactInfo.aspx")
Else
ErrorMessage.Text = "Please check username and password"
End If

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.

How do I populate multiple textboxes based on value of another textbox or dropdownlist?

hello again.
We have a webform that employees use to make request for such things as VPN access to the company resources from remote locations.
I am populating a dropdownlist box from Active Directory. This works fine.
Then I have a textbox that is also populated from Active Directory by simply assigning the value of the logged in user as shown:
textbox1.Text = User.Identity.Name
Based on the value of my name assigned to textbox1.Text
The rest of the texboxes are populated with my work information with the following code:
textbox1.Text = User.Identity.Name
textbox1.Text = StrConv(textbox1.Text, vbProperCase)
txtdate.Text = DateTime.Now.ToString("MM/dd/yyyy")
Try
'Creates a Directory Entry Instance with the Username and Password provided
Dim deSystem As New DirectoryEntry("LDAP://OU=Departments,DC=domaname, DC=com", "usrname", "password")
'Authenticacion type Secure
deSystem.AuthenticationType = AuthenticationTypes.Secure
'Creates a Directory Searcher Instance
Dim dsSystem As New DirectorySearcher(deSystem)
'sAMAccountName is equal to our username passed in.
dsSystem.Filter = "sAMAccountName=" & textbox1.Text
'Properties that the Procedures will load from Active Directory
dsSystem.PropertiesToLoad.Add("mail") 'email address
dsSystem.PropertiesToLoad.Add("department") 'dept
dsSystem.PropertiesToLoad.Add("physicalDeliveryOfficeName") 'office
dsSystem.PropertiesToLoad.Add("title") 'title, eg programmer1
dsSystem.PropertiesToLoad.Add("telephoneNumber") 'phone
dsSystem.PropertiesToLoad.Add("streetAddress") 'street address
dsSystem.PropertiesToLoad.Add("l") 'city
dsSystem.PropertiesToLoad.Add("st") 'state
dsSystem.PropertiesToLoad.Add("postalCode") 'zip code
dsSystem.PropertiesToLoad.Add("EmployeeId") 'empid
dsSystem.PropertiesToLoad.Add("givenName") '//first name from active directory
dsSystem.PropertiesToLoad.Add("sn") '//lastname from active directory
'Find the user data
Dim srSystem As SearchResult = dsSystem.FindOne()
'Obtains the properties recently loaded
txtemail.Text = srSystem.Properties("mail").Item(0).ToString
dept.Text = srSystem.Properties("department").Item(0).ToString
office.Text = srSystem.Properties("physicalDeliveryOfficeName").Item(0).ToString
txttitle.Text = srSystem.Properties("title").Item(0).ToString
phone.Text = srSystem.Properties("telephoneNumber").Item(0).ToString
workaddress.Text = srSystem.Properties("streetAddress").Item(0).ToString
city.Text = srSystem.Properties("l").Item(0).ToString
state.Text = srSystem.Properties("st").Item(0).ToString
zipcode.Text = srSystem.Properties("postalCode").Item(0).ToString
hiddenempId.Value = srSystem.Properties("EmployeeId").Item(0).ToString
HiddenFName.Value = srSystem.Properties("givenName").Item(0).ToString
HiddenLName.Value = srSystem.Properties("sn").Item(0).ToString
This works fine as well.
Here is where my problem lies.
Initially, when the user logs in, based on logged user name from Active Directory, the rest of the textboxes get populated with the user's info.Sorry for repeating myself here.
However, sometimes, the user logged in is not necessarily the user needing reguest.
In other words, I can log in to fill a request for another employee.
In this case, I am required to select the name of the user I am completing the request for from the dropdownlist that is populated from Active Directory.
When I select this name from dropdownlist, it replaces my own name on textbox1.Text.
This works fine but the rest of the textboxes retain my own information.
What do I need to do to ensure that the name that replaces my original name on textbox1.Text also replaces the information on the rest of the textboxes?
I will post additional information as requested.
Many thanks in advance
Instead of loading all the text boxes when the form loads, load them from the TextChanged event of the user name text box. That way, any time the user name text box changes, all the other text boxes will automatically be re-loaded to reflect the change.

How to loop through rows in a Datatable?

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.

FormsAuthentication Rememberme

I am using forms authentication and the I wanted the remember me functionality.
How can I just retain the username alone.
I wanted the username to be stored on cookies and when the user is logged out. I want to user name to be displayed on the username text box.
Is there an example that can be provided?
In the login method (Probably your "Login" button click):
Response.Cookies["userName"].Value = txtUserName.Text;
Then on the Page_Load check for that cookie and assign the textbox a value.
if (!String.IsNullOrEmpty(Request.Cookies["userName"])) {
txtUserName.Text = Request.Cookies["userName"];
}

Getting Text property in codebehind from ASP.NET TextBox with TextMode = Password

I have a <asp:TextBox with TextMode="Password". How can I read the value that the user entered, using the codebehind?
I want to create a new user with code like this, but PasswordTextBox.Text is always an empty string.
Membership.CreateUser(Username, PasswordTextBox.Text)
That's correct. You're probably setting PasswordTextBox.Text = '' in the Page_Load(). Don't do that if IsPostback() is true:
if not IsPostback() then
PasswordTextBox.Text = ''
end if
there has to be something else going on. I have no problems getting the value in TextBox.Text.
There's nothing special about reading a password text box. I'm guessing the problem is somewhere else in your code. Do you happen to overwrite the values in the Page_Load()?

Resources