Enum with Attributes and Extension Methods

I wanted a way to tag up an enum, so that I could use enums within code (instead of string matching) to ensure consistency; while at the same time providing values to the enums (and since c# enums are always inherited from an int, we can't give string values like VB could).
This also happens to allow multiple "values" for each enum value, which is something that can't be done any other way.
The AppSettingKeyAttribute class defines an attribute to store a Key (string).
The AppSettingsKey enum then uses the attribute on each of its values, to store the App Setting's Key
The Key extension method will then retrieve the AppSettingKeyAttribute's value given an AppSettingsKey.
Finally, the Value extension method uses the Key extension method to actually retrieve the value from the web.config

This was an adaptation of the same technique described here:
http://www.codeproject.com/Articles/4279/Mapping-Text-to-Enum-entries
http://geekswithblogs.net/rakker/archive/2006/05/19/78952.aspx
Language:
C#
Keywords:
Code Snippet

class AppSettingKeyAttribute : Attribute
{
    public string Key { get; protected set; }

    public AppSettingKeyAttribute(string KeyName)
    {
        this.Key = KeyName;
    }
}

public enum AppSettingKeys
{
    [
AppSettingKey("SqlServer")]
    SqlServer_HostName,

    [AppSettingKey("SqlDatabase")]
    SqlServer_Database,

    [AppSettingKey("SqlUsername")]
    SqlServer_Username,

    [AppSettingKey("SqlPassword")]
    SqlServer_Password
}

public static string Key(this AppSettingKeys inpKey)
{
    // Get the type
    Type type = inpKey.GetType();

    // Get fieldinfo for this type
    System.Reflection.FieldInfo fieldInfo = type.GetField(inpKey.ToString());

    // Get the stringvalue attributes
    AppSettingKeyAttribute[] attribs = fieldInfo.GetCustomAttributes(typeof(AppSettingKeyAttribute), false) as AppSettingKeyAttribute[];

    // Return the first if there was a match.
    return attribs.Length > 0 ? attribs[0].Key : null;
}

public static string Value(this AppSettingKeys inpKey)
{
    string outval = String.Empty;

    System.Configuration.Configuration WebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/");

    System.Configuration.AppSettingsSection AppSetting = WebConfig.AppSettings;

    outval = AppSetting.Settings[inpKey.Key()].Value;

    return outval;

}

 


Created 2012-01-25
comments powered by Disqus
Login