I looked around here on stackoverflow, as well Google, but was not able to find an answer that pertained to my problem, so i'm posting it here.
I have a login page where the user is directed to input their username and password, which are both stored in a MySQL database. The username is stored as plain text and the password is hashed (using the CrackStation - https://crackstation.net/hashing-security.htm#aspsourcecode) and the hash is stored in the database. I am able to successfully have the user login one time using the username and password, but I would like to use SESSION so that the user can navigate around the website and not have to login each time they go to a different page. I was easily able to use SESSION in my test environment because the password was stored as plain text, but now with the password being hashed i'm not able to get the Session to work in my code. So I wanted to know what can I do to get the password to validate in SESSION.
My code that I am using on my login page is the following:
protected void Page_Load(object sender, EventArgs e)
{
try
{
admin = Convert.ToInt16(Request.QueryString["Admin"]);
Instructor = Convert.ToInt16(Request.QueryString["Inst"]);
if (Session["username"] == null || (string)(Session["username"]) == "")
{
token = Request.QueryString["tokenNumber"];
lblUsername.Visible = true;
txtUsername.Visible = true;
lblPassword.Visible = true;
txtPassword.Visible = true;
btnlogin.Visible = true;
}
else if (Session["username"] != null || (string)(Session["username"]) != "")
{
username = (string)Session["username"];
userType = (string)Session["userType"];
pass = (string)Session["password"];
if (userType == "Participant")
{
Response.Redirect("/srls/StudentUser");
}
else if (userType == "Coordinator")
{
Response.Redirect("/srls/CoordinatorUser");
}
else if (userType == "Instructor")
{
Response.Redirect("/srls/InstructorUser");
}
}
}
catch (Exception exc) //Module failed to load
{
Exceptions.ProcessModuleLoadException(this, exc);
}
}
protected void btnlogin_Click(object sender, System.EventArgs e)
{
char activation;
if (Request.QueryString["tokenNum"] != null)
{
using (OdbcConnection dbConnection = new OdbcConnection(srlsConnStr))
{
dbConnection.Open();
{
OdbcCommand dbCommand = new OdbcCommand();
dbCommand.Connection = dbConnection;
dbCommand.CommandText = #"SELECT tokenNum FROM srlslogin WHERE user_email_pk = ?";
dbCommand.Parameters.AddWithValue("#user_email_pk", txtUsername.Text);
dbCommand.ExecuteNonQuery();
OdbcDataReader dataReader = dbCommand.ExecuteReader();
while (dataReader.Read())
{
if (token == dataReader["tokenNum"].ToString())
{
updateActivationStatus(txtUsername.Text);
LoginWithPasswordHashFunction();
}
else
{
test.Text = "You are not authorized to login! Please activate your account following the activation link sent to your email " + txtUsername.Text + " !";
}
}
}
dbConnection.Close();
}
}
else if (Request.QueryString["tokenNum"] == null)
{
using (OdbcConnection dbConnection = new OdbcConnection(srlsConnStr))
{
dbConnection.Open();
{
OdbcCommand dbCommand1 = new OdbcCommand();
dbCommand1.Connection = dbConnection;
dbCommand1.CommandText = #"SELECT * FROM srlslogin WHERE user_email_pk = ?;";
dbCommand1.Parameters.AddWithValue("#user_email_pk", txtUsername.Text);
dbCommand1.ExecuteNonQuery();
OdbcDataReader dataReader1 = dbCommand1.ExecuteReader();
if (dataReader1.Read())
{
activation = Convert.ToChar(dataReader1["activation_status"]);
if (activation == 'Y')
{
activation status, activation == Y";
LoginWithPasswordHashFunction();
}
else
{
lblMessage.Text = "Please activate your account following the Activation link emailed to you at <i>" + txtUsername.Text + "</i> to Continue!";
}
}
else
{
lblMessage.Text = "Invalid Username or Password";
}
dataReader1.Close();
}
dbConnection.Close();
}
}
}
private void LoginWithPasswordHashFunction()
{
List<string> salthashList = null;
List<string> usernameList = null;
try
{
using (OdbcConnection dbConnection = new OdbcConnection(srlsConnStr))
{
dbConnection.Open();
{
OdbcCommand dbCommand = new OdbcCommand();
dbCommand.Connection = dbConnection;
dbCommand.CommandText = #"SELECT slowhashsalt, user_email_pk FROM srlslogin WHERE user_email_pk = ?;";
dbCommand.Parameters.AddWithValue(#"user_email_pk", txtUsername.Text);
OdbcDataReader dataReader = dbCommand.ExecuteReader();
while (dataReader.HasRows && dataReader.Read())
{
if (salthashList == null)
{
salthashList = new List<string>();
usernameList = new List<string>();
}
string saltHashes = dataReader.GetString(dataReader.GetOrdinal("slowhashsalt"));
salthashList.Add(saltHashes);
string userInfo = dataReader.GetString(dataReader.GetOrdinal("user_email_pk"));
usernameList.Add(userInfo);
}
dataReader.Close();
if (salthashList != null)
{
for (int i = 0; i < salthashList.Count; i++)
{
bool validUser = PasswordHash.ValidatePassword(txtPassword.Text, salthashList[i]);
if (validUser == true)
{
Session["user_email_pk"] = usernameList[i];
OdbcCommand dbCommand1 = new OdbcCommand();
dbCommand1.Connection = dbConnection;
dbCommand1.CommandText = #"SELECT user_status FROM srlslogin WHERE user_email_pk = ?;";
dbCommand1.Parameters.AddWithValue("#user_email_pk", txtUsername.Text);
dbCommand1.ExecuteNonQuery();
OdbcDataReader dataReader1 = dbCommand1.ExecuteReader();
while (dataReader1.Read())
{
user_status = dataReader1["user_status"].ToString();
Session["userType"] = user_status;
}
Response.BufferOutput = true;
if (user_status == "Participant")
{
Response.Redirect("/srls/StudentUser", false);
}
else if (user_status == "Coordinator")
{
Response.Redirect("/srls/CoordinatorUser", false);
}
else if (user_status == "Instructor")
{
Response.Redirect("/srls/InstructorUser", false);
}
dataReader1.Close();
Response.Redirect(/srls/StudentUser) - Goes to Login Page";
}
else
{
lblMessage.Text = "Invalid Username or Password! Please Try Again!";
}
}
}
}
dbConnection.Close();
}
}
catch (Exception ex)
{
}
You should not store the username and password in the session. You should store the 'fact' that the user has been successfully logged in. But actually you shouldn't even be doing that yourself. ASP.NET comes with various authentication methods. Please have a look at http://www.asp.net/identity to get started.
That is not so good solution. Don't store username's login, password, type, so on, in your sessions. Once user is logging in your system, just store his ID. I use next way: I have login page, and I have MasterPage and all my web-forms are inherited from MasterPage. And in the MasterPage on Page_Init I do something like:
string users_role = MyClass.GetUsersRoleById(Session["id"].ToString());
I have user's role in the database, so by ID I may exclude user's role. And, for example, you have by one folder for every role. You may do something like:
if (String.IsNullOrEmpty(users_role)) //if null it means that user have no any role or you didn't checked for authorization first
Response.Redirect(users_role); //redirect to role's page: e.g. Admin, User, Student, Teacher, so on.
Related
ONLY FOR LEARNING PURPOSE: Help me to correct the code, I'm trying to get error msg that also shows "Only the password is wrong." It always skips the bolded part of the code.
protected void btnLogin_Click(object sender, EventArgs e)
{
if (txtusername.Text != null && txtpassword.Text != string.Empty)
{
sql = string.Format(#" select * from idpass where username ='{0}' and password = '{1}'", txtusername.Text, txtpassword.Text);
DataTable dtForNameAndRole = LoadDataByQuery(sql);
try
{
if (dtForNameAndRole.Rows.Count > 0)
{
Session["username"] = dtForNameAndRole.Rows[0]["username"].ToString();
Session["password"] = dtForNameAndRole.Rows[0]["password"].ToString();
txtpassword.Text = string.Empty;
txtusername.Text = string.Empty;
Response.Redirect("Dashboard.aspx");
}
else if (dtForNameAndRole.Rows.Count > 0)
{
txtusername.Text = dtForNameAndRole.Rows[0]["username"].ToString();
lblMessage.Text = "Wrong Password!";
}
else
{
}
}
catch
{
}
}
else
{
msgtr.Visible = true;
lblMessage.Text = "Sorry! Invalid user name or password.";
lblMessage.ForeColor = Color.Red;
return;
}
}
AS #Zohar Peled Stated this aproach is against all security conventions, don't do it in production.
But if you want to do it, you must check first the user and then the password (that normally would be hashed so you'll need some additional work if thats the case.
ALSO you need to parametrice your query so the LoadDataByQuery function MUST be reworked
All this said let's do this completly UNSECURE login work as you want:
string sql = string.Format(#" select * from idpass where username = #userName");
SqlParameterCollection parameters = new SqlParameterCollection();
var parameter = new SqlParameter();
parameter.ParameterName = "userName";
parameter.Value = txtusername.Text;
parameters.Add(parameter);
DataTable dtForNameAndRole = LoadDataByQueryAndParameters(sql, parameters);
try
{
if (dtForNameAndRole.Rows.Count > 0)
{
if (dtForNameAndRole.Rows[0]["password"].ToString() == txtpassword.Text)
{
Session["username"] = dtForNameAndRole.Rows[0]["username"].ToString();
Session["password"] = dtForNameAndRole.Rows[0]["password"].ToString();
txtpassword.Text = string.Empty;
txtusername.Text = string.Empty;
Response.Redirect("Dashboard.aspx");
}
else
{
txtusername.Text = dtForNameAndRole.Rows[0]["username"].ToString();
lblMessage.Text = "Wrong Password!";
}
}
[continue your code after the ** // **]
So I have a Class called "User" in which I have the following method and code:
public void Login()
{
LoginWindow l = new LoginWindow();
if (l.tbxEmail.Text != "" && l.tbxPassword.Text != "")
{
string query = "SELECT * FROM UsersTBL";
l.con.Open();
l.com = l.con.CreateCommand();
l.com.CommandText = query;
SqlDataReader dr = l.com.ExecuteReader();
if (dr.Read())
{
if (dr["Email"].Equals(l.tbxEmail.Text.ToString()) && dr["UserPassword"].Equals(l.tbxPassword.Text.ToString()))
{
AppWindow a = new AppWindow();
a.Show();
}
else
l.lblMissingParameter.Content = "Incorrect Password or Email entered";
}
}
}
And in my LoginWindow I have:
public partial class LoginWindow:Window
{
User u = new User();
private void BtnSignup_Click(object sender, RoutedEventArgs e)
{
u.Login();
}
}
When I try to call my Login method via class instantiation nothing works, why is that? Am I calling it the wrong way?
This should work, although I left comments on things that should be addressed.
User class:
public bool Login(SqlConnection con, string email, string password)
{
const string query = "SELECT 1 FROM UsersTBL WHERE Email = #email AND UserPassword = #password";
if (!string.IsNullOrWhiteSpace(email) && !string.IsNullOrWhiteSpace(password))
{
try
{
con.Open();
var cmd = con.CreateCommand();
cmd.CommandText = query;
//Correct SqlDbTypes if necessary
cmd.Parameters.Add("#email", SqlDbType.VarChar);
cmd.Parameters["#email"].Value = email;
cmd.Parameters.Add("#password", SqlDbType.VarChar);
//Should NOT be storing passwords as plain text in the database
cmd.Parameters["#password"].Value = password;
if (cmd.ExecuteScalar() == 1)
return true;
}
catch (Exception e)
{
//log e somehow or eliminate this catch block
}
finally
{
//Close the connection if still open
if (con != null && con.State != ConnectionState.Closed)
con.Close();
}
}
return false;
}
LoginWindow class:
public partial class LoginWindow : Window
{
private void BtnSignup_Click(object sender, RoutedEventArgs e)
{
var u = new User();
if (u.Login(con, tbxEmail.Text, tbxPassword.Text))
{
AppWindow a = new AppWindow();
a.Show();
}
else
lblMissingParameter.Content = "Incorrect Password or Email entered";
}
}
To clarify, you had this problem because the tbxEmail and tbxPassword variables in your User class where not the same as the ones in your main class.
You should create both variable at class scope:
public class User {
TextBox tbxEmail; // could be strings
PasswordBox tbxPassword;
public User (TextBox tbxEmail, TextBox tbxPassword) {
this.tbxEmail = tbxEmail;
this.tbxPassword = tbxPassword;
}
}
And then:
User user = new User(tbxEmail,tbxPassword);
user.Login();
Or, create a static method (static method can't use global variables, so everything you need have to be passed as parameter of the method or created inside of it).:
public static void Login (string email, string password){
// code here
}
I wrote a rudimentary login page for one of my school projects similar to this:
private void signInButton_Click(object sender, EventArgs e)
{
DataProcedures data = new DataProcedures();
User userInfo = new User(usernameTextbox.Text, passwordTextbox.Text);
userInfo.userId = data.verifyUser(userInfo);
if (userInfo.userId != -1)
{
AppWindow a = new AppWindow();
a.Show();
}
else
{
errorLabel.Show();
}
}
public int verifyUser(User userInfo)
{
MySqlConnection conn = new MySqlConnection(connectionString);
int userId = -1;
string returnedUserName;
string returnedPassword;
try
{
conn.Open();
MySqlCommand checkUserNameCmd = conn.CreateCommand();
checkUserNameCmd.CommandText = "SELECT EXISTS(SELECT userName FROM user WHERE userName = #username)";
checkUserNameCmd.Parameters.AddWithValue("#username", userInfo.username);
returnedUserName = checkUserNameCmd.ExecuteScalar().ToString();
MySqlCommand checkPasswordCmd = conn.CreateCommand();
checkPasswordCmd.CommandText = "SELECT EXISTS(SELECT password FROM user WHERE BINARY password = #password AND userName = #username)";//"BINARY" is used for case sensitivity in SQL queries
checkPasswordCmd.Parameters.AddWithValue("#password", userInfo.password);
checkPasswordCmd.Parameters.AddWithValue("#username", userInfo.username);
returnedPassword = checkPasswordCmd.ExecuteScalar().ToString();
if (returnedUserName == "1" && returnedPassword == "1")
{
MySqlCommand returnUserIdCmd = conn.CreateCommand();
returnUserIdCmd.CommandText = "SELECT userId FROM user WHERE BINARY password = #password AND userName = #username";
returnUserIdCmd.Parameters.AddWithValue("#password", userInfo.password);
returnUserIdCmd.Parameters.AddWithValue("#username", userInfo.username);
userId = (int)returnUserIdCmd.ExecuteScalar();
}
}
catch (Exception ex)
{
Console.WriteLine("Exception thrown verifying user: " + ex);
}
finally
{
conn.Close();
}
return userId;
}
Hope this helps.
here is my login button click code. i have set the session["Username"] to the input of the customer in txtUser.text.
protected void btn_Login_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True");
conn.Open();
string checkuser = "select count(*) from UserData where Username = '" + txtUser.Text + "'";
SqlCommand scm = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(scm.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkPassword = "select Password from UserData where Username ='" + txtUser.Text + "'";
SqlCommand passCom = new SqlCommand(checkPassword, conn);
string password = passCom.ExecuteScalar().ToString().Replace(" ", "");
if (password == txtPassword.Text)
{
Session["Username"] = txtUser.Text;
Response.Write("<script>alert('Record saved successfully')</script>");
Response.Redirect("OrderNow.aspx");
}
else
{
lblcrederror.Text = ("Credentials dont match");
}
and here is where i call it. (ordernow.aspx) this is where the customer is redirected when he/she places and order. im planning to pass the values of the customer (email address username phone number) into the textboxes before submitting the order.
private void GetMyCart()
{
DataTable dtProducts; // declare data table = dtProducts.
if (Session["MyCart"] != null) // check whether session is null or not.
{
dtProducts = (DataTable)Session["MyCart"]; //if session is not null, assign all session to dtproducts.
}
else
{
dtProducts = new DataTable(); //if session is null, create new datatable (dtproducts).
}
if (dtProducts.Rows.Count > 0) // if rows.count is greater than 0, it means there is a value records from the session.
{
txtCustomerName.Text = Session["Username"].ToString();
//txtCustomerPhoneNo.Text = Session["Contact"].ToString();
//txtCustomerEmailID.Text = Session["Email"].ToString();
//txtCustomerAddress.Text = Session["DeliveryAddress"].ToString();
txtTotalProducts.Text = dtProducts.Rows.Count.ToString(); // this will display all of the chosen records
btnIslandGas.Text = dtProducts.Rows.Count.ToString();
dlCartProducts.DataSource = dtProducts;
dlCartProducts.DataBind();
UpdateTotalBill();
pnlMyCart.Visible = true;
pnlCheckOut.Visible = true;
pnlEmptyCart.Visible = false;
pnlCategories.Visible = false;
pnlProducts.Visible = false;
pnlOrderPlaceSuccessfully.Visible = false;
}
else // session is empty
{
pnlEmptyCart.Visible = true; // since session is empty and there is no value record, pull up the empty shopping cart page
pnlMyCart.Visible = false;
pnlCheckOut.Visible = false;
pnlCategories.Visible = false;
pnlProducts.Visible = false;
pnlOrderPlaceSuccessfully.Visible = false;
dlCartProducts.DataSource = null;
dlCartProducts.DataBind();
txtTotalProducts.Text = "0"; // total products, price and number logo is set to 0.
txtTotalPrice.Text = "0";
btnIslandGas.Text = "0";
}
the Session["Username"] is working. meaning it is binded with the txtCustomername.text. but the rest are not working (email,address,phone no.)
As I understand, what you are doing is that on your login page in case the user is authenticated i.e in your code when the passwords are successfully matched. The Session variables viz. Contact, Email, DeliveryAddress are not set at all. Only Name is set.
After this you make redirection to ordernow.aspx page. Hence you don't get them there. You only get one you set.
In register page you set the other Session variables but you have to understand that it's only after that they will be available in ordernow.aspx
So if you go from register to ordernow.aspx you will get the values but not when you go from login page to ordernow.aspx
You need to set the other Session variables as well in the Login page before making redirection to the ordernow page and accessing them there.
Update:
You are only getting password from the database on the basis of the username, but instead you need to get the whole user record with other details like email, contact , address as well. Then match the password, if it matches you have your user and all his other details with which you need to set Session variables.
Update Second:
if (temp == 1)
{
conn.Open();
string checkPassword = "select * from UserData where Username ='" + txtUser.Text + "'";
SqlCommand passCom = new SqlCommand(checkPassword, conn);
using (SqlDataReader oReader = passCom.ExecuteReader())
{
while (oReader.Read())
{
if(oReader["UserName"].ToString().Replace(" ", "") == txtPassword.Text.Trim())
{
Session["Username"] = oReader["FirstName"].ToString();
Session["Contact"] = oReader["Contact"].ToString();
Session["Email"] = oReader["Email"].ToString();
Session["DeliveryAddress"] = oReader["DeliveryAddress"].ToString();
Response.Redirect("OrderNow.aspx");
}
else
{
lblcrederror.Text = ("Credentials dont match");
break;
}
}
myConnection.Close();
}
}
I'm making my final project for C# (school) this year and I promised the last time I got help on this site that I would make sure my SQL was secure and I would make my application secure. Could someone look over my Login Screen and tell me if this is a proper and secure way?
I start by opening my main mdiContainer via Program.cs:
private void Form1_Load(object sender, EventArgs e)
{
fL.ShowDialog();
}
Then this login form shows:
string User = txtUser.Text;
string Pw = txtPw.Text;
int Correct = clDatabase.login(User, Pw);
if (Correct == 1)
{
this.Hide();
}
else
{
MessageBox.Show("De gegevens die u heeft ingevult kloppen niet", "Fout!"); //Above means your input is not correct
}
And in clDatabase.login
public static int login(string GebruikersnaamI, string WachtwoordI)
{
int correct = 0;
SqlConnection Conn = new SqlConnection(clStam.Connstr);
Conn.Open();
using (SqlCommand StrQuer = new SqlCommand("SELECT * FROM gebruiker WHERE usernm=#userid AND userpass=#password", Conn))
{
StrQuer.Parameters.AddWithValue("#userid", GebruikersnaamI);
StrQuer.Parameters.AddWithValue("#password", WachtwoordI);
SqlDataReader dr = StrQuer.ExecuteReader();
if (dr.HasRows)
{
correct = 1;
MessageBox.Show("loginSuccess");
}
else
{
correct = 2;
//invalid login
}
}
Conn.Close();
return correct;
}
Dialog for loginsucces is only there for debug purposes atm
Is this secure? Is this the proper way to have a login form?
EDIT Updated code login form:
private void button1_Click(object sender, EventArgs e)
{
ErrorProvider EP = new ErrorProvider();
if (txtUser.Text == string.Empty || txtPw.Text == string.Empty)
{
if (txtUser.Text == string.Empty)
txtUser.BackColor = Color.Red;
if (txtPw.Text == string.Empty)
txtPw.BackColor = Color.Red;
MessageBox.Show("Er moet wel iets ingevuld zijn!", "Fout");
}
else
{
string User = txtUser.Text;
string Pw = txtPw.Text;
Boolean Correct = clDatabase.login(User, Pw);
if (Correct == true)
{
this.Hide();
}
else
{
MessageBox.Show("Deze combinatie van username en password is niet bekend", "Fout!");
}
}
}
clDatabase:
public static Boolean login(string GebruikersnaamI, string WachtwoordI)
{
Boolean correct = false;
using (SqlConnection Conn = new SqlConnection(clStam.Connstr))
{
Conn.Open();
using (SqlCommand StrQuer = new SqlCommand("SELECT * FROM gebruiker WHERE usernm=#userid AND userpass=#password", Conn))
{
StrQuer.Parameters.AddWithValue("#userid", GebruikersnaamI);
StrQuer.Parameters.AddWithValue("#password", WachtwoordI);
using (SqlDataReader dr = StrQuer.ExecuteReader())
{
if (dr.HasRows)
{
correct = true;
}
else
{
correct = false;
//invalid login
}
}
}
Conn.Close();
}
return correct;
}
It is secure as far as SQL Injection is concerned, as you are passing parameters. But, do not store password as plain text, instead store its hashed value.
See: How to securely save username/password (local)?
When I use the following code, if the user name and password are same, it is working fine, if I provide wrong username and password it is nether giving me message or logging in:
private void btnSubmit_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = Helper.getconnection();
con.Open();
SqlCommand cmd = new SqlCommand("select SupportName, Password from Logins where SupportName='" + txtSupportName.Text + "' and Password='" + txtPassword.Text + "'", con);
SqlDataReader dr = cmd.ExecuteReader();
string Name = txtSupportName.Text;
string Pwd = txtPassword.Text;
while (dr.Read())
{
if ((dr["SupportName"].ToString() == Name) && (dr["Password"].ToString() == Pwd))
{
// MessageBox.Show("welcome");
Form Support = new Support();
Support.ShowDialog();
}
else
{
MessageBox.Show("SupportName and password are invalid");
}
}
dr.Close();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
if (txtSupportName.Text == string.Empty)
{
MessageBox.Show("Please enter a value to Support Name!");
txtSupportName.Focus();
return;
}
if (txtPassword.Text == string.Empty)
{
MessageBox.Show("Please enter a value to Description!");
txtPassword.Focus();
return;
}
}
There seem to be a few issues with your code:
You should validate your inputs before running the query
You should parameterize your queries (there are lots of samples on SO) instead of using string concatenation
You seem to be assuming you will get a result from your SQL query. You should maybe check dr.HasRows to see if the details are correct, or check if dr.Read() returns true to determine whether to display the message box or not
You should dispose of your DB objects using using blocks. E.g. (not sure why formatting isn't working):
using (SqlConnection con = Helper.getconnection())
{
...
}
instead of calling Dispose and Close explicitly. Even if you do want to call Dispose and Close explicitly you should do so in a finally block.
Daniel Kelly has written a good answer I just implement it and add separate methods to segregate responsibility
private bool Login(string supportName, string password)
{
if(string.IsNullOrEmpty(supportName) || string.IsNullOrEmpty(password))
{
throw new ArgumentException();
}
using(var connection = Helper.getconnection())
using(var command = connection.CreateCommand())
{
conmmand.CommandText = "SELECT 1 FROM Logins WHERE SupportName=#SupportName AND Password=#Password";
command.Parameters.AddWithValue("#SupportName", supportName);
command.Parameters.AddWithValue("#Password", password);
return command.ExecuteScalar() != null;
}
}
private void ShowSupportForm()
{
var supportName = txtSupportName.Text;
var password = txtPassword.Text;
if (string.IsNullOrEmpty(supportName))
{
MessageBox.Show("Please enter a value to Support Name!");
txtSupportName.Focus();
return;
}
if (string.IsNullOrEmpty(password))
{
MessageBox.Show("Please enter a value to Passwod!");
txtPassword.Focus();
return;
}
if(Login(supportName, password))
{
using(var form = new Support())
{
form.ShowDialog(this);
}
}
else
{
MessageBox.Show("SupportName and password are invalid");
}
}
private void btnSubmit_Click(object sender, EventArgs e)
{
ShowSupportForm();
}
There is problem in you code. You forgot to check if data reader has any row or not.
if (dr.HasRows)
{
while (dr.Read())
{
if ((dr["SupportName"].ToString() == Name) && (dr["Password"].ToString() == Pwd))
{
// MessageBox.Show("welcome");
Form Support = new Support();
Support.ShowDialog();
}
else
{
MessageBox.Show("SupportName and password are invalid");
}
}
}
else
{
MessageBox.Show("SupportName and password are invalid");
}
Just simply add HasRows to check if your username and password exist on your table / it retrieve data on your database.
if(dr.HasRows)
{
//username and password exists
while (dr.Read())
{
if ((dr["SupportName"].ToString() == Name) && (dr["Password"].ToString() == Pwd))
{
// MessageBox.Show("welcome");
Form Support = new Support();
Support.ShowDialog();
}
}
}
else
{
//username and password not exists
MessageBox.Show("SupportName and password are invalid");
}
Best Regards