How to check either both properties or none of them are present in configuration element?

507 Views Asked by At

Is there way to write some ConfigurationValidatorAttribute or in some other way that will allow either both Prop1 and Prop2 are present or none of them?

EDITED

In the following config file when I'll try to get Domains I want to get runtime exception because domain3 element must have both Prop1 and Prop2 or none of them, but not only one of them!

Just like IsRequired is checked in runtime and throws error if the element doesn't has Name attribute.

<MySection>
        <Domains>
          <Domain Name="domain1" Prop1="1" Prop2="4" /> 
          <Domain Name="domain2" /> 
          <Domain Name="domain3" Prop1="1" /> 
        </Domains>         
    </MySection>

public class ConfigElement : ConfigurationElement
{     
    [ConfigurationProperty("Name", IsRequired = true)]
    public string Name
    {
        get { return (string)this["Name"]; }
        set { this["Name"] = value; }
    }        

    [ConfigurationProperty("Prop1")]
    public int Prop1
    {
        get { return (int)this["Prop1"]; }
        set { this["Prop1"] = value; }
    }

    [ConfigurationProperty("Prop2")]
    public int Prop2
    {
        get { return (int)this["Prop2"]; }
        set { this["Prop2"] = value; }
    }
}
1

There are 1 best solutions below

1
On BEST ANSWER

Override the PostDeserialize of ConfigurationElement in your ConfigElement Class

 protected override void PostDeserialize()
        {
            base.PostDeserialize();
            //Do what you want
        }

There is a good example on this blog post.