|
dev
newsgroups
|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
.NET 2.0 ConfigurationSection FrustrationsI have been really struggling here this week; maybe I'm just too tired to grasp the new API for configuration. I have a custom configuration class that descends from ConfigurationSection. I have a couple of simple string properties setup declaratively via the ConfigurationProperty attribute. All works well until I begin adding validators to those same properties. Here's a great example: [ConfigurationProperty("someValue"), RegexStringValidator(@"\w+")] public string SomeValue { get { return (string)this["someValue"]; } set { this["someValue"] = value; } } This seems simple enough; however, I always get an error when the configuration section is handled. It does not matter what value I put in, it fails (e.g. <add someValue="Work" />). If I remove the validator, it works just fine. So, I decided to do some digging via the debugger. It's difficult since it's all handled via reflection. I created a custom validator so I could set a breakpoint and see what the heck was going on. public class MyValidator : ConfigurationValidatorBase { public override bool CanValidate(Type type) { return (type == typeof(string)); } public override void Validate(object value) { // * Set breakpoint here. throw new ApplicationException("The value is: " + (string)value); } } .... [ConfigurationProperty("someValue"), ConfigurationValidator(typeof(MyValidator))] public string SomeValue { get { return (string)this["someValue"]; } set { this["someValue"] = value; } } When debugging and the breakpoint inside the validator class' Validate method is hit; I can see the problem. The value argument is an empty string at this point (""). Huh??? That's why my RegexStringValidator failed. I reverted back to using it but with this regex instead: @"\w*". You guessed it, it works then. It works even when the value is invalid (e.g. <add someValue="*%! This should certainly fail!!" />). Why is the deserialized value an empty string? No validation can be properly added if the value is empty during the validation process. I know it's reading the value in properly if there is no validation; I can display SomeValue with success. I'm frustratingly stumped! Can anyone shed some light over here? Thanks in advance, Matt |
|||||||||||||||||||||||