Tired of looking for errors in log files? Use OneTrueError - Automated exception management in .NET.

Reintroducing my compiler class.

I created a class a couple of years ago which simplifies the CodeCom handling when you want to dynamically create objects in .NET. I got reminded of it when I read a question at stackoverflow.com.

The class can be used to easily generate .NET (C#) objects by having a class definition in a string variable.

First you have to define an interface (or base class) in your project:

    public interface IWorld
        string Hello(string value);

Then you need to add a class to a string variable:

    string code = @"namespace MyNamespace
      class Temp : IWorld
          public string Hello(string value)
              return ""World "" + value;

And let’s generate an object and invoke the method:

    Compiler compiler = new Compiler();

    //repeat for all types (to automatically add namespaces and assemblies to the CodeDom compiler)

    // compile the code. Will throw an exception if it do not work.

    // create an instance
    var obj = compiler.CreateInstance<IWorld>();

    // and invoke it
    string result = obj.Hello("World!");

Note that it was a long time ago that I wrote it. The example might not work 100%. (The Compiler class do work, the example might use it incorrectly).

Source code

Posted in CodeProject | Tagged , | Leave a comment

Three reasons to why you should use view models

I’m answered a couple of questions at stackoverflow regarding the benefit of view models. Here is a summary of all my answers focusing on view models in ASP.NET MVC.

Reason 1: Remove logic from your views.

When you start working with ASP.NET MVC you’ll most likely ask yourself why you should use a view model. Using your domain model or entity model works perfectly fine. And it does. For a while. But as you continue to use your models you’ll discover that you have to add some adaptations in your views. Here is a typical usage adaptation (using razor view engine):

Hello @model.UserName

Your age: @(model.Age != 0 ? model.Age.ToString() : "n/a")

Not so bad, is it? The problem is that you have introduced logic into your view, which is bad for two reasons:

A) You can not unit test that code, and the only way to make sure that it works is user testing.
B) You need to repeat that code for every view that intends to use your model (code duplication = code smell)

All those small adaptations will lead to a big mess eventually.

Reason two: Security

One of the biggest advantages with view models are to remove security risks. Your database objects or domain objects will most likely contain properties that the user should not be able to change. It can be a property called IsAdmin or Reputation.

All those properties will automatically be changed by the model binder if they exist in the model (and are posted in the FORM which is quite easy to do if you know HTML). Simply remove them from the view model and they’ll never be changed.

Reason three: Loose coupling

By using domain models or entity models you are adding coupling between your lower layers and the presentation layer and that is seldom good. Google “loose coupling” to find out more.

Basically it means that if you change your domain/entity model you have to change all your views that use that model. If you use a ViewModel you only have to change the code that maps between an entity/domain model and the view model.

How to make the model mapping easier

I usually use a framework called AutoMapper to manage the mappings between viewmodels and other models. AutoMapper and it’s alternatives usually let yuo use a single line of code to do the mapping.

Posted in Architecture, CodeProject | Tagged | 1 Comment

Generic type restriction for enums

I was looking for a way to restrict a generic type identifier to only allow enums. Since you are not allowed to use where T : Enum I checked the metadata for Enum and found that it implements ValueType, IComparable, IFormattable, IConvertible. You cant use ValueType as restriction, but struct works fine.

In other words, use “where T : struct, IComparable, IFormattable, IConvertible” to make a type restriction which should work well as an enum restriction.

The reason to why I needed the specification is that I want to be able to fetch the DescriptionAttribute from enums. I use it to be able to add friendly names to enum values.

Example enum:

public enum MyEnum
    [Description("Some value"]

    [Description("Foo bar")]

Fetch value:

MyEnum value = MyEnum.FooBar;

// will display "Foo bar"

The extension method that does the magic:

        public static string GetDescription<T>(this T instance)
            where T : struct, IConvertible, IFormattable, IComparable
            var type = typeof (T);
            var memberInfo = type.GetMember(instance.ToString())[0];

            var attribute = (DescriptionAttribute)memberInfo.GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault();
            return attribute == null ? instance.ToString() : attribute.Description;
Posted in CodeProject, extensionmethods | Leave a comment

Render a view to a string variable

It’s sometimes useful to render a view or a partial to a string variable instead of returning an ActionResult. the following code does just that, add it to your base controller.

protected string RenderPartialViewToString(string viewName, object model)
    if (string.IsNullOrEmpty(viewName))
        viewName = ControllerContext.RouteData.GetRequiredString("action");

    ViewData.Model = model;

    using (StringWriter sw = new StringWriter()) {
        ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
        ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
        viewResult.View.Render(viewContext, sw);

        return sw.GetStringBuilder().ToString();
Posted in CodeProject | Tagged | Leave a comment

How to create documentation using code comments.

Use the regular XmlDoc tags to document your code, it’s usually enough to type /// in Visual studio to get the default tags.

Then use SandCastle to generate documentation. It can create regular help files, but also web based help. Remember that you have to check the “XML Documentation file” option in Visual Studio -> Project Settings -> Build -> Output.

SandCastle is not the easiest tool to work with. I usually use Sandcastle helpfile builder which is a user friendly GUI for sandcastle.

Posted in CodeProject | Tagged , | Leave a comment

jquery ui autocomplete: Uncaught TypeError: Cannot read property ‘element’ of undefined

I got that exception when I loaded some options through JSON (with ASP.NET MVC). It took a lot of digging before I finally found what the cause was. And it’s not what I expected:

I’ve made a custom menu plugin in the jQuery namespace. And it seems like autocomplete tries to use ‘menu’ function ($jQuery.menu) too, which failed utterly. I removed my plugin and everything worked smoothly.

Here’s how you can use the autocomplete plugin yourself with ajax (I preload all available options):

In your Razor view:

<script type="text/javascript">
    var baseUri = '@Url.Content("~")'; // to get it working in root or a virtual dir
    $(function() {
      $.getJSON(baseUri + 'myController/myAction', function(data) {
          $('myTextbox').autocomplete({ source: data });

And in your controller:

public ActionResult Items()
    var items = _repository.GetYourItems().Select(p => p.Title).ToList(); // only get titles
    return Json(items, JsonRequestBehavior.AllowGet); //it's safe to get these items using GET
Posted in Uncategorized | Tagged , | Leave a comment

Liskovs Substitution Principle

I’m a big fan of patterns and principles. And I’m going explain all SOLID principles in different blog posts. This post is all about LSP.

LSP says that you should always be able to use a base class or interface instead of the actual implementation and still get the expected result. If you can’t, your breaking LSP.

An example:

public interface IDuck
   void Swim();
public class Duck : IDuck
   public void Swim()
      //do something to swim
public class ElectricDuck : IDuck
   public void Swim()
      if (!IsTurnedOn)

      //swim logic  

And the calling code

void MakeDuckSwim(IDuck duck)

As you can see, there are two examples of ducks. One regular duck and one electric duck. The electric duck can only swim if it’s turned on. This breaks LSP since it must be turned on to be able to swim (the MakeDuckSwim method will not work as expected if a duck is electric and not turned on).

You can of course solve it by doing something like this:

void MakeDuckSwim(IDuck duck)
    if (duck is ElectricDuck)

But that would break Open/Closed principle (SOLID) and has to be implemented everywhere (and therefore still generate instable code).

The proper solution would be to automatically turn on the duck in the Swim method and by doing so make the electric duck behave exactly as defined by the IDuck interface.

The solution with turning on the duck inside the Swim method can have side effects when working with the actual implementation (ElectricDuck). But that can be solved by using a explicit interface implementation. imho it’s more likely that you get problems by NOT turning it on in Swim since it’s expected that it will swim when using the IDuck interface.

What LSP is really saying is that all classes must follow the contracts that they have been given. Just as you may not update items in your website with GET if you are following the HTTP protocol.

Posted in Architecture, CodeProject | Tagged , | Leave a comment

How to become a computer expert

Computer expert flowchart

Posted in Uncategorized | Leave a comment

More natural string formatting using an extension method

If you are like me, you don’t determine if you should include parameters in string before you start writing, thus you haven’t decided that string.Format should be used until it’s too late. You then need to go back and refactor that string, which can destroy the smooth coding flow that you got going.

Lets be saved by an extension method:

public static class StringExtensions
	public static string FormatWith(this string instance, params object[] arguments)
	    return string.Format(instance, arguments);

Which allows you to reformat the code as:

// Simple example
Console.WriteLine("Hello '{0}'!".FormatWith("world"));

// Multiple parameters:
var str = @"Happy birthday {0}!
    {1} is a beatiful age, isn't ?".FormatWith(user.Name, user.Age);
Posted in extensionmethods | Tagged | Leave a comment

HtmlHelper for enums in ASP.Net MVC3

Have you tried to get enums working with HtmlHelpers? It can be a hassle and here is my solution for it. It requires that you tag each entry in the enum with a [Description] attribute.

public static class SelectExtensions

    public static string GetInputName<TModel, TProperty>(Expression<Func<TModel, TProperty>> expression)
        if (expression.Body.NodeType == ExpressionType.Call)
            MethodCallExpression methodCallExpression = (MethodCallExpression)expression.Body;
            string name = GetInputName(methodCallExpression);
            return name.Substring(expression.Parameters[0].Name.Length + 1);

        return expression.Body.ToString().Substring(expression.Parameters[0].Name.Length + 1);

    private static string GetInputName(MethodCallExpression expression)
        // p => p.Foo.Bar().Baz.ToString() => p.Foo OR throw...
        MethodCallExpression methodCallExpression = expression.Object as MethodCallExpression;
        if (methodCallExpression != null)
            return GetInputName(methodCallExpression);
        return expression.Object.ToString();

    public static MvcHtmlString EnumDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression) where TModel : class
        string inputName = GetInputName(expression);
        var value = htmlHelper.ViewData.Model == null
            ? default(TProperty)
            : expression.Compile()(htmlHelper.ViewData.Model);

        return htmlHelper.DropDownList(inputName, ToSelectList(typeof(TProperty), value.ToString()));

    public static SelectList ToSelectList(Type enumType, string selectedItem)
        List<SelectListItem> items = new List<SelectListItem>();
        foreach (var item in Enum.GetValues(enumType))
            FieldInfo fi = enumType.GetField(item.ToString());
            var attribute = fi.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault();
            var title = attribute == null ? item.ToString() : ((DescriptionAttribute)attribute).Description;
            var listItem = new SelectListItem
                    Value = ((int)item).ToString(),
                    Text = title,
                    Selected = selectedItem == ((int)item).ToString()

        return new SelectList(items, "Value", "Text");


@Html.EnumDropDownListFor(m => m.SubscriptionMode);

If you want to be able to use it for validation, you need to be able to have a “undefined” entry in your enum and do the following change:

// replace "Value = ((int)item).ToString()," in to select list.
Value = (int)item == 0 ? string.Empty : ((int)item).ToString(),
Posted in CodeProject | Tagged | Leave a comment