tags:

views:

75

answers:

2

I would like to add a check to ensure all appSettings used in my class indeed exist in the configuration file. What is the most reliable way to do this?

I know I could check each value for null, but are any of you guys using an XSD approach? Or do a more dynamic approach, or is the best way to manually check and maintain a list of values that should be present?

+3  A: 

It is possible to use an encapsulating class that performs this null check for you, but that breaks the relationship of the configuration model almost making it pointless. Unless you define a standard within your own architecture to use that scheme always that is. You could easily define your own configuration manager class that receives the key, checks the regular configuration manager for null and then returns the result.

public class myConfig
{
    public string AppSettings(string key)
    {
        get
        {
            //if(System.Configuration.ConfigurationManager.AppSettings(key) != null)
            //    return System.Configuration.ConfigurationManager.AppSettings(key);
            //else
            //    return String.Empty;

            // Null coalescing for @Paul :)
            return System.Configuration.ConfigurationManager.AppSettings(key) ?? String.Empty;
        }
    }
}

Or something similar.

Joel Etherton
can't return a string as a NameValueCollection, also you could have just used the null coallescing operator ??
Paul Creasey
@Paul: True and probably. I've used this method in a project at work, I just don't have the exact code in front of me. I think I used a piece from memory but it's incomplete. I'll edit. Thanks.
Joel Etherton
+1  A: 

You could:

  • To create a wrapper class where you'll keep all your key values; this way you don't need to look into all your application, but just into one class
  • Or to create a custom configuration section, where you can validate all your required arguments in any way you want
Rubens Farias