I'm having issues with displaying the variable within a Message box. What I want to do is display in a messagebox which Combobox hasn't been filled in, it will display this in a list within the messagebox and then stop the user from saving to the database. The error is stating that it is a use of an unassigned variable but I have assigned it at the top of the 'if' statement.
private void btnSaveDB_Click(object sender, EventArgs e)
{
if (cmbPolType.SelectedItem == null ||
cmbPolNum.SelectedItem == null ||
cmbTPReg.SelectedItem == null ||
cmbLossType.SelectedItem == null ||
cmbLossDesc.SelectedItem == null ||
cmbInsdFault.SelectedItem == null)
{
string polType, polNum, lossType, lossDesc, tpReg, insdFault = null;
if (cmbPolType.SelectedItem==null)
{
polType = "Policy Type";
}
if (cmbPolNum.SelectedItem==null)
{
polNum = "Policy Number";
}
if (cmbLossType.SelectedItem==null)
{
lossType = "Loss Type";
}
if (cmbLossDesc.SelectedItem ==null)
{
lossDesc = "Loss Description";
}
if (cmbTPReg.SelectedItem==null)
{
tpReg = "TP Reg";
}
if (cmbInsdFault.SelectedItem==null)
{
insdFault = "Insd at Fault";
}
MessageBox.Show("You have not selected options for the following: " + lossDesc );
}
No lossDesc is not initialized in that way as well as the other strings variables but the insdFault. (The error message points to lossDesc because is the only one used in the remainder of the code).
Instead of initializing each one, I suggest to use a simple List<string> where you add your error messages and type all of them at the end of the test
List<string> missingData = new List<string>();
if (cmbPolType.SelectedItem == null)
missingData.Add("Policy Type");
if (cmbPolNum.SelectedItem == null)
missingData.Add("Policy Number");
if (cmbLossType.SelectedItem == null)
missingData.Add("Loss Type");
if (cmbLossDesc.SelectedItem == null)
missingData.Add("Loss Description");
if (cmbTPReg.SelectedItem == null)
missingData.Add("TP Reg");
if (cmbInsdFault.SelectedItem == null)
missingData.Add("Insd at Fault");
if(missingData.Count > 0)
{
MessageBox.Show("You have not selected options for the following: " +
Environment.NewLine +
string.Join(Environment.NewLine, missingData.ToArray()));
}
else
{
... save to database ? ....
}
This removes the need to use and initialize a bunch of string variables and uses the string.Join method to get the whole error message in a single string with each error on a separate line.
Related
While submitting a form, in one of the fields i am inserting vulnerable characters like =cmd|'/C calc'!A0. So in security terms it is termed as CSV-injection in export functionality
I have written code like this for above error. but its not working
[WebMethod]
public static string SaveRecord(RRSOCSaving RRSOCSaving, string Indication)
{
string strReturnId = "";
string strAppURL = ConfigurationManager.AppSettings["AppUrl"].ToString();
string strmail_Content = "";
CommonDB commonObj = new CommonDB();
try
{
// Cross site scripting issue code tag..!!
if (commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_CODE)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.CITY)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_SITENAME)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_SITENAME_LANDL_1)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_SITENAME_LANDL_2)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_ASST_MANAGER_NAME)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_ASST_MANAGER_MOBNO)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_MANAGER_NAME)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.MANAGER_MOBNO)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.EMP_NEAREST_STORE)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.EMP_NEAREST_STORE_MOBNO)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.SUPERVISOR_MOBNO)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.SECURITY_SUP_NAME_STORE)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.SECURITY_SUP_MOBNO_STORE)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.ALPM_ALPO_NAME)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.ALPM_ALPO_MOBNO))
{
strReturnId = "Something went wrong due to malicious script attack..!!!";
}
else
{
if (RRSOCSaving.ROLE_ASSIGNED == "SLP State Head")
{
bool blnState1 = Array.Exists(RRSOCSaving.ASSIGNED_STATE.ToString().ToUpper().Split(','), element => element == (RRSOCSaving.STATE).ToString().ToUpper());
if (blnState1)
{
strmail_Content = Get_Email_Content(RRSOCSaving.STORE_CODE, RRSOCSaving.UserName, Indication, RRSOCSaving.STATE, RRSOCSaving.SITE_STORE_FORMAT, RRSOCSaving.STORE_SITENAME);
// SendEmail(RRSOCSaving.UserName, RRSOCSaving.STORE_CODE, RRSOCSaving.SLP_EMAILID, ConfigurationManager.AppSettings["NHQEmail"].ToString(), strmail_Content, Indication);
strReturnId = CommonDB.INSERT_INTO_RRSOC_INFO(RRSOCSaving, Indication);
}
else
{
strReturnId = "User can add data for " + RRSOCSaving.ASSIGNED_STATE + " only";
}
}
else if (RRSOCSaving.ROLE_ASSIGNED == "NHQ Admin")
{
strmail_Content = Get_Email_Content(RRSOCSaving.STORE_CODE, RRSOCSaving.UserName, Indication, RRSOCSaving.STATE, RRSOCSaving.SITE_STORE_FORMAT, RRSOCSaving.STORE_SITENAME);
// SendEmail(RRSOCSaving.UserName, RRSOCSaving.STORE_CODE, RRSOCSaving.SLP_EMAILID, ConfigurationManager.AppSettings["NHQEmail"].ToString(), strmail_Content, Indication);
strReturnId = CommonDB.INSERT_INTO_RRSOC_INFO(RRSOCSaving, Indication);
//strReturnId = "Record Saved Succesfully";
}
}
// strReturnId = CommonDB.INSERT_INTO_RRSOC_INFO(RRSOCSaving);
}
catch (Exception)
{
throw;
}
return strReturnId;
}
public bool HackerTextExistOrNot(string Text)
{
bool flgValid = false;
Regex htmltags = new Regex(#"<.*?>");
Match chkMatch = htmltags.Match(Text);
if (chkMatch.Success)
{
flgValid = true;
}
return flgValid;
}
Please suggest how to stop this error.
Your HackerTextExistOrNot method is checking for the existance of html tags.
You should however check if the text is starting with one of the formular triggering characters.
To protect yourself against the injection attack ensure that none of the given text begins with any of the following characters:
Equals to ("=")
Plus ("+")
Minus ("-")
At ("#")
So you can check like this:
var attackChars = new char[]{'=','+','-','#'};
if(attackChars.Contains(text[0])
{
}
Here I need to avoid null from datagridview (winform)
private void SendUpdate()
{
if ((string)dataGridView1.SelectedRows[0].Cells[0].Value != string.Empty )
{
if (1 == dataGridView1.SelectedRows.Count)
{
int Id = Convert.ToInt32(dataGridView1.SelectedRows[0].Cells[0].Value);
Update up = new Update();
up.AssignValue(Id);
up.textBox1.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
up.comboBox1.Text = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
up.textBox2.Text = dataGridView1.SelectedRows[0].Cells[3].Value.ToString();
up.textBox3.Text = dataGridView1.SelectedRows[0].Cells[4].Value.ToString();
up.textBox4.Text = dataGridView1.SelectedRows[0].Cells[5].Value.ToString();
up.textBox5.Text = dataGridView1.SelectedRows[0].Cells[6].Value.ToString();
up.ShowDialog();
}
else
{
MessageBox.Show("Please Select the Single Data Which Required to Update");
}
}
else
{
MessageBox.Show("You Select the empty Row");
}
}
I had try !=string.empty; , !=null; , !="";
but error not solved.
1 == dataGridView1.SelectedRows.Count it true
But
(string)dataGridView1.SelectedRows[0].Cells[0].Value have null value
Show error
System.NullReferenceException: 'Object reference not set to an instance of an object.'
System.Windows.Forms.DataGridViewCell.Value.get returned null.
https://stackoverflow.com/a/32390609/9543244
private void SendUpdate()
{
if (String.IsNullOrWhiteSpace(dataGridView1.SelectedRows[0].Cells[0].Value as string))
{
MessageBox.Show("You Select the empty Row");
}
}
is not working
it eliminate all even row haveing data
I have a signup page that have many filed. Many of them should filled by user.
I use RequiredFieldValidator and RegularExpressionValidator for validate in client side.
Should I validate them in server side? How?
I wrote this code. I use many if and else if. Is this correct?
CaptchaControl1.ValidateCaptcha(txtSecureImg.Text);
if (CaptchaControl1.UserValidated)
{
if (txtFName.Text != string.Empty && txtLName.Text != string.Empty && txtUserName.Text != string.Empty && txtEmail.Text != string.Empty && txtPass.Text != string.Empty && txtCPass.Text != string.Empty && txtSecureImg.Text != string.Empty)
{
if (RegEx.EmailValidate(txtEmail.Text) == 1 && RegEx.PasswordValidate(txtPass.Text) == 1 && RegEx.UserName(txtUserName.Text) == 1)
{
try
{
// insert in database
}
catch (Exception)
{
lblMsg.Text = "Error";
}
}
else if(RegEx.EmailValidate(txtEmail.Text) == 0)
{
EmailRegularExpression.Visible = true;
}
else if(RegEx.PasswordValidate(txtPass.Text) == 0)
{
passRegularExpression.Visible = true;
}
else if(RegEx.UserName(txtUserName.Text) == 0)
{
UnameRegularExpression.Visible = true;
}
}
else if(txtFName.Text == string.Empty)
{
RequiredFieldValidator1.Visible = true;
}
// continue like above for another filed
}
else
{
lblMsg.Text = "Please insert Secure Image";
}
And :
public static int EmailValidate(string Mail)
{
int i = 0;
Regex regExEmail = new Regex(#"\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*");
if (regExEmail.IsMatch(Mail))
i = 1;
return i;
}
I'm assuming this is Web Forms...
The validation is run automatically. You can just use the Page.IsValid property: msdn
You'll still need to manually check the captcha field though.
CaptchaControl1.ValidateCaptcha(txtSecureImg.Text);
if (CaptchaControl1.UserValidated && Page.IsValid)
{
// Insert in db.
}
Since you use those validators, then you don't need to validate form in server side again like your codes.
But you should call Page.Validate()and then check page with Page.IsValid method.
from here
example
I have a gridview object that I am using to bind to a datasource. Upon the selectedIndexChanging event of the gridview, I would like to bring the data shown in the gridview into the textboxes on the form. However, when the data contains alphanumeric characters such as &'"", the data from the grid is showing ;amp, #S etc. and all other weird characters whenever I enter an alphanumeric character. Is there a way to prevent these characters from popping up in the textboxes when taking data from the grid?
The code that I have so far:
protected void grdActions_SelectedIndexChanged(object sender, EventArgs e)
{
int selectedRow1 = grdActions.SelectedRow.RowIndex;
hdnIndexNo.Value = grdActions.Rows[selectedRow1].Cells[1].Text;
ddlActionType.SelectedValue = grdActions.Rows[selectedRow1].Cells[3].Text;
if (grdActions.Rows[selectedRow1].Cells[4].Text == null || grdActions.Rows[selectedRow1].Cells[4].Text == string.Empty || grdActions.Rows[selectedRow1].Cells[4].Text == " ")
{
txtDetails.Text = string.Empty;
}
else
{
txtDetails.Text = grdActions.Rows[selectedRow1].Cells[4].Text;
}
if (grdActions.Rows[selectedRow1].Cells[5].Text == null || grdActions.Rows[selectedRow1].Cells[5].Text == string.Empty || grdActions.Rows[selectedRow1].Cells[5].Text == " ")
{
txtCompletedDate.Text = string.Empty;
}
else
{
txtCompletedDate.Text = Convert.ToDateTime(grdActions.Rows[selectedRow1].Cells[5].Text).ToString("dd-MMM-yyyy");
}
ddlActionOwner.SelectedValue = grdActions.Rows[selectedRow1].Cells[7].Text;
if (grdActions.Rows[selectedRow1].Cells[8].Text == null || grdActions.Rows[selectedRow1].Cells[8].Text == string.Empty || grdActions.Rows[selectedRow1].Cells[8].Text == " ")
{
txtAssignedTo.Text = string.Empty;
}
else
{
txtAssignedTo.Text = grdActions.Rows[selectedRow1].Cells[8].Text;
}
if (grdActions.Rows[selectedRow1].Cells[9].Text == null || grdActions.Rows[selectedRow1].Cells[9].Text == string.Empty || grdActions.Rows[selectedRow1].Cells[9].Text == " ")
{
lblComments.Visible = false;
txtComments.Visible = false;
}
else
{
lblComments.Visible = true;
txtComments.Visible = true;
txtComments.Text = grdActions.Rows[selectedRow1].Cells[9].Text;
}
I used the Server.HTMLDecode() when transferring the data fromthe gridview to the textboxes. This ensured that all special characters were removed before it was sent back to the textboxes on the form
I have a problem here because my coding is not working(error) and I don't know how to correct it.Can you guys check if this statement right or wrong? My conditions is
1)if textbox productname is null or empty and dropdownlist1 not selected, text will null.
2)if textbox productname is filled(string) then text will filled in
3)if if textbox productname is null or empty and dropdownlist1 selected, text will select value.
Refer bold text.THANKS!!
if (String.IsNullOrEmpty(txtSearchProductname.Text) == true)
{
if (**DropDownList1.SelectedValue.ToString == null**)
{
txtSearchProductname.Text = " ";
}
else
{
SqlProductmaster.InsertParameters["ProductName"].DefaultValue = DropDownList1.SelectedValue.ToString();
}
}
else
{
SqlProductmaster.InsertParameters["ProductName"].DefaultValue = txtProductName.Text.ToString();
}
Two issues:
You have ToString, not ToString(). ToString refers to the function itself; you need the parentheses to invoke the method
You should not be calling ToString() at all, since the value may be null; this will generate a NullReferenceException. Just check if DropDownList1.SelectedValue == null.
This should be all you need:
if (String.IsNullOrEmpty(txtSearchProductname.Text))
{
if (DropDownList1.SelectedValue == null)
{
txtSearchProductname.Text = " ";
}
else
{
SqlProductmaster.InsertParameters["ProductName"].DefaultValue = DropDownList1.SelectedValue;
}
}
else
{
SqlProductmaster.InsertParameters["ProductName"].DefaultValue = txtProductName.Text;
}
.ToString is a method. You want to check the result of calling that method, so you need to call it (hence, .ToString()).
You don't need that many ToString. If DropDownList1.SelectedValue is null, then DropDownList1.SelectedValue.ToString() will throw an exception.
if (string.IsNullOrEmpty(txtSearchProductname.Text) == true)
{
if (DropDownList1.SelectedValue == null)
{
txtSearchProductname.Text = " ";
}
else
{
SqlProductmaster.InsertParameters["ProductName"].DefaultValue = DropDownList1.SelectedValue;
}
}
else
{
SqlProductmaster.InsertParameters["ProductName"].DefaultValue = txtProductName.Text;
}
The first thing I see is that you have a ToString method without the parenthesis. It should look like this:
if (DropDownList1.SelectedValue.ToString() == null)
As others have pointed out, the second issue is the comparison to null after converting the item to a string. Converting a null to a string will cause an error (the string representation of a null doesn't exist). Instead, as they indicated, you should remove the ToString() entirely and compare the SelectedValue to null like so:
if (DropDownList1.SelectedValue == null)
You are using the SelectedValue of the DropDownList with a ToString() which is not needed. See below.
if (String.IsNullOrEmpty(txtSearchProductname.Text) == true)
{
if (string.IsNullOrEmpty(DropDownList1.SelectedValue))
{
txtSearchProductname.Text = " ";
}
else
{
SqlProductmaster.InsertParameters["ProductName"].DefaultValue = DropDownList1.SelectedValue;
}
}
else
{
SqlProductmaster.InsertParameters["ProductName"].DefaultValue = txtProductName.Text.ToString();
}
HTH