Monday, December 31, 2007

Attaching strings to enums

I Found this little cool way to attach strings to enums. Using .NET 3.5 you can do something cool and simple like this


public static class EnumExtension
{
public static string GetDescription(this Enum enumObj)
{
FieldInfo fieldInfo =
enumObj.GetType().GetField(enumObj.ToString());
object[] attribArray = fieldInfo.GetCustomAttributes(false);
if (attribArray.Length == 0)
return String.Empty;
else
{
DescriptionAttribute attrib =
attribArray[0] as DescriptionAttribute;
return attrib.Description;
}
}
}

class Program
{
public enum EmployeeType
{
[Description("Regular Employee")]
RegularEmploye,
[Description("Store Manager")]
StoreManager,
[Description("Chain Store Manager")]
ChainStoreManager,
[Description("Department Manager")]
DepartmentManager,
[Description("On Floor Supervisor")]
Supervisor
}

static void Main(string[] args)
{
string str = EmployeeType.ChainStoreManager.GetDescription();
}
}


Basically I have added an extension to the enum class to extract the value of the Description Attribute. Now, every Enum class will have a GetDescription method attached to it. This is a nice and clean way to string values out of your enums....







only supported in VS2008 using .NET 3.5

Friday, December 28, 2007

MVP Article coming soon...

I am currently working on an article for the code project showing MVP using AOP and DI (Dependency Injection). I hope to be done before the holidays...

The article will cover the following:

- How to make the view unaware of the controller (using DI)
- How to handle long running processes at the controller level
- How to move logic outside of the controller and place it in the business layer
- How to handle threading within the view, using AOP.

Keep checking, I hope to be done within a few days...