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.
Related
I am doing a project. This project involves a database with a table called 'Customers'. In the same project, I have a form called 'frmAddNewCustomer'. This form takes in 9 attributes relating to the customer. There is a button that when clicked has code that allows these attributes to be entered into the database respectively. I also have a class called 'CustomerDAL' that allows me to performs tasks on the database table (Insert, Update, Delete etc.) and class holds the method that I used to enter data into the database from the 'frmAddNewCustomer' form. Finally, I have a Class called 'CustomerModel' which represents a record in the database. In the CustomerDAL class, the parameters for the method mentioned earlier (the one that allows me to enter data to the database through the UI form) are an object created from the CustomerModel class. my problem is that in the UI form it says that the method has no overload for 9 arguements.
this is the customer model class:
public int CustomerID { get; set; }
public string Title { get; set; }
public string Forename { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
public string Streetname { get; set; }
public string Town { get; set; }
public string County { get; set; }
public string Postcode { get; set; }
public string WeddingGiftList { get; set; }
public CustomerModel( string title, string forename, string surname, string email, string streetname,string town, string county, string postcode, string weddingGiftlist)
{
Title = title;
Forename = forename;
Surname = surname;
Email = email;
Streetname = streetname;
Town = town;
County = county;
Postcode = postcode;
WeddingGiftList = weddingGiftlist;
}
public CustomerModel()
{
}
this is the CustomerDAL class:
private static string _connectionString = ConfigurationManager.ConnectionStrings["SimpsonsConnection"].ConnectionString;
public static int AddNewCustomer(CustomerModel newCustomer)
{
using (SqlConnection connection = new SqlConnection(_connectionString))
{
connection.Open();
string sqlQuery = string.Format("INSERT INTO [Customer] VALUES('{0}', '{1}', '{2}', '{3}', '{4}', '{5}','{6}','{7}','{8}')", newCustomer.Title, newCustomer.Forename, newCustomer.Surname, newCustomer.Email, newCustomer.Streetname, newCustomer.Town, newCustomer.County, newCustomer.Postcode, newCustomer.WeddingGiftList);
SqlCommand insertCommand = new SqlCommand(sqlQuery, connection);
int rowsAffected = insertCommand.ExecuteNonQuery();
connection.Close();
return rowsAffected;
}
}
//this is the UI forms click event on the button:
//this is to add the customer details to the database when the 'Create button is clicked'
if ( cmbxTitle.Text != "" || txtForename.Text != "" || txtSurname.Text != "" || txtEmail.Text != "" || txtStreetName.Text != "" || txtTown.Text != "" || txtCounty.Text != "" || txtPostCode.Text != "" || cmbxWeddingGiftList.Text != "")
{
int rowsAffected = CustomerDAL.AddNewCustomer(cmbxTitle.Text, txtForename.Text, txtSurname.Text, txtEmail.Text, txtStreetName.Text, txtTown.Text, txtCounty.Text, txtPostCode.Text, cmbxWeddingGiftList.Text);
if(rowsAffected == 1)
{
MessageBox.Show("Customer has been added successfully");
Form myNextScreen = new frmMenu();
myNextScreen.Show();
}
else
{
MessageBox.Show("Customer was not able to be registered. Please re-enter details carefully");
}
}
else
{
lblInfo.Visible = true;
MessageBox.Show("Please enter all details");
}
In the UI form my error is when I reference the 'AddNewCustomer' method from the CustomerDAL class.error Image
I'm just not sure how to fix this error as I think I have 9 arguments?
It would mean a lot if you could help me with this as I'm relatively new to databases in c#
In my opinion, your problem can be in not defining the object
int rowsAffected = CustomerDAL.AddNewCustomer(new CustomerModel{....});
instead of this
int rowsAffected = CustomerDAL.AddNewCustomer(cmbxTitle.Text, txtForename.Text, txtSurname.Text, txtEmail.Text, txtStreetName.Text, txtTown.Text, txtCounty.Text, txtPostCode.Text, cmbxWeddingGiftList.Text);
have this
var newCustomer = new Customer
{
Title = cmbxTitle.Text,
//rest of customer properties
};
int rowsAffected = CustomerDAL.AddNewCustomer(newCustomer)
Noob question! Need some help!
So I'm using GoogleSheets API to store user credentials.
I created a custom list with all the data of every user in the GoogleSheet, I need to verify if the data inserted by user matches something within the list.
I managed to check if the username matches, but how to check if the password matches that username?
##The class
public class ListadeJogadoresRegistados
{
public int id { get; set; }
public string nome { get; set; }
public string pwd { get; set; }
public int hiscore { get; set; }
}
##Building the list
private static List<ListadeJogadoresRegistados> GetListaJogadores()
{
var request = service.Spreadsheets.Values.Get(SpreadsheetID, range);
var response = request.Execute();
var values = response.Values;
var jogador = new List<ListadeJogadoresRegistados>();
foreach (var row in values)
{
jogador.Add(new ListadeJogadoresRegistados
{
id = Int32.Parse((string)row[0]),
nome = (string)row[1],
pwd = (string)row[2],
hiscore = Int32.Parse((string)row[3])
});
}
return jogador;
}
##Data validation
public static bool ValidarLogin(string username, string pwd)
{
var jogadores = GetListaJogadores();
ListadeJogadoresRegistados item = jogadores.Find(item => item.nome == username && item.pwd == pwd);
if (item != null) // check item isn't null
{
// it is logged in
}
return true;
I am trying to get all data from DB and display it in a table using ajax and stored procedure.
public List<string> ShowDetailsFromDB()
{
using (adoHelper = new AdoHelper(connectionString))
{
List<string> users = new List<string>();
string procedureName = "GetDetails";
SqlDataReader dataReader = adoHelper.ExecuteDataReaderByProcedure(procedureName);
while (dataReader.Read())
{
User user = new User();
user.userId = dataReader[1] as string;
user.password = dataReader[2] as string;
user.userName = dataReader[3] as string;
user.address = dataReader[4] as string;
user.email = dataReader[5] as string;
user.phone = dataReader[6] as string;
//here I want to assign each object property as list element
}
return users;
}
}
Below are two ways to generate a list of strings from the properties of a User instance.
internal class User
{
public string userId { get; set; }
public string password { get; set; }
public string userName { get; set; }
public string address { get; set; }
public string email { get; set; }
public string phone { get; set; }
public string[] GetProperties()
{
return new string[]
{
userId,
password,
userName,
address,
email,
phone
};
}
static PropertyInfo[] properties = typeof(User).GetProperties();
public string[] GetPropertiesAuto()
{
return properties.Select((prop) => prop.GetValue(this) as string).ToArray();
}
}
The above can be used in your code quite simply, although you have to return a list of string array to get all the properties for all the users.
static public List<string[]> ShowDetailsFromDB()
{
using (var adoHelper = new AdoHelper(connectionString))
{
List<string[]> users = new List<string[]>();
string procedureName = "GetDetails";
SqlDataReader dataReader = adoHelper.ExecuteDataReaderByProcedure(procedureName);
while (dataReader.Read())
{
var user = new User
{
userId = dataReader[1] as string,
password = dataReader[2] as string,
userName = dataReader[3] as string,
address = dataReader[4] as string,
email = dataReader[5] as string,
phone = dataReader[6] as string
};
//here I want to assign each object property as list element
users.Add(user.GetPropertiesAuto());
}
return users;
}
}
You can do it easy using a List of Users.
public class User
{
public string userId { get; set; }
}
public List<User> ShowDetailsFromDB()
{
using (adoHelper = new AdoHelper(connectionString))
{
List<User> users = new List<User>();
string procedureName = "GetDetails";
SqlDataReader dataReader = adoHelper.ExecuteDataReaderByProcedure(procedureName);
while (dataReader.Read())
{
User user = new User
{
userId = dataReader[1] as string
};
users.Add(user);
//here I want to assign each object property as list element
}
return users;
}
}
Please tell me if it works
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
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.