Doiremik
Doiremik

Reputation: 265

Validate Values in the App.Config

just a quick fire question and wondering on the correct approach.

In the appConfig in the Appsettings I want to validate the values that I have entered.So for example if I have

<appSettings>
    <add key="UseEncryption" value="false"/>
    <add key="MaxThreshold" value="10"/>
    <add key="ProcessDate" value="01/12/2012"/>
</appSettings>  

the program compiles and executes as normal. However a support team can change these values and rerun the app. In light of coding a Gui to change all these values and validate them on the way in... is there another way to validate them.

For example I want to check that MaxThrehold is an Int, Processdate is a valid date etc

I was writing a function that would be run at the start of the application that would check each of the settings and stop the application if they where not correct.

Is this the best approach.. having a validator type function for each app setting.

I keep a class called CurrentEnvironment and in here I have all the get/sets for any settings I need in the App Config.. so for each Key I would also have a validitor function to check the values.

regards

Upvotes: 1

Views: 2923

Answers (2)

Marcus Davies
Marcus Davies

Reputation: 248

for each of your keys use TryParse on the object

DateTime.TryParse(appsetting[keyname])

Upvotes: 1

Oded
Oded

Reputation: 499012

I was writing a function that would be run at the start of the application that would check each of the settings and stop the application if they where not correct.

That's a fine approach, though you do need to ensure that this function does run at the start of execution.

Another approach is to create a custom configuration section (inherit from ConfigurationSection and add custom properties) - make sure these properties are of the types you want to test against. When the config file deserializes, if the types cannot be parsed properly, the application will not start up.

Upvotes: 4

Related Questions