I am trying to implement something similar to IntegerAboveThresholdAttribute except that it should work with decimals.
This is my implementation of me using it as a BusinessException
[DecimalAboveThreshold(typeof(BusinessException), 10000m, ErrorMessage = "Dollar Value must be 10000 or lower.")]
However, I receive an error saying An attribute must be a constant expression, typeof expression, or array creation expression of an attribute parameter type. I was wondering if it is possible to fix this, and if not, is it possible to do something similar?
Here is the source code for DecimalAboveThresholdAttribute:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CoreLib.Messaging;
namespace (*removed*)
{
public class DecimalBelowThresholdAttribute : BusinessValidationAttribute
{
private decimal _Threshold;
public DecimalBelowThresholdAttribute(Type exceptionToThrow, decimal threshold)
: base(exceptionToThrow)
{
_Threshold = threshold;
}
protected override bool Validates(decimal value)
{
return (decimal)value < _Threshold;
}
}
}
I also would like to know if I can do this with DateTimes as well.
You are not allowed to use decimals as attribute parameters. This is a built in restriction in .NET attributes. You can find the available parameter types on MSDN. So it won't work with decimal and DateTime. As a workaround (although it won't be typesafe) you can use strings:
public DecimalBelowThresholdAttribute(Type exceptionToThrow, string threshold)
: base(exceptionToThrow)
{
_Threshold = decimal.Parse(threshold);
}
Usage:
[DecimalAboveThreshold(typeof(BusinessException), "10000", ErrorMessage = "Dollar Value must be 10000 or lower.")]