views:

18

answers:

1

Some I do quite a lot of is read integers from AppSettings. What's the best way to do this?

Rather than do this every time:

int page_size; 
if (int.TryParse( ConfigurationManager.AppSettings["PAGE_SIZE"], out page_size){

}

I'm thinking a method in my Helpers class like this:

int GetSettingInt(string key) { 
  int i;
  return int.TryParse(ConfigurationManager.AppSettings[key], out i) ? i : -1;
}

but this is just to save some keystrokes.

Ideally, I'd love to put them all into some kind of structure that I could use intellisense with so I don't end up with run-time errors, but I don't know how I'd approach this... or if this is even possible.

What's a best practices way of getting and reading integers from the AppSettings section of the Web.Config?

ONE MORE THING...

wouldn't it be a good idea to set this as readonly?

readonly int pageSize = Helpers.GetSettingInt("PAGE_SIZE") doesn't seem to work.

A: 

I've found an answer to my problem. It involves extra work at first, but in the end, it will reduce errors.

It is found at Scott Allen's blog OdeToCode and here's my implementation:

Create a static class called Config

public static class Config {

   public static int PageSize {
       get { return int.Parse(ConfigurationManager.AppSettings["PAGE_SIZE"]); }
   }
   public static int HighlightedProductId {
     get { 
      return int.Parse(ConfigurationManager.AppSettings["HIGHLIGHT_PID"]); 
     }
   }
}

Advantage of doing this are three-fold:

  • Intellisense
  • One breakpoint (DRY)
  • Since I only am writing the Config String ONCE, I do a regular int.Parse.

If someone changes the AppSetting Key, it will break, but I can handle that, as those values aren't changed and the performance is better than a TryParse and it can be fixed in one location.

The solution is so simple... I don't know why I didn't think of it before. Call the values like so:

Config.PageSize

Config.HighlightedProductId

Yay!

Atømix