Chris McKelt

Remembering Thoughts

 

Recent comments

Archive

Authors

Categories

None


Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2012

Enum extension methods

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Text;

namespace Challenger.Global.Util.Extensions
{
    public static class EnumExtensionMethods
    {

        public static T ParseAsEnumByDescriptionAttribute<T>(this string description)  // where T : enum
        {
            if (string.IsNullOrEmpty(description))
            {
                throw new ArgumentNullException(description, @"Cannot parse an empty description");
            }

            Type enumType = typeof(T);
            if (!enumType.IsEnum)
            {
                throw new InvalidOperationException(string.Format("Invalid Enum type{0}", typeof(T)));
            }

            foreach (T item in Enum.GetValues(typeof(T)))
            {
                DescriptionAttribute[] attributes = (DescriptionAttribute[])item.GetType().GetField(item.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (attributes.Length > 0 && attributes[0].Description.ToUpper() == description.ToUpper())
                {
                    return item;
                }
            }
            throw new InvalidOperationException(string.Format("Couldn't find enum of type {0} with attribute of '{1}'", typeof(T), description));
        }

        public static string GetDescription(this Enum enumerationValue)
        {
            DescriptionAttribute[] attributes = (DescriptionAttribute[])enumerationValue.GetType().GetField(enumerationValue.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
            return attributes.Length > 0 ? attributes[0].Description : enumerationValue.ToString();
        }

        public static EnumDto GetDto(this Enum enumerationValue)
        {
            return new EnumDto { Value = enumerationValue, Description = GetDescription(enumerationValue) };
        }

        public static IList<EnumDto> ToEnumDtoList(this Enum enumerationValue)
        {
            var vals = Enum.GetValues(typeof (Enum));
            IList<EnumDto> list = (from object val in vals
                                   let desc = ((Enum) val).GetDescription()
                                   select new EnumDto() {Description = desc, Value = (Enum) val}).ToList();

            return list;
        }
       
        /// <summary>
        /// Gets all items for an enum value.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public static IEnumerable<T> GetAllItems<T>(this Enum value)
        {
            return from object item in Enum.GetValues(typeof(T)) select (T)item;
        }

        /// <summary>
        /// Gets all items for an enum type.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public static IEnumerable<T> GetAllItems<T>() where T : struct
        {
            return Enum.GetValues(typeof(T)).Cast<T>();
        }

        /// <summary>
        /// Gets all combined items from an enum value.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        /// <example>
        /// Displays ValueA and ValueB.
        /// <code>
        /// EnumExample dummy = EnumExample.Combi;
        /// foreach (var item in dummy.GetAllSelectedItems<EnumExample>())
        /// {
        ///    Console.WriteLine(item);
        /// }
        /// </code>
        /// </example>
        public static IEnumerable<T> GetAllSelectedItems<T>(this Enum value)
        {
            int valueAsInt = Convert.ToInt32(value, CultureInfo.InvariantCulture);

            return from object item in Enum.GetValues(typeof(T)) let itemAsInt = Convert.ToInt32(item, CultureInfo.InvariantCulture) where itemAsInt == (valueAsInt & itemAsInt) select (T)item;
        }

        /// <summary>
        /// Determines whether the enum value contains a specific value.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="request">The request.</param>
        /// <returns>
        ///     <c>true</c> if value contains the specified value; otherwise, <c>false</c>.
        /// </returns>
        /// <example>
        /// <code>
        /// EnumExample dummy = EnumExample.Combi;
        /// if (dummy.Contains<EnumExample>(EnumExample.ValueA))
        /// {
        ///     Console.WriteLine("dummy contains EnumExample.ValueA");
        /// }
        /// </code>
        /// </example>
        public static bool Contains<T>(this Enum value, T request)
        {
            int valueAsInt = Convert.ToInt32(value, CultureInfo.InvariantCulture);
            int requestAsInt = Convert.ToInt32(request, CultureInfo.InvariantCulture);

            if (requestAsInt == (valueAsInt & requestAsInt))
            {
                return true;
            }

            return false;
        }


        public static T ToEnum<T>(this string enumerationString)
        {
            return (T)Enum.Parse(typeof(T), enumerationString);
        }
    }
}

Posted by chris on Friday, October 23, 2009 9:33 AM
Permalink | Comments (1) | Post RSSRSS comment feed

Log4Net config

    <log4net>
        <appender name="WindowsEventAppender" type="log4net.Appender.EventLogAppender">
            <param name="LogName" value="Application" />
            <applicationName value="Rating" />
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%date [%thread] %-5level %logger%newline =&gt; %message%newline" />
            </layout>
            <filter type="log4net.Filter.LevelRangeFilter">
                <param name="LevelMin" value="ERROR" />
            </filter>
        </appender>
        <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
            <file value="Application.log" />
            <appendToFile value="true" />
            <maximumFileSize value="300KB" />
            <maxSizeRollBackups value="2" />
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%level %thread %logger - %message%newline" />
            </layout>
        </appender>

        <root>
            <level value="DEBUG" />
            <appender-ref ref="WindowsEventAppender" />
            <appender-ref ref="RollingFile" />
        </root>
    </log4net>

Posted by Chris on Thursday, October 15, 2009 8:33 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Context Specification

namespace Example
{
    using System;

    using Microsoft.VisualStudio.TestTools.UnitTesting;

    using Rhino.Mocks;

    public abstract class ContextSpecification<T>
    {
        protected Exception executionException;

        protected T sut { get; set; }

        [TestInitialize]
        public void Start()
        {
            this.Context();
            this.SetupMockResults();
            this.Because();
        }

        [TestCleanup]
        public void CleanUp()
        {
            this.Clean();
        }

        protected virtual void Context()
        {
        }

        protected virtual void SetupMockResults()
        {
        }

        protected virtual void Because()
        {
        }

        protected virtual void Clean()
        {
        }

        protected TInterface GetDependency<TInterface>() where TInterface : class
        {
            return MockRepository.GenerateMock<TInterface>();
        }

        public void Execute(Action action)
        {
            try
            {
                action();
            }
            catch (Exception ex)
            {
                executionException = ex;
            }
        }

    }
}

Posted by chris on Monday, October 12, 2009 4:48 AM
Permalink | Comments (1) | Post RSSRSS comment feed