1

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; }
    }
}
theateist
  • 13,879
  • 17
  • 69
  • 109
  • What is the behaviour that you would want if this validation failed? Runtime exception? – Davin Tryon Jul 24 '12 at 16:32
  • I don't think you can get a compilation error since the app.config can always be changed at a later stage. But you can add xsd validation, see http://stackoverflow.com/questions/334473/providing-intellisense-xsd-validation-to-configsections. – Maarten Jul 24 '12 at 17:55
  • @dtryon, I edited my post. Yes I want runtime exception similar to as `IsRequeired`, for example, throws excetpion – theateist Jul 25 '12 at 08:10

1 Answers1

2

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.

Davin Tryon
  • 66,517
  • 15
  • 143
  • 132
ZafarYousafi
  • 8,640
  • 5
  • 33
  • 39
  • This, coupled with ElementInformation.IsPresent is also useful if you want your "It's not there default" to differ from your "It's there default". – Josh Sterling May 11 '16 at 01:20