I'm using Asp.Net 2.0. I have a scenario where i need to check a user input against any of two ranges. For e.g. I need to check a textbox value against ranges 100-200 or 500-600. I know that i can hook up 2 Asp.Net RangeValidators to the TextBox, but that will try to validate the input against both the ranges, an AND condition,if you will. CustomValidator is an option, but how would I pass the 2 ranges values from the server-side. Is it possible to extend the RangeValidator to solve this particular problem?
[Update]
Sorry I didn't mention this, the problem for me is that range can vary. And also the different controls in the page will have different ranges based on some condition. I know i can hold these values in some js variable or hidden input element, but it won't look very elegant.
A CustomValidator should work. I'm not sure what you mean by "pass the 2 ranges values from the server-side". You could validate it on the server-side using a validation method like this:
void ValidateRange(object sender, ServerValidateEventArgs e)
{
int input;
bool parseOk = int.TryParse(e.Value, out input);
e.IsValid = parseOk &&
((input >= 100 || input <= 200) ||
(input >= 500 || input <= 600));
}
You will then need to set the OnServerValidate property of your CustomValidator to "ValidateRange", or whatever you happen to call it.
Is this the sort of thing you're after?
I do not believe this is possible using the standard RangeValidator control.
I did some searching and I believe your best solution is going to be to create your own CustomValidator control which you can include in your project to handle this scenario.
http://www.dotnetjunkies.ddj.com/Article/592CE980-FB7E-4DF7-9AC1-FDD572776680.dcik
You shouldn't have to compile it just to use it in your project, as long as you reference it properly.
You can use the RegularExpressionValidator with the ValidationExpression property set to
Edit: (whoops, 650 and 201 etc. were valid with the old pattern)
^(1\d{2}|200|5\d{2}|600)$
This will test the entered text for 100-200 and 500-600.
I extended the BaseValidator to achieve this. Its fairly simple once you understand how Validators work. I've included a crude version of code to demonstrate how it can be done. Mind you it's tailored to my problem(like int's should always be > 0) but you can easily extend it.
public class RangeValidatorEx : BaseValidator
{
protected override void AddAttributesToRender(System.Web.UI.HtmlTextWriter writer)
{
base.AddAttributesToRender(writer);
if (base.RenderUplevel)
{
string clientId = this.ClientID;
// The attribute evaluation funciton holds the name of client-side js function.
Page.ClientScript.RegisterExpandoAttribute(clientId, "evaluationfunction", "RangeValidatorEx");
Page.ClientScript.RegisterExpandoAttribute(clientId, "Range1High", this.Range1High.ToString());
Page.ClientScript.RegisterExpandoAttribute(clientId, "Range2High", this.Range2High.ToString());
Page.ClientScript.RegisterExpandoAttribute(clientId, "Range1Low", this.Range1Low.ToString());
Page.ClientScript.RegisterExpandoAttribute(clientId, "Range2Low", this.Range2Low.ToString());
}
}
// Will be invoked to validate the parameters
protected override bool ControlPropertiesValid()
{
if ((Range1High <= 0) || (this.Range1Low <= 0) || (this.Range2High <= 0) || (this.Range2Low <= 0))
throw new HttpException("The range values cannot be less than zero");
return base.ControlPropertiesValid();
}
// used to validation on server-side
protected override bool EvaluateIsValid()
{
int code;
if (!Int32.TryParse(base.GetControlValidationValue(ControlToValidate), out code))
return false;
if ((code < this.Range1High && code > this.Range1Low) || (code < this.Range2High && code > this.Range2Low))
return true;
else
return false;
}
// inject the client-side script to page
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (base.RenderUplevel)
{
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "RangeValidatorEx", RangeValidatorExJs(),true);
}
}
string RangeValidatorExJs()
{
string js;
// the validator will be rendered as a SPAN tag on the client-side and it will passed to the validation function.
js = "function RangeValidatorEx(val){ "
+ " var code=document.getElementById(val.controltovalidate).value; "
+ " if ((code < rangeValidatorCtrl.Range1High && code > rangeValidatorCtrl.Range1Low ) || (code < rangeValidatorCtrl.Range2High && code > rangeValidatorCtrl.Range2Low)) return true; else return false;}";
return js;
}
public int Range1Low
{
get {
object obj2 = this.ViewState["Range1Low"];
if (obj2 != null)
return System.Convert.ToInt32(obj2);
return 0;
}
set { this.ViewState["Range1Low"] = value; }
}
public int Range1High
{
get
{
object obj2 = this.ViewState["Range1High"];
if (obj2 != null)
return System.Convert.ToInt32(obj2);
return 0;
}
set { this.ViewState["Range1High"] = value; }
}
public int Range2Low
{
get
{
object obj2 = this.ViewState["Range2Low"];
if (obj2 != null)
return System.Convert.ToInt32(obj2);
return 0;
}
set { this.ViewState["Range2Low"] = value; }
}
public int Range2High
{
get
{
object obj2 = this.ViewState["Range2High"];
if (obj2 != null)
return System.Convert.ToInt32(obj2);
return 0;
}
set { this.ViewState["Range2High"] = value; }
}
}
Related
I'm coding a trading system using C#.Most of my logic is if some conditions occur at the same time,enter buy.
But in some scenario,I need an exclude logic:if some conditions occur at the same time not buy.
I tried to set a variable named Falling1 = true; and set Falling1=false; while the not buy conditions occur at the same time.
And then in my buy logic I need Falling1=true;.
namespace NinjaTrader.NinjaScript.Strategies
{
public class JJcrossCode : Strategy
{
private bool Falling1;
protected override void OnStateChange()
{
if (State == State.SetDefaults)
{
Description = #"Enter the description for your new custom Strategy here.";
Name = "JJcrossCode";
Falling1 = true;
}
else if (State == State.Configure)
{
}
else if (State == State.DataLoaded)
{
SetProfitTarget(#"Short", CalculationMode.Ticks, 20);
}
}
protected override void OnBarUpdate()
{
if (BarsInProgress != 0)
return;
if (CurrentBars[0] < 7)
return;
// Set 1
if (Open[0] > Close[0] && High[0] < High[1] && Low[0] < Low[1])
{
Falling1 = false;
}
// Set 2
// 01-crossabovelower
if (((CrossAbove(JurbolBBmacd1.Macd, JurbolBBmacd1.BollingerLower, 3))
&& (RSI1.Avg[0] < 67)&& (Falling1=true)
{
EnterLong(Convert.ToInt32(Size), #"Long");
}
}
}
The issue is that it seems the system can't recognize && (Falling1=true) in // 01-crossabovelower,I guess there are some structure issues in my code.
you want
&& (Falling1==true)
The way you wrote it you are doing an assignment
I am programming a simulation thingy that I can use as a basis for a game or something later. I am programming in C# and with Unity. Unity is up to date on version 2017.1.0f3 (or 3.3.0.2 ?).
The simulation just spawns some random people and when they get older they may search for a partner and reproduce themselves.
Now I have some weird behaviour in that "search for a partner"-method. I will show the code below in a second. The method takes a list of people as an argument and validates that list to filter out every person that is older than 15 years and don't have a partner already. Also related persons get filtered out because I don't really want incest inside my simulation .. (yet? ^^)
To clarify my problem: in the List<> called potentialPartners are somehow people already having a partner. I am sure that it is no multithreading-caused problem because those partners were not set in the same frame. Also I by myself don't do any multithreading stuff yet, there're just the threads Unity creates as default.
public void SearchForPartner(List<PawnLogic> pawnsInRange)
{
if (!this.PartnerAllowed)
return;
System.Random rnd = new System.Random();
List<PawnLogic> potentialPartners = new List<PawnLogic>();
var pP = pawnsInRange.Where(x => x.PartnerAllowed && x.Gender != this.Gender && !this.IsKindred(x) && !x.IsKindred(this));
if (pP.Count() > 0)
potentialPartners.AddRange(pP);
if (potentialPartners.Count == 0)
return;
this.Partner = potentialPartners[rnd.Next(0, potentialPartners.Count)];
if (this.Partner.IsAlive)
{
this.Partner.Partner = this;
if (this.News != null)
{
this.News.Invoke(this, new NewsEventArgs(this, this.FirstLastName + " and " + this.Partner.FirstLastName + " become a couple."));
}
if (Gender == 'M')
this.Partner.SetNewLastname(this.thisPawn.LastnameNumber);
else
this.SetNewLastname(Partner.thisPawn.LastnameNumber);
}
else
this.Partner = null;
}
I guess my problem comes from the property "PartnerAllowed" because if I remember correctly the &&-operator only validates the right hand side if the left hand side returns true.
public bool PartnerAllowed
{
get
{
return this.partner == null && this.Age >= 16;
}
}
Just to be complete here is the IsKindred-method.. I don't really think that my problem comes outside of this but maybe I am not seeing something important.
public bool IsKindred(PawnLogic check)
{
if (Generation <= check.Generation - 4)
return false;
if ((Father == null || Mother == null || check.Father == null || check.Mother == null) && Siblings.Count == 0)
return false;
if (check == Mother || check == Father)
return true;
if (Siblings.Contains(check))
return true;
for (int i = 0; i < Siblings.Count; i++)
{
if (Siblings[i].Children.Contains(check))
return true;
}
if (Father != null && Father.IsKindred(check))
return true;
if (Mother != null && Mother.IsKindred(check))
return true;
return false;
}
My Partner-property looks like this:
public PawnLogic Partner
{
get
{
if (this.partner == null && this.thisPawn.PartnerNumber != null)
{
int indexOfPartner = this.thisPawn.PartnerNumber.ToInt();
if (indexOfPartner != -1)
this.partner = new PawnLogic(indexOfPartner);
else
this.partner = null;
}
return this.partner;
}
private set
{
if (value == null)
this.thisPawn.PartnerNumber = null;
else
{
this.thisPawn.PartnerNumber = value.Number;
this.partner = value;
}
}
}
I have no idea how to fix this. Especially because it works in another program which I wrote first. But I needed to transfer the code to this new project because Unity doesn't use .Net 4.6 yet. Maybe there was a change in Linq's behaviour between the framework-versions? Do someone can help me?
It is just a private project, but I want it to work properly anyway. :P
Let me know if you need more code or explanation to understand what is happening, what is supposed to happen or how something works.
Thank you for your time and effort :)
I have 3 pairs of textboxes in a windows form :-
TxtboxSourceFolder1 -> TxtboxDestinationFolder1
TxtboxSourceFolder2 -> TxtboxDestinationFolder2
TxtboxSourceFolder3 -> TxtboxDestinationFolder3
I am creating a List<string> SrcFolders and a List<string> DestFolders.
Now I have to validate the user input:-
1) Is there a value for TxtboxSourceFolder1, If yes, Is there a corresponding value in TxtboxDestinationFolder1 ? If all answers are yes, and the values are legitimate then add them to corresponding lists. And then repeat.
To me it seems like to check if a textbox is empty:-
private int ConstructSourceDestinationFolderList()
{
if (Directory.Exists(txtboxSrcFolder1.Text) && Directory.Exists(txtboxDestFolder1.Text))
{
trans.szSourceFolderList.Add(txtboxSrcFolder1.Text.ToString());
trans.szDestinationFolderList.Add(txtboxDestFolder1.Text);
}
else
{
return 1;
}
if (!String.IsNullOrWhiteSpace(txtboxSrcFolder2.Text))
{
if (Directory.Exists(txtboxSrcFolder2.Text) && Directory.Exists(txtboxDestFolder2.Text))
{
trans.szSourceFolderList.Add(txtboxSrcFolder2.Text);
trans.szDestinationFolderList.Add(txtboxDestFolder2.Text);
}
else
{
return 1;
}
}
if (!String.IsNullOrWhiteSpace(txtboxSrcFolder3.Text))
{
if (Directory.Exists(txtboxSrcFolder3.Text) && Directory.Exists(txtboxDestFolder3.Text))
{
trans.szSourceFolderList.Add(txtboxSrcFolder3.Text);
trans.szDestinationFolderList.Add(txtboxDestFolder3.Text);
}
else
{
return 1;
}
}
return 0;
}
Now I have to do the same thing for all of the textboxes. This seems cumbersome. Is there a more compact way to design this validation?
I have 3 textbox
1,Age(year),
2,Age(month),
3,Age(Day))
By Default all 3 texbox value is 0(integer) which means the object assigned to each control is holding the value 0.
ibusbus.icdobus.user_month =0
ibusbus.icdobus.user_year=0
ibusbus.icdobus.user_Day=0
Now I need to validation if the user is make a empty of those textboxes.
So what I did is
public bool IsUserAgeYearisNull()
{
return (ibusbus.icdobus.user_year <= 0);
}
public bool IsUserAgeMonthisNull()
{
return (ibusbus.icdobus.user_month <= 0);
}
public bool IsUserAgeDayisNull()
{
return (ibusbus.icdobus.user_day <= 0);
}
So If user is make empty it is throwing a message.Here there is no issues
But in case User is enter year as 12 and enter 0 for both month and age.It is showing erro for month and Day that user need to enter the value.Here the user can enter 0 but it should not throw error.
Need to check all condition in all functions.
public bool IsUserAgeYearisNull()
{
if (ibusCalcWiz.icdoCalcWiz.user_age_month == 0 && ibusCalcWiz.icdoCalcWiz.user_age_day == 0)
return (ibusCalcWiz.icdoCalcWiz.user_age_year <= 0);
else
return true;
}
public bool IsUserAgeMonthisNull()
{
if (ibusCalcWiz.icdoCalcWiz.user_age_year == 0 && ibusCalcWiz.icdoCalcWiz.user_age_day == 0)
return (ibusCalcWiz.icdoCalcWiz.user_age_month <= 0);
else
return true
}
public bool IsUserAgeDayisNull()
{
if (ibusCalcWiz.icdoCalcWiz.user_age_year == 0 && ibusCalcWiz.icdoCalcWiz.user_age_month == 0)
return (ibusCalcWiz.icdoCalcWiz.user_age_day <= 0);
else
return true;
}
you can also create a common function.
public bool isValid()
{
return (busCalcWiz.icdoCalcWiz.user_age_year > 0 ||
ibusCalcWiz.icdoCalcWiz.user_age_month > 0 ||
ibusCalcWiz.icdoCalcWiz.user_age_day > 0);
}
and call from all function. Like :
public bool IsUserAgeDayisNull()
{
return isValid();
}
You can use a RangeValidator for each of TextBoxes.
Using RangeValidator as suggested earlier would be a better idea rather than writing lots of code. it will become hard to maintain the code in long run.
When the following function is called, it is not showing the corresponding photoBoxes. I've done a debugging walkthrough, it even reaches the parts necessary to Show() and Hide(). I don't know what I can do. It's not showing anything
public void SmokerTakeIngredientFromTable(agents agent, List<smokers> smoker)
{
int index = 0;
bool smoker_takes_ingredients = false;
while (!smoker_takes_ingredients)
{
if ((smoker[index].item != agent.item_1) && (smoker[index].item != agent.item_2))
{
if (index == 0)
{
leftarrow_img.Show();
rightarrow_img.Hide();
downarrow_img.Hide();
}
else if (index == 1)
{
leftarrow_img.Hide();
rightarrow_img.Show();
downarrow_img.Hide();
}
else if (index == 2)
{
leftarrow_img.Hide();
rightarrow_img.Hide();
downarrow_img.Show();
}
agent.item_1 = 3;
agent.item_2 = 3;
break;
}
index++;
}
}
This is what the designer for these photoBoxes look like:
This is the properties page for one of the photoBoxes (they are all identical apart from the actual image file, they all have Visible = false too)
When making visibility changes I need to refresh the form using this.Refresh()