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

Griffin.Container: Register services using your own attribute.

As you might now, I recommend that you register most classes using the [Component] attribute. However, you might not want to add an external dependency to all class libraries. You can avoid that now with a new feature. And that is to use your own attribute.

You can of course use the feature to customize the registration process. Let say that we’ve created a new attribute called ContainerServiceAttribute, so that we can decorate one of our classes:

[ContainerService]
public class SomeService
{
}

To register all classes with the new attribute use the following:

var registrar = new ContainerRegistrar(Lifetime.Transient);

// the new magic.
registrar.RegisterUsingAttribute<ContainerServiceAttribute>(Assembly.GetExecutingAssembly());

var container = registrar.Build();

The attribute itself is responsible of the registration. Here is a simplistic example:

class ContainerServiceAttribute : Attribute, IAttributeRegistrar
{
    public void Register(Type concrete, IContainerRegistrar registrar)
    {
        //concrete = decorated class. In this case "SomeService"
        registrar.RegisterConcrete(concrete, Lifetime.Default);
    }
}

Use the type to decide which interfaces etc that the class should be registered as.

The feature is available in version 1.0.3. Install it using nuget.

Code is available at github.

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

Resolving all services through dependency injection in Griffin.Container

I’ve just added a new feature to Griffin.Container: Support for resolving all implementations of a service by using constructors.

You can now do something like this:

public interface IStatefulService
{
	void Ping();
}

public class FtpConnection : IStatefulService
{
}

public class Pop3Connection : IStatefulService
{
}

public class ConnectionPinger
{
	public ConnectionPinger(IEnumerable<IStatefulService> services)
	{
		_services = services;
	}
	
	public void PingAll()
	{
		_services.Each(x => x.Ping());
	}
}

Griffin.Container can be found at github.

Posted in Uncategorized | Tagged , , | Leave a comment

To “var” or not to “var”, is that really the question?

There are several blog posts and discussions about whether to use var or not. They tend to focus on whether the type is obvious or not. It seems like people are afraid to suddenly be writing code in a dynamic language just because they can’t read the type anymore. I got news for you: You’ll still get a compiler error and an intellisense warning if you pass the wrong type to a method.

A most common argument is that “var” should only be used together with LINQ. That makes no sense. Why is it acceptable to use with linq? Because it makes the code more readable than writing the complex type? You got it! :)

The fact is that the type isn’t that import anymore. Your business object probably got several representations today. You got your Entity Framework entity, your WCF service DTO, your ASP.NET MVC view model etc etc. That is, you have several representations of the same information which you work with. The actual type doesn’t really matter since it’s only valid in it’s own layer/class/scope. If you by mistake got another representation than your intended one, you’ll get feedback instantaneously from Visual Studio.

Is this code hard to read?

public ActionResult Create(UserViewModel model)
{
    var user = _repository.Create(model.UserName);
    user.LastName = model.LastName;
    _repository.Save(user);

    var admin = _user.Get(user.Id);
    var email = _emailFactory.Create("RegistrationEmail");
    email.SetTemplateTag("userName", user.UserName);
    email.To = admin.Email;
    smtpClient.Send(email);

    return RedirectToAction("Index");
}

The fact is that the type is only important when you use crappy names:

User a = myObj.Get(1);

instead of

var admin = userRepository.Get(1);

As a developer you should always strive after writing as clean code as possible. Using var will shorten the code and therfore make it more readable. It will also move the focus from the types to what the code actually does.

Finally, here is my favorite motivation against “var”:

When I write code, not only do I think about performance and maintainability, I think about perhaps someday migrating it to another language. As such, I rarely use “var”.

Cheers!

Update

Many objects today are complex (i.e. not primitive or just having primitive properties). How do you treat them?

Do you type your code like this:

User user = _repos.Get(1);
Department department = user.Department;
_someService.Invoke(department);

instead of:

User user = _repos.Get(1);
_someService.Invoke(user.Department);

Of course not. Why not? Because given the context of the user, it’s obvious what the department type is. Same thing goes for when using your services, repositories and similar. If you load the user from a repository you know that it’s a db entity. No need to show the type.

Posted in Architecture | 25 Comments

Updated the localization administration area

I’ve updated the administration area for the localization features in an attempt to make it easier to handle the localization.

I’ve replaced the link texts with icons so that they take less space. I’ve also added filtering options (so that you can translate one area/controller at a time) and a filtering option which allows you to only show texts that hasn’t been translated yet.

Update the nuget package (“griffin.mvccontrib.admin”) to get it.

Posted in Libraries | Tagged , | 6 Comments

New article: Having fun with Griffin.Container

I’ve written a new article which guides you through the most of the features in Griffin.Container.

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

Griffin.Container: Introducing the command support.

Commands are a great way to decouple logic in an application, since the command invoker have no knowledge of where the command is handled. You also move the focus from the how the task is solved to the task itself.

A command which is used together with Griffin.Container can look like this:

public class CreateUser : ICommand
{
	public CreateUser(string firstName, string lastName)
	{
		if (firstName == null) throw new ArgumentNullException("firstName");
		if (lastName == null) throw new ArgumentNullException("lastName");

		FirstName = firstName;
		LastName = lastName;
	}

	public string FirstName { get; private set; }
	public string LastName { get; private set; }
}

Notice that the commands are immutable and do not return a value. A command should always validate all entered information (always catch errors as early as possible). Mandatory fields should be specified in the constructor while optional is set through methods or properties.

That is important if you want to be able to scale your application later on. You can for instance at any time serialize the command and send it to another server, thanks to that the command is immutable and do not return value is expected. I’ll demonstate how you can achieve that using decorators and Griffin.Networking in a later blog post.

Let’s focus on the command now. We need to dispatch it in some way so that it can be invoked.

Here is an example ASP.NET MVC3 controller:

public class UserController : Controller
{
	ICommandDispatcher _dispatcher;

	public UserController(ICommandDispatcher dispatcher)
	{
		_dispatcher = dispatcher;
	}

	[HttpPost, Transactional]
	public ActionResult Create(CreateModel model)
	{
		if (!ModelState.IsValid)
			return View(model);

		var cmd = new CreateCommand(model.FirstName, model.LastName);
		_dispatcher.Dispatch(cmd);

		return RedirectToAction("List");
	}
}

We do not know where the command is invoked, we should really not care either. We could even go a step further and not care about when the command is executed (as long as we have some kind of notification system to inform the user of failed commands). It all depends on how scalable your application should be (now or later).

We could start with an application where everything is synchronous and executed in the same process and end up with a application where the commands are distributed over several servers.

Getting a result

Commands should not return a result. It complicates the command handling and forces everything to be synchronous (or even more complex). It’s of course a trade off, but it also makes everything more flexible.

You still have the information which you used to invoke the command. You can use that information to update the UI to fake that a new item has been created/updated (which it will eventually). You could also inform the user that the item has been handled and that he need to refresh the UI to see it.

If you need an ID, switch to GUIDs and generate and attach it to the command before invoking it. There are GUIDs which works well with databases.

Handling the command

Commands are handled by classes which implements the interface IHandlerOf<T>.

A typical implementation looks something like this:

[Component]
public class CreateUserHandler : IHandlerOf<CreateUser>
{
	private IUserRepository _repository;

	public CreateUserHandler(IUserRepository repository)
	{
		_repository = repository;
	}

	public void Invoke(CreateUser cmd)
	{
		var user = _repository.Create(cmd.FirstName, cmd.LastName);

		DomainEvent.Publish(new UserCreated(user));
	}
}

The [Component] attribute will allow you to automatically register the class in the container. Read more about that in the core documentation

Nesting commands

No. Do not nest commands. A command is created for a specific use case. It’s not intended to get reused. Nesting commands can quickly produce complex code which is hard to follow and maintain.

Instead break out common functionality to a third class which is used by both commands.

Decorators

Decorators allows you to add functionality to the command handlers without actually having to modify them.

You could for instance create an decorator which meassure the performance of every command. It would look something like this:

public class PerformanceMonitor<T> : IHandlerOf<T> where T : class, ICommand
{
    private readonly IHandlerOf<T> _inner;

    public PerformanceMonitor(IHandlerOf<T> inner)
    {
        _inner = inner;
    }

    public void Invoke(T command)
    {
        var w = new Stopwatch();
        w.Start();
        _inner.Invoke(command);
        w.Stop();
        Console.WriteLine("Invocation of {0} took {1}ms.", command.GetType().Name, w.ElapsedMilliseconds);
    }
}

All decorators are attached the the handlers by using factories. A factory which would attach the performance decorator to all commands would look something like:

[Component]
public class ExceptionDecoratorFactory : IDecoratorFactory
{
	// used to determine which commands to decorate
    public bool CanDecorate(Type commandType)
    {
        return true;
    }

	// invoked if we can decorate a command
    public IHandlerOf<T> Create(IHandlerOf<T> inner) where T : class, ICommand
    {
        return new PerformanceMonitor(inner);
    }
}

The factory itself should be added to the container. The command dispatcher automatically finds all factories which have been registered.

Exception decorator

A decorator called ExceptionDecorator<T> is included in the framework. It automatically logs all failed commands and their properties.

Example output:

FailureCommand
    Parameters:
        FirstName: Arne
    Exception:
        System.InvalidOperationException: That wont work, dude!
           at Griffin.Container.Tests.Commands.DecoratorTests.FailureHandler.Invoke(FailureCommand command) in C:projectscsharpgauffinGriffin.ContainerSourceGriffin.Container.TestsCommandsDecoratorTests.cs:line 53
           at Griffin.Container.Tests.Commands.DecoratorTests.PerformanceMonitor`1.Invoke(T command) in C:projectscsharpgauffinGriffin.ContainerSourceGriffin.Container.TestsCommandsDecoratorTests.cs:line 39
           at Griffin.Container.Commands.ExceptionDecorator`1.Invoke(T command) in C:projectscsharpgauffinGriffin.ContainerSourceGriffin.ContainerCommandsExceptionDecorator.cs:line 39

Validation decorator

There is also a validation decorator included that is used to validate properties on the commands. It uses DataAnnotation attributes for the validation.

Example command (required parameters are manually validated in the constructor while optional properties is validated using DataAnnotations):

public class CreateUser : ICommand
{
	public CreateUser(string firstName, string lastName)
	{
		if (firstName == null) throw new ArgumentNullException("firstName");
		if (lastName == null) throw new ArgumentNullException("lastName");

		FirstName = firstName;
		LastName = lastName;
	}

	public string FirstName { get; private set; }
	public string LastName { get; private set; }

	[StringLength(40)]
	public string Title { get; set; }
}

Getting the code

The code is available at github and is included in the main project.

You can get it by using nuget: install-package griffin.container.

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

ASP.NET MVC3: Custom error for 401 Unauthorized

Have you tried to display a custom error message if authorization fails..

[Authorize(Roles="User")]
public class ItemController : Controller
{
}

.. by specifying it in the customErrors section in web.config:

    <customErrors defaultRedirect="~/Error/" mode="On">
      <error statusCode="404" redirect="~/Error/NotFound/" />
      <error redirect="~/Error/NotAuthorized/" statusCode="401" />
    </customErrors>

So did I without getting it to work. The [HandleError] attribute can not handle it either since it only handles exceptions (as the contract IExceptionFilter says).

Solution

public class BetterAuthorizeAttribute : AuthorizeAttribute
{
	protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
	{
		throw new NotAuthorizedHttpException(Roles);
	}
}

public class NotAuthorizedHttpException : HttpException
{
	public NotAuthorizedHttpException(string missingRoles)
		: base(401, string.Format("You do not have the required role(s) '{0}'.", string.Join(", ", missingRoles)))
	{
	}
}

That solution allows us to use the exception filter (HandleErrorAttribute) to serve the error page. Customization get’s easier since we only have to make a change in global.asax to be able to serve any page. (i.e. switch the HandleError filter to our custom one).

Posted in Uncategorized | Tagged | Leave a comment

Double check pattern

I just answered a question at SO about lazy loading which involved the double check pattern. It’s a really useful pattern for lazy loading since it hurt performance a lot less than always locking.

I thought that I should share explain why by using some comments:

public sealed class Lazy<T> where T : class
{
    private readonly object _syncRoot = new object();
    private readonly Func<T> _factory;
    private T _value;

    public Lazy(Func<T> factory)
    {
        if (factory == null) throw new ArgumentNullException("factory");

        _factory = factory;
    }

    public T Value
    {
        get
        {
            // here is the first check. It only returns true
            // if the instance have not been created, right?
            if (_value == null)
            {
                // so when we enter here, we are within a very small time frame:
                // That is from the above check until the new instance is
                // assigned to the variable.

                // Which is a <strong>very</strong> small time frame
                // (unless you rely on external resources).

                // So let's lock to make sure that no other thread
                // have already started to create the object.
                lock (_syncRoot)
                { 
                    // We enter here as soon as any other thread (if there were one)
                    // have stopped working, which means that the value could 
                    // have been assigned.

                    // So let's check if another thread have already done the work for us.
                    if (_value == null)
                    {
                        //no, so let's create the object.
                        _value = _factory();
                    }
                }
            }
            return _value;
        }
    }

    public override string ToString()
    {
        return _value == null ? "Not created" : _value.ToString();
    }
}

The double check pattern allows us to have lock free code (other than when the instance is created) which is a huge performance gain compared to using a single lock.

Feel three to use the code in .NET versions earlier than 4.

Posted in Architecture, CodeProject | Tagged , | 1 Comment

Adding a required indicator in ASP.NET MVC3 using jQuery

You might want to indicate that fields in ASP.NET MVC3 is required visually.

Sample image

It’s easy thanks to the HTML attributes that the unobtrusive validation API generates.

Start by adding a new CSS class in your site.css called something like .required-indicator.

.required-indicator { color: red; font-size: 1.2em; font-weight: bold; }

Then add a small jQuery script somewhere (in the layout or an application.js):

$(function() {
    $('[data-val-required]').after('<span class="required-indicator">*</span>');
});

Done! Here is a sample fiddle.

Posted in Uncategorized | Tagged , | 2 Comments

How to handle transactions in ASP.NET MVC3

I got annoyed about having to repeat the transaction handling in every POST method of my controllers. First of all: I don’t want to have to take the unit of work in the constructor of each controller, since that implicitly says that all/most methods uses transactions. And I do not want to have to resolve a factory, since that says that all methods might use transactions. Finally using a singleton is the worst of solutions.

Before

The problem wasn’t that hard to solve thanks to the flexibility of ASP.NET MVC3. But let’s start by looking at a typical post method:

[HttpPost]
public virtual ActionResult Create(CreateModel model)
{
	if (!ModelState.IsValid)
		return View(model);

	var instruction = new Instruction(CurrentUser);
	Mapper.Map(model, instruction);

	using (var uow = _unitOfWorkFactory.Create())
	{
		_repository.Save(instruction);
		
		uow.SaveChanges();
	}
	
	return RedirectToAction("Details", new {id = instruction.Id});
}

After

What I did was to create a new action filter called TransactionalAttribute. It checks if the model state is valid and that no exceptions have been thrown. It uses the DependencyResolver to find a IUnitOfWork implementation if everything checks out OK. Since this is done in an action filter, the transaction will not be created unless it’s actually required. All you have to do is to register the UoW factory in your IoC container and tag your action:

[HttpPost, Transactional]
public virtual ActionResult Create(CreateModel model)
{
	if (!ModelState.IsValid)
		return View(model);

	var instruction = new Instruction(CurrentUser);
	Mapper.Map(model, instruction);
	_repository.Save(instruction);
	
	return RedirectToAction("Details", new {id = instruction.Id});
}

There is a small catch: You must add an error to the ModelState if you catch exceptions in your class. The transaction will otherwise get committed.

[HttpPost, Transactional]
public virtual ActionResult Create(CreateModel model)
{
	if (!ModelState.IsValid)
		return View(model);

	try
	{
		model.Category = model.Category ?? "Allmänt";

		var instruction = new Instruction(CurrentUser);
		Mapper.Map(model, instruction);
		_repository.Save(instruction);
		
		return RedirectToAction("Details", new {id = instruction.Id});
	}
	catch (Exception err)
	{
		// Adds an error to prevent commit.
		ModelState.AddModelError("", err.Message);
		Logger.Error("Failed to save instruction for app " + CurrentApplication, err);
		return View(model);
	}
}

Implementation

The attribute itself looks like this:

public class TransactionalAttribute : ActionFilterAttribute
{
	private IUnitOfWork _unitOfWork;

	public override void OnActionExecuting(ActionExecutingContext filterContext)
	{
		if (filterContext.Controller.ViewData.ModelState.IsValid && filterContext.HttpContext.Error == null)
			_unitOfWork = DependencyResolver.Current.GetService<IUnitOfWork>();

		base.OnActionExecuting(filterContext);
	}

	public override void OnActionExecuted(ActionExecutedContext filterContext)
	{
		if (filterContext.Controller.ViewData.ModelState.IsValid && filterContext.HttpContext.Error == null && _unitOfWork != null)
			_unitOfWork.SaveChanges();

		base.OnActionExecuted(filterContext);
	}
}

Simple, but effective! :)

Extras

The actual unit of work implementation depends on which kind of data layer you are using. You can use the following code snippet if you are using nhibernate and have successfully registered the ISession in your container:

public class NhibernateUnitOfWork : IUnitOfWork
{
	private readonly ISession _session;
	private ITransaction _transaction;

	public NhibernateUnitOfWork(ISession session)
	{
		_session = session;
		_transaction = session.BeginTransaction();
	}

	public void Dispose()
	{
		if (_transaction == null)
			return;

		if (!_transaction.WasCommitted)
			_transaction.Rollback();

		_transaction.Dispose();
		_transaction = null;
	}

	public void SaveChanges()
	{
		_transaction.Commit();
	}

}

The Unit of work interface is really simple:

public interface IUnitOfWork : IDisposable
{
	void SaveChanges();
}
Posted in CodeProject | Tagged , | 9 Comments