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 ");
});
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 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";
}
I have created a regex function and called it when the data is being saved.
public static bool CheckSpecialCharacter(string value)
{
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(#"[~`!##$%^*()=|\{}';.,<>]");
if (regex.IsMatch(value))
{
return false;
}
else
{
return true;
}
}
Used here:
if (ClassName.CheckSpecialCharacter(txt_ExpName1.Text)==false)
{
lblErrMsg.Text = "Special characters not allowed";
return;
}
Now instead of writing "Special characters not allowed", I want to attach the 1st special character that was entered in the textbox, so
if # was entered, the message should be read as "Special character # not allowed"
Is it possible to do this? please help.Thanks.
Try following code.
public static string CheckSpecialCharacter(string value)
{
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(#"[~`!##$%^*()=|\{}';.,<>]");
var match = regex.Match(value);
if (match.Success)
{
return match.Value;
}
else
{
return string.empty;
}
}
usage:
var value = ClassName.CheckSpecialCharacter(txt_ExpName1.Text);
if (!string.IsNullOrEmpty(value ))
{
lblErrMsg.Text = value + " Special characters not allowed";
return;
}
OR you can do it by returning bool and adding one out parameter in the function, but i will not suggest that.. check this link
EDIT - To do the same thing in Javascript
function CheckSpecialCharacter(value)
{
var res = value.match(/[~`!##$%^*()=|\{}';.,<>]/g);
return res == null ? "" : res[0];
}
usage:
var value = CheckSpecialCharacter(document.getElementById("txt_ExpName1").value);
if(value != "")
{
document.getElementById("lblErrMsg").innerHTML = value + " Special characters not allowed";
}
Try this:
public static bool CheckSpecialCharacter(string value, out string character)
{
var regex = new System.Text.RegularExpressions.Regex(#"[~`!##$%^*()=|\{}';.,<>]");
var match = regex.Match(value);
character = regex.Match(value).Value;
return match.Length == 0;
}
and then
string character;
if (ClassName.CheckSpecialCharacter(txt_ExpName1.Text, out character) == false)
{
lblErrMsg.Text = character + " Special characters not allowed";
return;
}
You can just use the Matches(string) function from Regex to get the matches then check the first element like this :
var regex = new Regex(#"[~`!##$%^*()=|\{}';.,<>]");
var matches = regex.Matches("This contains # two b#d characters");
if (matches.Count > 0)
{
var firstBadCharacter = matches[0];
}
Then you can wrap the result of your check in an Exception :
throw new ArgumentException("Special character '" + firstBadCharacter + "' not allowed.");
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";
}
}
I have situation where I have a number of validators with the same error message on a page, when the page is validated these duplicates are shown in the validation summary.
I would like to remove these duplicates from the validation summary server side.
Here's some pseudo code of what I'd like to do.
validationSummery.ErrorMessages = validationSummery.ErrorMessages.DistinctBy(x=>x.ErrorText);
Having looked into the validation control it appears there is no access to the messages it displays.
I could iterate over all of the page validators which are invalid before the validation summary gets to them and set only one of each message type to valid but then I would not get the error message next to each control.
Does anyone know a way to do this?
It's not pretty but with the use of dotPeek to get the source for the ValidationSummary along with a bit of reflection I created a UniqueMessageValidationSummary control.
/// <summary>
/// Extended version of Validation Summary which overrides OnRender and re-implements get error
/// messages method to ensure the control only renders unique error messages.
///
/// Utilizes .NET code cleaned from .Peek and reflection to access subclass
/// </summary>
public class UniqueMessageValidationSummary : ValidationSummary
{
internal string[] GetErrorMessages(out bool inError)
{
var strArray = (string[])null;
inError = false;
var length = 0;
var validators = Page.GetValidators(ValidationGroup);
for (var index = 0; index < validators.Count; ++index)
{
var validator = validators[index];
if (!validator.IsValid)
{
inError = true;
if (validator.ErrorMessage.Length != 0)
++length;
}
}
if (length != 0)
{
strArray = new string[length];
var index1 = 0;
for (var index2 = 0; index2 < validators.Count; ++index2)
{
var validator = validators[index2];
if (!validator.IsValid && !string.IsNullOrEmpty(validator.ErrorMessage))
{
strArray[index1] = string.Copy(validator.ErrorMessage);
++index1;
}
}
}
var uniqueErrors = new List<string>();
if (strArray != null)
{
var objRegExp = new Regex("<(.|\n)+?>");
foreach (var error in strArray)
{
if (uniqueErrors.All(x => objRegExp.Replace(error, string.Empty) != objRegExp.Replace(x, String.Empty)))
{
uniqueErrors.Add(error);
}
}
}
return uniqueErrors.ToArray();
}
protected override void Render(HtmlTextWriter writer)
{
var renderUplevelCopy = true;
const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
var baseType = GetType().BaseType;
if (baseType != null)
{
var field = baseType.GetField("renderUplevel", flags);
if (field != null)
renderUplevelCopy = (bool)field.GetValue(this);
}
string[] strArray;
bool flag1;
if (DesignMode)
{
flag1 = true;
renderUplevelCopy = false;
strArray = new[]
{
"ValSummary_error_message_1",
"ValSummary_error_message_2"
};
}
else
{
if (!Enabled)
return;
bool inError;
strArray = GetErrorMessages(out inError);
flag1 = ShowSummary && inError;
if (!flag1 && renderUplevelCopy)
Style["display"] = "none";
}
if (Page != null)
Page.VerifyRenderingInServerForm(this);
var flag2 = renderUplevelCopy || flag1;
if (flag2)
RenderBeginTag(writer);
if (flag1)
{
string text1;
string str1;
string str2;
string text2;
string text3;
switch (DisplayMode)
{
case ValidationSummaryDisplayMode.List:
text1 = "b";
str1 = string.Empty;
str2 = string.Empty;
text2 = "b";
text3 = string.Empty;
break;
case ValidationSummaryDisplayMode.SingleParagraph:
text1 = " ";
str1 = string.Empty;
str2 = string.Empty;
text2 = " ";
text3 = "b";
break;
default:
text1 = string.Empty;
str1 = "<ul>";
str2 = "<li>";
text2 = "</li>";
text3 = "</ul>";
break;
}
if (HeaderText.Length > 0)
{
writer.Write(HeaderText);
WriteBreakIfPresent(writer, text1);
}
if (strArray != null)
{
writer.Write(str1);
foreach (var t in strArray)
{
writer.Write(str2);
writer.Write(t);
WriteBreakIfPresent(writer, text2);
}
WriteBreakIfPresent(writer, text3);
}
}
if (!flag2)
return;
RenderEndTag(writer);
}
private static void WriteBreakIfPresent(HtmlTextWriter writer, string text)
{
if (text == "b")
{
writer.WriteBreak();
}
else
writer.Write(text);
}
}