How to build a exclude condition in C# - c#

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

Related

I get a wrong resultset of a List<> when using Linq's Where with lambda

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 :)

Visual Studio C# and Short-circuit evaluation

With the || Operator, Microsoft describes short circuit evaluation here Short Circuit Evaluation
However, I have the following code which seems to contradict this process:
if ((_opcLoaded || DoLoadOPC()) &&
(_tagsAdded || DoAddTags()) &&
DoWriteRecipe() &&
(DoResume()))
What I'm trying to prevent is the function DoAddTags from being called if _tagsAdded is true (DoAddTags sets _tagsAdded to true).
However, I'm finding that DoAddTags is called even when _tagsAdded is true. It's the same for _opcLoaded and DoLoadOPC. I've had to put a condition inside DoAddTags to check for _tagsAdded, which shouldn't be necessary.
Can someone explain why this is happening?
Here is the Complete Code
//
// Resume a Paused recipe
case MonitoredTasks.Resume:
Task.Factory.StartNew(() =>
{
MonitoredTask = MonitoredTasks.None;
if ((_opcLoaded || DoLoadOPC()) &&
**(_tagsAdded || DoAddTags())** &&
DoWriteRecipe() &&
(DoResume()))
{
MonitoredTask = MonitoredTasks.None;
RunningState = RecipeRunningStates.Running;
Status = CIPStatuses.Running;
}
else
{
MonitoredTask = MonitoredTasks.Resume;
}
});
break;
And the code for DoAddTags
/// <summary>
/// Adds all necessary tags to the OPC Server Manager
/// </summary>
/// <returns></returns>
bool DoAddTags()
{
bool result = false;
var oldActivity = Activity;
//
// Not doing anything OPC related?
if (Activity != CIPActivities.AddingOPCTags && !_tagsAdded && Activity != CIPActivities.StartingOPC)
{
lock (_locks[LOCK_OPC])
{
Activity = CIPActivities.AddingOPCTags;
Status = CIPStatuses.Initialising;
RecipeError = Errors.None;
try
{
//
// Reset connection and internal tags list
_serverManager.Reset();
//
// Now to add all OPC Tags - Area
CIPStatusTag = _serverManager.AddTag(_area.CIPStatusTag);
RecipeIDTag = _serverManager.AddTag(_area.RecipeIDTag);
RecipeInstructionIDTag = _serverManager.AddTag(_area.RecipeInstructionIDTag);
HandshakingTag = _serverManager.AddTag(_area.HandshakingTag);
GlobalInstructionIDTag = _serverManager.AddTag(_area.GlobalInstructionIDTag);
InstructionAttemptsTag = _serverManager.AddTag(_area.InstructionAttemptsTag);
//
// Area tags OK?
if (CIPStatusTag == null || RecipeIDTag == null || RecipeInstructionIDTag == null || HandshakingTag == null || GlobalInstructionIDTag == null || InstructionAttemptsTag == null)
{
RecipeError = Errors.InvalidAreaTags;
DoError(new RecipeErrorHandlerEventArgs(this) { Message = FormatMessage("CIPRecipe.DoAddTags - Invalid AREA Tags"), Sender = this });
}
else
{
VM_CIPInstruction vm = null;
bool instructionTagErrors = false;
//
// For each area instruction that is used, assig a link to the instruction
foreach (var i in _areaInstructions)
{
//
// Create a View Model for the specified area instruction : this allows us to determine the number of parameters (tags) that apply to the instruction
vm = new VM_CIPInstruction(i.Value.Instruction);
//
// Assign device reference tags
if (vm.DeviceReferencesAvailable)
{
i.Value.DeviceTag = _serverManager.AddTag(i.Value.Instruction.DeviceReferenceTag);
instructionTagErrors = i.Value.DeviceTag == null;
}
//
// For each required parameter, add tag
for (int paramNo = 1; paramNo <= vm.NoOfParams; paramNo++)
{
switch (paramNo)
{
case 1:
//
// Tag defined? Add it
if (vm.AreaInstruction.Param1Tag >= 0)
{
i.Value.Param1 = _serverManager.AddTag(i.Value.Instruction.Param1Tag);
if (i.Value.Param1 == null)
{
instructionTagErrors = true;
}
}
else
{
instructionTagErrors = true;
}
break;
case 2:
//
// Tag defined? Add it
if (vm.AreaInstruction.Param2Tag >= 0)
{
i.Value.Param2 = _serverManager.AddTag(i.Value.Instruction.Param2Tag);
if (i.Value.Param2 == null)
{
instructionTagErrors = true;
}
}
else
{
instructionTagErrors = true;
}
break;
case 3:
//
// Tag defined? Add it
if (vm.AreaInstruction.Param3Tag >= 0)
{
i.Value.Param3 = _serverManager.AddTag(i.Value.Instruction.Param3Tag);
if (i.Value.Param3 == null)
{
instructionTagErrors = true;
}
}
else
{
instructionTagErrors = true;
}
break;
case 4:
//
// Tag defined? Add it and then check quality
if (vm.AreaInstruction.Param4Tag >= 0)
{
i.Value.Param4 = _serverManager.AddTag(i.Value.Instruction.Param4Tag);
if (i.Value.Param4 == null)
{
instructionTagErrors = true;
}
}
else
{
instructionTagErrors = true;
}
break;
case 5:
//
// Tag defined? Add it and then check quality
if (vm.AreaInstruction.Param5Tag >= 0)
{
i.Value.Param5 = _serverManager.AddTag(i.Value.Instruction.Param5Tag);
if (i.Value.Param5 == null)
{
instructionTagErrors = true;
}
}
else
{
instructionTagErrors = true;
}
break;
case 6:
//
// Tag defined? Add it and then check quality
if (vm.AreaInstruction.Param6Tag >= 0)
{
i.Value.Param6 = _serverManager.AddTag(i.Value.Instruction.Param6Tag);
if (i.Value.Param6 == null)
{
instructionTagErrors = true;
}
}
else
{
instructionTagErrors = true;
}
break;
}
}
if (instructionTagErrors)
{
RecipeError = Errors.InvalidInstructionTags;
DoError(new RecipeErrorHandlerEventArgs(this) { Message = FormatMessage(String.Format("CIPRecipe.DoAddTags - Invalid Instruction {0} Tags", vm.Name)), Sender = this });
break;
}
}
//
// Any problems adding tags?
if (RecipeError == Errors.None)
{
Activity = CIPActivities.StartingOPC;
//
// Once all tags added, start OPC Server
result = _serverManager.Start();
if (!result)
{
Status = CIPStatuses.AddTagsFailed;
RecipeError = Errors.OPC;
DoError(new RecipeErrorHandlerEventArgs(this) { Message = FormatMessage("CIPRecipe.DoAddTags - Start of OPC failed"), Sender = this });
}
else
{
**_tagsAdded = true;**
Status = CIPStatuses.TagsAdded;
}
}
else
{
Status = CIPStatuses.AddTagsFailed;
}
}
}
catch (Exception ex)
{
RecipeError = Errors.Exception_AddTags;
DoError(new RecipeErrorHandlerEventArgs(this) { Message = FormatMessage("CIPRecipe.DoAddTags"), Exception = ex, Sender = this });
}
finally
{
Activity = oldActivity;
}
}
}
return Status == CIPStatuses.TagsAdded;
}
I've highlighted the relevant lines with **
On the first pass DoAddTags is executed and _tagsAdded set to TRUE- I've placed a breakpoint here, so I know it is being set. Shortly afterwards (with or without the former breakpoint) DoAddTags is again entered (on the first line) despite_doAddTags == true.
I've even set a breakpoint on the code "(_tagsAdded || DoAddTags())". _tagsAdded == true, yet DoAddTags is still entered.
So what I'm seeing is, and all the Watches/Debugging info is consistent with is that DoAddTags is being called whilst _tagsAdded == true
This code won't display the behavior you describe, the short-circuiting works just as described.
What actually happens: _tagsAdded is initially false, so DoAddTags() is called, which sets _tagsAdded to true.
Then the debugger kicks in, you inspect _tagsAdded and see it's true.
Instead step through your code using F11 and inspect or watch all relevant variables.

creating a group of controls

I ran into little problem today as I was working on my game...
The problem is I have this condition running on 1 milisecond timer :
if (jump == true &&
jumped == 0 &&
(Player.Location == new Point(Player.Location.X, Block1.Location.Y - Player.Height) ||
Player.Top == this.Height - Player.Height))
{
do something...
}
The "Block1" is one object in the game (Picturebox) and I need like 10 or 20 or even 100 more of these blocks with the same condition, so how could I simplify it? It would be 50 or even more lines of one condition. Basically I would like to know if there is a way of mixing all "Blocks" (pictureboxes) into a group (named Blocks) or something I could still access with Blocks.Location.Y etc
There are too many conditions in this single check, IMO. I'd break them down and then work on each condition in a stand-alone manner which will make things easier to debug as well as to read/comprehend in the future.
// Too much going on here; let's refactor.
if (jump == true
&& jumped == 0
&& (Player.Location == new Point(Player.Location.X, Block1.Location.Y - Player.Height)
|| Player.Top == this.Height - Player.Height))
{
//do something...
}
Instead of creating a large if statement, pull the conditions into a single method:
// first refactor
private bool IsValidForSomeAction()
{
if(!jump)
{
return false;
}
if(jumped != 0)
{
return false;
}
if(Player.Top == this.Height - Player.Height)
{
return true;
}
if (Player.Location == new Point(Player.Location.X, Block1.Location.Y - Player.Height))
{
return true;
}
return false;
}
After the first refator, it becomes clear that there is no need to create a new Point for the final comparison:
// second refactor
private bool IsValidForSomeAction()
{
if(!jump)
{
return false;
}
if(jumped != 0)
{
return false;
}
if(Player.Top == this.Height - Player.Height)
{
return true;
}
// only the Y location matters, no need to create a new Point for the comparison.
if (Player.Location.Y == Block1.Location.Y - Player.Height)
{
return true;
}
return false;
}
Now, let's focus on what really matters: if (Player.Location.Y == Block1.Location.Y - Player.Height). The condition boils down to the difference between the Block's Y location and the Player's Height.
Given that there may be 10, 20, 50, or 100+ Blocks to compare, then create a private field containing a collection of all the Blocks.
// override the onload event and find all the picture boxes:
private readonly List<PictureBox> _boxes = new List<PictureBox>();
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
_boxes.AddRange(this.Controls.OfType<PictureBox>()
}
The _boxes field can then be used for the final validation:
// third refactor
private bool IsValidForSomeAction()
{
if(!jump)
{
return false;
}
if(jumped != 0)
{
return false;
}
if(Player.Top == this.Height - Player.Height)
{
return true;
}
// only the Y location matters, no need to create a new Point for the comparison.
if(_boxes.Any(x => x.Location.Y - Player.Height == Player.Location.Y)
{
return true;
}
return false;
}

How to disable more than one NumericUpDown controls using one method?

i have a form with more than one NumericUpDown as controls to input answer. i want every input is true for an operation (multiplication, sum etc), NumericUpDown for that operation will be disable. i have used the code below (just for sum operation), but i think its not efficient because i have to make a method to check every operation.
private void IsSumTrue() {
if (add1 + add2 == sum.Value)
{
sum.Enabled = false;
}
}
private void IsDifferenceTrue()
{
if (add1 - add2 == difference.Value)
{
difference.Enabled = false;
}
}
private void IsProductTrue()
{
if (add1 * add2 == product.Value)
{
product.Enabled = false;
}
}
private void IsQuotientTrue()
{
if (add1 / add2 == quotient.Value)
{
quotient.Enabled = false;
}
}
anyone have idea how to make it more efficient with just a method for all operation?
below is my idea, but to check the value is true for every NumericUpDown i don't know how.
private void DisableIfValueIsTrue()
{
foreach(Control control in this.Controls)
{
NumericUpDown value = control as NumericUpDown;
// if(value [NEED HELP]
}
}
Considering your situtaion, you can set a tag for each NumericUpDown in design mode like this:
sum.Tag=1;
square.Tag=2;
etc
Then define some int variables:
int iSum=add1+add2;
int iSquare= //Whatever you want
etc
And finally loop through your controls this way:
foreach (NumericUpDown control in this.Controls.OfType<NumericUpDown>())
{
int intCondition = Convert.ToInt32(control.Tag) == 1
? iSum
: Convert.ToInt32(control.Tag) == 2
? iSquare
: Convert.ToInt32(control.Tag) == 3
? i3
: i4; //You should extend this for your 8 controls
control.Enabled = intCondition == control.Value;
}
OK! Second way I offer
Since you will have to always check 8 different conditions, you could simply forget about looping through the controls and just change your method like this:
private void DisableIfValueIsTrue()
{
sum.Enabled = add1 + add2 != sum.Value;
difference.Enabled= add1 - add2 != difference.Value;
product.Enabled= add1 * add2 != product.Value;
quotient.Enabled= (add2 !=0) && (add1 / add2 != quotient.Value);
//etc
}
I came across this while doing some research and would like to give my solution I used for my situation and hope it helps people. I needed minimum and maximum numbers for a calculation, so mine are named appropriately and I correlated these with some CheckBoxes. I used null in beginning of minimum and end of maximum to account for empty. I also had to create an event handler SubscribeToEvents() shown below.
In my load event for my form:
SubscribeToEvents();
_checkBoxs = new[] { cbXLight, cbLight, cbMedium, cbHeavy, cbXHeavy, cbXXHeavy, cbXXXHeavy };
_minimumsNumericUpDowns = new[] { null, nLightMin, nMediumMin, nHeavyMin, nXHeavyMin, nXXHeavyMin, nXXXHeavyMin };
_maximumsNumericUpDowns = new[] { nXLightMax, nLightMax, nMediumMax, nHeavyMax, nXHeavyMax, nXXHeavyMax, null };
then I created a method:
private void DisableNumericUpDowns()
{
// disable everything:
foreach (var n in _minimumsNumericUpDowns)
{
if (n != null)
n.Enabled = false;
}
foreach (var n in _maximumsNumericUpDowns)
{
if (n != null)
n.Enabled = false;
}
}
The event handler:
private bool _eventsSubscribed;
private void SubscribeToEvents()
{
if (_eventsSubscribed)
return;
_eventsSubscribed = true;
cbXXHeavy.CheckedChanged += CheckBox_NumericState;
cbXHeavy.CheckedChanged += CheckBox_NumericState;
cbXLight.CheckedChanged += CheckBox_NumericState;
cbHeavy.CheckedChanged += CheckBox_NumericState;
cbLight.CheckedChanged += CheckBox_NumericState;
cbMedium.CheckedChanged += CheckBox_NumericState;
cbXXXHeavy.CheckedChanged += CheckBox_NumericState;
}
Now I can used this to check when they are enabled and if they are greater than or less than 0 if needed in the method CheckBox:
private void CheckBox_NumericState(object sender, EventArgs e)
{
// disable everything
DisableNumericUpDowns();
// see if more than one checkbox is checked:
var numChecked = _checkBoxs.Count((cb) => cb.Checked);
// enable things if more than one item is checked:
if (numChecked <= 1) return;
// find the smallest and enable its max:
var smallest = -1;
for (var i = 0; i < _checkBoxs.Length; i++)
{
if (!_checkBoxs[i].Checked) continue;
if (_maximumsNumericUpDowns[i] != null)
{
_maximumsNumericUpDowns[i].Enabled = true;
}
smallest = i;
break;
}
// find the largest and enable its min:
var largest = -1;
for (var i = _checkBoxs.Length - 1; i >= 0; i--)
{
if (!_checkBoxs[i].Checked) continue;
if (_minimumsNumericUpDowns[i] != null)
{
_minimumsNumericUpDowns[i].Enabled = true;
}
largest = i;
break;
}
// enable both for everything between smallest and largest:
var tempVar = largest - 1;
for (var i = (smallest + 1); i <= tempVar; i++)
{
if (!_checkBoxs[i].Checked) continue;
if (_minimumsNumericUpDowns[i] != null)
{
_minimumsNumericUpDowns[i].Enabled = true;
}
if (_maximumsNumericUpDowns[i] != null)
{
_maximumsNumericUpDowns[i].Enabled = true;
}
}
}
So I can check each state as required:
I want to check if Extra Light is check:
// Extra Light
if (!cbXLight.Checked) return;
if (nXLightMax.Enabled == false)
{
_structCategoryType = XLight;
CheckStructureSheets();
}
else
{
if (nXLightMax.Value > 0)
{
_dMax = nXLightMax.Value;
_structCategoryType = XLight;
CheckStructureSheets();
}
else
{
MessageBox.Show(#"Extra Light Max cannot be zero (0)");
}
}
and next light checks both:
// Light
if (cbLight.Checked)
{
if (nLightMin.Enabled == false && nLightMax.Enabled == false)
{
_structCategoryType = Light;
CheckStructureSheets();
}
else
{
if (nLightMin.Enabled && nLightMin.Value > 0)
{
if (nXLightMax.Enabled && nLightMin.Enabled && nLightMax.Enabled == false)
{
_dMin = nLightMin.Value;
_structCategoryType = Light;
CheckStructureSheets();
}
else
{
if (nLightMax.Value > 0)
{
_dMin = nLightMin.Value;
_dMax = nLightMax.Value;
_structCategoryType = Light;
CheckStructureSheets();
}
else
{
MessageBox.Show(#"Light Max cannot be zero (0)");
return;
}
}
}
else if (nLightMin.Enabled == false && nLightMax.Enabled)
{
if (nLightMax.Value > 0)
{
_dMax = nLightMax.Value;
_structCategoryType = Light;
CheckStructureSheets();
}
else
{
MessageBox.Show(#"Light Max cannot be zero (0)");
}
}
else
{
MessageBox.Show(#"Light Min cannot be zero (0)");
return;
}
}
}
Hope this helps someone.
Tim
thanks for #AlexJoliq and #BrettCaswell. just want to inform that before Alex edited his answer from using "==" to "!=", i (thought) already solved the problem. but i don't know where is the more effective and efficient way, alex's or mine.
below is my code for DisableIfValueIsTrue():
if (add1 + add2 == sum.Value) sum.Enabled = false;
if (add1 - add2 == difference.Value) difference.Enabled = false;
if (add1 * add2 == product.Value) product.Enabled = false;
if (add1 / add2 == quotient.Value) quotient.Enabled = false;

Asp.Net : Extended range validation

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; }
}
}

Categories

Resources