Problem chaining rules with CSLA Common Required rule

Problem chaining rules with CSLA Common Required rule

Old forum URL: forums.lhotka.net/forums/t/10455.aspx


Eben posted on Monday, June 20, 2011

I am having some trouble trying to chain two rules using the Csla.Rules.CommonRules.Required rule as the inner rule.  Basically, I want the Width2 property to be required if the Shape property is not equal to "Circular".  Here is my code:

private class ShapeGate : BusinessRule
{
    public ShapeGate(Csla.Core.IPropertyInfo primaryProperty)
        : base(primaryProperty)
    { }
 
    private IBusinessRule _innerRule =
        (IBusinessRulenew Csla.Rules.CommonRules.Required(Width2Property);
 
    protected override void Execute(RuleContext context)
    {
        StormPipe pipe = (StormPipe)context.Target;
        var shapeProp = pipe.ReadProperty(ShapeProperty);
        if (!shapeProp.Equals("Circular"StringComparison.InvariantCultureIgnoreCase))
            _innerRule.Execute(context.GetChainedContext(_innerRule));
    }
}
The problem I have is that when I run the app and put in a value other than circular for the shape property, I get this error message on the Shape property:
rule://myApp.business.stormpipe-shapegate/Shape:Object reference not set to an instance of an object.
It works fine if I replace this line:
(IBusinessRulenew Csla.Rules.CommonRules.Required(Width2Property);
With this:
(IBusinessRule) new Required<double?>(Width2Property);
Where Required<T> is my own custom made required rule.  In that case, it behaves the way I would expect (ie: when I put in a shape that is not circular, I get a nice error message on the Width2 property stating that Width2 is required)

Don't get hung up too much on the logic of the rule, as this is just practice at this point, but what I want to know is why a custom business rule works fine as an inner rule in this scenario, but Csla.Rules.CommonRules.Required does not seem to work.

Thanks,
Eben

Peran replied on Monday, June 20, 2011

Hi Eban,

Your inner rule requires the value of Width2Property, therefore you need to add Width2Property as an input property on your gate rule. e.g.

   public ShapeGate(Csla.Core.IPropertyInfo primaryProperty)
        : base(primaryProperty)
{ 
            this.InputProperties.Add(Width2Property);
}
Regards
Peran

Eben replied on Monday, June 20, 2011

That was perfect!  My custom required rule obviously did not use the InputProperties collection, it only used the PrimaryProperty.  Therefore, I was not able to reproduce the error in my custom method.  Adding the desired field to the InputProperties collection in the gate rule was exactly what I needed.

Thanks Peran!

-Eben

Copyright (c) Marimer LLC