I recently discovered the Enterprise Validation Library and am using it to validate my app.config file. I mostly have strings which were simple to apply validation to. I also have some booleans for example:
class Options
{
public bool IsRed { get; set; }
public bool IsBlue { get; set; }
}
and then inside my app.config:
<!--Options-->
<add key ="IsRed" value="true"/>
<add key ="IsBlue" value="Maybe"/>
Is it possible to apply validation rules to check that make sure the value in the app.config file is actually a bool?
The best I've been able to come up with is this:
class Options
{
[TypeConversionValidator(typeof(bool), MessageTemplate = "IsRed value must be a true/false")]
public string IsRed { get; set; }
[TypeConversionValidator(typeof(bool), MessageTemplate = "IsBlue value must be a true/false")]
public string IsBlue { get; set; }
}
Which would work, but then I'm dealing with strings instead of booleans.
I have decided to use dynamic types. My code now looks like this:
class Options
{
[TypeConversionValidator(typeof(bool), MessageTemplate = "IsRed value must be a true/false")]
public dynamic IsRed { get; set; }
[TypeConversionValidator(typeof(bool), MessageTemplate = "IsBlue value must be a true/false")]
public dynamic IsBlue { get; set; }
}
private ValidationResults LoadOptions()
{
_options.IsRed = ConfigurationManager.AppSettings["IsRed"];
_options.IsBlue = ConfigurationManager.AppSettings["IsBlue"];
var valFactory = EnterpriseLibraryContainer.Current.GetInstance<ValidatorFactory>();
var cusValidator = valFactory.CreateValidator<Options>();
var optionValidator = cusValidator.Validate(_options);
if (optionValidator.IsValid)
{
_options.IsBlue = Convert.ToBoolean(_options.IsBlue);
_options.IsRed = Convert.ToBoolean(_options.IsRed);
}
return optionValidator;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.