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>());

Implementing a basic IoC container using C#

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

Table of contents

  • References
  • Downloads
  • Continue reading

    Improving LINQ code reusability: Select method

    Select method is used to project each element of a sequence into a new form, i.e. it can be used to map a collection of one type to a collection of another type. In this article I’ll show you a simple approach that will allow you to reuse the code used in the Select method.

    Table of contents

    The Problem

    Consider the following model:

    Let’s suppose that you have a services layer, so you don’t want to expose your domain objects directly to the client applications. Instead you create a set of data contracts (or DTOs, if you prefer):

    At some stage you’ll have to convert those Domain objects to data contracts. This is a common way of doing it:

    var details = repository.All<Album>().Select(album => new AlbumDetail {
        AlbumId = album.AlbumId,
        Price = album.Price,
        Title = album.Title,
    
        ArtistId = album.ArtistId,
        GenreId = album.GenreId,
        ArtistName = (album.Artist == null) ? null : album.Artist.Name,
        GenreName = (album.Genre == null) ? null : album.Genre.Name
    });
    

    There is a problem with this approach – if you need to query the same collection but using different criteria you have to duplicate the code inside the Select method.

    Solution 1 – Creating a method for the mapping

    In order to reuse the code, we can create a method that converts Album objects (Domain) to data contract objects:

    private static AlbumSummary CreateAlbumSummary(Album album)
    {
        return new AlbumSummary {
            AlbumId = album.AlbumId,
            Title = album.Title,
    
            ArtistName = (album.Artist == null) ? null : album.Artist.Name
        };
    }
    
    private static AlbumDetail CreateAlbumDetail(Album album)
    {
        return new AlbumDetail {
            AlbumId = album.AlbumId,
            Price = album.Price,
            Title = album.Title,
    
            ArtistId = album.ArtistId,
            GenreId = album.GenreId,
            ArtistName = (album.Artist == null) ? null : album.Artist.Name,
            GenreName = (album.Genre == null) ? null : album.Genre.Name
        };
    }
    

    Using the code:

    var albums = Albums.Select(CreateAlbumDetail);
    var albumsByGenre = Albums.Where(x => x.GenreId == genreId).Select(CreateAlbumDetail);
    
    // alternative way
    var albums2 = Albums.Select(x => CreateAlbumDetail(x));
    var albumsByGenre2 = Albums.Where(x => x.GenreId == genreId).Select(x => CreateAlbumDetail(x));
    

    Solution 2 – Creating a generic ObjectMapper object

    The previous solution solves the code reusability problem, but there’s still a tight coupling between components. Abstractions should be used to implement loose coupling between components – in this case, to abstract the mapping code.

    Step 1: define a contract (interface) with a method that converts one object of type TSource to an object of type TDestination:

    public interface IObjectMapper
    {
        TDestination Map<TSource, TDestination>(TSource source);
    }
    

    Step 2: create a class that implements IObjectMapper (click to expand):

    public class ObjectMapper : IObjectMapper
    {
        private Dictionary<Type, Func<object, object>> Mappers = new Dictionary<Type, Func<object, object>>
        {
            { typeof(Tuple<Album, AlbumDetail>), CreateAlbumDetail },
            { typeof(Tuple<Album, AlbumSummary>), CreateAlbumSummary }
    
            // more mappings here
            // ....
        };
    
    
        public TDestination Map<TSource, TDestination>(TSource source)
        {
            if(source == null)
                return default(TDestination);
    
            Func<object, object> mapper = null;
            Type key = typeof(Tuple<TSource, TDestination>);
    
            if(Mappers.TryGetValue(key, out mapper))
            {
                var newObject = mapper(source);
                return (TDestination) newObject;
            }
    
            string errorMessage = string.Format("Invalid mapping (Source: {0}, Destination: {1})";,
                                                typeof(TSource).FullName, 
                                                typeof(TDestination).FullName);
            
            throw new InvalidOperationException(errorMessage);
        }
    
    
        private static object CreateAlbumDetail(object source)
        {
            var album = source as Album;
    
            return new AlbumDetail {
                AlbumId = album.AlbumId,
                Price = album.Price,
                Title = album.Title,
    
                ArtistId = album.ArtistId,
                GenreId = album.GenreId,
                ArtistName = (album.Artist == null) ? null : album.Artist.Name,
                GenreName = (album.Genre == null) ? null : album.Genre.Name
            };
        }
    
        private static object CreateAlbumSummary(object source)
        {
            var album = source as Album;
    
            return new AlbumSummary {
                AlbumId = album.AlbumId,
                Title = album.Title,
                
                ArtistName = (album.Artist == null) ? null : album.Artist.Name
            };
        }
    }
    

    Example 1: Using LINQ

    Using the mapper in a LINQ expression – convert an Album collection to an AlbumSummary collection:

    IObjectMapper mapper = new ObjectMapper();
    
    IEnumerable<AlbumSummary> summaries = repository.All<Album>()
                                            .Select(mapper.Map<Album, AlbumSummary>);
    

    Example 1: Mapping a single object

    Using the mapper for a single object:

    var album = new Album {
        AlbumId = 1,
        Price = 10.0m,
        Title = "The Dreamer",
        Artist = new Artist { ArtistId = 1, Name = "José James" },
        Genre = new Genre { GenreId = 1, Name = "Jazz" }
    };
    
    IObjectMapper mapper = new ObjectMapper();
    
    AlbumDetail albumDetail = mapper.Map<Album, AlbumDetail>(album);
    

    Unit Testing

    Some NUnit tests:

    [Test]
    public void Given_a_non_existing_mapping_when_mapping_object_then_should_throw_InvalidOperationException()
    {
        // arrange
        IObjectMapper mapper = new ObjectMapper();
        var albumDetail = new AlbumDetail();
    
        // act/assert
        Assert.Throws<InvalidOperationException>(() => 
            // non-existing mapping
            mapper.Map<AlbumDetail, AlbumSummary>(albumDetail)
        );
    }
    
    [Test]
    public void Given_an_album_when_mapping_to_album_summary_should_equals_expected_album_summary()
    {
        // arrange
        IObjectMapper mapper = new ObjectMapper();
        
        var album = new Album {
            AlbumId = 4,
            Price = 10.0m,
            Title = "Heritage",
            Artist = new Artist { ArtistId = 4, Name = "Opeth" },
            Genre = new Genre { GenreId = 4, Name = "Metal" }
        };
    
        var expectedAlbumSummary = new AlbumSummary {
            AlbumId = 4,
            ArtistName = "Opeth",
            Title = "Heritage"
        };
        
        // act
        AlbumSummary albumSummary = mapper.Map<Album, AlbumSummary>(album);
        
        // assert
        Assert.AreEqual(albumSummary, expectedAlbumSummary);
    }
    

    Final thoughts

    In this article you learned how to reuse the code used in the Select method, and how you can use that code to map single objects. But writing mapping code is tedious and time consuming. There are mapping tools out there that can make your life easier – AutoMapper is one of them. I’ve used it in the past and I definitely recommend it. So, why use Automapper? Quoting their website:

    “What makes AutoMapper interesting is that it provides some interesting conventions to take the dirty work out of figuring out how to map type A to type B. As long as type B follows AutoMapper’s established convention, almost zero configuration is needed to map two types”

    “Mapping code is boring. Testing mapping code is even more boring. AutoMapper provides simple configuration of types, as well as simple testing of mappings”

    References

    Downloads

    Download the demo project (VS2010): LINQ-Select.zip

    Technorati Tags: , , ,

    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

    
    

    Entity Framework and T4: Generate Query Objects on the fly, part 1

    Generate Query Objects on the fly for your Entity Framework entities using T4 templates. Don’t worry about LINQ, let the objects do all the work for you.

    Table of contents

  • Configuration
  • References
  • Downloads
  • I’ve read some stuff about T4 templates in the last 2-3 years, but only recently I decided to give it a try. My first attempt was to generate Query Objects for Entity Framework, that’s what I’ll talk about in this article – what’s their purpose and how to use them.

    In part 2 I’ll create a demo ASP.NET MVC application that uses query objects created with this template. I already have another T4 template that creates javascript objects for my entities, and I’m developing a custom ASP.NET view template for those objects.

    Many thanks to Colin Meek [4], his work has really helpful.

    What is a Query Object?

    A Query Object is an object that represents a database query [1]:

    A Query Object is an interpreter [Gang of Four], that is, a structure of objects that can form itself into a SQL query. You can create this query by referring to classes and fields rather than tables and columns. In this way those who write the queries can do so independently of the database schema and changes to the schema can be localized in a single place.

    Assuming that you have a repository like this (I’m using this implementation):

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

    Instead of:

    var albuns = from x in repository.All<Album>()
                     where x.Artist.Name == "Metallica"
                     && x.Genre.Name.Contains("Metal")
                     && x.Price >= 5 && x.Price
                     select x;
    

    You can do this way:

    var search = new AlbumSearch();
    search.PriceFrom = 5;
    search.PriceTo = 10;
    search.Artist = new ArtistSearch(){ Name = "Metallica" };
    search.Genre = new GenreSearch(){ NameContains = "Metal" };
    
    var albuns = from x in repository.All<Album>(search.GetExpression())
                      select x;
    

    Continue reading

    Improve your UI code with Strategy Pattern

    This article is intended to provide a brief introduction to the Strategy Design Pattern, and how can help us to improve our User Interface code.

    The scenario – A simple blogging application

    Blogging application - showing actions by role

    You have a blog application and you want to limit user actions based on their roles.
    You have the following roles:

    • User
    • Writer
    • Editor

    and the following actions:

    • New Post – Creates a new blog post
    • Edit Post – Edits an existing blog post
    • Submit Post – Submits a post for approval
    • Reject Post – Rejects a previously submitted blog post
    • Publish Post – Publishes a previously submitted blog post

    The table below shows the actions per role type

    Actions

    User

    Writer

    Editor

    New post

    x

    Edit post

    x

    Submit post

    x

    Reject post

    x

    Publish post

    x

    Role type is represented by an enumeration:

    public enum RoleType
    {
        User,
        Writer,
        Editor
    }
    

    What’s the best solution for our problem?

    Continue reading