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:18 UTC
Read the original article
Hit count: 330
c#
|configuration
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?
© Stack Overflow or respective owner