Hello please help me out in writing switch statement for the below else if statement
if(ClientAddressTextBox.Text == "")
{
MessageBox.Show("Please Enter Client Address");
this.ActiveControl = ClientAddressTextBox;
}
else if (InnerpathTextBox.Text == "")
{
MessageBox.Show("Please Enter Internal Path");
this.ActiveControl = InnerpathTextBox;
}
else if (InspectorIDTextBox.Text == "")
{
MessageBox.Show("Please Enter Inspector ID");
this.ActiveControl = InspectorIDTextBox;
}
else if (SerialNumberTextBox.Text == "")
{
MessageBox.Show("Please Enter Serial Number");
this.ActiveControl = SerialNumberTextBox;
}
You could do something like this:
var controls = new []
{
new {Ctrl = InnerpathTextBox, Error = "Please Enter Client Address"},
new {Ctrl = ClientAddressTextBox, Error = "Please Enter Internal Path"},
new {Ctrl = InspectorIDTextBox, Error = "Please Enter Inspector ID"},
new {Ctrl = SerialNumberTextBox, Error = "Please Enter Serial Number"}
};
var firstToFailValidation = controls.FirstOrDefault(item => item.Ctrl.Text == "");
if (firstToFailValidation != null)
{
MessageBox.Show(firstToFailValidation.Error);
this.ActiveControl = firstToFailValidation.Ctrl;
}
You might want to check for nulls though. This code assumes that none of the controls or the .Text properties are null.
I'd approach this as follows:
var validationMessages = new[]{new{Control = InnerpathTextBox,
Message = "Please Enter Internal Path"},
new{Control = InspectorIDTextBox,
Message = "Please Enter Inspector Id"},
//etc
};
foreach(var vm in validationMessages)
{
if(string.IsNullOrWhiteSpace(vm.Control.Text))
{
MessageBox.Show(vm.Message);
this.ActiveControl = vm.Control;
break;
}
}
You can use Something like this:
private bool IfTextBoxEmpty(string text, string message, Control control)
{
if (text == "")
{
MessageBox.Show(message);
this.ActiveControl = control;
return true;
}
return false;
}
And the Usage:
if (!IfTextBoxEmpty(ClientAddressTextBox.Text, "Please Enter Client Address", ClientAddressTextBox)
{
//if not - Do Something
}
This is a pseudo code for a switch statement.
string statement;
switch(statement)
{
case (ClientAddressTextBox.Text == ""):
MessageBox.Show("Please Enter Client Address");
this.ActiveControl = ClientAddressTextBox;
break;
case (InnerpathTextBox.Text == ""):
...
}
and so on.
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])
{
}
How to re enter a string in text box if string doesn't match?
code I'm trying is but it stucks in loop and does not allow me to enter string again in textbox.
Can anybody guide me how to do this
the code is:
public void userpass()
{
int us = 0; //for user pass
string readText2 = File.ReadAllText(pathuser);
using (StreamReader sr2 = new StreamReader(pathuser))
{
string usernam = username.Text;
string line;
string[] lines = new String[500];
while ((line = sr2.ReadLine()) != null )
{
lines[us] = line;
if (lines[us] == usernam && usernam != "")
{
check = 1;
MessageBox.Show(usernam);
Form2 f2 = new Form2();
this.Hide();
break;
}
us++;
}
if (lines[us-1] != usernam && usernam != null)
{
this.DialogResult = DialogResult.None;
DialogResult result = new DialogResult();
result = MessageBox.Show("Invalid Username or Password?", "Retry", MessageBoxButtons.OK);
if (result == DialogResult.OK)
{
username.Clear();
}
}
}
Okay so i think your problem is mostly checking if the value exist in the file. You can use this function to check if it exist or not and then you can do what you need :
public bool findValueInFile(string filePath, string value)
{
//Get all lines from the txt file
string[] lines = File.ReadAllLines(filePath);
//Go thru all the lines
foreach(string line in lines)
{
//If we find the line we're looking for
if (line.Equals(value))
{
return true;
}
}
//If we haven't found anything return false
return false;
}
After calling this function depending on the return you can show a messagebox or do something else :
if(findValueInFile(yourPath, yourValue))
{
// We found the value
}
else
{
// We didn't find the value
}
i want to display error message without alert box by using javascript.
i have tried with code.
function validatetextbox() {
var txtuname = document.getElementById('<%=txt_uname.ClientID %>').value;
if(txtuname=="") {
document.getElementById("text_uname").innerHTML= "Enter Username"; } }
but it is not working, please give some suggestions
You need to use document.getElementById('<%=txt_uname.ClientID %>') instead of document.getElementById("text_uname")
Complete function
function validatetextbox() {
var txtuname = document.getElementById('<%=txt_uname.ClientID %>').value;
if (txtuname == "") {
document.getElementById('<%=txt_uname.ClientID %>').innerHTML = "Enter Username";
}
}
try to cache dom, and set innerHTML
function validatetextbox() {
var inputEl = document.getElementById('<%=txt_uname.ClientID %>'),
txtuname = inputEl.value;
if ( txtuname == "" ) {
inputEl.innerHTML = "Enter Username";
}
}
It seems like you need to show alert in txt_uname .. then you should do like this:
function test(){
var txtuname =document.getElementById('<%=txt_uname.ClientID %>').value;
if(txtuname == "") {
document.getElementById('<%=txt_uname.ClientID %>').value= "Enter Username";
}
}
try this
function test()
{
var row = lnk.parentNode.parentNode;
var txtuname= row.cells[your cell number].childNodes[your node number].innerHTML;
if(txtuname=="")
{
txtuname="enter username";
}
}
here is what i am trying to do, i am using LinQ data context to insert new record to database,
for some reason, my linq showing this error "LinqDataSource 'AirAsiaDC' has no values to insert. Check that the 'values' dictionary contains values." weird part, when i check the record which i tried to insert before, it is there. what i do wrong here?
by the way, here is my code :
protected void DetailsView1_ItemCommand(object sender,
DetailsViewCommandEventArgs e)
{
AirAsiaDCDataContext Linq = new AirAsiaDCDataContext();
try
{
if (e.CommandName == "Edit")
{
TextBox tbname = (TextBox)DetailsView1.FindControl("DeptName");
department dpt;
if ((tbname.Text != null) && (tbname.Text != ""))
{
dpt = Linq.departments.Single(d => d.departmentcode == code);
dpt.departmentname = tbname.Text;
dpt.updateby = "hendra";
dpt.lastupdate = DateTime.Now;
Linq.SubmitChanges();
Response.Redirect("Department.aspx");
}
else
{
divError.Visible = true;
lblError.Text = "Department name can not be empty";
}
}
else if (e.CommandName == "Insert")
{
TextBox tbcode = (TextBox)DetailsView1.FindControl("DeptCode");
TextBox tbname = (TextBox)DetailsView1.FindControl("DeptName");
department dpt = new department();
if (((tbcode.Text != null) && (tbcode.Text != ""))
&& ((tbname.Text != null) && (tbname.Text != "")))
{
dpt.departmentcode = tbcode.Text;
dpt.departmentname = tbname.Text;
dpt.createby = "hendra";
dpt.createdate = DateTime.Now;
dpt.updateby = "hendra";
dpt.lastupdate = DateTime.Now;
Linq.departments.InsertOnSubmit(dpt);
Linq.SubmitChanges();
}
else if ((tbcode.Text == null) || (tbcode.Text == ""))
{
divError.Visible = true;
lblError.Text = "Department code can not be empty";
}
else if ((tbname.Text == null) || (tbname.Text == ""))
{
divError.Visible = true;
lblError.Text = "Department name can not be empty";
}
}
}
catch (Exception ex)
{
divError.Visible = true;
lblError.Text = ex.Message.ToString();
}
}
i even try to use try and catch but get nothing, and my linq keep on showing that error and throw me to error screen.
I have the following JavaScript function. I have two textboxes, two hiddenfields and two labels. and a button. On the click of a button I am calling this function.
On typing value in the textbox, It shows an autoCompleteList. On picking a value from this, it fetches the value from DB and fills the corresponding label. Also, at the same time it stores the corresponding selected value in hiddenfield.
Whenever one changes the value in textbox and without selecting the value from autoPopulated list, It must show the alert.
The function is working fine, If I fill a single textbox, but when I fill both, It goes to the Point A, instead of showing the alert of Point B
function ConfirmBox()
{
var txtBoxValue = document.getElementById("<%= txtFromPartNumber.ClientID %>").value;
var txtBoxValue1 = document.getElementById("<%= txtToPartNumber.ClientID %>").value;
var release = document.getElementById("<%= lblFromPartNumber.ClientID %>").innerText;
var release1 = document.getElementById("<%= lblToPartNumber.ClientID %>").innerText;
var hdnFromValueID = "<%= hdnFromReleaseNumber.ClientID %>";
var hdnToValueID = "<%= hdnToReleaseNumber.ClientID %>";
if ((txtBoxValue && txtBoxValue.trim() != "" && release))
{
if (document.getElementById(hdnFromValueID).value.trim() == txtBoxValue.trim())
{
if ((txtBoxValue1 && txtBoxValue1.trim() != "" && release1))
{
if (document.getElementById(hdnToValueID).value.trim() == txtBoxValue1.trim())
{
return true; //Point A
}
else
{// Point B
//alert("To Part no. has been changed. Please enter it again.");
var msg = document.getElementById("alertMessage");
msg.innerHTML = "To Part no. has been changed. Please enter it again.";
var myExtender = $find("ctl00_ContentPlaceHolder1_ModalPopupExtenderAlert");
myExtender.show();
document.getElementById("<%= txtToPartNumber.ClientID %>").focus();
return false;
}
}
else
{
//window.alert("Please choose a Valid To Part number");
var msg = document.getElementById("alertMessage");
msg.innerHTML = "Please choose a Valid To Part number.";
var myExtender = $find("ctl00_ContentPlaceHolder1_ModalPopupExtenderAlert");
myExtender.show();
return false;
}
}
else
{
//alert("From Part no. has been changed.Please enter it again.");
var msg = document.getElementById("alertMessage");
msg.innerHTML = "From Part no. has been changed.Please enter it again.";
var myExtender = $find("ctl00_ContentPlaceHolder1_ModalPopupExtenderAlert");
myExtender.show();
document.getElementById("<%= txtFromPartNumber.ClientID %>").focus();
return false;
}
}
else
{
//window.alert("Please choose a Valid From Part number");
var msg = document.getElementById("alertMessage");
msg.innerHTML = "Please choose a Valid From Part Number.";
var myExtender = $find("ctl00_ContentPlaceHolder1_ModalPopupExtenderAlert");
myExtender.show();
return false;
}
}