NLog.MongoDB - A MongoDB Target for NLog

by Jason Wicker 3. October 2011 23:43

I've been playing with MongoDB quite a bit lately to wrap my head around it. 

We use NLog at work, and I thought MongoDB would be a great way to store NLog entries so I threw this MongoDB target to connect the two.

To install, place the binaries in your bin, and configure NLog like so: 

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
			xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<extensions>
		<add assembly="NLog.MongoDB"/>
	</extensions>

	<targets>
		<target name="Mongo" type="MongoDB" host="localhost" port="27017"/>
	</targets>
	<rules>
		<logger name="*" minLevel="Info" appendTo="Mongo"/>
	</rules>
</nlog>

Fork it on GitHub

or

Get the binaries here:

NLog.MongoDB.Binaries.zip (728.05 kb)

Zipped Source here:

NLog.MongoDB.zip (14.99 mb)

Tags: , ,

MongoDB

A Script-Block Templated Delegate for Inline-Scripts in Razor Partials

by Jason Wicker 21. June 2011 20:16

One of the best-practices recommendations I have struggled with is to have all your <script> tags at the bottom of the page. This is easily accomplished from a standard view; Create a section in your layout called "scripts" that renders just below where you load the libraries and use this section wherever you need scripting. No problem.

Notice I said, "standard view"? What happens if you have a partial that requires some script to run? Some would argue that the scripts should not be in the partial, but I have had a few special cases where this simply isn't possible.

I have a common "Message" partial, who's job is to render messages to the page. Most of these messages are HTML and display normally, but some messages are actually "growl" type notification messages and the partial needs to execute a function on rendering. HERE is the problem. You can't write to a section from a partial, plus partials are sometimes rendered via AJAX.

I needed a way to get the script block from my partial rendered after the scripts are loaded if part of an entire view, but I want to load the scripts inline, should I render the partial using AJAX (since the libraries will be loaded already at this point).

Sure, I could use a Head.js or some other script loading library, but some of these break the "unobtrusive" libraries that come with MVC and I didn't want to lose that functionality.

Templated Delegates to the Rescue

I created a ScriptBlock extension-method that accepts a templated delegate from anywhere in a view. The extensions method determines if the request is AJAX or not and writes the script back to the view if it is. If the partial is part of an entire view page, the script is captured in a StringBuilder, stored in HttpContext. A counterpart extension method "WriteScriptBlocks" can then be included in my layout, wherever I want the scripts to render.

Check it out.

Extentions Methods:

public static class ViewPageExtensions
{        
        private const string SCRIPTBLOCK_BUILDER = "ScriptBlockBuilder";
 
        public static MvcHtmlString ScriptBlock(
            this WebViewPage webPage,
            Func<dynamicHelperResult> template)
        {
            if (!webPage.IsAjax)
            {
                var scriptBuilder = webPage.Context.Items[SCRIPTBLOCK_BUILDER] 
                                   as StringBuilder ?? new StringBuilder();
 
                scriptBuilder.Append(template(null).ToHtmlString());
 
                webPage.Context.Items[SCRIPTBLOCK_BUILDER] = scriptBuilder;
 
                return new MvcHtmlString(string.Empty);
            }
            return new MvcHtmlString(template(null).ToHtmlString());
        }
 
        public static MvcHtmlString WriteScriptBlocks(this WebViewPage webPage)
        {
            var scriptBuilder = webPage.Context.Items[SCRIPTBLOCK_BUILDER] 
                               as StringBuilder ?? new StringBuilder();
 
            return new MvcHtmlString(scriptBuilder.ToString());
        }
}

Using the templated delegate as a parameter is great, because any model-view-binding is executed before the content is delivered to this function. Since it's a template, Intellisense and code coloring also works.  Here it is, in use:

Partial:

@model ViewMessage
 
@if (Model.Type == MessageType.Success || Model.UseNotification)
{     
    var message = Model.Message.FixForJson();
    if(Model.HasLink)
    {
        message += "<br/><a href='{0}'>{1}</a>".ToFormat(Model.LinkUrl, Model.LinkText);
    }   
    // My Script Block Extension Method, notice all the code-coloring and binding is still functional
    @this.ScriptBlock(
    @<script  type='text/javascript'>
        $(document).ready(function () {
            notify('@message''@Model.Type.ToString()''@Model.Type.ToString().ToLower()');
        });
    </script>)
 
} else {
<div class="message @Model.DisplayType clear">
 
    @if (this.Model.ShowCloseButton) { <span class="jq-close">close [x]</span>  } 
    
    <img src="/content/images/icons/@Model.Type.ToString()_Large.png" alt="@Model.Type.ToString()" />
    <h2 class="messageTitle">@Model.Message</h2>
    @if (Model.HasLink) { <p><a href="@Model.LinkUrl">@Model.LinkText</a></p> }        
    @Html.Raw(Model.ErrorList)
</div>
<div class="clear"></div>

Layout:

   ... Content

    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js"></script>
    <script type="text/javascript" src="//ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
    <script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
    <script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.validate.unobtrusive.min.js"></script>
    <script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.unobtrusive-ajax.min.js"></script>
    
 
    <script type="text/javascript" src="@Links.Scripts.Site_js"></script>
 
    @RenderSection("Scripts"false)
    @this.WriteScriptBlocks()
</body>
</html>

Enjoy!

Tags: , ,

Razor | MVC

A Light-Weight MVC Route Debugging App

by Jason 9. December 2009 10:26

I have a huge MVC project that I am working with that has a pretty complex routing schema. Debugging routes gets pretty hairy, so I was delighted to find the RouteDebug assembly that Phil Haack put together. It helped me immensely, but my project takes too long to compile for quick route testing. 

I needed a quick way of creating routes and testing the route values, so I created a super-light-weight small website to use his assembly with nothing else.  You can put your route creation code right into the Global.asax and instantly get the results. I found this super useful and I hope you do too.

 

RouteDebug-Web.zip (12.19 kb)

Tags: , ,

Expression-Based URLs in MVC - Using a Specific Route with LinkBuilder

by Jason 8. December 2009 15:29

In the MVC Future Assembly there lives a super handy class called "LinkBuilder". This class takes an expression and builds a URL using your configured routes.

Creating an extension method in your own project to use this class is pretty straight forward:

public static string Action<TController>(this UrlHelper helper, Expression<Action<TController>> action)

    where TController : Controller

{

    return Microsoft.Web.Mvc.LinkBuilder.BuildUrlFromExpression(helper.RequestContext, helper.RouteCollection, action);

}

You can also use this library to create your own "ActionLink" extensions too. BUT, this isn't why I wrote this article.

I wanted to extend this method to specify an EXACT route to use, as I had a special route to format the URLs and the above method uses the first route it finds that could work - usually the default route.

After struggling for hours trying to parse the expression myself (UGH!), a simple solution presented itself:

public static string Action<TController>(this UrlHelper helper, Expression<Action<TController>> action, string routeName)

    where TController : Controller

{

    var routeCollection = helper.RouteCollection;

 

    // Check to ensure this route exists first. If not, don't filter the routes.

    if (helper.RouteCollection[routeName] != null)
         routeCollection  = new RouteCollection { helper.RouteCollection[routeName] };

 

    return Microsoft.Web.Mvc.LinkBuilder.BuildUrlFromExpression(helper.RequestContext, routeCollection, action);

}

This method filters the RouteCollection down to the exact route you are want to use and passes the filtered collection to the LinkBuilder... ahhh, routing-bliss.

Now you can use it in your views like this:

<%= Url.Action<CredentialsController>(c => c.Edit(credID), "CredentialActions") %>

 

 

Tags: , ,

Using Policy Injection with ASP.NET MVC and Unity

by Jason Wicker 3. December 2009 09:02

There are a million and a half articles out there about Policy Injection and the Policy Injection Blocks (from Enterprise Library). Most of them are by my new favorite blogger, David Hayden. If you aren't familiar with Unity, check out these posts first.

The articles span the life-cycle of Unity from before Policy Injection was introduced and some of the actual type names change from article to article, so it wasn't as straight forward as I am going to make it here.

First of all, I didn't want to use a config file - I wanted to configure my policies in the same place I was configuring my dependencies; in the Global.asax code-behind.

It turns out that this is super easy!

Assuming you already have a reference to the Unity library "Microsoft.Practices.Unity", all you need to add is a reference to the "Microsoft.Unity.Interception" library, found in Microsoft Enterprise Library 4.1

You probably already have a place where you are configuring your dependencies:

// Register for Dependency Injection

container.RegisterType<IDataContextProvider, DataContextProvider>();

Now all you need to do is setup the container with an extension that's called 'Interception' then configure each of the Interfaces you want to intercept with Policies. Like so:

// Register for Policy Injection

container.AddNewExtension<Interception>().Configure<Interception>()

    .SetDefaultInterceptorFor<IDataContextProvider>(new TransparentProxyInterceptor());

Now, when you use Unity to resolve your objects, it will detect if any policies are decorated on the interface or the concrete class. If there are policies, Unity creates a transparent proxy object and executes your policies like it does in the Policy Application Blocks. Check out this article to see how to create handlers.

Now you are ready to place your "Policy Attributes" on your classes. Later, I will show you some of my favorite policies I have written for MVC.

Tags: , , , ,

A Generic Repository for LinqToSql

by Jason 5. November 2009 13:01

In my last article, I showed you a way of creating an interface for the LinqToSql DataContext so that you can mock the actual implementation for unit testing. Well, there is another benifit to creating such an interface. The interface we created, uses LinqToSql's underying generic methods. Using this, we can create a completely generic repository class, to handle all data transactions from our data-layer.

I won't get into the Repository Pattern or Domain Driven Design, because there are too many people out there, WAY smarter than me discussing it in full. I use this pattern mainly for convenience in testing and reducing code, but it is worth reading up on -- it is some great stuff!

First off, there are literally a THOUSAND articles out there talking about the Repository Pattern and quite a few articles discussing implementing this with the LinqToSql DataContext. None of them were quite what I needed, so I present to you, my version with ideas borrowed from this article and this one (both of these concepts are awesome, however they lacked the IDataContext piece so that it can be unit tested.

IDataContext

First, let's assume that you have already followed my last article, and your DataContext implements IDataContext.

public interface IDataContext : IDisposable

{

    IQueryable<TEntity> GetQueryable<TEntity>() where TEntity : class;

    ITable GetEditable<TEntity>() where TEntity : class;

    void Insert<TEntity>(TEntity instance) where TEntity : class;

    void InsertAll<TEntity>(IEnumerable<TEntity> instances) where TEntity : class;

    void Delete<TEntity>(TEntity instance) where TEntity : class;

    void DeleteAll<TEntity>(IEnumerable<TEntity> instances) where TEntity : class;

    void SubmitChanges();

    int ExecuteCommand(string command, params object[] parameters);

    DbConnection Connection { get; }

}

Implemented in your DataContext

partial class SampleDataContext : IDataContext

{

    public virtual IQueryable<TEntity> GetQueryable<TEntity>() where TEntity : class

    {

        return this.GetTable<TEntity>();

    }

 

    public virtual ITable GetEditable<TEntity>() where TEntity : class

    {

        return this.GetTable<TEntity>();

    }

 

    public void Insert<TEntity>(TEntity instance) where TEntity : class

    {

        this.GetTable<TEntity>().InsertOnSubmit(instance);

    }

 

    public void InsertAll<TEntity>(IEnumerable<TEntity> instances) where TEntity : class

    {

        this.GetTable<TEntity>().InsertAllOnSubmit(instances);

    }

 

    public void Delete<TEntity>(TEntity instance) where TEntity : class

    {

        this.GetTable<TEntity>().DeleteOnSubmit(instance);

    }

 

    public void DeleteAll<TEntity>(IEnumerable<TEntity> instances) where TEntity : class

    {

        this.GetTable<TEntity>().DeleteAllOnSubmit(instances);

    }

}

IDataRepository

Once implemented, let's create our interface for the IDataRepository. We will need the basic data operations: List, GetAddDelete and SubmitChanges.

public interface IDataRepository<T>

        where T : class

{

    IQueryable<T> List();

    T Get(int id);

    T Get(Expression<Func<T, bool>> selector);

    void Add(T instance);

    void Delete(T instance);

    void SubmitChanges();

}

DataRepository<T>

Ah, moving on to the actual implementation... Use IDataContext to implement the repository methods.

public class DataRepository<T> : IDataRepository<T>

        where T : class

{

    private readonly IDataContext _DataContext;

 

    public DataRepository(IDataContext dataContext)

    {

        _DataContext = dataContext;

    }

 

    public IQueryable<T> List()

    {

        return _DataContext.GetQueryable<T>();

    }

 

    public T Get(int id)

    {

        var itemParameter = Expression.Parameter(typeof(T), "item");

 

        var whereExpression = Expression.Lambda<Func<T, bool>>

            (

            Expression.Equal(

                Expression.Property(

                    itemParameter,

                    typeof(T).GetPrimaryKey().Name

                    ),

                Expression.Constant(id)

                ),

            new[] { itemParameter }

            );

 

        return _DataContext.GetQueryable<T>().SingleOrDefault(whereExpression);

    }

 

    public T Get(Expression<Func<T, bool>> selector)

    {

        return _DataContext.GetQueryable<T>().SingleOrDefault(selector);

    }

 

    public void Add(T instance)

    {

        _DataContext.GetEditable<T>().InsertOnSubmit(instance);

    }

 

    public void Delete(T instance)

    {

        _DataContext.GetEditable<T>().DeleteOnSubmit(instance);

    }

 

    public void SubmitChanges()

    {

        _DataContext.SubmitChanges();

    }

}

This class uses Dependency Injection and accesses the DataContext as IDataContext. This allows us to create unit tests for this class with a mocked data-context.

There are two Get methods, both of which pass a Where expression down to the Linq extensions. The first attempts to build an expression manually. This is assuming that you use int as your IDs. If you don't you can always update the code to fit your needs. GetPrimaryKey() is an extension method written by the genius, Mike Hadlow over here. It's awesome, and I included it down below.

Both return a single instance from the DataContext, but the Get(Expression<Func<T,bool>> selector) function allows a more complex lookup (for complex identities or whatever). It's passed as an expression, just like the "Where()" function, in the Linq extensions.

Sample Usage

So what does this buy us? Well, with this simple generic class we suddenly have a full, strongly-typed repository layer for each object in the DataContext.

Check it out:

public class Controller

{

    readonly IDataRepository<User> _UserRepository;

    readonly IDataRepository<Car> _CarRepository;

 

    // Go ahead and use Dependency Injection -- you know you wanna.

    public Controller(IDataRepository<User> userRepository, IDataRepository<Car> carRepository)

    {

        // You can now declare and use "specific" repositories for your Linq objects.

 

        _UserRepository = userRepository;

        _CarRepository = carRepository;

    }

 

    public void DoSomething()

    {

        // Basic get by ID

        var car = _CarRepository.Get(1);

 

        // Complex selector

        var differentCar = _CarRepository.Get(c => c.Name == "Ford");

 

        // Basic list

        var listOfUsers = _UserRepository.List();

 

        // List, with filters

        var filteredUsers = _UserRepository.List()

            .Where(u => u.Name.StartsWith("T"));

 

        // Add

        _UserRepository.Add(new User { Name = "Fred"});

        _UserRepository.SubmitChanges();

 

        // Update

        var editableUser = _UserRepository.Get(1);

        editableUser.Name = "New Name";

        _UserRepository.SubmitChanges();

    }

 

}

Obviously, you can only create a Repository<T> for a class in your context. Otherwise, you would see an epic exception.

Another great thing about this pattern is it's benifits with code-coverage. You can create unit tests for each of these methods and in effect cover your entire data-layer. Not to mention the value in having less code laying around.

OH, and here's that extension method:

public static PropertyInfo GetPrimaryKey(this Type entityType)

{

    foreach (PropertyInfo property in entityType.GetProperties())

    {

        ColumnAttribute[] attributes = (ColumnAttribute[])property.GetCustomAttributes(typeof(ColumnAttribute), true);

        if (attributes.Length == 1)

        {

            ColumnAttribute columnAttribute = attributes[0];

            if (columnAttribute.IsPrimaryKey)

            {

                if (property.PropertyType != typeof(int))

                {

                    throw new ApplicationException(string.Format(

                        "Primary key, '{0}', of type '{1}' is not int", property.Name, entityType));

                }

                return property;

            }

        }

    }

    throw new ApplicationException(string.Format(

        "No primary key defined for type {0}", entityType.Name));

}

 

RepositorySample.zip (9.40 kb)

Tags: , , , ,

IDataContext - Using an Interface for the LinqToSql DataContext

by Jason 4. November 2009 09:23

As you know, I have recently become a huge fan of the Dependency Injection (DI) and Inversion of Control (IoC) patterns, but was stumped when trying to implement this pattern down to my data layer. I LOVE LinqToSQL, but I wasn't sure how I could make the Linq DataContext an abstract interface. I stumbled upon a great article discussing How to make the DataContext "Unit Testable". From this, I boiled down a version of an interface that was easy to implement in the DataContext.

An Interface for the DataContext: IDataContext

LinqToSql exposes Sql Server tables as theunmockable Table which is a sealed class. But LinqToSql namespace has an interface ITable which the Table type implements and that is easy to mock, also this ITable exposes InsertOnSubmit, InsertAllOnSubmit, DeleteOnSubmit, DeleteAllOnSubmit. So in our interface we exposed the ITable instead of that concrete Table which makes this partial Database class completely unit testable.

public interface IDataContext : IDisposable

{

    IQueryable<TEntity> GetQueryable<TEntity>() where TEntity : class;

 

    ITable GetEditable<TEntity>() where TEntity : class;

 

    void Insert<TEntity>(TEntity instance) where TEntity : class;

 

    void InsertAll<TEntity>(IEnumerable<TEntity> instances) where TEntity : class;

 

    void Delete<TEntity>(TEntity instance) where TEntity : class;

 

    void DeleteAll<TEntity>(IEnumerable<TEntity> instances) where TEntity : class;

 

    void SubmitChanges();

 

    int ExecuteCommand(string command, params object[] parameters);

 

    DbConnection Connection { get; }

}

As you can see, all the basic functions of the DataContext exist for your consuming class.

Implement that Sucker

Now we need to implement this interface in our DataContext. Right-click on your DBML file, and select "View Code".  This creates a partial class file for the DataContext. In it, you can implement the interface.

partial class SomeDataContext: IDataContext

{

    public virtual IQueryable<TEntity> GetQueryable<TEntity>() where TEntity : class

    {

        return this.GetTable<TEntity>();

    }

 

    public virtual ITable GetEditable<TEntity>() where TEntity : class

    {

        return this.GetTable<TEntity>();

    }

 

    public void Insert<TEntity>(TEntity instance) where TEntity : class

    {

        this.GetEditable<TEntity>().InsertOnSubmit(instance);

    }

 

    public void InsertAll<TEntity>(IEnumerable<TEntity> instances) where TEntity : class

    {

        this.GetEditable<TEntity>().InsertAllOnSubmit(instances);

    }

 

    public void Delete<TEntity>(TEntity instance) where TEntity : class

    {

        this.GetEditable<TEntity>().DeleteOnSubmit(instance);

    }

 

    public void DeleteAll<TEntity>(IEnumerable<TEntity> instances) where TEntity : class

    {

        this.GetEditable<TEntity>().DeleteAllOnSubmit(instances);

    }

}

Example Usage

Now, your consuming classes are free to use the DataContext as the Interface "IDataContext" which can be mocked in Unit Tests.

public class SomeController

{

    readonly IDataContext _DataContext;

 

    public SomeController(IDataContext dataContext)

    {

        _DataContext = dataContext;

    }

 

    public void DoSomething()

    {

        var foo = _DataContext.GetQueryable<Foo>()

                 .SingleOrDefault(f => f.FooId == 1);

 

    }

}

Conclusion

This demonstrates how you can make your DataContext an interface that is mockable and could be injected at runtime for DI. In the next article, I will show how you can create a generic repository using the IDataContext.

 

Tags: , , ,

In-Class AOP | Using Action<T> Delegates to Reduce Redunant Code

by Jason 23. October 2009 14:39

I am a recent fanboy of AOP (aspect oriented) design patterns, so maybe this isn't anything new to you, but MAN it's changed my life. Staying hard-and-fast on the "DRY" principle (don't repeat yourself) is an awesome concept, but it isn't always easy. Take for instance the "Try/Catch/Finally" block. When accessing external resources, you sometimes need to wrap each call in a this block to manage the resource in the event of a failure. Something like, the following:

public void DoSomething()

{

    try

    {

        // Perform the action

        _service.Do();

    }

    catch (Exception exc)

    {

        // Log exception, etc.

        Log(exc);

        _service.Abort();

    }

    finally

    {

        // Clean up resources

        _service.Close();

    }

}

Now it isn't terribly obvious how you can get around this (at least it wasn't for me). If only we could have every call to this service wrapped in the same try/catch/finally block... Enter the Action<T> delegate. With this guy, you can create a method within this class (or a base blass) that provides this block as a wrapper for your action. For instance:

private void Invoke(Action<IService> action)

{

    try

    {

        // Perform the action

        func(_service);

    }

    catch (Exception exc)

    {

        // Log exception, etc.

        Log(exc);

    }

    finally

    {

        // Clean up resources

        _service.Close();

    }

}

Then, you could make your calls like through the "Invoke" method and everything would be wrapped in the common Try/Catch/Finally block. Check it out:

public void DoSomething()

{

    Invoke(s=>

        s.Do()

        );

}

It's that easy! Now, if you are going to be returning values, then you may want to create an overload using the Func<> delegate, like this:

private TReturnType Invoke<TReturnType>(Func<IService, TReturnType> action)

{

    try

    {

        // Perform the action

        return func(_service);

    }

    catch (Exception exc)

    {

        // Log exception, etc.

        Log(exc);

    }

    finally

    {

        // Clean up resources

        _service.Close();

    }

}

Then it could be used like so:

public string DoSomething()

{

    return Invoke(s=>

        s.Do()

        );

}

As you can see, this kind of thinking could have a major impact on your code and increase your code's reusability.

Enjoy.

Tags: , ,

Enum<T> - Better Enum Parsing using Strongly-Typed Generics

by Jason 22. October 2009 13:55

When dealing with Enums (parsing, getting values, etc.) there is entirely too much casting and Types being passed around. For instance, to simply parse a string to it’s Enum value, one would do this:

TestEnum testEnum = (TestEnum)Enum.Parse(typeof(TestEnum), "Super");

We had to define the enum type THREE (count them) THREE times, in a single row. Blech! With this helper, this statement becomes much cleaner:

var testEnum = Enum<TestEnum>.Parse("Super");

Only ONE declaration of the Enum type. Nice! (Okay, so I cheated and used the 'var' keyword, but you get the point)

Also, there are some really handy helpers built-in, like:
 TryParse - four overloads, two returning a bool with an out parameter and two that just returns NULL if it fails to parse.
 ToEnumerable - returns a typed-list of all the Enum options

Example:

// Fails parsing, enum value = null

var enumTest = Enum<TestEnum>.TryParse("WrongValue");

 

// Get an IEnumerable of the Enums

var list = Enum<TestEnum>.ToEnumerable();

Plus more goodies -- feel free to take a look.

Now, I am certain that I am not the first to create a generic helper to make parsing Enums easier (article one, article two to name a few) but here is a complete Enum<T> helper class for all your Enum needs. Note, I even recreated all the standard static methods available in Enum, so that there will be no need to pass the “typeof(X)” parameter.

// So this...

string name = Enum<TestEnum>.GetName(TestEnum.Super);

 

// Instead of this...

string name = Enum.GetName(typeof(TestEnum), TestEnum.Super);

Enum<T> Code:

public static class Enum<T>

    where T: struct

{

    public static T Parse(string name)

    {

        return Parse(name, false);

    }

 

    public static T Parse(string name, bool ignoreCase)

    {

        return (T)Enum.Parse(typeof(T), name, ignoreCase);

    }

 

    public static T? TryParse(string name)

    {

        return TryParse(name, false);

    }

 

    public static T? TryParse(string name, bool ignoreCase)

    {

        T value;

        if (!string.IsNullOrEmpty(name) && TryParse(name, out value, ignoreCase))

            return value;

        return null;

    }

 

    public static bool TryParse(string name, out T value)

    {

        return TryParse(name, out value, false);

    }

 

    public static bool TryParse(string name, out T value, bool ignoreCase)

    {

        try

        {

            value = Parse(name, ignoreCase);

            return true;

        }

        catch (ArgumentException)

        {

            value = default(T);

            return false;

        }

    }

 

    public static IEnumerable<T> ToEnumerable()

    {

        foreach (var value in Enum.GetValues(typeof(T)))

             yield return (T)value;

    }

 

    public static IEnumerable<object> GetValues()

    {

        foreach (var value in Enum.GetValues(typeof(T)))

            yield return value;

    }

 

    public static IDictionary<object, string> GetDictionary()

    {

        Dictionary<object, string> dictionary = new Dictionary<object, string>();

        foreach (var value in GetValues())

            dictionary.Add(

                Convert.ChangeType(value, Enum.GetUnderlyingType(typeof(T))),

                GetName(value));

 

        return dictionary;

    }

 

    #region Strongly-Typed Enum Extenders

 

    public static string Format(object value, string format)

    {

        return Enum.Format(typeof(T), value, format);

    }

 

    public static string GetName(object value)

    {

        return Enum.GetName(typeof(T), value);

    }

 

    public static IEnumerable<string> GetNames()

    {

        return Enum.GetNames(typeof(T));

    }

 

    public static Type GetUnderlyingType()

    {

        return Enum.GetUnderlyingType(typeof(T));

    }

 

    public static bool IsDefined(object value)

    {

        return Enum.IsDefined(typeof(T), value);

    }

 

    public static T ToObject(object value)

    {

        return (T)Enum.ToObject(typeof(T), value);

    }

 

    public static T ToObject(byte value)

    {

        return (T)Enum.ToObject(typeof(T), value);

    }

 

    public static T ToObject(sbyte value)

    {

        return (T)Enum.ToObject(typeof(T), value);

    }

 

    public static T ToObject(int value)

    {

        return (T)Enum.ToObject(typeof(T), value);

    }

 

    public static T ToObject(uint value)

    {

        return (T)Enum.ToObject(typeof(T), value);

    }

 

    public static T ToObject(long value)

    {

        return (T)Enum.ToObject(typeof(T), value);

    }

 

    public static T ToObject(ulong value)

    {

        return (T)Enum.ToObject(typeof(T), value);

    }

 

    public static T ToObject(short value)

    {

        return (T)Enum.ToObject(typeof(T), value);

    }

 

    public static T ToObject(ushort value)

    {

        return (T)Enum.ToObject(typeof(T), value);

    }

 

    #endregion

}

Enjoy!

Source Code:

Enum.zip (858.00 bytes)

Tags: , ,

Stack Overflow

GitHub

 

Month List