I am writing a custom configuration section, and I would like to check the configuration property with a callback, as in this example:
using System; using System.Configuration; class CustomSection : ConfigurationSection { [ConfigurationProperty("stringValue", IsRequired = false)] [CallbackValidator(Type = typeof(CustomSection), CallbackMethodName = "ValidateString")] public string StringValue { get { return (string)this["stringValue"]; } set { this["stringValue"] = value; } } public static void ValidateString(object value) { if (string.IsNullOrEmpty((string)value)) { throw new ArgumentException("string must not be empty."); } } } class Program { static void Main(string[] args) { CustomSection cfg = (CustomSection)ConfigurationManager.GetSection("customSection"); Console.WriteLine(cfg.StringValue); } }
And my App.config file looks like this:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="customSection" type="CustomSection, config-section"/> </configSections> <customSection stringValue="lorem ipsum"/> </configuration>
My problem is that when the ValidateString function is called, the value parameter is always an empty string, and therefore the check is not performed. If I just delete the validator, the string value will be correctly initialized with the value in the configuration file.
What am I missing?
EDIT . I found that in fact the verification function is called twice: the first time with the default value of the property, which is an empty string if nothing is specified, the second time with the real value read from the configuration file. Is there any way to change this behavior?
source share