How to disable the Submit Button for a given duration? - c#

I am building a login form. If the user attempts to login with invalid username/password for 3 attempts then the submit button must be disabled for a given duration.
How can I do that?
Here is my existing code:
protected void Button1_Click(object sender, EventArgs e)
{
int count = 0;
string username = TextBox1.Text.Trim();
string password = TextBox2.Text.Trim();
String connString = ConfigurationManager.ConnectionStrings["Myconnection"].ToString();
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand("Login", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#username", username);
cmd.Parameters.AddWithValue("#password", password);
conn.Open();
SqlDataReader read = cmd.ExecuteReader();
read.Read();
if (read.HasRows)
{
Session["LoggedIn"] = "correct";
Response.Redirect("WebForm2.aspx", false);
}
else
{
Label1.Visible = true;
Label1.Text = "Wrong user/password";
conn.Close();
}
if (System.Convert.ToInt32(ViewState["Tries"]) == 2)
{
Label1.Text = "Exceeded 3 times Attempts.Please Login after some time";
TextBox1.Enabled = false;
TextBox2.Enabled = false;
Button1.Enabled = false; // Button1 is the submit button
}
else
{
// Otherwise, increment number of tries.
ViewState["Tries"] = System.Convert.ToInt32(ViewState["Tries"]) + 1;
if (System.Convert.ToInt32(ViewState["Tries"]) == 2)
Label1.Text = "Exceeded 3 times Attempts.Please Login after some time";
}
}

For this you can create a table in your code or in database something like
LockingTime
Userid LockTime LockedDateTime
1 30 01/03/2012 12:30
As per th table
UserId = id of the user locked
LockTime - amount of time user Get locked
LockDateTime - DateTime when user account locked
When user login fails three time you enter data in table as explained...
Now when user tries to login to system you should check
select * from table name userid=#userid and GetDate() >
DATEADD (mi, LockTime, LockDateTime)
Note : query is just a suggession this not actual query as i m not added lockdate + locktime which is depends on the database and function avilable

Related

C# MySql Login Admin panel

I have a project and that project has a login part. Users will be able to login with their own accounts and will be transferred to a different Form. But I want to login to the admin panel, I don't know how to login. When I type name="admin" password="admin123" from the same login, it will switch to the admin form. Admin account in the same table
private void jImageButton2_Click(object sender, EventArgs e)
{
string user = textBox1.Text;
string pasw = textBox2.Text;
MySqlConnection baglanti = new MySqlConnection("Server=localhost;Database=emlak;Uid=root;Pwd='';");
MySqlCommand cmd = new MySqlCommand();
baglanti.Open();
cmd.Connection = baglanti;
string veri = cmd.CommandText = "SELECT kullanici_adi FROM kayitol WHERE ID='32'"; // admin name
string veri2 = cmd.CommandText = "SELECT kullanici_sifre FROM kayitol WHERE ID= '32'";//admin password
cmd.CommandText = "SELECT * FROM kayitol where kullanici_adi='" + textBox1.Text + "' AND kullanici_sifre='" + textBox2.Text + "'"; //UserLogin
MySqlDataReader dr = cmd.ExecuteReader();
if (label6.Text == textBox3.Text) // verification
{
if (dr.Read())
{
MessageBox.Show("Giriş Başarılı..");// Login True
musteriform.Show();
this.Hide();
}
else
{
MessageBox.Show("Kullanıcı adı ya da şifre yanlış"); // Login false
}
if (user == veri&& pasw==veri2)
{
Form2 frm2 = new Form2(this);
frm2.Show();
}
}
else
{
MessageBox.Show("Doğrulama Kodu Hatalı"); // False verification
}
The user whose ID is equal to 32 is the admin user. When you enter the password and name of the user admin account correctly, it will be transferred to the admin form.
Sorry if I didn't explain myself fully. I need help by typing from google translate
if (rd.HasRows) // Girilen K.Adı ve K.Parola Dahilinde Gelen Data var ise
{
while (rd.Read())
{
if (rd["ID"].ToString() == "1") // Admin Panel Login
{
Form2 frm2 = new Form2();
frm2.Show();
this.Hide();
}
else
{
mf.randevuveri = txtKullanici.Text;
mf.Show();
this.Hide();
}
}
}

C# - Cannot get value from database

In my application I have a login system. It's basic so I don't need any encryption. The problem is that when I want to login, I insert the credentials (username and password) but it doesn't make anything. My code is:
public void iniciarsessaobutton_Click(object sender, EventArgs e)
{
string txtuser = textusername.Text;
string txtpass = textlogin.Text;
MySqlCommand cmd = new MySqlCommand("SELECT password FROM empregados WHERE user='" + txtuser + "';", mConn);
mConn.Open();
MySqlDataReader login = cmd.ExecuteReader();
login.Read();
string getpass = login["password"].ToString();
if (getpass == txtpass)
{
mConn.Close();
MessageBox.Show("Sessão iniciada");
Admin adm = new Admin();
this.Hide();
adm.Show();
}
else
{
mConn.Close();
MessageBox.Show("Não foi possivel iniciar sessão. Insira a password corretamente.");
}
}
I'd like to propose some fixes mentioned in the comments along with some general improvements. See my comments in the code for the issues addressed:
public void iniciarsessaobutton_Click(object sender, EventArgs e)
{
string txtuser = textusername.Text;
string txtpass = textlogin.Text;
// Put your connection into a using() block
using (MySqlConnection conn = new MySqlConnection(variableWithYourConnectionStringHere))
{
// Put your commend into a using() block
// enclose your column names in backticks to avoid conflict with MySql reserved keywords
// add a placeholder (#username) for your parameter
// use LIMIT 1 if you only expect 1 row matching your condition
using(MySqlCommand cmd = new MySqlCommand("SELECT `password` FROM empregados WHERE `user` = #username LIMIT 1", conn))
{
mConn.Open();
// add a parameter with your TextBox value
cmd.Parameters.AddWithValue("#username", txtuser);
// If you only retrieve 1 value, use ExecuteScalar to return only 1 value
// cast the returned object as string
string getpass = cmd.ExecuteScalar() as string;
if (getpass == txtpass)
{
MessageBox.Show("Sessão iniciada");
Admin adm = new Admin();
this.Hide();
adm.Show();
}
else
{
MessageBox.Show("Não foi possivel iniciar sessão. Insira a password corretamente.");
}
}
}
}

Refresh session state on button press

I have a button that when pressed, looks for a value based on a listbox choice and if it finds records in the table, it takes that value from listbox and puts it into a session, refreshes the page and the session is then used as a data source, ie. find where session = session.
Now what happens is if i want to do two consecutive searches, the button doesnt store new session, instead it takes the old session. So if I search for x first, then y, it will add x when page is refreshed.
protected void search(object sender, EventArgs e)
{
con.Open();
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM Driver WHERE City = '" + JourOrigin.SelectedItem + "' ";//retrieves driver names from table
dr = cmd.ExecuteReader();
dr.Read();
if(Session["city"] != null)
{
Session["city"] = null;
JourOrigin.SelectedValue = null;
}
else
{
if(dr.HasRows)
{
Session["city"] = JourOrigin.SelectedItem.ToString();
Response.Redirect("~/Account/FindDriver.aspx");
NoCity.Visible = false;
}
else
{
DriversJourney.Items.Clear();
DriversJourney.Items.Add("No Drivers in selected city, try another city");
NoCity.Visible = true;
NoCity.Text = "No drivers in selected city, please try another city";
}
}
con.Close();
}
I managed to clear the session if there is a session already, but I have to press value twice to store it. Is it possible to "refresh" a session every time the button is pressed?
You must try this code:
protected void search(object sender, EventArgs e)
{
con.Open();
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM Driver WHERE City = '" + JourOrigin.SelectedItem + "' ";//retrieves driver names from table
dr = cmd.ExecuteReader();
dr.Read();
if(Session["city"] != null)
{
Session["city"] = null;
}
if(dr.HasRows)
{
Session["city"] = JourOrigin.SelectedItem.ToString();
Response.Redirect("~/Account/FindDriver.aspx");
NoCity.Visible = false;
}
else
{
DriversJourney.Items.Clear();
DriversJourney.Items.Add("No Drivers in selected city, try another city");
NoCity.Visible = true;
NoCity.Text = "No drivers in selected city, please try another city";
}
con.Close();
}

how can i pass the session value and put it in textboxes?

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();
}
}

Form loading again when the data in the drop down is selected

I have a registration where the user will enter the following details:
Email address,
Password,
Confirm password,
A drop down menu with option Employee or Contractor.
When Employee is selected they are not required to provide start date but for contractor they have to provide start date.
protected void Button1_Click(object sender, EventArgs e)
{
{
{
SqlConnection sqlCon = new SqlConnection(strCon);
SqlCommand cmd = new SqlCommand("UpdateRequest", sqlCon);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "UpdateRequest";
cmd.Connection = sqlCon;
cmd.Parameters.AddWithValue("#EmailAddress", txtEmailAddress.Text);
cmd.Parameters.AddWithValue("#Password", txtPassword.Text);
cmd.Parameters.AddWithValue("#ConfirmPassword", txtConfirmPassword.Text);
cmd.Parameters.AddWithValue("#JobRole", ddJobRole.Text);
cmd.Parameters.AddWithValue("#StartDate", txtStartDate.Text);
SqlParameter rpv = new SqlParameter();
rpv.DbType = DbType.Int32;
rpv.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(rpv);
try
{
sqlCon.Open();
cmd.ExecuteScalar();
int retValue = Convert.ToInt32(rpv.Value);
if (retValue == 10)
lblMessage.Text = "Request was sent successfully!";
if (retValue == 11)
lblMessage.Text = "*Email Address is already registered.";
if (retValue == 12)
lblMessage.Text = "*Passwords do not match.";
if (retValue == 13)
lblMessage.Text = "Sorry, Your application was already denied earlier.";
}
catch (Exception)
{
lblMessage.Text = "";
}
}
}
}
protected void ddJobRole_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddJobRole.SelectedValue == "Contractor")
{
RequiredFieldValidator27.Enabled = true; //Initally disabled it
}
else
{
RequiredFieldValidator27.Enabled = false;
}
}
Here the problem is whenever I select any option from the drop down the form loads again and asks password and confirm password for the second time. Can anyone tell me what the problem is?
The password and the confirmation password fields are not kept their values after the post back for security reasons. This input controls are not have the same behavior as the rest controls.
Now from the code I see, you do not actually need to make full post back for this behavior on code behind, you can easy use javascript and do the same on client side with out post back, and without loose the input of the password.

Categories