tisdag 10 juni 2014

Enum with DescriptionAttribute

public static class EnumExtensions
{
    public static T GetAttribute(this Enum enumeration) where T : Attribute
    {
        var type = enumeration.GetType();
        var memberInfos = type.GetMember(enumeration.ToString());
        var attribute = memberInfos[0].GetCustomAttributes(typeof (T), false);

        var attributes = attribute.Cast().ToList();
        
        return attributes.SingleOrDefault();
    }

    public static string Description(this Enum enumeration)
    {
        var attribute = GetAttribute(enumeration);
        if (attribute == null)
            return "";

        return attribute.Description;
    }
}

public enum GroundType
{
    [Description("Jord")]
    Soil = 1,
    [Description("Gräs")]
    Grass = 2
}

public class DescriptionAttribute : Attribute
{
    private readonly string _descr;

    public DescriptionAttribute(string descr) { _descr = descr; }

    public string Description
    {
        get { return _descr; }
    }

    public override string ToString() { return Description; }
}
Use like so:
var groundType = GroundType.Soil;
var desc = groundType.Description();

torsdag 24 april 2014

Small settings factory class

Public Class WidgetSettingsFactory
 Public Function GetItemSettings(Of T As ItemSettings)(ByVal externalName As String, ByVal doc As Document) As ItemSettings
        Dim retval As T = GetSettingsFromType(GetType(T))
        Dim helpers As New Helpers()
        Dim templateId As Integer = doc.TemplateId
        Dim nodeId As Integer = doc.NodeId
        Dim documentId As Integer = doc.DocumentId

        Dim itemProperties As Dictionary(Of String, String) = helpers.GetItemProperties(externalName, templateId)
        If Not itemProperties Is Nothing Then
            For Each item As KeyValuePair(Of String, String) In itemProperties
                retval.SetProperty(item.Key, helpers.ReplaceDynPropNameWithValue(item.Value, nodeId))
            Next
        End If

        Dim dataSettings As Dictionary(Of String, String) = helpers.GetDocumentDataSettings(externalName, templateId, documentId)
        If Not dataSettings Is Nothing Then
            For Each item As KeyValuePair(Of String, String) In dataSettings
                retval.SetProperty(item.Key, helpers.ReplaceDynPropNameWithValue(item.Value, nodeId))
            Next
        End If
        Return retval
    End Function

    ''' 
    ''' Returns a settings object that is inherited from ItemSettings
    ''' 
    ''' Type of Settings object
    ''' A new instance of the incoming type of object
    ''' 
    Public Shared Function GetSettingsFromType(ByVal settingsType As Type) As ItemSettings
        Return settingsType.Assembly.CreateInstance(settingsType.FullName)
    End Function
End Class