I have a piece of code, in which I set true or false depending upon the conditions.
Below is that code
public bool HackerTextExistOrNot(string text)
{
bool flgValid = false;
var attackChars = new char[] { '=', '+', '-', '#' };
if(attackChars.Contains(text[0]))
{
flgValid = false;
}
else
{
flgValid = true;
}
return flgValid;
}
I have checked for both the bool conditions, but it always goes in strReturnId in main function.
Below is the code.
public static string SaveRecord(RRSOCSaving RRSOCSaving, string Indication)
{
string strReturnId = "";
string strAppURL = ConfigurationManager.AppSettings["AppUrl"].ToString();
string strmail_Content = "";
CommonDB commonObj = new CommonDB();
GET_DATA_BY_STORE objGetData = new GET_DATA_BY_STORE();
try
{
if (objGetData.HackerTextExistOrNot(RRSOCSaving.STORE_CODE) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.STATE) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.CITY) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.SITE_STORE_FORMAT) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.STORE_SITENAME) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.STORE_SITENAME_LANDL_1) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.STORE_SITENAME_LANDL_2) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.STORE_ASST_MANAGER_NAME) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.STORE_ASST_MANAGER_MOBNO) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.STORE_MANAGER_NAME) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.MANAGER_MOBNO) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.EMP_NEAREST_STORE) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.EMP_NEAREST_STORE_MOBNO) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.SUPERVISOR_NAME) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.SUPERVISOR_MOBNO) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.SECURITY_SUP_NAME_STORE) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.SECURITY_SUP_MOBNO_STORE) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.NAME_ALIGNED_LPO) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.LPO_MOBILENO) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.ALPM_ALPO_NAME) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.ALPM_ALPO_MOBNO) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.AREA_MANAGER_NAME) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.AREA_MANAGER_MOBNO) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.ZONAL_HEAD_NAME) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.ZONAL_HEAD_NO) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.DVR_IP_ADDRESS) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.SIGNET_IP_ADDRESS) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.NEAREST_POLICE_STN_NAME) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.NEAREST_POLICE_STN_CONTNO) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.NEAREST_HOSP_NAME) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.NEAREST_HOSP_CONTNO) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.NEAREST_FIRE_STN_CONTNAME) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.NEAREST_FIRE_STN_CONTNO) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.STORE_ADDRESS) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.STORE_SPACE_SQFT) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.LAUNCH_DATE) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.CST_TIN_NO) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.STORE_EMAILID) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.NO_OF_POS) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.NO_OF_CAMERA) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.DVR_MODEL_GESECURITY) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.CAMERA_MODEL) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.ALIGNED_LPO_MAILDID) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.FACILTY_TEAMNAME) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.FACILITY_TEAMNO) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.STATE_HEAD_OPS_NAME) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.STATE_HEAD_OPS_NO) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.LPA) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.SLP_STATE_HEAD) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.SLP_STATE_HEAD_NO) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.UserName) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.CREATED_DATE) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.UserName) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.LAST_UPDATED_DATE) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.ISACTIVE) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.LATITUDE) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.LONGITUDE) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.SLP_EMAILID) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.ZONAL_ECNUMBER) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.ZONAL_NAME) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.SLP_STATE_ECNUMBER) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.ALPM_ALPO_ECNUMBER) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.IS_STORE_IN_MALL) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.MALL_CONTROL_ROOM_NO) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.IS_NIGHT_SEC_GUARD_AVAIL) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.NIGHT_SEC_GUARD_NAME) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.NIGHT_SEC_GUARD_NO) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.IS_NIGHT_PATROL_PARTY_AVAIL) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.PATROL_PARTY_NAME) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.PATROL_PARTY_NO) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.ALPM_ALPO_EMAILID) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.ALIGNED_LPO_ECNUMBER) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.SLP_STATE) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.FORMAT_GROUP) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.ALPM_NAME) ||
objGetData.HackerTextExistOrNot(RRSOCSaving.ALPM_ECNUMBER))
{
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";
}
}
}
catch (Exception)
{
throw;
}
return strReturnId;
}
UPDATE I mean to say always in
strReturnId = "Something went wrong due to malicious script attack..!!!";
It seems like your
HackerTextExistOrNot
method returns true when hacker text does NOT exist. Instead of using flgValid just return attackChars.Contains(text[0]) and it should be working correctly.
One more thing - you are creating table each time entering this method, you might consider refactoring this code.
Related
When the check against the emailaddress is added to the if statement, as per below, the if statement if (origin.Equals(true)).
bool origin = false;
Contact contact = item as Contact;
foreach (Item subItem in contactItems)
{
Contact subcontact = subItem as Contact;
if ((contact.DisplayName.Equals(subcontact.DisplayName) || (contact.DisplayName is null && subcontact.DisplayName is null)) && ((contact.CompanyName is null && subcontact.CompanyName is null) || (contact.CompanyName.Equals(subcontact.CompanyName)) && ((contact.EmailAddresses[EmailAddressKey.EmailAddress1] is null && subcontact.EmailAddresses[EmailAddressKey.EmailAddress1] is null) || (contact.EmailAddresses[EmailAddressKey.EmailAddress1].Equals(subcontact.EmailAddresses[EmailAddressKey.EmailAddress1])))))
{
if (origin.Equals(true))
{
try
{
Console.WriteLine(contact.DisplayName + " " + subcontact.DisplayName);
Console.WriteLine(contact.EmailAddresses[EmailAddressKey.EmailAddress1]);
subcontact.Delete(DeleteMode.HardDelete);
}
catch
{
Console.WriteLine("Cannot delete" + " " + subcontact.DisplayName);
}
}
origin = true;
}
}
If I remove the if (origin.Equals(true)) or removed && ((contact.EmailAddresses[EmailAddressKey.EmailAddress1] is null && subcontact.EmailAddresses[EmailAddressKey.EmailAddress1] is null) || (contact.EmailAddresses[EmailAddressKey.EmailAddress1].Equals(subcontact.EmailAddresses[EmailAddressKey.EmailAddress1])) from the other if statement, the contact goes through the try-catch block.
Can anyone see why?
if ((contact.DisplayName.Equals(subcontact.DisplayName) || (contact.DisplayName is null && subcontact.DisplayName is null)) && ((contact.CompanyName is null && subcontact.CompanyName is null) || (contact.CompanyName.Equals(subcontact.CompanyName)) && ((contact.EmailAddresses[EmailAddressKey.EmailAddress1] is null && subcontact.EmailAddresses[EmailAddressKey.EmailAddress1] is null) || (contact.EmailAddresses[EmailAddressKey.EmailAddress1].Equals(subcontact.EmailAddresses[EmailAddressKey.EmailAddress1])))))
should be:
if ((contact.DisplayName.Equals(subcontact.DisplayName) || (contact.DisplayName is null && subcontact.DisplayName is null)
&& ((contact.CompanyName is null && subcontact.CompanyName is null) || (contact.CompanyName.Equals(subcontact.CompanyName))
&& ((contact.EmailAddresses[EmailAddressKey.EmailAddress1] is null && subcontact.EmailAddresses[EmailAddressKey.EmailAddress1] is null) || (contact.EmailAddresses[EmailAddressKey.EmailAddress1].Equals(subcontact.EmailAddresses[EmailAddressKey.EmailAddress1])))
the problem as I can see, is in the amount of ( ) you use, which I believe is incorrect.
Try to clean up your if statements to prevent these types of mistakes from happening, since this one was pretty long, and a few of your parenthesis are unnecessary
EDIT:
I tried running some code and it works. I did make some mistakes in the sample of the IF statement I mentioned above.. Maybe try copying my code, and substituting your specific code into it. It should work this way.
public static void Main()
{
bool origin = false;
int[] t = {0,4,6,8,5,6,4,5};
foreach(int i in t){
if ((true || (true && true)) // if ((contact.DisplayName.Equals(subcontact.DisplayName) || (contact.DisplayName is null && subcontact.DisplayName is null))
&& ((true && true) || (true)) // && ((contact.CompanyName is null && subcontact.CompanyName is null) || (contact.CompanyName.Equals(subcontact.CompanyName)))
&& ((true && true) || (true))) // && ((contact.EmailAddresses[EmailAddressKey.EmailAddress1] is null && subcontact.EmailAddresses[EmailAddressKey.EmailAddress1] is null) || (contact.EmailAddresses[EmailAddressKey.EmailAddress1].Equals(subcontact.EmailAddresses[EmailAddressKey.EmailAddress1])))))
{
if (origin.Equals(true))
{
try
{
Console.WriteLine("here");
}
catch
{
Console.WriteLine("Cannot delete" );
}
}
origin = true;
}
}
}
I suggest a little Helper:
private bool EqualOrBothNull( string fromContact, string fromSubcontact )
{
if ( fromContact == null && fromSubcontact == null ) return true;
if ( fromContact != null && fromContact.Equals(fromSubcontact) ) return true;
return false;
}
then you can use it like this:
if ( EqualOrBothNull( contact.DisplayName, subContact.DisplayName ) &&
EqualOrBothNull( contact.CompanyName, subContact.CompanyName ) &&
EqualOrBothNull( contact.EmailAddresses[EmailAddressKey.EmailAddress1],
subContact.EmailAddresses[EmailAddressKey.EmailAddress1])
)
{
// ...
}
This increases readability and will make it easier to find the bug if any.
Thanks for all the potential answers unfortunately they didn't fix the issue, the code is much easier to read though! In the end I separated the email address check to another IF statement which seems to be working
how to solve the error which contains operator '&&' cannot be applied to operands of type 'string' and 'string'. The code fallows as :
bool AttorneysData()
{
if (((txtFirstName.Text != "")
&& ((txtSurname.Text != "")
&& (txtAddress.Text
&& (txtTelNo.Text
&& (txtEmail.Text
&& (txtCreatePassword.Text
&& (txtConfirmPassword.Text
&& (cboDisciplineExpertise.Text
&& (cboGeographicalLocation.Text
&& (cboBudgetEstimation.Text
&& (txtNoofIndividuals.Text
&& (cboTypeofClients.Text
&& (txtCompanyName.Text && txtYearsofExperience.Text))))))))))))))
{
return true;
}
else
{
return false;
}
}
You need to use logical operators each time. IF you want to chack all strings to inequality to empty string then use String.IsNullOrEmpty() method instead of != operator.
Also there is no reason to use () in your expression. You need to use brackets to prioritize operations but in your code there is no prioritets conflict because all operations can executes successively from left to right.
Your if statement already contains logical expression that returns boolean result then you can swap it with return operator.
return String.IsNullOrEmpty(txtFirstName.Text)
&& String.IsNullOrEmpty(txtSurname.Text)
&& String.IsNullOrEmpty(txtAddress.Text)
&& String.IsNullOrEmpty(txtTelNo.Text)
&& String.IsNullOrEmpty(txtEmail.Text)
&& String.IsNullOrEmpty(txtCreatePassword.Text)
&& String.IsNullOrEmpty(txtConfirmPassword.Text)
&& String.IsNullOrEmpty(cboDisciplineExpertise.Text)
&& String.IsNullOrEmpty(cboGeographicalLocation.Text)
&& String.IsNullOrEmpty(cboBudgetEstimation.Text)
&& String.IsNullOrEmpty(txtNoofIndividuals.Text)
&& String.IsNullOrEmpty(cboTypeofClients.Text)
&& String.IsNullOrEmpty(txtCompanyName.Text)
&& String.IsNullOrEmpty(txtYearsofExperience.Text);
Every term (term1 && term2 && ...) of the if statement's condition has to resolve to a boolean (true/false) value
You could solve it this way:
bool AttorneysData()
{
if (txtFirstName.Text != ""
&& txtSurname.Text != ""
&& txtAddress.Text != ""
&& txtTelNo.Text != ""
&& txtEmail.Text != ""
&& txtCreatePassword.Text != ""
&& txtConfirmPassword.Text != ""
&& cboDisciplineExpertise.Text != ""
&& cboGeographicalLocation.Text != ""
&& cboBudgetEstimation.Text != ""
&& txtNoofIndividuals.Text != ""
&& cboTypeofClients.Text != ""
&& txtCompanyName.Text != ""
&& txtYearsofExperience.Text != "")
{
return true;
}
else
{
return false;
}
}
Or in a slightly more elegant way:
return txtFirstName.Text != ""
&& txtSurname.Text != ""
&& txtAddress.Text != ""
&& txtTelNo.Text != ""
&& txtEmail.Text != ""
&& txtCreatePassword.Text != ""
&& txtConfirmPassword.Text != ""
&& cboDisciplineExpertise.Text != ""
&& cboGeographicalLocation.Text != ""
&& cboBudgetEstimation.Text != ""
&& txtNoofIndividuals.Text != ""
&& cboTypeofClients.Text != ""
&& txtCompanyName.Text != ""
&& txtYearsofExperience.Text != "";
Also, consider using the string.IsNullOrEmpty method which will test for spaces and other empty characters:
return !string.IsNullOrEmpty(txtSurname.Text)
&& !string.IsNullOrEmpty(txtAddress.Text)
...
I have a list of YES/NO questions and each question has a radio button indicating the answer. When the user selects YES, a panel will be visible and it has textboxes inside it for the additional required input. When the user answers YES, they MUST fill in the textboxes that appear.
Currently I'm hard-coding it this way:
if (txtQ1Specify.Visible == true)
{
if (txtQ1Specify.Text.Length == 0)
{
lblError.Text = "Please answer all questions.";
}
}
if (txtQ2Specify.Visible == true)
{
if (txtQ2Specify.Text.Length == 0)
{
lblError.Text = "Please answer all questions.";
}
}
if (txtQ3Specify.Visible == true)
{
if (txtQ3Specify.Text.Length == 0)
{
lblError.Text = "Please answer all questions.";
}
}
if (txtQ4SpecifyCompany.Visible == true || txtQ4SpecifyRelative.Visible == true)
{
if (txtQ4SpecifyCompany.Text.Length == 0 || txtQ4SpecifyRelative.Text.Length == 0)
{
lblError.Text = "Please answer all questions.";
}
}
if (txtQ5SpecifyCompany.Visible == true || txtQ5SpecifyRelative.Visible == true)
{
if (txtQ5SpecifyCompany.Text.Length == 0 || txtQ5SpecifyRelative.Text.Length == 0)
{
lblError.Text = "Please answer all questions.";
}
}
if (txtQ6Specify.Visible == true)
{
if (txtQ6Specify.Text.Length == 0)
{
lblError.Text = "Please answer all questions.";
}
}
if (txtQ7Specify.Visible == true)
{
if (txtQ7Specify.Text.Length == 0)
{
lblError.Text = "Please answer all questions.";
}
}
After this checking I want to execute some code.
The page looks like this:
How can I check for textbox inputs based in visibility?
You could use LINQ to find out if there are any visible and empty TextBoxes like so:
var query =
from t in Page.Controls.OfType<TextBox>()
where t.Visible && t.Text == ""
select t;
bool hasUnanswered = query.Any();
This can be easily done on the client side .
First you need to identify which all text box are visible . For this you can use jquery Visible Selector
Now If more than one text box is visible . Show some message to the user and focus and highlight the text box which need to be filled .
$(document).ready(function(){
var visibleCount =$('input[type="text"]:visible').length;
if (visibleCount > 0)
{
// Add your logic here
}
});
I managed to do it using a very long if statement. Here goes nothing:
if ((pnlQ1Yes.Visible == true && txtQ1Specify.Text.Length == 0) ||
(pnlQ2Yes.Visible == true && txtQ2Specify.Text.Length == 0) ||
(pnlQ3Yes.Visible == true && txtQ3Specify.Text.Length == 0) ||
(pnlQ4Yes.Visible == true && (txtQ4SpecifyCompany.Text.Length == 0 || txtQ4SpecifyRelative.Text.Length == 0)) ||
(pnlQ5Yes.Visible == true && (txtQ5SpecifyCompany.Text.Length == 0 || txtQ5SpecifyRelative.Text.Length == 0)) ||
(pnlQ6Yes.Visible == true && txtQ6Specify.Text.Length == 0) ||
(pnlQ7Yes.Visible == true && txtQ7Specify.Text.Length == 0))
{
lblError.Text = "Please answer all questions.";
}
else
{
...
}
It first checks if the panel is visible, then it checks the textbox inside the panel for values. Then I repeat this kind of checking for the rest of the panels and textboxes.
On the text box, it should allow the user to enter only six decimal places. For example, 1.012345 or 1,012345.
If seven decimal places are tried, the entry should not be allowed.
Please refer to the below code.
private void textBox1_KeyDown_1(object sender, KeyEventArgs e)
{
bool numericKeys = (
( ((e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9) ||
(e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9)) &&
e.Modifiers != Keys.Shift) ||
e.KeyCode == Keys.OemMinus ||
e.KeyCode == Keys.OemPeriod ||
e.KeyCode == Keys.Decimal ||
e.KeyCode == Keys.Oemcomma
);
bool navigationKeys = (
e.KeyCode == Keys.Up ||
e.KeyCode == Keys.Right ||
e.KeyCode == Keys.Down ||
e.KeyCode == Keys.Left ||
e.KeyCode == Keys.Home ||
e.KeyCode == Keys.End ||
e.KeyCode == Keys.Tab);
bool editKeys = (e.KeyCode == Keys.Delete ||
e.KeyCode == Keys.Back);
TextBox aTextbox = (TextBox)sender;
aTextbox.Text = "2,33333";
if (!string.IsNullOrEmpty(aTextbox.Text))
{
double maxIntensity;
string aTextValue = aTextbox.Text;
bool value = double.TryParse(aTextValue,
NumberStyles.Any,
CultureInfo.InvariantCulture.NumberFormat,
out maxIntensity);
if (value)
{
string aText = maxIntensity.ToString();
MessageBox.Show("the value is {0}", aText);
string[] args = aText.Split('.');
if (numericKeys)
{
bool handleText = true;
if (args.Length > 2)
{
handleText = false;
}
else
{
if (args.Length == 2 && args[1] != null && args[1].Length > 5)
{
handleText = false;
}
}
if (!handleText)
{
e.SuppressKeyPress = true;
e.Handled = true;
}
}
}
}
if (!(numericKeys || editKeys || navigationKeys))
{
e.SuppressKeyPress = true;
e.Handled = true;
}
}
To achieve the culture neutrality, the text value is converted to double first and then
the double value is converted to string.
bool value = double.TryParse(aTextValue,
NumberStyles.Any,
CultureInfo.InvariantCulture.NumberFormat,
out maxIntensity);
if (value)
{
string aText = maxIntensity.ToString();
}
Splitting the strings to separate the real part and mantissa part (both are stored are strings), then I check the length of the mantissa part. If the length of the string is more than 5, I'd like to suppress the key.
Is there aother approach to do this?
I've had luck with code similar to the following:
public class RegexMaskedTextBox : TextBox
{
private Regex _regex = new Regex(string.Empty);
public string RegexPattern
{
get { return _regex.ToString(); }
set { _regex = new Regex(value); }
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
string sNewText = this.Text;
string sTextToInsert = e.KeyChar.ToString();
if (this.SelectionLength > 0)
{
sNewText = this.Text.Remove(this.SelectionStart, this.SelectionLength);
}
sNewText = sNewText.Insert(this.SelectionStart, sTextToInsert);
if (sNewText.Length > this.MaxLength)
{
sNewText = sNewText.Substring(0, this.MaxLength);
}
e.Handled = !_regex.IsMatch(sNewText);
base.OnKeyPress(e);
}
}
I think I would solve this by using regular expressions. On the key down event you can check the regex.
Maybe you want to check this out: Regular expression for decimal number
I have the following code on an asp.net button click
if(str == ipaddr1 || ipaddr2 || ipaddr3 || ipaddr4 || ipaddr5 || ipaddr6 || ipaddr7)
// do this
else
//cancel click event
How can I optimize this piece of code?
Update: Apologies everyone! I did not mean to compare it with the literal string ipaddr. I mean to compare it to the value ipaddr1, ipaddr2 holds and so on
replace with:
Regex.IsMatch(str, "^ipaddr[1-7]$")
Optimised for readability not necessarily performance.
HashSet<T> is the best container to check containing:
var ips = new HashSet<string> { "ip1", "ip2", "ip3", "ip4", "ip5" };
if (ips.Contains(input))
{
// do stuff
}
For any type:
var ips = new HashSet<IPHostEntry> { ip1, ip2, ip3, ip4, ip5 };
if (ips.Contains(input))
{
// do stuff
}
Was:
if(str = qry.StartsWith("23.55") || str = qry.StartsWith("xuz") || str = qry.StartsWith("i3") || str = qry.StartsWith("i444") || str = qry.StartsWith("ki5") || str = qry.StartsWith("65fr6")) // do this else // do this
Become:
var arr = new[] { "23.55", "xuz", "i3", "i444", "ki5", "65fr6") };
if (arr.Any(str => input.StartsWith(str, StringComparison.Ordinal))
{
// do stuff
}
StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase are very important for performance.
What about
if(str.Substring(0,6) == "ipaddr" && str[6] >= '1' && str[6] <= '7')
For your information, your original code does not even compile. This
if(str == "ipaddr1" || "ipaddr2" || "ipaddr3" || "ipaddr4" || "ipaddr5" || "ipaddr6" || "ipaddr7")
Needs to be replaced with this to compile
if(str == "ipaddr1" || str == "ipaddr2" || str == "ipaddr3" || str == "ipaddr4" || str == "ipaddr5" || str == "ipaddr6" || str == "ipaddr7")
So the original code is actually even more tedious than you thought.
UPDATE
According to your updated question, the best option is to put your string variables into a List<string> called, for example ipaddr. Then to see if the string str is included, simply do this:
if( ipaddr.Contains( str ) )
{
//contained in the list
}
I would do something like:
str.Length == 7 && str.StartsWith("ipaddr") && str[6] > '0' && str[6] < '8'
Edit:
After your update, I would do something like:
string[] validStrings = { ipaddr1, ipaddr2, ... };
bool isStrValid = validStrings.Contains(str);
For better performance, consider using a HashSet<string> instead of an array, especially if the list of valid strings doesn't change.
Both more readable, and more performant would be:
switch(str)
{
case "ipaddr1":
case "ipaddr2":
case "ipaddr3":
case "ipaddr4":
case "ipaddr5":
case "ipaddr6":
case "ipaddr7":
//do something
break;
default:
//do something else
break;
}
(although, admittedly massively verbose...)
I would do a
List<string> variables = new List<string> { "ip1","ip2","ip3","ip4","ip5" };
if (variables.Contains(inputstring))
...