How To Use Nested Ternary Operator In C#? - c#

Here i have used if , else if condition to show an error message and make some label visible and invisible, but i am trying to use ternary operator to do so but i am quite unfamiliar with ternery operator and unable to use it for all condition i have in my if else code.
So any help with my code will be highly appreciated. Thank you.
Below is my code
catch (Exception ex)
{
if (ex.Message == "Parent Menu Title Required")
{
metroLabel4.Visible = true;
metroLabel5.Visible = false;
metroLabel6.Visible = false;
metroLabel4.Text = ex.Message;
}
else if (ex.Message == "Menu Title Required")
{
metroLabel4.Visible = false;
metroLabel5.Visible = true;
metroLabel6.Visible = false;
metroLabel5.Text = ex.Message;
}
else if (ex.Message == "Form Name Required")
{
metroLabel4.Visible = false;
metroLabel5.Visible = false;
metroLabel6.Visible = true;
metroLabel6.Text = ex.Message;
}
else
{
metroLabel4.Visible = true;
metroLabel5.Visible = true;
metroLabel6.Visible = true;
metroLabel4.Text = "Parent Menu Title Required";
metroLabel5.Text = "Menu Title Required";
metroLabel6.Text = "Form Name Required";
}
}

The ternary operator is not a good fit for your problem. It is used to set the value of one variable to one of two values, based on a predicate:
var thingToSet = predicateA ?
ifPredicateAIsTrue :
ifPredicateAIsFalse;
This is the same as:
if (predicateA)
thingToSet = ifPredicateAIsTrue;
else
thingToSet = ifPredicateAIsFalse;
To nest ternary expressions, place a new ternary expression in the value to set:
var otherThingToSet = predicateB ? (
predicateC ?
ifPredicateCIsTrue :
ifPredicateCIsFalse
) : (
predicateD ?
ifPredicateDIsTrue :
ifPredicateDIsFalse
);
This is equivalent to:
if (predicateB)
{
if (predicateC)
otherThingToSet = ifPredicateCIsTrue;
else
otherThingToSet = ifPredicateCIsFalse;
}
else
{
if (predicateD)
otherThingToSet = ifPredicateDIsTrue;
else
otherThingToSet = ifPredicateDIsFalse;
}
As you can see, this is not really a good fit for your problem, as you're trying to set the value of several variables, based on the exception message.
A better fit for your problem would be a switch statement:
switch (ex.Message)
{
case "Parent Menu Title Required":
metroLabel4.Visible = true;
metroLabel5.Visible = false;
metroLabel6.Visible = false;
metroLabel4.Text = ex.Message;
break;
case "Menu Title Required":
metroLabel4.Visible = false;
metroLabel5.Visible = true;
metroLabel6.Visible = false;
metroLabel5.Text = ex.Message;
break;
case "Form Name Required":
metroLabel4.Visible = false;
metroLabel5.Visible = false;
metroLabel6.Visible = true;
metroLabel6.Text = ex.Message;
break;
default:
metroLabel4.Visible = true;
metroLabel5.Visible = true;
metroLabel6.Visible = true;
metroLabel4.Text = "Parent Menu Title Required";
metroLabel5.Text = "Menu Title Required";
metroLabel6.Text = "Form Name Required";
break;
}

Your code is equivalent to:
const string ParMnuTitReq ="Parent Menu Title Required";
const string MnuTitReq ="Menu Title Required";
const string FrmNamReq ="Form Name Required";
string m = ex.Message;
metroLabel4.Visible = m != MnuTitReq && m != FrmNamReq;
metroLabel5.Visible = m != ParMnuTitReq && m != FrmNamReq;
metroLabel6.Visible = m != ParMnuTitReq && m != MnuTitReq;
// This can be done in the form designer
metroLabel4.Text = ParMnuTitReq;
metroLabel5.Text = MnuTitReq;
metroLabel6.Text = FrmNamReq;
You don't need ternary expressions. Instead, you can combine logical expressions. In the case of the Visible property which is of type bool, you can directly assign the result of the logical expression.
You can always assign the same text to the labels, as they won't be visible if the text does not apply. You could even drop the 3 last code lines and instead assign the text in the form designer. This reduces your original 23 lines of code (not counting lines with braces only) to 7.
Nested or chained ternary expressions can be used if you must be able to assign more than 2 different values.
string t = x == 1 ? "case 1" : x == 2 ? "case 2" : x == 3 ? "case 3" : "other case";
Is equivalent to
string t;
if (x == 1) {
t = "case 1";
} else if (x == 2) {
t = "case 2";
} else if (x == 3) {
t = "case 3";
} else {
t = "other case";
}

Related

CSV-injection in export functionality in asp.net application

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])
{
}

Checkbox and radio doesn't work as expected when checking

I have application where i am trying to make checkbox checked based on value i get from string. String name is called aktivan and returns values Da or Ne, i checked with messagebox and values are here and valid. If value are Da it need to check checkbox but it doesn't work.
chkAktivan.Checked = aktivan == "Da" ? true : false; // doesn't work
chkAktivan.Checked = true; // working
chkAktivan.Checked = false; // working
Same is for radio, based on string values Muški or Ženski it need to set values but also does't working all time its checking Ženski radio.
if (spol == "Muški")
{
radioMuski.Checked = true;
radioZenski.Checked = false;
}
else
{
radioMuski.Checked = false;
radioZenski.Checked = true;
}
You should trim the values before using them, like this.
if (spol.Trim() == "Muški")
{
radioMuski.Checked = true;
radioZenski.Checked = false;
}
else
{
radioMuski.Checked = false;
radioZenski.Checked = true;
}
And also this.
chkAktivan.Checked = aktivan == "Da" ? true : false;
To this:
chkAktivan.Checked = aktivan.Trim() == "Da" ? true : false;
partial answer
For the first part of your question, regarding this line:
chkAktivan.Checked = aktivan == "Da" ? true : false;
Try changing it to:
chkAktivan.Checked = (aktivan == "Da" ? true : false);
OR MORE SIMPLY:
chkAktivan.Checked = "Da".Equals(aktivan);

How Can I use switch statement instead of too many else if

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.

jQuery running C# code after other codes

I have a click event on a button which runs some code which is in C# so I put my C# code in jQuery using #{...} however, codes in #{...} runs after other codes.
HTML Code:
<button type="submit" id="TestRegex" class="btn btn-default">Test Regex</button>
jQuery:
$("#TestRegex").click(function () {
#{
var testdata = Request["TestData"];
var expression = Request["RegexPattern"];
string regexMatchResult = "No Match";
string dateMatchResult = "No Match";
if (!string.IsNullOrEmpty(testdata) || !string.IsNullOrEmpty(expression))
{
bool regexMatch =
System.Text.RegularExpressions.Regex.IsMatch(testdata, expression, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
bool dateMatch = false;
foreach (var item in System.Text.RegularExpressions.Regex.Matches(testdata, expression))
{
dateMatch = string.Compare(item.ToString(), testdata, true) == 0;
}
regexMatchResult = regexMatch ? "RegEx Match" : "No Match";
dateMatchResult = dateMatch ? "Date Matches" : "No Match";
}
}
$('#RegExMatch').text("#regexMatchResult"); //
$('#DateMatchResult').text("#dateMatchResult"); // These codes are run before codes above
});
this part should be at the top
#{
var testdata = Request["TestData"];
var expression = Request["RegexPattern"];
string regexMatchResult = "No Match";
string dateMatchResult = "No Match";
if (!string.IsNullOrEmpty(testdata) || !string.IsNullOrEmpty(expression))
{
bool regexMatch =
System.Text.RegularExpressions.Regex.IsMatch(testdata, expression, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
bool dateMatch = false;
foreach (var item in System.Text.RegularExpressions.Regex.Matches(testdata, expression))
{
dateMatch = string.Compare(item.ToString(), testdata, true) == 0;
}
regexMatchResult = regexMatch ? "RegEx Match" : "No Match";
dateMatchResult = dateMatch ? "Date Matches" : "No Match";
}
}
and then in Script tag
$(document).ready(function(){
$('#RegExMatch').text("#regexMatchResult"); //
$('#DateMatchResult').text("#dateMatchResult");
$("#TestData").text("#testdata ");
$("#RegexPattern").text("#expression ");
});

LinQ datasource showing this error "LinqDataSource 'AirAsiaDC' has no values to insert. Check that the 'values' dictionary contains values"

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.

Categories

Resources