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

An easier way to debug windows services

Have you got tired of attaching the Visual Studio debugger to the service application? I got the solution just for you! It’s a small helper class containing a static method which you need to invoke.

public static void Main(string[] argv)
{
    // just include this check, "Service1" is the name of your service class.
    if (WindowsServiceHelper.RunAsConsoleIfRequested<Service1>())
        return;

    // all other code 
}

Then go to project properties, the “Debug” tab and add “-console” as Command Arguments.

Shows the debug settings under project properties

How to configure Visual Studio

That’s it. What I do is simply to allocate a console using the winapi and then invoke (through reflection) the proper protected methods in your service class.

Source code for the helper class:

public static class WindowsServiceHelper
{
    [DllImport("kernel32")]
    static extern bool AllocConsole();

    public static bool RunAsConsoleIfRequested<T>() where T : ServiceBase, new()
    {
        if (!Environment.CommandLine.Contains("-console"))
            return false;

        var args = Environment.GetCommandLineArgs().Where(name => name != "-console").ToArray();

        AllocConsole();

        var service = new T();
        var onstart = service.GetType().GetMethod("OnStart", BindingFlags.Instance | BindingFlags.NonPublic);
        onstart.Invoke(service, new object[] {args});

        Console.WriteLine("Your service named '" + service.GetType().FullName + "' is up and running.\r\nPress 'ENTER' to stop it.");
        Console.ReadLine();

        var onstop = service.GetType().GetMethod("OnStop", BindingFlags.Instance | BindingFlags.NonPublic);
        onstop.Invoke(service, null);
        return true;
    }
}
Posted in CodeProject | Tagged , | Leave a comment

Inversion of control containers – Best practices

Disclaimer: I’ve used IoC containers for a couple of years now and also made a couple of my own (just to learn, nothing released). I’ve also consumed loads of documentation in the form of blogs and stackoverflow questions. And I thought that I should share what I’ve learned. In other words: These are my very own subjective best practices.

An IoC container is not a Service Locator

One of the first mistakes that you’ll make is to register the container in the container or create a singleton to get access to it. It basically means that you can do something like:

public class MyService
{
    MyService(IServiceResolver myContainer)
    {
    }

    public void DoSomething()
    {
        var service = _container.Resolve<ISomeService>();
        service.DoMore();
    }
}

Do not do that. Service location is another pattern that you get as a “bonus” when you use a IoC container. Some even call Service Location as an anti-pattern. Google it.

The most important reasons is that you hide a dependency that you won’t discover until you forget to register IAnotherService. What if the method is only used during edge cases? Then the dependency wont be discovered until that edge case is fulfilled.

Using the constructor to inject dependencies will also help you discover violations to Single Responsibility principle. Having a lot of dependencies might suggest that you need to break your class into several smaller classes.

There are some cases when you THINK that you really need to use the container in your class. Example:

    public class YourService
    {
        public YourService(IContainer container)
        {
        }

        public void YourMethod()
        {
            var user = _container.Get<IUser>();
        }
    }

The proper solution is to register a factory in the container:

    public class YourService
    {
        public YourService(IDomainModelFactory factory)
        {
        }

        public void YourMethod()
        {
            var user = _factory.Create<IUser>();
        }
    }

The smaller interface, the better

Interfaces are not classes. There is nothing saying that there should be a 1-1 mapping between them. imho it’s far better to create several small interfaces and let the same class implement them than creating a larger one having all all features that the class have.

Do design the interfaces before you design the classes. The reason is that if you do the opposite you’ll usually end up with one interface per class.

Smaller interfaces also makes it easier to let your application grow since you can move smaller parts of the implementation (as in creating a new class for one of the interfaces).

Don’t choose a longer lifetime to get better performance

This is a mistake that I’ve done dozens of times. Object creation will usually not be a problem when you are running your application.

The advantage with short lifetimes is that it get easier to handle context sensitive dependencies such as a database connections.

Using a longer lifetime (which lives longer than the mentioned context sensitive dependencies) usually means that you create same kind of service location implementation or custom factories.

Hence you get code like this:

public class UserService : IUserService
{
    public void Add()
    {
        var (var uow = UnitOfWork.create())
        {
            // do stuff.
            uow.Save();
        }
    }
}

instead of

public class UserService : IUserService
{

    public UserService(IUnitOfWork uow)
    {

    }

    public void Add()
    {
        // do stuff with the unit of work here.
    }
}

what’s the problem with the first approach? Well. It’s usually the CALLER that knows what should be done in a unit of work, not the service itself. I’ve seen people create complex Unit Of Work solutions to get round that problem. The other simpler approach is to use TransactionScope.

Both of those solutions are either slower or more complex than services with shorter lifetime. Save the optimizations to when object instantiation have been proven to be a problem.

Don’t mix lifetimes

Mixing lifetimes can lead to undesired effects if you are not careful. Especially when projects have begun to grow and getting more complex dependency graphs.

Example

// EF4 context, scoped lifetime
class Dbcontext : IDbContext
{
}

// short lifetime, takes db context as a dependency
class Service1 : IService1
{
}

// Single instance, keeps a cache etc.
class Service2 : IService2
{
}

Service2 takes service1 as a dependency which in turn requires a dbcontext. Let’s say that the dbcontext has an idle timeout which closes the connection after a while. That would make service1 fail and also service2 which depends on it.

Simply be careful when using different lifetimes.

Try to avoid primitives as constructor parameters

Try to avoid using primitives as constructor parameters (for instance a string). It’s better to take in object since it makes extension (subclassing) easier.

Hey, I need my primitives you say. Take this example:

public class MyRepository
{
    public MyRepository(string connectionString)
    {
    }
}

Well. You’re class breaks SRP. It acts as a connection factory and a repository. Break the factory part out:

public class MyRepository
{
    public MyRepository(IConnectionFactory factory)
    {
    }
}

Avoid named dependencies

Named dependencies are as bad as magic strings. Don’t use them.

If you need different implementations simply create different interfaces such as IAccountDataSource and IBillingDataSource instead of just taking in IDataSource.

imho this is a possible violation of Liskovs Substitution principle.

Posted in Architecture, CodeProject | Tagged | Leave a comment

Making custom dataannotation attributes work with MVC client side validation

In a previous blog entry I showed you a easier approach to localized DataAnnotation attributes.

The problem with that approach was that client side validation didn’t work. It isn’t hard to fix. All you need is to borrow some code from the built in DataAnnotation support and reference the custom attributes instead.

Here is a sample implementation.

    public class RequiredAttributeAdapter : DataAnnotationsModelValidator<RequiredAttribute>
    {
        public RequiredAttributeAdapter(ModelMetadata metadata, ControllerContext context, RequiredAttribute attribute)
            : base(metadata, context, attribute)
        {
        }

        public static void SelfRegister()
        {
            DataAnnotationsModelValidatorProvider
                .RegisterAdapter(
                    typeof (RequiredAttribute),
                    typeof (RequiredAttributeAdapter));
        }

        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
        {
            return new[] { new ModelClientValidationRequiredRule(ErrorMessage) };
        }
    }

Then simply call RequiredAttributeAdapter.SelfRegister(); somewhere in your Global.asax

Posted in Uncategorized | Tagged , | Leave a comment

Handling JSON responses in jquery plugins

I’ve been coding several jquery plugins lately and most of my plugins uses Ajax and JSON to handle data. Each plugin gets a specific JSON string returned that must follow a specific format. For instance, the table plugin expects to get total number of rows and an array containing the rows to add:

	var jsonResponse = { 
		"TotalRowCount": 2,
		"Debug": true,
		"TableMode": 'Append', 
		"Rows" : [
			{ "Id": 1, "Title": "Fool", "FirstName": "Jonas", "LastName": "Gauffin", "Age": 34, "Options": "<a href="/add">aa</a>" },
			{ "Id": 2, "FirstName": "Arne", "LastName": "Purka", "Age": 14},
		]
	};

Nothing strange with that. The problem is when I want to return something else than rows. The plugin cannot handle that. I might for instance want to return an error message informing the user that something went wrong.

My first attempt was to change so that all plugins used a structure like this:

var response = {
    "ContentType": 'Rows',
    "Body": {
      "TotalRowCount": 2,
      "Debug": true,
      "TableMode": 'Append',
      "Rows" : [
        { "Id": 1, "Title": "Fool", "FirstName": "Jonas", "LastName": "Gauffin", "Age": 34, "Options": "<a href="/add">aa</a>" },
        { "Id": 2, "FirstName": "Arne", "LastName": "Purka", "Age": 14},
      ]
    }
}

where the Body data would be everything in the first JSON code sample. But since javascript is dynamic I felt that it’s really not necessary to wrap everything like that. I just add the ContentType to all original JSON responses.

	var jsonResponse = { 
		"ContentType": 'Rows',
		"TotalRowCount": 2,
		"Debug": true,
		"TableMode": 'Append', 
		"Rows" : [
			{ "Id": 1, "Title": "Fool", "FirstName": "Jonas", "LastName": "Gauffin", "Age": 34, "Options": "<a href="/add">aa</a>" },
			{ "Id": 2, "FirstName": "Arne", "LastName": "Purka", "Age": 14},
		]
	};

In this way I only have to check the ContentType before doing anything else and then take an appropriate action.

Right now I’m trying to figure out if I should add a general JSON response pre processor which is invoked before the actual plugin get’s to handle the response. (declare it in my own jquery plugin namespace and invoke it from each plugin if it exist). In that way I can move all general handling (like handling errors) to a separate place instead having to duplicate it in all plugins.

Posted in Architecture | Tagged , , | Leave a comment

Single Responsibility Prinicple

SRP is one of the easiest principles to learn, but one of the hardest to master. The reason to this is that it can be quite hard to see if a method or class breaks SRP or not. I got a few simple rules that will help you check if you are breaking the principle.

First of all, lets check the definition of SRP:

every object should have a single responsibility, and that responsibility should be entirely encapsulated by the class

Hence my interpretation varies a bit from the original statement, as I like to apply it to classes, methods and interfaces. If you do not agree: Go buy an ice-cream, eat it, put a smile on your face and continue reading.

XmlDoc is an excellent tool if you use it correctly. So many users abuse it and screams out to the world their product/library/etc has DOCUMENTATION! The DoXZ! yay! What they fail to mention is that the documentation is simply a reflection of the methods and classes. Read my other blog posts to get a few tips on how to write good documentation. Back to SRP. Documentation can be a tool for SRP too. If you find yourself using AND’s when describing a method, class or an method argument you have most likely broken SRP. Refactor.

When talking about SRP it’s important to know what is meant with single responsibility. When it comes to methods, they should only contain logic for one type of responsibility. Here is a small example:

public class UserService
{
     public void Register(string email, string password)
     {
          if (!email.Contains("@"))
              throw new ValidationException("Email is not an email!");

         var user = new User(email, password);
         _database.Save(user);

         _smtpClient.Send(new MailMessage("mysite@nowhere.com", email){Subject="HEllo fool!"});
     }
}

The name Register suggests that the method should register the user in the system. Doing email validation doesn’t seem to belong in an register method. Let’s break it out into a new method.

public class UserService
{
     public void Register(string email, string password)
     {
          if (!ValidateEmail(email))
              throw new ValidationException("Email is not an email!");

         var user = new User(email, password);
         _database.Save(user);

         _smtpClient.Send(new MailMessage("mysite@nowhere.com", email){Subject="HEllo fool!"});
     }

     public bool ValidateEmail(string email)
     {
         return email.Contains("@");
     }
}

One might wonder why that line of code should be moved. It’s so small. In reality email validation might be larger, but that’s not really important. Following SRP usually makes it easier to follow DRY (Don’t repeat yourself) too, since you make methods smaller and let them solve a specific problem. Hence it’s a lot easier to reuse code.

If we continue to look at the method we’ll see that it also sends an email and is therefore also responsible of delivering the email. Lets move that to a new method too.

public class UserService
{
     public void Register(string email, string password)
     {
          if (!ValidateEmail(email))
              throw new ValidationException("Email is not an email!");

         var user = new User(email, password);
         _database.Save(user);

         SendEmail(new MailMessage("mysite@nowhere.com", email){Subject="HEllo fool!"});
     }

     public virtual bool ValidateEmail(string email)
     {
         return email.Contains("@");
     }

     public bool SendEmail(MailMessage message)
     {
         _smtpClient.Send(message);
     }
}

omg! We did it again. A single line method. Is this sh!t really necessary? Yep, it is. When the application grows you’ll see that you might want some templating. By using a separate method you could replace commonly used macros like #SITEURL#, #PRODUCTNAME# etc in that method instead of duplicating the code in each method that wants to send an email.

Now it’s time to move on and look at the class. Do it follow the SRP? Do it? Nooo, don’t try to fool me. I got some NINJA zkillz. promise! SendEmail and ValidateEmail has nothing to do with a class named UserService. Let’s refactor.


public class UserService
{
     EmailService _emailService;

     public UserService(EmailService emailService)
     {
         _emailService = emailService;
     }
     public void Register(string email, string password)
     {
          if (!_emailService.ValidateEmail(email))
              throw new ValidationException("Email is not an email!");

         var user = new User(email, password);
         _database.Save(user);

         emailService.SendEmail(new MailMessage("mysite@nowhere.com", email){Subject="HEllo fool!"});
     }
}

public class EmailService
{
     public bool virtual ValidateEmail(string email)
     {
         return email.Contains("@");
     }

     public bool SendEmail(MailMessage message)
     {
         _smtpClient.Send(message);
     }
}

Actually I’m unsure of if the ValidateEmail method belongs in the EmailService class. What do you think? Leave a comment.

SRP is nothing that you do once. It’s something that you should keep doing during all types of development (like when writing new code and when you maintain existing one).

Summary

Try to follow the following rules to get a hang of SRP:

  1. Document your code. Using AND’s should make you check your code again.
  2. You should be able to associate all method names with the class/interface name. (A method called ValidateEmail cannot be associated with a class called UserService)
  3. A method should only contain logic that can be associated with the method name.
Posted in Architecture, CodeProject | Tagged , , | 7 Comments

A less evil singleton

I’ve been working a bit more with my Griffin Framework and I’m almost ready to release the Specification library in it. The specification library is an abstraction layer similar to CommonLog and CommonServiceLocator although it contains alternatives to both of them and a bit more.

When I designed the logging interfaces I did decide to use sort of an singleton (LogManager) to be able to get a logger in each class that needs one. Since logging is such a core functionality and also well defined I didn’t see a reason to use a regular service interface which could be used in the constructor (inversion of control). imho it would only clutter all constructors since most classes will be using a logger.

The singleton facade works best for small classes that most likely will not be changed. My LogManager looks like this (comments and code contracts have been removed):

public class LogManager
    {
        private static ILogManager _logManager = new NullLogManager();

        public static void Assign(ILogManager logManager)
        {
            _logManager = logManager;
        }

        public static ILogger GetLogger(Type type)
        {
            return _logManager.GetLogger(type);
        }

        public static ILogger GetLogger<T>()
        {
            return _logManager.GetLogger(typeof (T));
        }
    }

By using this approach all users can easily get a logger while the implementors have a lot of flexibility to generate the ILogManager which is used by the facade. The logging abstraction layer do actually not care about how the ILogManager is created or configured. It’s an implementation detail only know by the user of the actual logging framework.

I do not recommend anyone to use a singleton facade unless it’s absolutely required. Usually it should only be used in frameworks, your own internal one or one like this.

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

Reintroducing my compiler class.

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

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

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

    public interface IWorld
    {
        string Hello(string value);
    }

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

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

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

    Compiler compiler = new Compiler();

    //repeat for all types (to automatically add namespaces and assemblies to the CodeDom compiler)
    compiler.AddType(typeof(string));

    // compile the code. Will throw an exception if it do not work.
    compiler.Compile(code);

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

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

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

Source code

Posted in CodeProject | Tagged , | Leave a comment

Three reasons to why you should use view models

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

Reason 1: Remove logic from your views.

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

Hello @model.UserName

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

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

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

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

Reason two: Security

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

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

Reason three: Loose coupling

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

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

How to make the model mapping easier

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

Posted in Architecture, CodeProject | Tagged | 1 Comment

Generic type restriction for enums

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

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

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

Example enum:

public enum MyEnum
{
    [Description("Some value"]
    SomeValue,

    [Description("Foo bar")]
    FooBar
}

Fetch value:

MyEnum value = MyEnum.FooBar;

// will display "Foo bar"
Console.WriteLine(value.GetDescription());

The extension method that does the magic:

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

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

Render a view to a string variable

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

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

    ViewData.Model = model;

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

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