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

When is a logger a dependency?

There are some discussion about whether loggers should get injected into your classes (dependency injection) or if you should use the logger facade (like LogManager.GetLogger<MyClass>()).

The answer rather simple:

As for all classes, dependencies which is mandatory should get injected.

That means that you should inject the logger if the class will fail without it (= not deliver the expected result). If the class can work without a logger: simply use the logger facade.

Posted in Architecture | 7 Comments

Writing decoupled and scalable applications

Preface

This article is the first in a series of three articles. It’s purpose is only to introduce you do domain events and commands. The next article will show you how you with almost no effort (thanks to Griffin.Decoupled) can get started the command/event type of applications. The series will end with and article showing how you can use the DDD domain model together with the command and event handling.

Continue reading

Posted in Architecture | 7 Comments

Service locator is not an anti pattern.

(this article have been rewritten since it didn’t seem like I managed to communicate my thoughts properly)

There are several blog posts that states that service locator is an anti pattern. With this article I’ll try to explain why it’s not. Do understand that I’m not saying that it should be used for dependency management.

Continue reading

Posted in Architecture, CodeProject | 13 Comments

Dealing with exceptions, Logging and displaying error messages

I got a client which is really firm on that the user should know what went wrong when exceptions are thrown. So we are displaying error messages like

“The database did not respond”
“The database operation failed”
“Failed to load configuration setting X”

etc etc.

If it were just me, I would simply just print something like:

“Oops, something unexpected happened. Please try again or contact the support department”

Why?

Ok. So let’s assume that we show the user a more detailed error message. What is he/she supposed to do with it? Remember, it’s from an exception. If something exceptional happens it unlikely that the user can fix the problem by reading an error message. At tops the user can try do perform the operation again.

When the user have got tired of trying he/she calls the support department. If we’re lucky the user manages to quote the error message exactly. But really. Do that help us? Not really. We still have to go through our logs to find out what happened.

The correct approach to dealing with exceptions

So what should we do when an exception happens? Well. Try to prevent it from happening in the future. That goes for all exceptions. Some can be prevented, whilst others can’t. The point is that we should at least try.

To be able to try to fix the exceptions we have to find them. Using a big fat log for everything is not a very good way. Instead try to have a seperate log for all unhandled exceptions. Make sure that you read that log. You might want to build something that emails that log to you daily.

Posted in Architecture, CodeProject | Tagged | 2 Comments

Why Domain Driven Design (DDD) is so great

This article aims to describe why I think that DDD aids you tremendously in creating robust and flexible applications.

Today we got several cool frameworks and libraries that we can use. ORMs, WCF, ServiceStack, SignalR, WebApi, IoC etc etc. Just thinking of all can make any serious developer go crazy of joy.

Continue reading

Posted in Architecture, CodeProject | Tagged | 12 Comments

Small temp file helper for integration tests

I’m writing some integration tests and needed to be able to create/cleanup temp files during the test. So I’ve created a small helper for that (so that the file will be deleted even if the test fails)

[TestClass]
public class WebClientTests
{
    [TestMethod]
    public void Upload()
    {
        var subject = new EfecteWebClient(new HardCodedConfig());
        var repos = new ChangeRequestRepository(subject);
        var changeRequest = repos.Get("ACHG-00002978");

        UploadResult result;
        using (var tempFile = new TempFile("Hello world"))
        {
            var stream = new FileStream(tempFile.FullPath, FileMode.Open);
            result = subject.Upload(() => changeRequest.Title, UploadType.Set, new HttpFile("myFile", "mydocument.txt", stream));
        }

        Assert.IsFalse(result.Errors.Any());
    }
}

See? the tempfile class implements IDisposable so that the tests won’t be cluttered with the cleanup.

Implementation:

public class TempFile : IDisposable
{
    public TempFile()
    {
    }

    public TempFile(string contents)
    {
        if (contents == null) throw new ArgumentNullException("contents");
        FullPath = Path.GetTempFileName();
        File.WriteAllText(FullPath, contents);
    }

    public string FullPath { get; private set; }

    public void Dispose()
    {
        File.Delete(FullPath);
    }

    public string Read()
    {
        return File.ReadAllText(FullPath);
    }

    public void Write(string text)
    {
        if (text == null) throw new ArgumentNullException("text");
        File.WriteAllText(FullPath, text);
    }
}
Posted in Uncategorized | Leave a comment

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