ArgumentException: The string must be at least XXX characters long

Cross-posted from kennyw.com:

I hit this obtuse exception the other day. The stack had System.Configuration code on it, which is the only way I managed to track it down to a StringValidator attribute. A few things that would have been helpful:

  1. Having the name of the culprit in the exception string (i.e. “The string ‘foo’ must be at least 24 characters long.”)
  2. Including the configuration element of which string ‘foo’ is a property of (i.e. “The string ‘foo’ must be at least 24 characters long to be used for property ‘bar’ on element ‘baz’.”)

Turns out that this was not actually a .config file error. After subclassing StringValidator and creating a ConfigurationValidatorAttribute to bridge into the declarative system, I discovered that the exception was being thrown while validating the default value.

I had naively thought that if you have a required ConfigurationProperty, then you do not need to set up a default value. I was wrong. I discovered that this is a known bug in the .Net Configuration validation framework that has been resolved “By Design”.

I completely understand why they want to run the validators on default values, but the framework really should check if a property is required and suppress default value validation in that case. As it is, the default value is never used, and the framework properly throws an exception if the required property isn’t explicitly set by the user.

As a result, the following is the “correct” way to have a required property that works with the config validation framework:

[ConfigurationProperty(namePropertyName, IsRequired = true,
// We need to set a default value for our string validator to work
DefaultValue = “dummy”)]
[StringValidator(MinLength = 1)]
public string Name { … }

This entry was posted in Software Development and tagged , , . Bookmark the permalink.

Leave a Reply