I am trying to write a reusable business rule that would take an editable collection property and an int value and add a broken rule to my root if the count of the collection is greater than the value.
So far, I have written the following business rule but I was hoping you can help me optimize it. Somehow it doesn't feel pretty. I would rather specify the type of the collection which is specified when the property is registered than that of the item. All I really need to get out of all this is the count of the collection (regardless of the item type).
I am using CSLA 4.3.12
Thanks
publicclassCollectionMaxCountRule<C> : PropertyRule
{
privateint MaxCount { get; set; }
public CollectionMaxCountRule(IPropertyInfo primaryProperty, int maxCount): base(primaryProperty)
{
MaxCount = maxCount;
PrimaryProperty = primaryProperty;
InputProperties = newList<IPropertyInfo>() { primaryProperty };
AffectedProperties.Add(primaryProperty);
}
protectedoverridevoid Execute(RuleContext context)
{
ICollection<C> _list = (ICollection<C>)context.InputPropertyValues[PrimaryProperty];
if (_list.Count > MaxCount)
context.AddErrorResult(PrimaryProperty, string.Format("{0} {1}", ResourceFiles.LibraryResources.CollectionMaxCountRule_Error_MaxCount, MaxCount.ToString()));
}
}
It is added using the following:
BusinessRules.AddRule(
newCollectionMaxCountRule<CostEstimate>(CostEstimateCollectionProperty, int.Parse(ConfigurationManager.AppSettings["MaxCostEstimateCount"])));