Say I have defined a custom AdapterElement : ConfigurationElement
with properties Type
, Name
and Version
. Since Name
and Version
uniquelly identifies the Type
property, I would like to enforce the configuration file to have one of the following structures:
<adapter type="TypeOfAdapter"/>
<adapter name="NameOfAdapter" version="VersionOfAdapter"/>
I could easily mark those three properties with IsRequired = false
and let users specify the combination the want. However, the following combinations are not valid and I would like to forbid them:
<adapter type="TypeOfAdapter" version="VersionOfAdapter"/>
<adapter type="TypeOfAdapter" name="NameOfAdapter"/>
Is there any easy way of achieving this?
I had to do a bit of reading around to find answers on this one.
How about adding a PostDeserialise check for validity to your AdapterElement class?
protected override void PostDeserialize()
{
bool isValid = Type != null && Name == null && Version == null
|| Type == null && Name != null && Version != null;
if (!isValid)
{
throw new ArgumentException("Must specify either Type or Name and Version");
}
base.PostDeserialize();
}
According to a blog I found there is no more obvious way of verifying validity of Multiple Attributes on a single configuration section - but it appears to be true for configuation elements too.