I want to use strong password in my program. So I searched for strong password validation but I didnt understand how to call that function while saving.
This is the function I want to use for password validation:
private bool ValidatePassword(string password, out string ErrorMessage)
{
var input = password;
ErrorMessage = string.Empty;
if (string.IsNullOrWhiteSpace(input))
{
throw new Exception("Password should not be empty");
}
var hasNumber = new Regex(#"[0-9]+");
var hasUpperChar = new Regex(#"[A-Z]+");
var hasMiniMaxChars = new Regex(#".{8,15}");
var hasLowerChar = new Regex(#"[a-z]+");
var hasSymbols = new Regex(#"[!##$%^&*()_+=\[{\]};:<>|./?,-]");
if (!hasLowerChar.IsMatch(input))
{
ErrorMessage = "Password should contain At least one lower case letter";
return false;
}
else if (!hasUpperChar.IsMatch(input))
{
ErrorMessage = "Password should contain At least one upper case letter";
return false;
}
else if (!hasMiniMaxChars.IsMatch(input))
{
ErrorMessage = "Password should not be less than or greater than 12 characters";
return false;
}
else if (!hasNumber.IsMatch(input))
{
ErrorMessage = "Password should contain At least one numeric value";
return false;
}
else if (!hasSymbols.IsMatch(input))
{
ErrorMessage = "Password should contain At least one special case characters";
return false;
}
else
{
return true;
}
}
The save button code:
private void btnSave_Click(object sender, EventArgs e) {
var data = DBConnection.DBConnect();
SqlCommand cmd = new SqlCommand("Insert_Users", data);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#StaffName", SqlDbType.VarChar).Value = txtStaffName.Text;
cmd.Parameters.Add("#Email", SqlDbType.NVarChar).Value = txtEmail.Text;
cmd.Parameters.Add("#UserName", SqlDbType.NVarChar).Value = txtUsername.Text;
cmd.Parameters.Add("#Password", SqlDbType.VarChar).Value = txtPassword.Text;
cmd.Parameters.Add("#Phoneno", SqlDbType.NVarChar).Value = txtPhoneNo.Text;
cmd.Parameters.Add("#Admin", SqlDbType.Char).Value = chkIsAdmin.CheckState == CheckState.Checked ? 1 : 0;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds);
MessageBox.Show("Saved Sucessfully");
LoadUsers();
}
Can someone give me an idea how I can use this function to perform password validation, please?
Maybe I do not get the problem but it's that simple?:
private void btnSave_Click(object sender, EventArgs e) {
var error = string.Empty;
if(ValidatePassword(txtPassword.Text, error))
{
var data = DBConnection.DBConnect();
SqlCommand cmd = new SqlCommand("Insert_Users", data);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#StaffName", SqlDbType.VarChar).Value = txtStaffName.Text;
cmd.Parameters.Add("#Email", SqlDbType.NVarChar).Value = txtEmail.Text;
cmd.Parameters.Add("#UserName", SqlDbType.NVarChar).Value = txtUsername.Text;
cmd.Parameters.Add("#Password", SqlDbType.VarChar).Value = txtPassword.Text;
cmd.Parameters.Add("#Phoneno", SqlDbType.NVarChar).Value = txtPhoneNo.Text;
cmd.Parameters.Add("#Admin", SqlDbType.Char).Value = chkIsAdmin.CheckState == CheckState.Checked ? 1 : 0;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds);
MessageBox.Show("Saved Sucessfully");
LoadUsers();
}
else
{
throw new Exception(error); // Or Console.WriteLine(error) or whatever
}
}
Related
protected void btnLogin_Click(object sender, EventArgs e)
{
string EmailAddr = "";
string Password = "";
string strConn = ConfigurationManager.ConnectionStrings["EPortfolioConnectionString"].ToString();
SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand("SELECT * FROM Parent WHERE [EmailAddr]=#EmailAddr AND [Password]=#Password", conn);
cmd.Parameters.AddWithValue("#EmailAddr", EmailAddr);
cmd.Parameters.AddWithValue("#Password", Password);
SqlDataAdapter daParentLogin = new SqlDataAdapter(cmd);
DataSet result = new DataSet();
conn.Open();
daParentLogin.Fill(result, "Login");
conn.Close();
if (result.Tables["Login"].Rows.Count > 0)
{
lblMessage.Text = "Invalid login credentials";
}
else
{
Response.Redirect("SubmitViewingRequest.aspx");
}
}
the codes above doesn't validate the email address and password with the database. any email address and password entered is considered correct. can i get help? thank you!
Change your if condition
if (result.Tables["Login"].Rows.Count > 0) // For Successfully Login
{
Response.Redirect("SubmitViewingRequest.aspx");
}
else // For Invalid User credentials
{
lblMessage.Text = "Invalid login credentials";
}
This happens when we mistakenly put if conditions in reverse order. Please change your code with if conditions replaced like this:
protected void btnLogin_Click(object sender, EventArgs e)
{
string EmailAddr = "";
string Password = "";
string strConn = ConfigurationManager.ConnectionStrings["EPortfolioConnectionString"].ToString();
SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand("SELECT * FROM Parent WHERE [EmailAddr]=#EmailAddr AND [Password]=#Password", conn);
cmd.Parameters.AddWithValue("#EmailAddr", EmailAddr);
cmd.Parameters.AddWithValue("#Password", Password);
SqlDataAdapter daParentLogin = new SqlDataAdapter(cmd);
DataSet result = new DataSet();
conn.Open();
daParentLogin.Fill(result, "Login");
conn.Close();
if (result.Tables["Login"].Rows.Count > 0)
{
Response.Redirect("SubmitViewingRequest.aspx");
}
else
{
lblMessage.Text = "Invalid login credentials";
}
}
Hope this helps
I have a get details form, and I know that using try and catch as a way of validation here is bad practice. How would I check to see if the CustID exists and then tell the user that what they entered does not exist?
Apologies if this is a silly question and it's obvious and..., I'm a beginner.
public void getdetails()
{
lblMessage.Text = "";
if (txtCID.Text == "")
{
lblMessage.Text = "Please enter a Customer ID before obtaining details.";
}
else
{
command.Connection.Open();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "GetCustomer";
SqlParameter param = new SqlParameter();
param.ParameterName = "#CustID";
param.SqlDbType = SqlDbType.Int;
param.Direction = ParameterDirection.Input;
param.Value = txtCID.Text;
command.Parameters.Add(param);
adapter.SelectCommand = command;
adapter.Fill(table);
txtFName.Text = table.Rows[0].Field<string>("FirstName");
txtFName.DataBind();
txtLName.Text = table.Rows[0].Field<string>("Surname");
txtLName.DataBind();
rdoGender.Text = table.Rows[0].Field<string>("Gender").ToString();
txtAge.DataBind();
txtAge.Text = table.Rows[0].Field<int>("Age").ToString();
txtAge.DataBind();
txtAdd1.Text = table.Rows[0].Field<string>("Address1").ToString();
txtAge.DataBind();
txtAdd2.Text = table.Rows[0].Field<string>("Address2").ToString();
txtAge.DataBind();
txtCity.Text = table.Rows[0].Field<string>("City").ToString();
txtAge.DataBind();
txtPhone.Text = table.Rows[0].Field<string>("Phone").ToString();
txtAge.DataBind();
txtMobile.Text = table.Rows[0].Field<string>("Mobile").ToString();
txtAge.DataBind();
txtEmail.Text = table.Rows[0].Field<string>("Email").ToString();
txtEmail.DataBind();
command.Connection.Close();
}
}
Since you fill a DataTable it's easy to determine if the customer existed, use DataTable.Rows.Count > 0:
bool customerExists = table.Rows.Count > 0;
if(!customerExists)
{
lblMessage.Text = $"The customer with CustomerID={txtCID.Text} is unknown.";
}
Apart from that...
Use the using-statement for your connection and everything that implements IDisposable
convert the string to int with C#, don't let the database do it for you. On that way, using int.TryParse, you also validate the input
So here is your method including these and other improvements:
public void LoadCustomerDetails()
{
lblMessage.Text = "";
if (String.IsNullOrWhiteSpace(txtCID.Text))
{
lblMessage.Text = "Please enter a CustomerID before obtaining details.";
return;
}
DataTable table = new DataTable();
int customerID;
using (var conn = new SqlConnection(Properties.Settings.Default.TestDbCon))
using (var da = new SqlDataAdapter("GetCustomer", conn))
using (var cmd = da.SelectCommand)
{
cmd.CommandType = CommandType.StoredProcedure;
if (!int.TryParse(txtCID.Text.Trim(), out customerID))
{
lblMessage.Text = "Please enter a valid integer CustomerID before obtaining details.";
return;
}
cmd.Parameters.Add("#CustID", SqlDbType.Int).Value = customerID;
da.Fill(table); // you don't need to open/close the connection with Fill
}
if (table.Rows.Count == 0)
{
lblMessage.Text = $"No customer with CustomerID={customerID} found.";
return;
}
DataRow custumerRow = table.Rows.Cast<DataRow>().Single(); // to cause an exception on multiple customers with this ID
txtFName.Text = custumerRow.Field<string>("FirstName");
txtLName.Text = custumerRow.Field<string>("Surname");
rdoGender.Text = custumerRow.Field<string>("Gender").ToString();
txtAge.Text = custumerRow.Field<int>("Age").ToString();
txtAdd1.Text = custumerRow.Field<string>("Address1").ToString();
txtAdd2.Text = custumerRow.Field<string>("Address2").ToString();
txtCity.Text = custumerRow.Field<string>("City").ToString();
txtPhone.Text = custumerRow.Field<string>("Phone").ToString();
txtMobile.Text = custumerRow.Field<string>("Mobile").ToString();
txtEmail.Text = custumerRow.Field<string>("Email").ToString();
}
I'm not sure I fully understood your question. What I would do is:
public bool getdetails()
{
bool found = false;
int id;
bool isnumber;
lblMessage.Text = "";
isnumber = int.TryParse(txtCID.Text, out id);
if (!isnumber)
{
lblMessage.Text = "Please enter a valid Customer ID before obtaining details.";
}
else
{
command.Connection.Open();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "GetCustomer";
SqlParameter param = new SqlParameter();
param.ParameterName = "#CustID";
param.SqlDbType = SqlDbType.Int;
param.Direction = ParameterDirection.Input;
param.Value = id;
command.Parameters.Add(param);
adapter.SelectCommand = command;
adapter.Fill(table);
if (table.Rows.Count > 0)
{
txtFName.Text = table.Rows[0].Field<string>("FirstName");
txtFName.DataBind();
txtLName.Text = table.Rows[0].Field<string>("Surname");
txtLName.DataBind();
rdoGender.Text = table.Rows[0].Field<string>("Gender").ToString();
txtAge.DataBind();
txtAge.Text = table.Rows[0].Field<int>("Age").ToString();
txtAge.DataBind();
txtAdd1.Text = table.Rows[0].Field<string>("Address1").ToString();
txtAge.DataBind();
txtAdd2.Text = table.Rows[0].Field<string>("Address2").ToString();
txtAge.DataBind();
txtCity.Text = table.Rows[0].Field<string>("City").ToString();
txtAge.DataBind();
txtPhone.Text = table.Rows[0].Field<string>("Phone").ToString();
txtAge.DataBind();
txtMobile.Text = table.Rows[0].Field<string>("Mobile").ToString();
txtAge.DataBind();
txtEmail.Text = table.Rows[0].Field<string>("Email").ToString();
txtEmail.DataBind();
found = true;
}
else
{
lblMessage.Text = "User with ID " + id + " does not exists";
}
command.Connection.Close();
}
return found;
}
The function will return false if either the id is not specified or does not exist. Another problem is that you don't check if txtCID.Text contains a valid number: in this case a SQL error is would thrown!
I added a number conversion check that ensures that at least the stored procedure execution runs without errors. Anyway, you should wrap the whole procedure in a try-catch to intercept any unpredictable error (db offline or internal db error, etc).
Then, I use table.Rows.Count to verify if the stored procedure returned a result.
Mario.
I declared the variable PosterDirectory here
SqlConnection con = new SqlConnection(Helper.GetConnectionString());
String PosterDirectory;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Role"].ToString() != "Admin")
{
Session.Clear();
Response.Redirect("Default.aspx");
}
if (!IsPostBack)
{
GetEvent(int.Parse(Request.QueryString["EventID"].ToString()));
}
}
Supposedly PosterDirectory would be given a value within the GetEvent function.
void GetEvent(int EventID)
{
con.Open();
SqlCommand com = new SqlCommand(
"select * from event where EventID = #EventID", con);
com.Parameters.Add("#EventID", SqlDbType.Int).Value = EventID;
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
//Fill in the input fields based on the EventID
txtName.Text = reader["Name"].ToString();
txtVenue.Text = reader["Venue"].ToString();
txtStreet.Text = reader["Street"].ToString();
txtCity.Text = reader["City"].ToString();
txtCountry.Text = reader["Country"].ToString();
txtMap.Text = reader["Map"].ToString();
txtStartDate.Text = Convert.ToDateTime(reader["DateTimeStarted"].ToString()).ToString("yyyy-MM-dd");
txtStartTime.Text = Convert.ToDateTime(reader["DateTimeStarted"].ToString()).TimeOfDay.ToString();
txtEndDate.Text = Convert.ToDateTime(reader["DateTimeEnded"].ToString()).ToString("yyyy-MM-dd");
txtEndTime.Text = Convert.ToDateTime(reader["DateTimeEnded"].ToString()).TimeOfDay.ToString();
PosterDirectory = reader["Poster"].ToString();
txtDesciption.Text = reader["Description"].ToString();
}
con.Close();
}
I will use the String PosterDirectory later on for my SQL Parameter to retrieve the filepath of a photo.
protected void btnUpdate_Click(object sender, EventArgs e)
{
//Get the Date and Time Strings
DateTime DateStarted = Convert.ToDateTime(txtStartDate.Text);
TimeSpan TimeStarted = TimeSpan.Parse(txtStartTime.Text);
DateTime DateEnded = Convert.ToDateTime(txtEndDate.Text);
TimeSpan TimeEnded = TimeSpan.Parse(txtEndTime.Text);
DateTime DateTimeStarted = DateStarted + TimeStarted;
DateTime DateTimeEnded = DateEnded + TimeEnded;
//Get the DateTimeCreated
DateTime DateTimeLastUpdated;
con.Open();
//if (fuPoster.HasFile)
{
SqlCommand com = new SqlCommand(
"update event set Name=#Name, Venue=#Venue, Street=#Street, City=#City, Country=#Country, Map=#Map, DateTimeStarted=#DateTimeStarted, DateTimeEnded=#DateTimeEnded, DateTimeUpdated=#DateTimeUpdated, Poster=#Poster, Description=#Description where EventID=#EventID",
con);
com.Parameters.Add("#EventID", SqlDbType.Int).Value = int.Parse(Request.QueryString["EventID"].ToString());
com.Parameters.Add("#Name", SqlDbType.NVarChar).Value = txtName.Text;
com.Parameters.Add("#Venue", SqlDbType.NVarChar).Value = txtVenue.Text;
com.Parameters.Add("#Street", SqlDbType.NVarChar).Value = txtStreet.Text;
com.Parameters.Add("#City", SqlDbType.NVarChar).Value = txtCity.Text;
com.Parameters.Add("#Country", SqlDbType.NVarChar).Value = txtCountry.Text;
com.Parameters.Add("#Map", SqlDbType.NVarChar).Value = txtMap.Text;
com.Parameters.Add("#DateTimeStarted", SqlDbType.DateTime).Value = DateTimeStarted;
com.Parameters.Add("#DateTimeEnded", SqlDbType.DateTime).Value = DateTimeEnded;
com.Parameters.Add("#DateTimeUpdated", SqlDbType.DateTime).Value = DateTime.Now;
DateTimeLastUpdated = DateTime.Now;
if (fuPoster.HasFile)
{
com.Parameters.Add("#Poster", SqlDbType.Text).Value = "images/" + fuPoster.FileName;
fuPoster.SaveAs(Server.MapPath("images/" + fuPoster.FileName));
}
else
{
com.Parameters.Add("#Poster", SqlDbType.Text).Value = PosterDirectory;
}
com.Parameters.Add("#Description", SqlDbType.Text).Value = txtDesciption.Text;
com.ExecuteNonQuery();
con.Close();
//Auditing Event
AuditEvent(DateTimeLastUpdated);
Response.Redirect("Event.aspx");
}
//else
//{
// SqlCommand com = new SqlCommand(
// "update event set Name=#Name, Venue=#Venue, Street=#Street, City=#City, Country=#Country, Map=#Map, DateTimeStarted=#DateTimeStarted, DateTimeEnded=#DateTimeEnded, DateTimeUpdated=#DateTimeUpdated, Description=#Description where EventID=#EventID",
// con);
// com.Parameters.Add("#EventID", SqlDbType.Int).Value = int.Parse(Request.QueryString["EventID"].ToString());
// com.Parameters.Add("#Name", SqlDbType.NVarChar).Value = txtName.Text;
// com.Parameters.Add("#Venue", SqlDbType.NVarChar).Value = txtVenue.Text;
// com.Parameters.Add("#Street", SqlDbType.NVarChar).Value = txtStreet.Text;
// com.Parameters.Add("#City", SqlDbType.NVarChar).Value = txtCity.Text;
// com.Parameters.Add("#Country", SqlDbType.NVarChar).Value = txtCountry.Text;
// com.Parameters.Add("#Map", SqlDbType.NVarChar).Value = txtMap.Text;
// com.Parameters.Add("#DateTimeStarted", SqlDbType.DateTime).Value = DateTimeStarted;
// com.Parameters.Add("#DateTimeEnded", SqlDbType.DateTime).Value = DateTimeEnded;
// com.Parameters.Add("#DateTimeUpdated", SqlDbType.DateTime).Value = DateTime.Now;
// com.Parameters.Add("#Description", SqlDbType.Text).Value = txtDesciption.Text;
// DateTimeLastUpdated = DateTime.Now;
// com.ExecuteNonQuery();
// con.Close();
// //Auditing Event
// AuditEvent(DateTimeLastUpdated);
// Response.Redirect("Event.aspx");
//}
}
Members aren't persisted between requests. The Form class is only valid for a single request.
For context, read up on the ASP.NET Page Life Cycle.
You could put your value into a hidden form field or the view state.
i'm creating a system that has an add-edit-delete function but whenever i try to edit a value from my ms sql server 2005 it keeps on telling me "cannot find table 0". below is my code i'm using visual studio c# 2008:
private void button2_Click(object sender, EventArgs e)
{
try
{
SqlDataAdapter dad = new SqlDataAdapter();
SqlCommandBuilder scb = new SqlCommandBuilder(dad);
dad.UpdateCommand = new SqlCommand("UPDATE tblSchools SET Number = #id, School_Name = #school, Province = #prov, City = #city, Brgy = #brgy, Lot_Num = #lot, Area = #area, Mem_Date_Rec = #date, Cenro = #cenro", conn);
dad.UpdateCommand.Parameters.Add("#school", SqlDbType.VarChar).Value = textBox1.Text;
dad.UpdateCommand.Parameters.Add("#prov", SqlDbType.VarChar).Value = comboBox1.Text;
dad.UpdateCommand.Parameters.Add("#city", SqlDbType.VarChar).Value = textBox2.Text;
dad.UpdateCommand.Parameters.Add("#brgy", SqlDbType.VarChar).Value = textBox4.Text;
dad.UpdateCommand.Parameters.Add("#lot", SqlDbType.NVarChar).Value = textBox5.Text;
dad.UpdateCommand.Parameters.Add("#area", SqlDbType.Decimal).Value = textBox6.Text;
dad.UpdateCommand.Parameters.Add("#date", SqlDbType.DateTime).Value = dateTimePicker1.Value.Date;
dad.UpdateCommand.Parameters.Add("#cenro", SqlDbType.NVarChar).Value = textBox8.Text;
dad.UpdateCommand.Parameters.Add("#id", SqlDbType.Int).Value = ds.Tables[0].Rows[tblNamesBS.Position][0];
conn.Open();
dad.UpdateCommand.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
above the code i made a global function
DataSet ds = new DataSet();
SqlConnection conn = new SqlConnection("Data Source=MJ-PC\\SQLEXPRESS;Initial Catalog=Users;Integrated Security=True");
BindingSource tblNamesBS = new BindingSource();
what seems to be the problem here??
oh and to add up i made a datagridview that has a double click event, below is my code:
private void dg_DoubleClick(object sender, EventArgs e)
{
try
{
button2.Visible = true;
button5.Visible = true;
DataTable dt = new DataTable();
SqlDataAdapter dad = new SqlDataAdapter("SELECT * FROM tblSchools WHERE Number ="+
Convert.ToInt16(dg.SelectedRows[0].Cells[0].Value.ToString()) + "", conn);
dad.Fill(dt);
textBox1.Text = dt.Rows[0][1].ToString();
comboBox1.Text = dt.Rows[0][2].ToString();
textBox2.Text = dt.Rows[0][3].ToString();
textBox4.Text = dt.Rows[0][4].ToString();
textBox5.Text = dt.Rows[0][5].ToString();
textBox6.Text = dt.Rows[0][6].ToString();
//dateTimePicker1.Value = dt.Rows[0][7];
textBox8.Text = dt.Rows[0][8].ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
will this code affect my edit?
You have declared an empty data set
DataSet ds = new DataSet();
And later you try to access Table[0] in it but there isn't one defined.
protected void AjaxFileUpload_img_UploadComplete(object sender, AjaxFileUploadEventArgs e)
{
try
{
if (radbtn_select.SelectedItem.Text == "Sample")
{
var s = e.FileName;
int length = e.FileSize;
byte[] imgbyte = new byte[e.FileSize];
if (sample_code == "")
{
ErrorMsg.Visible = true;
ErrorMsg.Text = "Sample not found.Please enter the sample code..";
}
cmd = new SqlCommand("sp_pdm_shopping_upload", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
cmd.Parameters.Add(new SqlParameter("#sample", SqlDbType.Char, 15));
SqlParameter contentparameter = null;
contentparameter = (new SqlParameter("#image", SqlDbType.Image));
contentparameter.Direction = ParameterDirection.Input;
cmd.Parameters.Add(contentparameter);
cmd.Parameters.Add(new SqlParameter("#type", SqlDbType.Char, 10));
cmd.Parameters["#sample"].Value = txt_code.Text;
cmd.Parameters["#image"].Value = imgbyte;
cmd.Parameters["#type"].Value = "IMG";
cmd.ExecuteNonQuery();
con.Close();
ErrorMsg.Visible = true;
ErrorMsg.Text = "The image has been uploaded successfully.";
}
}
catch
{
return;
}
}
Does not get textbox value and radio button value in upload time.
How can I solve the problem?