Ehsan Ghanbari

Experience, DotNet, Solutions

Simple command handler in .net

 

I want to introduce a simple command handler pattern in order to separate commands and queries of your applications if it’s needed. Sometimes especially in large-scale applications, you need to have two layers for reading and write separated and assign two teams to work on them.

You can use the pattern in this post based on the complexity and needs of your application. I recommend that don’t call this CQRS pattern as it’s something completely different and more complex.

 

Get started and Create an interface with no any member:

public interface ICommand

    {

    }

You will see later in this blog post that ICommand is just a flag to determine the commands for the handler. Every command which is trying to make a change in application’s state should return a result. so create another interface named ICommandResult

public interface ICommandResult

    {

        string Message { get; }

        bool Success { get; }

    }

implement the above interface as CommandResult and derive the FailureResult and SuccessResult classes from:

internal abstract class CommandResult : ICommandResult

    {

        public string Message { get; protected set; }

        public bool Success { get; protected set; }

    }



internal class FailureResult : CommandResult

    {

        public FailureResult(string message)

        {

            Success = false;

            Message = message;

        }

    }



    internal class SuccessResult : CommandResult

    {

        public SuccessResult(string message)

        {

            Success = true;

            Message = message;

        }

    }

Now create an interface for handling the validations in CommandBus class:

internal interface IValidationHandler<in TCommand> where TCommand : ICommand

    {

        IEnumerable<ValidationResult> Validate(TCommand command);

    }

 And create a class for validations:

public class ValidationResult

    {

        /// <summary>

        /// Initializes a new instance of the <see cref="ValidationResult"/> class.

        /// </summary>

        public ValidationResult()

        {

        }



        /// <summary>

        /// Initializes a new instance of the <see cref="ValidationResult"/> class.

        /// </summary>

        /// <param name="memeberName">Name of the memeber.</param>

        /// <param name="message">The message.</param>

        public ValidationResult(string memeberName, string message)

        {

            MemberName = memeberName;

            Message = message;

        }



        /// <summary>

        /// Initializes a new instance of the <see cref="ValidationResult"/> class.

        /// </summary>

        /// <param name="message">The message.</param>

        public ValidationResult(string message)

        {

            Message = message;

        }



        /// <summary>

        /// Gets or sets the name of the member.

        /// </summary>

        /// <value>

        /// The name of the member.  May be null for general validation issues.

        /// </value>

        public string MemberName { get; set; }



        /// <summary>

        /// Gets or sets the message.

        /// </summary>

        /// <value>

        /// The message.

        /// </value>

        public string Message { get; set; }

    }

And now create the most used interface in this pattern. ICommandBus will be called as bus handler in every command:

public interface ICommandBus

    {

        ICommandResult Send<TCommand>(TCommand command) where TCommand : ICommand;

        IEnumerable<ValidationResult> Validate<TCommand>(TCommand command) where TCommand : ICommand;

    }

To implementing this interface, create a class again with the following definition:

  internal class CommandBus : ICommandBus

    {

        public ICommandResult Send<TCommand>(TCommand command) where TCommand : ICommand

        {

            var handler = DependencyResolver.Current.GetService<ICommandHandler<TCommand>>();



            if (!((handler != null) && handler != null))

            {

                throw new CommandHandlerNotFoundException(typeof(TCommand));

            }

            return handler.Execute(command);

        }



        public IEnumerable<ValidationResult> Validate<TCommand>(TCommand command) where TCommand : ICommand

        {

            var handler = DependencyResolver.Current.GetService<IValidationHandler<TCommand>>();

         

            if (!((handler != null) && handler != null))

            {

                throw new ValidationHandlerNotFoundException(typeof(TCommand));

            }

            return handler.Validate(command);

        }

    }

The above class will handle every command received from the bus. And now for executing the handler or so-called for implementing the business, you need an interface:

internal interface ICommandHandler<in TCommand> where TCommand : ICommand

    {

        ICommandResult Execute(TCommand command);

    }

And finally as I’m personally interested in to have my own exception handler, so I create a customized handler:

public class CommandHandlerNotFoundException : Exception

    {

        public CommandHandlerNotFoundException(Type type)

            : base(string.Format("Command handler not found for command type: {0}", type))

        {

        }

    }



    internal class ValidationHandlerNotFoundException : Exception

    {

        public ValidationHandlerNotFoundException(Type type)

            : base(string.Format("Validation handler not found for command type: {0}", type))

        {

        }

    }

Finished! Now let’s use the above codes in a real work application. We are going to handle the products of an e-commerce application as its business is easier to comprehend for everybody:

    public interface IProductCommand : ICommand

    {

        string Name { get; set; }



        string OriginalName { get; set; }



        string Description { get; set; }



        decimal Price { get; set; }

     

    }

  

    public class ProductCommand : IProductCommand

    {

        public string Name { get; set; }



        public string OriginalName { get; set; }



        public string Description { get; set; }



        public decimal Price { get; set; }     

    }



    public class CreateProductCommand : ProductCommand

    {

    }



    public class EditProductCommand : ProductCommand

    {

        public Guid ProductId { get; set; }



        public DateTime CreationDate { get; set; }



        public DateTime LastUpdateDate { get; set; }

    }



public class DeleteProductCommand : ICommand

    {

        public Guid[] ProductIds { get; set; }

    }

You can see that I created an interface derived from ICommand named IProductCommand and finally created the target classes. And at the end we should create the Product handler class:

internal partial class ProductCommandHandler :

        ICommandHandler<CreateProductCommand>,

        ICommandHandler<EditProductCommand>,   

        ICommandHandler<DeleteProductCommand>       

    {

        private readonly IProductRepository _productRepository;

        private readonly IMembershipRepository _membershipRepository;     

        private readonly IUnitOfWork _unitOfWork;

        private readonly ICacheManager _cacheManager;

        private readonly ILogger _logger;



        public ProductCommandHandler(

            IProductRepository productRepository,        

            IUnitOfWork unitOfWork,

            ILogger logger,

            ICacheManager cacheManager)

        {

            _productRepository = productRepository;          

            _unitOfWork = unitOfWork;

            _logger = logger;

            _cacheManager = cacheManager;        

        }

       

        public ICommandResult Execute(CreateProductCommand command)

        {

            try

            {

                if (command == null)

                {

                    throw new ArgumentNullException();

                }



                var product = new Product();

                AddProductAppurtenance(command, product);

                _productRepository.Add(product);

                _unitOfWork.Commit();

                return new SuccessResult(ProductCommandMessage.ProductCreatedSuccessfully);

            }

            catch (Exception exception)

            {

                _logger.Error(exception.Message);

                return new FailureResult(ProductCommandMessage.ProductCreationFailed);

            }

        }



        public ICommandResult Execute(EditProductCommand command)

        {

            try

            {

                if (command == null)

                {

                    throw new ArgumentNullException();

                }



                var product = _productRepository.GetProductDetailById(command.ProductId);

                ClearProductAppurtenance(product);

                AddProductAppurtenance(command, product);

                _productRepository.Edit(product);

                _unitOfWork.Commit();



                return new SuccessResult(ProductCommandMessage.ProductEditedSuccessfully);

            }

            catch (Exception exception)

            {

                _logger.Error(exception.Message);

                return new FailureResult(ProductCommandMessage.ProductEditionFailed);

            }

        }



        public ICommandResult Execute(DeleteProductCommand command)

        {

            if (command.ProductIds == null)

            {

                throw new ArgumentNullException();

            }



            var exceptions = new List<Exception>();

            foreach (var productId in command.ProductIds)

            {

                try

                {

                    var product = DeleteProduct(productId);

                    _productRepository.Edit(product);

                }

                catch (Exception exception)

                {

                    exceptions.Add(exception);

                    return new FailureResult(ProductCommandMessage.ProductDeletionFailed);

                }

            }



            if (exceptions.Any())

            {

                throw new AggregateException(exceptions);

            }



            _unitOfWork.Commit();

            return new SuccessResult(ProductCommandMessage.ProductsDeletedSuccessufully);

        }  

 

We used all of the classes introduced in infrastructure.

Note 1: so you need to have an IOC container tool, to the best of my Knowledge, AsClosedTypesOf in Autofac resolves the ICommandHandler. This a piece of code I wrote for IOC handler:

  public class CommandModule : Module

    {

        protected override void Load(ContainerBuilder builder)

        {

            builder.RegisterModule<RepositoryModule>();

            builder.RegisterType<CommandBus>().As<ICommandBus>().InstancePerRequest();

            builder.RegisterAssemblyTypes(ThisAssembly).AsClosedTypesOf(typeof(ICommandHandler<>)).InstancePerRequest();

        }

    }

Note 2: a penny for your thoughts! how to use ICommandBus!? See the below piece of code as an example:

[HttpPost]

        public JsonResult DeleteProduct(DeleteProductCommand command)

        {

            var result = _commandBus.Send(command);

            return JsonMessage(result);

        }

have fun.



Handling custom error in mvc

In asp.net MVC there is a custom error in web.config like below:

<customErrors mode="On">

<error statusCode="404" redirect="~/404.html"/>

</customErrors>

 

Sometimes you want to redirect the user to your own custom error controller and log the error message. You can handle it! Firstly create your own Error controller:

 

public class ErrorController : Controller

    {

        public ActionResult HttpError404()

        {

            return View("HttpError404");

        }



        public ActionResult HttpError500()

        {

            return View("HttpError500");

        }



        public ActionResult General()

        {

            return View("General");

        }

    }

 

Secondly, you need to handle this controller in a higher level in your application, refer to global.asax and create the Application_Error method with the following definition:

protected void Application_Error(object sender, EventArgs e)

        {

            Exception exception = Server.GetLastError();        

            Response.Clear();

            HttpException httpException = exception as HttpException;

            RouteData routeData = new RouteData();

            routeData.Values.Add("controller", "Error");



            if (httpException != null)

            {

                switch (httpException.GetHttpCode())

                {

                    case 404:

                        routeData.Values.Add("action", "HttpError404");

                        break;

                    case 500:

                        routeData.Values.Add("action", "HttpError500");

                        break;

                    default:

                        routeData.Values.Add("action", "General");

                        break;

                }

            }



            routeData.Values.Add("error", exception);

            Server.ClearError();

            Response.TrySkipIisCustomErrors = true;

            IController errorController = new ErrorController();

            errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));

        }

 

Done! Now you can create your own Views of ErrorController and have your handled ErrorController.



Call Asp.net Web API from C#

If you search in the web for calling web API from C# Code, not from URL, you will find lots of sample on getting and hard enough on the POST! I don't know why but I want to share with you a simple example. As a usual open visual studio and create a web API project from the MVC project template.

Suppose these two simple post and get API actions:     

   [HttpPost]

        [Route("api/Test/PostValue")]

        public IHttpActionResult PostValue([FromBody]string value)

        {

            //Persis in data base or what you want

            return Ok();

        }



        [HttpGet]

        [Route("api/Test/GetValue")]

        public IHttpActionResult GetValue()

        {

            //Fetch from data base

            return Ok();

        }

Now We want to post a data to the PostValue and get a data from GetValue considering the parameters of the Post is FromBody which means that you should send the target value from the body of your request not in Url in the case of calling by Postman or other tools. To call the above action methods from c#, simply create an instance of HttpClient and call the appropriate methods:

  public ActionResult Post()

        {

            var client = new HttpClient();

            var response = client.PostAsJsonAsync("http://localhost:52863/" + "/Api/Test/PostValue", "a value for api").Result;

            return View();

        }





        public ActionResult Get()

        {

            var client = new HttpClient();

            var response = client.GetAsync("http://localhost:52863/" + "/Api/Test/GetValue");

            return View();

        }

 or simply call them in a console application to see the result.



Use yield instead of populating a temporary list

In C# programming language, to fetch an item from a list or collection, there are some ways. Most of the developers forget to use yield keyword and they create a list and populate it based on a needed condition in the simplest possible form. Look at the following sample of populating a list in order to fetch some integer values:

 public List<int> FetchValuesLessThanTen(List<int> source)

        {

            var finalList = new List<int>();

            foreach(var item in source)

            {

                if (item < 10)

                    finalList.Add(item);

            }

            return finalList;

        }

So, it works! But in order to achieve a better performance, C# provides you yield keyword:

  1.  public IEnumerable<int> FetchValuesLessThanTen(List<int> source)
  2.         {
  3.             foreach(var item in source)
  4.             {
  5.                 if (item < 10)
  6.                     yield return item;
  7.             }
  8.         }

 

Just note, as you see, I used  IEnumerable<int> as the output of the method because the List<int> is not an iterator interface type, and the body of the method not can be iterator block. So we have to change the output of the method to IEnumerable<>.



Why you can't project mapped entity in entity framework

If you have worked with entity framework for a long time with and LINQ of course, you probably have seen the Error: The entity cannot be constructed in a LINQ to Entities query. So when it happens and why? Think about the following piece of code:

public IQueryable<Lesson> GetAllLessons(int termId)

{

    return from p in db.Lessons

           where p.termId == termId

           select new Lesson{ Name = p.Name};

}

Note: a Lesson is an Object that has been mapped via the entity framework

Now if you run the code you will see the error we talked about, you should use DTO objects instead of the mapped object:

public IQueryable<LessonDTO> GetAllLessons(int termId)

{

    return from p in db.Lessons

           where p.termId == termId

           select new LessonDTO { Name = p.Name};

}

So what’s happening in the back? As you know the mapped entities in EF represent database tables. If you project onto a mapped entity, you partially load an entity, which is not a valid state. Entity Framework won't have any clue how to handle an update of the entity. So if EF would project the mapped object, you would risk losing some of your data in the Database, therefore it is not allowed to partially load entities.



About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns. I spend a lot of time on software architecture. Since 2008, I've been as a developer for different companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the past years, Read More

Post Tags
Pending Blog Posts
using Elmah in asp.net MVC4
Using FluentSecurity in MVC
Strategic design
Factory Pattern
time out pattern in ajax
Redis as a cache server
How to use PagedList In asp.net MVC
Multiple submit buttons in asp.net MVC
Domain driven design VS model driven architecture
What's the DDD-lite?