Every project has a group of settings that can be used to configure a web site. They can be stored in the web.config file or in a database. Typically what happens is you create a number of functions to read settings like...

Every project has a group of settings that can be used to configure a web site. Sometimes we store these in the web.config file and sometimes we store them in a database and typically what happens is you create a number of functions to read settings like:


public static string GetSetting_AsString(string settingKey) { /*...*/ }
public static string GetSetting_AsInt(string settingKey) { /*...*/ }
public static string GetSetting_AsBool(string settingKey) { /*...*/ }

This is boring and I finally got sick of copying and pasting all of these functions and decided to start living the Generics dream! With one simple function I have been able to replace all other generic functions with one beautiful one.

And here it is:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public static class SettingRepository
{
    public static T GetSetting<T>(string settingKey, T defaultValue )
    {
        if (string.IsNullOrEmpty(settingKey))
            return defaultValue;

        ProjectEntities dc = new ProjectEntities();
        Setting setting = dc.Settings.Where(s => s.SettingKey == settingKey).FirstOrDefault();

        if (setting == null)
            return defaultValue;

        return (T)Convert.ChangeType(setting.SettingValue, typeof(T));
    }
}

This function gets a setting from a table named Setting in our database.

To retrieve strongly type settings is really easy.


public static void SettingRepositoryTest()
{
    string stringSetting = SettingRepository.GetSetting("stringKey", "Default Value");
    int intSetting = SettingRepository.GetSetting("intKey", 99);
    bool boolSetting = SettingRepository.GetSetting("boolKey", true);
    DateTime dateTimeSetting = SettingRepository.GetSetting("dateTimeKey", DateTime.Now);
}

You may also like

Kentico 6.0 Custom BizForm Validation

We have been working with Kentico and their BizForms module for a while now to implement “simple” forms to capture data. But like any work you do that uses the word simple, it quickly becomes a complex form with conditional validation. Revium uses custom form controls to extend Kentico BizForms.

Keep Reading

FluentSecurity + MvcSiteMapProvider = Better .Net Security Management

In my continual quest for find better ways of doing anything and everything this week I decided to tackle on of my arch nemesis: Security in ASP.Net, specifically Security in ASP.Net MVC3. You might ask why? We all know that there are at least 2 easy ways to implement security in MVC3.

Keep Reading

Newsletter sign up

Every couple of months we send out an update on what's been happening around our office and the web. Sign up and see what you think. And of course, we never spam.