Re-throwing exceptions without losing the original stack strace in .NET

This is nothing new – if you need to re-throw an exception in a catch block without losing the stack trace you use the throw statement like this:
01 throwThings are a bit different outside a catch block, though. Consider the following code sample:
02_throw_messagehandler_wrong.png

Just to give you some context, this excerpt is from a MessageHandler that I implemented to log HTTP requests and responses in a ASP.NET Web API application (based on Log message Request and Response in ASP.NET WebAPI). I have an ExceptionHandler class that will log all unhandled exceptions, that’s why I’m re-throwing the exception here.

The problem is that the following command will instantiate a new exception and clear the original stack trace:

throw exception;

Fortunately there is an easy fix. From .NET v4.5 you can use ExceptionDispatchInfo class to capture the current state of an exception and re-throw an exception without changing the original stack-trace:
03_throw_messagehandler_right

That’s it! Happy coding šŸ™‚

Advertisements

Refactoring tips and tricks: Exceptions

Consider the following class:

    public class FooService
    {
        private readonly ILogger _logger;

        public FooService(ILogger logger)
        {
            _logger = logger;
        }

        public void Foo()
        {
            try
            {
                // Foo code goes here...
            }
            catch (Exception ex)
            {
                _logger.LogException(ex);
            }
        }

        public void Bar()
        {
            try
            {
                // Bar code goes here...
            }
            catch (Exception ex)
            {
                _logger.LogException(ex);
            }
        }
    }
    

This is a very common scenario that I’ve seen in many different places over the last few years – each method has some code wrapped in a try-catch block. To get rid of the code duplication is easy, we can move the try-catch block to a new method that will take a delegate as a parameter (code to be executed):

    private void Try(Action action)
    {
        try
        {
            action();
        }
        catch (Exception ex)
        {
            _logger.LogException(ex);
        }
    }

Refactoring the class:

    public class FooService
    {
        private readonly ILogger _logger;

        public FooService2(ILogger logger)
        {
            _logger = logger;
        }

        public void Foo()
        {
            Try(() => {
                // Foo code goes here...
            });
        }

        public void Bar()
        {
            Try(() => {
                // Bar code goes here...
            });
        }

        private void Try(Action action)
        {
            try
            {
                action();
            }
            catch (Exception ex)
            {
                _logger.LogException(ex);
            }
        }
    }

 

 

Using Dictionaries to replace long if or switch statements

Imagine the following scenario – you have created some validators for your models: Foo, Bar and Xyz.

    public interface IValidator
    {
        bool Validate(object model);
    }

    // Validator for Foo class
    public class FooValidator : IValidator
    {
        public bool Validate(object model)
        {
            // ...
        }
    }

    // Validator for Bar class
    public class BarValidator : IValidator
    {
        public bool Validate(object model)
        {
            // ...
        }
    }

    // Validator for Xyz class
    public class XyzValidator : IValidator
    {
        public bool Validate(object model)
        {
            // ...
        }
    }

You decide to create a factory class for the validators to prevent users from creating instances directly using the new keyword. For example, this code would create a validator for Foo:

    var model = new Foo();
    var validatorFactory = new ValidatorFactory();
    IValidator validator = validatorFactory.CreateValidatorFor<Foo>();

    if (validator.Validate(model))
    {
        // ...
    }

Implementation of the factory:

    using System;

    public class ValidatorFactory
    {
        public IValidator CreateValidatorFor<T>()
        {
            Type modelType = typeof (T);
            IValidator validator = CreateValidatorFor(modelType);

            return validator;
        }

        public IValidator CreateValidatorFor(Type modelType)
        {
            if (modelType == null)
            {
                throw new ArgumentNullException("modelType");
            }

            if(modelType == typeof(Foo))
            {
                return new FooValidator();
            }
            else if(modelType == typeof(Bar))
            {
                return new BarValidator();
            }
            else if(modelType == typeof(Xyz))
            {
                return new XyzValidator();
            }

            string errorMessage = string.Concat("Could not find validator for type ", modelType.FullName);
            throw new ArgumentException("modelType", errorMessage);
        }
    }

As you can see, for each model you have an if statement. This works fine if you only need to create 2 or 3 validators but if you need more your code will get bigger and bigger and will be harder to read/maintain. The same applies to switch statements.

The first step to solve this problem is to create a Dictionary to store the validators. The key of the Dictionary will be the type of the model and the value will be a delegate that creates an instance of the validator for that model:

	var validators = new Dictionary<Type, Func<IValidator>>
	{
		{ typeof(Foo), () => new FooValidator() },
		{ typeof(Bar), () => new BarValidator() },
		{ typeof(Xyz), () => new XyzValidator() }
	};

Changing the implementation of the factory to use the dictionary:

    public class ValidatorFactory : IValidatorFactory
    {
        private static Dictionary<Type, Func<IValidator>> _validators =
			new Dictionary<Type, Func<IValidator>> {
            { typeof(Foo), () => new FooValidator() },
            { typeof(Bar), () => new BarValidator() },
            { typeof(Xyz), () => new XyzValidator() }
        };

        public IValidator CreateValidatorFor<T>()
        {
            Type modelType = typeof (T);
            IValidator validator = CreateValidatorFor(modelType);

            return validator;
        }

        public IValidator CreateValidatorFor(Type modelType)
        {
            if (modelType == null)
            {
                throw new ArgumentNullException("modelType");
            }

            Func<IValidator> validatorFunc;

            if (_validators.TryGetValue(modelType, out validatorFunc))
            {
                IValidator validator = validatorFunc();

                return validator;
            }

            string errorMessage = string.Concat("Could not find validator for type ", modelType.FullName);
            throw new ArgumentException("modelType", errorMessage);
        }
    }

That’s it, code looks much nicer now! To configure a new validator just add a new key/value pair to the _validators Dictionary.

Finally, testing the code using NUnit:

	// arrange
	var factory = new ValidatorFactory();

	// act
	IValidator validator = factory.CreateValidatorFor<Foo>();

	// assert
	Assert.That(validator, Is.TypeOf<FooValidator>());

Code Kata – Numbers to Words, using javascript and TDD

This code kata is based on the KataNumbersInWords kata – convert numbers into words:

  • 3: “three”
  • 159: “one hundred and fifty-nine”
  • 2400: “two thousand and four hundred”

Katas are a good way to learn/practice TDD and/or learn more about a particular technology – in my particular case I decided to to this kata to improve my javascript skills.

The purpose of the exercise is to write the code incrementally, one step at a time – starting with the simplest case scenario (1 digit numbers) and then adding the code to handle the other scenarios (2 digit numbers, 3 digit numbers, etc).

Assume that the input is valid (number).

Test cases:

  • 1 digit numbers
    • 0 should return “zero”
    • 3 should return “three”
    • 7 should return “seven”
  • 2 digit numbers
    • 10 should return “ten”
    • 14 should return “fourteen”
    • 20 should return “twenty”
    • 21 should return “twenty-one”
    • 56 should return “fifty-six”
  • 3 digit numbers
    • 209 should return “two hundred and nine”
    • 300 should return “three hundred”
    • 417 should return “four hundred and seventeen”
    • 560 should return “five hundred and sixty”
    • 698 should return “six hundred and ninety-eight”
  • 4 digit numbers
    • 3004 should return “three thousand and four”
    • 4000 should return “four thousand”
    • 5020 should return “five thousand and twenty”
    • 6300 should return “six thousand and three hundred”
    • 7111 should return “seven thousand and one hundred and eleven”
  • 5 digit numbers
    • 40000 should return “forty thousand”
    • 70393 should return “seventy thousand and three hundred and ninety-three”
    • 87654 should return “eighty-seven thousand and six hundred and fifty-four”
  • 6 digit numbers
    • 500000 should return “five hundred thousand”
    • 803308 should return “eight hundred and three thousand and three hundred and eight”
    • 999999 should return “nine hundred and ninety-nine thousand and nine hundred and ninety-nine”

You can see my implementation here (I’m using WebStorm v8 and JS Test Driver):

Download the code (WebStorm project): NumbersToWords.zip

Implementing a basic IoC container using C#

Implementing a basic IoC container using C#, step by step.

Table of contents

  • References
  • Downloads
  • Continue reading

    Use extension methods to keep your code simple and DRY

    In this article I’ll show you why and how to use generic extension methods to keep your code simple and DRY.

    Table of contents

    The Problem

    Consider this simple model:

    public class Format
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    
    public class Category
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }   
        
    public class Product 
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
    
        public IEnumerable<Category> Categories { get; set; }
        public IEnumerable<Format> Formats { get; set; }
    
        public bool HasCategories
        {
            get
            {
                if(Categories == null)
                    return false;
    
                return Categories.Any();
            }
        }
    
        public bool HasFormats
        {
            get
            {
                if(Formats == null)
                    return false;
    
                return Formats.Any();
            }
        }
    }
    

    As you can see, I have created to properties HasCategories and HasFormats in the Product class to check if the collections Categories and Formats have any element, respectively.
    The following ASP.NET MVC view shows how these properties can be used:

    @model Product
    
    <h1>@Model.Name</h1>
    
    <p>@Html.DisplayFor(model => model.Description)</p>
    
    <h2>Product Categories</h2>
    
    <ul>
    @if(Model.HasCategories)
        {
            foreach(var category in Model.Categories)
            {
            <li>@category.Name</li>
            }
        }
        else
        {
            <li>This product has no categories</li>
        }
    </ul>
    
    <h2>Formats Available</h2>
    <ul>
    @if(Model.HasFormats)
        {
            foreach(var format in Model.Formats)
            {
            <li>@format.Name</li>
            }
        }
        else
        {
            <li>No formats available</li>
        }
    </ul>
    
    

    There is a problem with this code though – the properties improve the code readability and can be reused, but you may have dozens or hundreds of classes that may need properties like these. It is a verious tedious and time consuming task to create such properties in all the classes we need – a better option would be to create an extension method to do that work for us.

    Extension methods to the rescue

    If you take a good look into the HasCategories and HasFormats properties you can see that the code is similar, the only thing that changes is the type of the properties.

    We can then create a generic extension method to check if any object that implements IEnumerable (List, etc) is null or empty:

    namespace Extensions
    {
        public static class IEnumerableExtensions
        {
            /// <summary>
            /// Determines whether an enumerable is null or empty.
            /// </summary>
            /// <typeparam name="T">Type of the enumerable</typeparam>
            /// <param name="collection">The collection.</param>
            /// <returns>
            ///   <c>true</c> if the enumerable is null or empty; otherwise, <c>false</c>.
            /// </returns>
            public static bool IsNullOrEmpty<T>(this IEnumerable<T> collection)
            {
                if(collection == null)
                    return true;
    
                return !collection.Any();
            }
        }
    }
    

    There’s no more need to have the properties HasCategories and HasFormats so they can be removed from the Product class. The code now looks simpler and cleaner:

    public class Product 
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
    
        public IEnumerable<Category> Categories { get; set; }
        public IEnumerable<Format> Formats { get; set; }
    }
    

    Finally, we can change the ASP.NET MVC view to use the extension method:

    @using Extensions
    @model Product
    
    <h1>@Model.Name</h1>
    <p>@Html.DisplayFor(model => model.Description)</p>
    
    <h2>Product Categories</h2>
    <ul>
    @if(Model.Categories.IsNullOrEmpty())
    {
        foreach(var category in Model.Categories)
        {
        <li>@category.Name</li>
        }
    }
    else
    {
        <li>This product has no categories</li>
    }
    </ul>
    
    <h2>Formats Available</h2>
    <ul>
    @if(Model.Formats.IsNullOrEmpty())
    {
        foreach(var format in Model.Formats)
        {
        <li>@format.Name</li>
        }
    }
    else
    {
        <li>No formats available</li>
    }
    </ul>
    
    

    Final thoughts

    In short, you can (and should) use extension methods to keep your code DRY.

    Basically you need to identity pieces of code that are generic enough and replace them with an extension method, if possible. You will have code that is easier to maintain and also more time to develop other funcionalities.

    References

    .NET Guidelines: Should I have one class per file?

    I had this discussion many times over the last few years:

    • Should we have a class per file?
    • What about other types such as interfaces, enums, …?

    Opinions on this subject vary a lot. This purpose of this article is to provide you some basic guidelines and why you should follow them.

    Table of contents

    Continue reading

    ASP.NET Web Services Dependency Injection using Unity

    Recently, I had to setup Unity IoC container in an existing ASP.NET 3.5 Web Forms application. This application had not only web pages (.aspx files), but also some Web Services (.asmx files). After some research, I found out David Hayden’s screencast: Unity IoC and ASP.NET screencast – Dependency Injection into Web Pages.

    You can use a similar technique for your Web Services – that’s what I’ll show you in this article.

    Table of contents

    Example – Adding logging to your application

    You have the following interface and its implementation:

    public interface ILogger
    {
        void Write(string message);
    }
    
    public class DebugLogger : ILogger
    {
        public void Write(string message)
        {
            Debug.WriteLine(message);
        }
    }
    

     

    Step 1: Setting up the container in Global.asax

    The first step is to setup Unity Container in Global.asax file. This is a good place to do it because it can be accessed either by web pages or by web services.
    The CreateContainer() method is the place where the dependencies are specified.

    public class Global : HttpApplication, IContainerAccessor
    {
        private static IUnityContainer _container;
    
        public static IUnityContainer Container
        {
            get
            {
                return _container;
            }
            private set
            {
                _container = value;
            }
        }
    
        IUnityContainer IContainerAccessor.Container
        {
            get
            {
                return Container;
            }
        }
    
        protected void Application_Start(object sender, EventArgs e)
        {
            CreateContainer();
        }
    
        protected virtual void CreateContainer()
        {
            IUnityContainer container = new UnityContainer();
            container.RegisterType<ILogger, DebugLogger>();
            
            Container = container;
        }
    }
    

     

    Step 2: Creating a base class for the services

    Create a generic BaseService that all your services will inherit from. The dependencies will be injected when you create an instance of the service (default constructor).

    public abstract class BaseService<T> : System.Web.Services.WebService where T : class
    {
        public BaseService()
        {
            InjectDependencies();
        }
    
        protected virtual void InjectDependencies()
        {
            HttpContext context = HttpContext.Current;
    
            if (context == null)
                return;
    
            IContainerAccessor accessor = context.ApplicationInstance as IContainerAccessor;
    
            if (accessor == null)
                return;
    
            IUnityContainer container = accessor.Container;
    
            if (container == null)
                throw new InvalidOperationException("Container on Global Application Class is Null. Cannot perform BuildUp.");
    
            container.BuildUp(this as T);
        }
    }
    

     

    Step 3: Setting up the services

    Now all you need to do is to inherit from the BaseService and invoke its base constructor.
    Don’t forget to add the [Dependency] attribute to your dependency, and it has to be public.

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class DummyService : BaseService<DummyService>
    {
        [Dependency]
        public ILogger Logger
        {
            get;
            set;
        }
    
        public DummyService() : base()
        {
        }
    
        [WebMethod]
        public string HelloWorld(string name)
        {
            string message = string.Format("Hello World, {0}!", name);
    
            this.Logger.Write(message);
    
            return message;
        }
    }
    

    That’s it! Now you just need to compile and run the application and see it in action šŸ™‚

    Feel free to download the demo application

    References

    Downloads

    Download the demo project (VS2010): UnityAsmxWebServices.zip

    Entity Framework and T4: Generate Specification Objects for your entities

    Learn how to use Specification Pattern and how to generate Specification Objects for your Entity Framework entities using T4 templates.

    Table of contents

    Specification Pattern Overview

    According to Martin Fowler and Eric Evans, a specification define a set of conditions that a candidate object must fulfill in order to meet the specification. Specifications can be used for:

    • Selection: When you need to select a set of objects based on some criteria
    • Validation: when you need to check that only suitable objects are used for a certain purpose

    The Specification Pattern can be represented like this in .NET (using generics):

    public interface ISpecification<T> where T : class
    {
        Expression<Func<T, bool>> GetExpression();
        bool IsSatisfiedBy(T entity);
    }
    

    We can also create Composite Specifications by combining other specifications – this allow us to reuse existing specifications to create more complex ones.

    Using Specification Pattern

    I’m using the MVC Music Store database, this is the model:

    Music Store Model
    And now some examples. I will assume that you have a repository like this (I’m using this implementation):

    public IQueryable All<T>(Expression<Func<bool, T>> expression) where T : class
    

    A generic Specification class

    public class Specification<T> : ISpecification<T> where T : class
    {
        private Expression<Func<T, bool>> expression;
    
        public Expression<Func<T, bool>> GetExpression()
        {
            return expression;
        }
    
        public Specification(Expression<Func<T, bool>> expression)
        {
            this.expression = expression;
        }
    
        public bool IsSatisfiedBy(T entity)
        {
            var query = (new[] { entity }).AsQueryable();
    
            return query.Any(this.expression);
        }
    }
    

    Creating specifications

    Using the generic class to create specifications:

    • One specification for jazz albums
    • One specification for cheap albums (price between 1 and 10)
    public static ISpecification<Album> JazzAlbumSpecification
    {
    	get
    	{
    		return new Specification<Album>(
    			x => x.Genre.Name == "Jazz"
    		);
    	}
    }
    
    public static ISpecification<Album> CheapAlbumSpecification
    {
    	get
    	{
    		return new Specification<Album>(
    			x => x.Price >= 1 && x.Price <= 10
    		);
    	}
    }
    

    Selecting objects

    var albums = from x in repository.All<Album>(JazzAlbumSpecification.GetExpression())
                 select x;
    

    Performing validation

    Album metalAlbum = GetMetalAlbum();
    Album jazzAlbum = GetJazzAlbum();
    
    bool isJazzAlbum = JazzAlbumSpecification.IsSatisfiedBy(metalAlbum); 
    isJazzAlbum = JazzAlbumSpecification.IsSatisfiedBy(jazzAlbum);
    

    Composing specifications

    Existing specifications can be combined to form more complex ones. Using these extension methods it’s easy to create composite specifications (see this article to understand how to combine lambda expressions):

    public static ISpecification<T> And<T>(this ISpecification<T> first, ISpecification<T> second) where T : class
    {
        return new Specification<T>(
            first.GetExpression()
            .And(second.GetExpression())
        );
    }
    
    public static ISpecification<T> Or<T>(this ISpecification<T> first, ISpecification<T> second) where T : class
    {
    	return new Specification<T>(
            first.GetExpression()
            .Or(second.GetExpression())
        );
    }
    

    The specifications defined above can now be combined to compose a new specification like this:

    ISpecification<Album> cheapJazzAlbumSpecification = JazzAlbumSpecification.And(CheapAlbumSpecification);
    
    // using the specification to select all cheap jazz albums
    var cheapJazzAlbums = from x in repository.All<Album>(cheapJazzAlbumSpecification.GetExpression())
                          select x;
    

    Using T4 to generate Specification Objects

    T4 is a code generator built right into Visual Studio. You can generate any text file using T4 templates: C#, javascript, HTML, XML and many others. If you’ve never heard about it, this is a good place to start:

    T4 (Text Template Transformation Toolkit) Code Generation – Best Kept Visual Studio Secret

    I’ve created a T4 template that generates automatically all the Specification Objects, one for each entity in our model. All the generated objects have all the public properties of their respective entities, including association properties. All objects were marked with the [Serializable] attribute, so you can easily serialize it if you need.

    In a previous article I’ve created query objects for Entity Framework, I’m generating exactly the same properties in this template. You can see a complete description of the generated properties here.

    This is the generated object model:


    The previous specifications can now be written like this:

    public static ISpecification<Album> JazzAlbumSpecification
    {
        get
        {
            return new AlbumSpecification() {
                Genre = new GenreSpecification() { Name = "Jazz" }
            };
        }
    }
    
    public static ISpecification<Album> CheapAlbumSpecification
    {
        get
        {
            return new AlbumSpecification() {
                PriceFrom = 1,
                PriceTo = 10
            };
        }
    }
    

    Configuration

    In the demo solution double-click ModelSpecification.tt and change the following lines, according to your needs:

    string inputFile = @"Model.edmx";
    string namespaceName = @"MusicStore.Model";
    string filenameSuffix = "Specification.gen.cs";
    

    When you save the template file or you rebuild the project the code will be regenerated. If you don’t want to generate the code, remove the value of the Custom Tool property in the property browser of the template file (by default the value is TextTemplatingFileGenerator).

    References

    [1] Specification Pattern

    [2] Specification (Martin Fowler/Eric Evans)

    [3] T4 (Text Template Transformation Toolkit) Code Generation – Best Kept Visual Studio Secret

    [4] LINQ to Entities: Combining Predicates

    [5] Implementing ISession in EF4

    Downloads

    Download the demo project: MusicStore-T4-Specification.rar