I'm getting incorrect 'MembershipCreateStatus' data [closed] - asp.net

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have the following code which creates a memebrship user, then calls other methods to insert the users other info into my SQL DB. The user is getting created. The info is getting into my database. Everything is working like it should, but for some reason, Rather then sending a success message to my Literal0.text, it always says "There is already a user with this email address.", even after the user is successfully created.I even added a check for Session("Created") to keep the code from running twice, still no luck. It works fine, just gives the wrong message at the end.
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If Not Session("Created") = "True" Then
Literal0.Text = ""
Dim FName As String = FNameBox.Text.Replace("'", "*1*").Replace("""", "*2*").Replace(" ", "")
Dim LName As String = LNameBox.Text.Replace("'", "*1*").Replace("""", "*2*").Replace(" ", "")
Username = FName + "." + LName
Dim SecretQ As String = "Please use the Contact Us page to request a reset password"
Dim SecretA As String = "ergwergkqejfqeoufwqeofiheowfqpkoadmvnwo"
Dim psw As Int32 = (TimeOfDay.Hour * TimeOfDay.Minute) * 863490
Dim firstsix As String = psw.ToString().Substring(0, 6)
password = FNameBox.Text.Replace("'", "*1*").Replace("""", "*2*").Replace(" ", "") + firstsix + "!"
Dim createStatus As MembershipCreateStatus
Dim newUser As MembershipUser = _
Membership.CreateUser(Username, password, _
Email.Text, SecretQ, _
SecretA, True, _
createStatus)
Select Case createStatus
Case MembershipCreateStatus.Success
Session("Created") = "True"
If Not String.IsNullOrEmpty(BlogSettings.Instance.SelfRegistrationInitialRole) Then
Dim role As String = Roles.GetAllRoles().FirstOrDefault(Function(r) r.Equals(BlogSettings.Instance.SelfRegistrationInitialRole, StringComparison.OrdinalIgnoreCase))
If Not String.IsNullOrEmpty(role) Then
Roles.AddUsersToRoles(New String() {Username}, New String() {role})
End If
End If
Dim pf = AuthorProfile.GetProfile(Username)
pf = New AuthorProfile(Username)
pf.DisplayName = Username
pf.EmailAddress = Email.Text
pf.FirstName = FNameBox.Text.Replace("'", "*1*").Replace("""", "*2*").Replace(" ", "")
pf.LastName = LNameBox.Text.Replace("'", "*1*").Replace("""", "*2*").Replace(" ", "")
pf.[Private] = True
pf.Save()
Literal0.Text = ""
AddUser()
Exit Select
Case MembershipCreateStatus.DuplicateUserName
Literal0.Text = "There is already a user with this username."
Exit Select
Case MembershipCreateStatus.DuplicateEmail
Literal0.Text = "There is already a user with this email address."
Exit Select
Case MembershipCreateStatus.InvalidEmail
Literal0.Text = "There email address you provided in invalid."
Exit Select
Case MembershipCreateStatus.InvalidAnswer
Literal0.Text = "There security answer was invalid."
Exit Select
Case MembershipCreateStatus.InvalidPassword
Literal0.Text = "The password you provided is invalid. It must be seven characters long and have at least one non-alphanumeric character."
Exit Select
Case Else
Literal0.Text = "There was an unknown error; the user account was NOT created."
Exit Select
End Select
End If
End Sub

I would suggest to check the code from the parts below:
please make some break points to the application, we should check if every time the debug point will go to the case below:
Case MembershipCreateStatus.DuplicateEmail
Literal0.Text = "There is already a user with this email address."
Exit Select
and please make sure the email do not exist in the DataTable.
For more information about the MembershipCreateStatus, please refer to the link below:
http://msdn.microsoft.com/en-us/library/system.web.security.membershipcreatestatus.aspx
Hope it's useful for you.

Related

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.

Automatically Logging In User After Custom Membership Creation (not using Wizard)

I'm using the following code to create a user account on my vb.net website. The code is in a button click. It works fine as far creating the membership but when the user is redirected to the next page they are not logged in. Apparently "newUser.IsApproved = True" is not working. Any thoughts on what I'm doing wrong. I want the user to be automatically logged in after the membership is created.
Dim createStatus As MembershipCreateStatus
Try
Dim newUser As System.Web.Security.MembershipUser = Membership.CreateUser(txtinput_Email.Value, txtinput_Password.Value, txtinput_Email.Value)
newUser.IsApproved = True
Catch ex As Exception
LabelCreateAccountResults.Text = ex.Message
' MessageBox.Show("There's an error: " & vbCrLf & ex.ToString)
Response.Write("<script language='javascript'>alert('" & ex.Message & "')</script>")
Exit Sub
End Try
Select Case createStatus
Case MembershipCreateStatus.Success
LabelCreateAccountResults.Text = "The user account was successfully created!"
Response.Redirect("yo-delivery.aspx")
Case MembershipCreateStatus.DuplicateUserName
LabelCreateAccountResults.Text = "That username already exists."
Case MembershipCreateStatus.DuplicateEmail
LabelCreateAccountResults.Text = "A user with that Email address already exists."
Case MembershipCreateStatus.InvalidEmail
LabelCreateAccountResults.Text = "PLease enter a VALID email address."
Case MembershipCreateStatus.InvalidPassword
LabelCreateAccountResults.Text = "The password entered is invalid. Please enter a passoword with at least 4 characters."
Case Else
LabelCreateAccountResults.Text = "Unknown Error: Account NOT created."
End Select
OK perhaps look into something along these lines
Dim username__1 As String = Username.Text
Dim password__2 As String = Password.Text
If Membership.ValidateUser(username__1, password__2) Then
Dim ticket As New FormsAuthenticationTicket(1, username__1, DateTime.Now, DateTime.Now.AddMinutes(20), False, String.Empty, _
FormsAuthentication.FormsCookiePath)
Response.Cookies.Add(New HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket)) With { _
Key .Expires = ticket.Expiration, _
Key .Path = FormsAuthentication.FormsCookiePath _
})
If Not String.IsNullOrEmpty(Request.QueryString("returnurl")) Then
Response.Redirect(Request.QueryString("returnurl"))
End If
Response.Redirect("~/Home")
End If

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.

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.

Compare values from data source to string

I'm just stumped on what to do with this code, I'm just trying to implement a 'no duplicates' catch on my insert customer form, but it just slips through my if statement to the else everytime. This is the source. Also I tried a .Equals with the same results :(
Protected Sub srcAllClients_Inserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceCommandEventArgs) Handles srcAllClients.Inserting
'Establish Variables
Dim emailAddress As String
Dim srcUsers As SqlDataSource = New SqlDataSource()
srcUsers.ConnectionString = ConfigurationManager.ConnectionStrings("ISSD21ConnectionString").ConnectionString
Dim view As DataView
view = DirectCast(srcUsers.Select(DataSourceSelectArguments.Empty), DataView)
srcUsers.SelectCommand = "SELECT EmailAddress FROM ISSDClients"
srcUsers.DataSourceMode = SqlDataSourceMode.DataReader
Dim reader As IDataReader
reader = DirectCast(srcUsers.Select(DataSourceSelectArguments.Empty), IDataReader)
emailAddress = FormView1.FindControl("txtEmail").ToString
While reader.Read()
If reader("EmailAddress") = (emailAddress) Then
lblError.Text = "Your Email is NOT Unique!"
'this is where we cancel the update and return an error
Else
lblError.Text = "Your Email is Unique!"
'nothing needs to happen, maybe just tell them that it went through
End If
End While
reader.Close()
End Sub
emailAddress = FormView1.FindControl("txtEmail").ToString
is just going to return the string "System.Web.UI.WebControls.TextBox". You're not accessing the actual property of the control that would hold the text value, you're just calling ToString() on the control itself.
Try this:
Dim emailBox As TextBox = CType(FormView1.FindControl("txtEmail"), TextBox);
emailAddress = emailBox.Text
In addition to Womp's answer...
In the while loop that is running through the email records, you need to break out of the loop once you find a matching email and alert the user.
if reader("EmailAddress") = (emailAddress) then
'1. Break from the Loop
End if
I would recommend that you pass the emailAddress to the SQL Server as a parameter.
Select Count(EmailAddress) From ISSDClients
Where EmailAddress = #EmailAddress
Execute this statement using ExecuteScalar and cast the result as an integer. If the result is zero then you are ok, otherwise display an error.
Doing it this way avoids using the while loop and should be much quicker if your table has lots of rows.
You also need to get the Text property from the Email Text box.
emailAddress = FormView1.FindControl("txtEmail").Text.ToString
You may want to take a look at the String.Compare method, which will make it easier to compare without respect to things like case sensitivity and culture. It does consider whitespace to be part of your string, so you may wish to trim the string prior to calling it, to help normalize.
For example, the following strings would be considered equal:
var firstString = "some StrinG to Compare ";
var secondString = " somE string to COMPARE";
var equal = (String.Compare(firstString.Trim(), secondString.Trim(), StringComparison.InvariantCultureIgnoreCase) == 0);

Resources