Custom ConfigurationSection: CallbackValidator called with empty string

Posted by Paolo Tedesco on Stack Overflow See other posts from Stack Overflow or by Paolo Tedesco
Published on 2010-05-06T11:13:44Z Indexed on 2010/05/06 11:28 UTC
Read the original article Hit count: 412

Filed under:
|

I am writing a custom configuration section, and I would like to validate a configuration property with a callback, like 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 validation fails. If i just remove the validator, the string value is correctly initialized to the value in the configuration file.

What am I missing?

EDIT I discovered that actually the validation function is being 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 a way to modify this behavior?

© Stack Overflow or respective owner

Related posts about c#

Related posts about configuration