I have two pages. The first page is a registration page where the user creates a user name and password. The second page is a log in page, where the user enters their user name and password. I want to validate that the two match, on the front-end. I stored the user name and password in a session and am not using a database. This isn't working and I'm unsure why:
protected void Button1_Click(object sender, EventArgs e)
{
List<Information> downloadList = (List<Information>)Session["DownloadList"];
foreach (Information obj1 in downloadList)
{
newName = String.Format("{0}", obj1.name);
newPassword = String.Format("{0}", obj1.email);
}
if(newName != TextBoxUserNameMatch.Text)
{
LabelLoginError.Text = "You Must Enter the Correct User Name";
}
else if(newPassword != TextBoxPasswordMatch.Text)
{
LabelLoginError.Text = "You Must Enter the Correct Password";
}
else
{
Response.Redirect("DownloadPage.aspx");
}
}
Can anyone tell me where I'm going wrong here? Here is the class information:
public class Information
{
public String name { get; set; }
public String email { get; set; }
public String phone { get; set; }
public String zip { get; set; }
public String state { get; set; }
public String login { get; set; }
public String password { get; set; }
public String reenter { get; set; }
public Information(String name, String email, String phone, String zip, String state, String login, String password, String reenter)
{
this.name = name;
this.email = email;
this.phone = phone;
this.zip = zip;
this.state = state;
this.login = login;
this.password = password;
this.reenter = reenter;
}
}
Here is the code behind my Registration page:
public partial class Registration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!this.IsPostBack)
{
Information download1 = new Information("", "", "", "", "", "", "", "");
Session["Info1"] = download1;
DropDownListState.Items.Add(download1.name);
}
}
protected void ButtonRegister_Click(object sender, EventArgs e)
{
String name = TextBoxName.Text;
String email = TextBoxEmail.Text;
String phone = TextBoxPhone.Text;
String zip = TextBoxZip.Text;
String state = DropDownListState.SelectedItem.Text;
String login = TextBoxLogIn.Text;
String password = TextBoxPassword.Text;
String reenter = TextBoxReenter.Text;
if(Session["DownloadList"] == null)
{
List<Information> downloadList = new List<Information>();
Session["DownloadList"] = downloadList;
}
Information obj1 = new Information(name, email, phone, zip, state, login, password, reenter);
List<Information> downloadList2 = (List<Information>)Session["DownloadList"];
downloadList2.Add(obj1);
Session["DownloadList"] = downloadList2;
Response.Redirect("Confirmation.aspx");
I believe these parts are working correctly because on my final page I have it printing out the user's name and email and that is working correctly.
Related
Some problems with the SetRawJsonValueAsync. When I use the code from documentation:
public class User
{
public string username;
public string email;
public User()
{
}
public User(string username, string email)
{
this.username = username;
this.email = email;
}
}
private void writeNewUser(string userId, string name, string email)
{
User user = new User(name, email);
string json = JsonUtility.ToJson(user);
mDatabaseRef.Child("users").Child(userId).SetRawJsonValueAsync(json);
}
Then firebase automatically converts it to the tree of values. Ok. But when i'm trying to get them back:
public void get_data()
{
mDatabaseRef.Child("users").Child(userId).GetValueAsync().ContinueWithOnMainThread(task => {
if (task.IsCompleted)
{
Debug.Log("completed");
string json = task.Result.Value;
User user = JsonUtility.FromJson<User>(json);
Debug.Log(user.username);
}
});
}
it stops and doesn't print username. Why? Or how i need to get json raws?
The issue here is task.Result.Value is a C# interpretation of the value in the database. I believe it should be a IDictionary<string, object> given the code that you posted.
What you want is task.Result.GetRawJsonValue():
public void get_data()
{
mDatabaseRef.Child("users").Child(userId).GetValueAsync().ContinueWithOnMainThread(task => {
if (task.IsCompleted)
{
Debug.Log("completed");
string json = task.Result.GetRawJsonValue();
User user = JsonUtility.FromJson<User>(json);
Debug.Log(user.username);
}
});
}
New to coding!
How can I get my register form to add the user's details instead of rewriting them everytime? And how can I get my log in form to loop through the XML file to find a matching username and password?
The code that I have does 2 things:
It rewrites the XML file instead of updating it.
It duplicates data.
Here is my User class:
public class User
{
public string fname;
public string lname;
public string username;
public string password;
public string Fname
{
get { return fname; }
set { fname = value; }
}
public string Lname
{
get { return lname; }
set {lname = value; }
}
public string Username
{
get { return username; }
set { username = value; }
}
public string Password
{
get { return password; }
set { password = value; }
}
public User() { }
public User (string fname, string lname, string username, string password)
{
this.fname = fname;
this.lname = lname;
this.username = username;
this.password = password;
}
}
Here is the sign up form code:
public partial class sign_up_form : Form
{
public sign_up_form()
{
InitializeComponent();
}
private void btn_create_Click(object sender, EventArgs e)
{
User users = new User();
users.fname = txt_fname.Text;
users.lname = txt_lname.Text;
users.username = txt_username.Text;
users.password = txt_password.Text;
XmlSerializer xs = new XmlSerializer(typeof(User));
using(FileStream fs = new FileStream("Data.xml", FileMode.Create))
{
xs.Serialize(fs, users);
}
}
}
This is the XML file:
<?xml version="1.0"?>
-<User xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<fname>asdf</fname>
<lname>asdf</lname>
<username>asdf</username>
<password>asdf</password>
<Fname>asdf</Fname>
<Lname>asdf</Lname>
<Username>asdf</Username>
<Password>asdf</Password>
</User>
I do not have any code for the log in form but it only has 2 text boxes (user and pass) and a log in button.
Any advice is appreciated.
I have a DataGridView which I want to fill from my database. I got an empty DataGridView. Here's my script and what I tried :
private void listUser_Load(object sender, EventArgs e)
{
List<User> lesUsers = Passerelle.getUsers();
dgvUser.DataSource = lesUsers;
}
My class :
class User
{
private int id { get; set; }
private int level { get; set; }
private string name { get; set; }
private string password { get; set; }
private string email { get; set; }
public User(int idP, int levelP, string nameP, string passwordP, string emailP)
{
id = idP;
level = levelP;
name = nameP;
password = passwordP;
email = emailP;
}
}
And the way I got my data :
public static List<User> getUsers()
{
MySqlDataReader result = executerSelect("SELECT id, level, name, email, password FROM users");
List<User> users = new List<User>();
if(result != null)
{
while(result.Read())
{
int id = int.Parse(result[0].ToString());
int level = int.Parse(result[1].ToString());
string name = result[2].ToString();
string email = result[3].ToString();
string password = result[4].ToString();
users.Add(new User(id, level, name, password, email));
}
}
return (users.ToList());
}
I already tried with a binding source but I'm not able to link with my datagridview
Thanks for help
You need to assign lesUsers , instead of getUsers which is a method
List<User> lesUsers = Passerelle.getUsers();
dgvUser.DataSource = lesUsers ;
EDIT
check if you have public properties which would be used to display the contents of the Class as columns in the DataGridView
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
protected void Button3_Click(object sender, EventArgs e)
{
UserStore<IdentityUser> userStore = new UserStore<IdentityUser>();
userStore.Context.Database.Connection.ConnectionString =
System.Configuration.ConfigurationManager.ConnectionStrings
["db1ConnectionString"].ConnectionString;
UserManager<IdentityUser> manager = new UserManager<IdentityUser>
(userStore);
//create new user and try to store in db
IdentityUser user = new IdentityUser();
user.UserName = txtUserName.Text;
user.Email = txtEmail.Text;
user.PhoneNumber = txtPhNo.Text;
if (txtPassword.Text == txtConfirmPassword.Text)
{
try
{
//create user object.
//DB will be created /expanded automatically.
IdentityResult result = manager.Create(user, txtPassword.Text);
if (result.Succeeded)
{
**UserInformation1 info = new UserInformation1
{
Address = txtAddress.Text,
FirstName = txtFirstName.Text,
LastName = txtLastName.Text,
PostalCode = Convert.ToInt32(txtPostalCode.Text),
PhoneNo = Convert.ToInt32(txtPhNo.Text),
Email = user.Email,
GUID = user.Id
};
UserInfoModel model = new UserInfoModel();
model.InsertUserInformation(info);**
//store user in db
var authenticationManager =
HttpContext.Current.GetOwinContext().Authentication;
//set to log in new user by cookie
var userIdentity = manager.CreateIdentity(user,
DefaultAuthenticationTypes.ApplicationCookie);
//log in the new user and redirect to homepage
authenticationManager.SignIn(new
Microsoft.Owin.Security.AuthenticationProperties(), userIdentity);
Response.Redirect("~/Pages/greetings_home.aspx");
}
else
{
litStatus.Text = result.Errors.FirstOrDefault();
}
}
catch (Exception ex)
{
litStatus.Text = ex.ToString();
}
}
else
{
litStatus.Text = "Password must match";
}
}
error:
System.OverflowException: Value was either too large or too small for an Int32. at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Convert.ToInt32(String value) at Pages_register.Button3_Click(Object sender, EventArgs e) in c:\Users\shreya\Documents\Visual Studio 2015\Project_Greetings\Pages\register.aspx.cs:line 38
My model class
public partial class UserInformation1
{
public int Id { get; set; }
public string GUID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public Int32 PostalCode { get; set; }
public Int32 PhoneNo { get; set; }
public string Email { get; set; }
}
Any Solution for this error
Use string type to store the phone numbers and postal codes
https://stackoverflow.com/a/23637154
But to avoid this exception you can use int.TryParse():
int result;
if(!int.TryParse(txtPostalCode.Text, out result))
{
// process wrong input
}
I have these classes, which i want to use it to login, to check if the email and password is the same, then it will redirect to the respective page.
public class Account
{
public Account(){}
public int accID { get; set; }
public string emailAddress { get; set; }
public string password { get; set; }
public string name { get; set; }
public string company { get; set; }
public string position { get; set; }
public string department { get; set; }
public string mobileNo { get; set; }
public string officeNo { get; set; }
}
public static SADataReader DoSelectQuery(String sql)
{
SAConnection myConnection = new SAConnection(DB_STR);
//open the connection
myConnection.Open();
//Create a command object.
SACommand myCommand = myConnection.CreateCommand();
//Specify a query.
myCommand.CommandText = sql;
//Create a DataReader for the command
SADataReader reader = myCommand.ExecuteReader();
return reader;
}
public static List<Account> getAllAccountFromReader(SADataReader reader){
List<Account> results = new List<Account>();
while (reader.Read())
{
int accID = reader.GetInt32(0);
string emailAddress = reader.GetString(1);
string password = reader.GetString(2);
string name = reader.GetString(3);
string company = reader.GetString(4);
string position = reader.GetString(5);
string department = reader.GetString(6);
string mobileNo = reader.GetString(7);
string officeNo = reader.GetString(8);
Account Accounts = new Account();
Accounts.accID = accID;
Accounts.emailAddress = emailAddress;
Accounts.password = password;
Accounts.name = name;
Accounts.company = company;
Accounts.position = position;
Accounts.department = department;
Accounts.mobileNo = mobileNo;
Accounts.officeNo = officeNo;
results.Add(Accounts);
}
return results;
}
public static List<Account> getAllAccounts()
{
//Specify a query.
string sql = "SELECT accountID,emailAddress,password,name,company,position,department,mobileNo,officeNo FROM account";
SADataReader reader = DoSelectQuery(sql);
List<Account> results = getAllAccountFromReader(reader);
return results;
}
.CS file to check for fields
protected void btnSubmit_Click(object sender, EventArgs e)
{
string email = tbEmail.Text;
string password = tbPW.Text;
List<Account> getAccounts = MinuteDB.getAllAccounts();
// Session["getAllAccount"] = getAccounts;
if(email ==?? && password == ??)
{
//Session["name"] = name.ToString();
//Session["ID"] = Convert.ToInt32(accID.ToString());
Response.Redirect("HomePage.aspx");
}
else if (email == "" && password == "")
{
ScriptManager.RegisterStartupScript(this, GetType(), "error", "alert('Please enter Login and Password!');", true);
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "error", "alert('Wrong Login Or Password!');", true);
}
}
How do i retrieve the email and password from the List getAccounts so that i can check for if (email == email from the list account && password == password from list account) ??
Try LINQ/extension methods.
var account = MinuteDB.getAllAccounts()
.Where(p=> p.emailAddress==email && p.password==password)
.FirstOrDefault();
if(account!=null)
{
Session["id"]=account.accID;
Session["name"]=account.name;
Response.Redirect("~/other_page.aspx");
}
Write following code in other_page.aspx to read session key-value.
int id=0;
string name="";
if(Session["id"]!=null)
id=int.Parse(Session["id"].ToString());
if(Session["name"]!=null)
name=Session["name"];
PS: Do not store password in the List<T>. You may assign Account object reference to the Session.
e.g
if(account!=null)
{
Session["account"]=account;
Response.Redirect("~/other_page.aspx");
}
and to retrieve the account value from session:
Account account=Session["account"] as Account;
if(account!=null)
{
//read the property value of Account
}
Are you wanting to find the email in the list of accounts and check the password entered matches? If so, superficially you just loop through each along the lines of:
private bool isPasswordValid(string email, string password)
{
foreach (Account account in Accounts)
{
if (account.emailAddress != email)
continue;
return (account.password == password);
}
return false;
}
You could alternatively return a Dictionary<string, Account> to simplify and speed up the search.
Update
So instead of the following line:
if(email ==?? && password == ??)
Insert
if (isPasswordValid(email, password))
// it is valid
else
// it is not valid, redirect
This assumes the getAccounts variable is accessible to isPasswordValid. In your current code it would not be visible, so you might want to pass it in as a parameter.