Monthly Archives: June 2010

Introducing a validation library

I’ve made a validation library which is focusing on model validation. Why another one when there are a few good ones like EntLib Validation ApplicationBlock and Data Annotations?

Three reasons:

1. It’s extendable

You can easily extend the library in different ways.

Own validation rules

You can create your own rules in the following way:

    public class CoolnessRule : IRule
    {
        public string Format(string fieldName, IModelLanguage rulesLanguage)
        {
            return string.Format(rulesLanguage["Coolness"], fieldName);
        }

        public bool SupportsType(Type type)
        {
            return type == typeof (string);
        }

        public bool Validate(object value)
        {
            return value.ToString() == "Jonas";
        }
    }

The Format method is used when formatting and localizing error messages. Each rule can be more or less complex and might to add range restrictions etc. Therefore it’s up to the rule to pull the language prompt (in this case “‘{0}’ must be called ‘Jonas’ to be cool“) and add the correct number for parameters.

The SupportsType method is used to determine if the specified type can be validated by the rule. For instance, the Max rule can validate all primitive types and strings (string length).

Validate method does the actual validation.

Validate in different ways

The actual validation can be done in different ways. Fluent and attribute validations are built in, more about them later. To add your own validation provider, do something like this:

    class MyRuleProvider : IRulesProvider
    {
        public bool Contains(Type type)
        {
            return type == typeof (Model2);
        }

        public ModelValidator Create(Type type)
        {
            ModelValidator validator = new ModelValidator();
            validator.Add("FirstName", new RequiredRule()); // first name is required
            validator.Add("Department", new BetweenRule(5, 20)); // department must be between 5 and 20 letters.
            validator.Add("Age", new BetweenRule(18, 65)); // age must be between 18 and 65 years.
            return validator;
        }
    }

The Contains method determines if this provider have support for the specified type. And the Create method is used to create the ModelValidator class containing all the rules.

Then you just need to add your provider to the library:

Validator.Add(new MyRuleProvider());

2. It’s multilingual

The multilingual support is quite flexible too. You can easily load language from any source you want. Myself are using text files to be able to categorize entries and use one file per model (I use the translation files for other stuff too, for instance localized error messages).

To load strings from a StringTable, you can do something like this:

    public class LanguageProvider : ILanguagePrompts
    {
        public string this[string modelName, string promptName]
        {
            get { return Get(modelName, promptName) ?? "[" + promptName + "]"; }
        }

        public string Get(string modelName, string promptName)
        {
            return Resource1.ResourceManager.GetString(modelName + "_" + promptName);
        }
    }

And to use your provider:

            Validator.LanguageHandler = new LanguageProvider();

In your string table you create entries like the following ones:

User_FirstName             FirstName
User_LastName             LastName

i.e. ModelName underscore PropertyName

3. It’s flexible

The library doesn’t force you to use validations in a certain way. You can use your own favorite way of creating validations.
The two built in providers use either code or attributes to provide validations.

Attribute validation

public class MyModel
{
  [Required]
  public string FirstName {get;set;}

  [Required, Min(15)]
  public string LastName {get;set;}
}

FirstName is required and LastName is required and must be maximum 15 characters long.

Your own validation rules will automatically be added to the validator when using attribute validation.

Fluent validation

Fluent validation means that you create a class which is used to validate models. The class is automatically loaded and instantiated by the library, all you need to do is to create it and place it in the same namespace as the model. It should be named [YourModelName]Validator, i.e. UserValidator.

public class MyModelValidator : FluentValidator<MyModel>
{
  public MyModelValidator()
  {
    Property("FirstName").Required();
    Property("LastName").Required().Min(15);
  }
}

To add support for your own validation rules, simply create extension methods for the Property class:

public static Property Tired(this Property instance)
{
  instance.Add(new TiredRule());
  return instance;
}

Usage

The most important part is how the library are used, right?

User user = new User();
user.FirstName = "Jonas";

var errors = Validator.Validate(user);
if (errors.Count > 0)
{
    // Handle the errors in any way you like.
    // both property names (localized and actual property name) and localized error message is accessible.
}

Source code

The source code can be found at CodePlex.


TodoApp – part 4: Welcome softcore!

The application as getting a bit more well designed when it comes to DRY KISS, SR. But before we continue, we have a small problem in the last iteration.

We didn’t find a good way to get typed data back instead of a data reader. We didn’t want to fill a List<> and return it, because it would take a lot of memory if we have millions of todo items. Instead we developed two classes turning a datareader into a typed IEnumrable.

The resulting code in the ItemRepository looks like this:

        /// <summary>
        ///   List all items.
        /// </summary>
        /// <returns>A collection of items, or a empty collection if no items was found.</returns>
        public IEnumerable<TodoItem> List()
        {
            var cmd = _db.CreateCommand("SELECT * FROM todo_items");
            return new ForwardOnlyCollection<TodoItem>(cmd.ExecuteReader(), OnFillItem);
        }

        /// <summary>
        ///   Callback from ForwardOnlyCollection
        /// </summary>
        /// <param name = "reader"></param>
        /// <param name = "item"></param>
        private static void OnFillItem(IDataReader reader, TodoItem item)
        {
            item.Id = (long) reader["id"];
            item.Title = (string) reader["title"];
            item.Description = (string) reader["description"];
        }

And the method in MainWindow was turned into:

        /// <summary>
        /// Loads items from the database and inserts them into the list box.
        /// </summary>
        private void PopulateListbox()
        {
            lbTodos.Items.Clear();
            foreach (var item in _repository.List())
                lbTodos.Items.Add(item);
        }

The MainWindow class is now totally unaware of the data source. Neat, huh?

The next day

After sleeping very nicely the developer (humm, the one making the Todo application) woke up with four letters circling around in his head: S K I S. He didn’t make any sense of them and went to work. After looking at the code he remembered what he did yesterday.

“We didn’t want to fill a List<> and return it, because it would take a lot of memory if we have millions of todo items”

omg! The letters was in the wrong order, they should be “KISS”. Keep it simple (and) stupid. How often do we have millions of todo items? That would be quite sad, wouldn’t it?

He refactored into a regular list instead:

        /// <summary>
        ///   List all items.
        /// </summary>
        /// <returns>A collection of items, or a empty collection if no items was found.</returns>
        public List<TodoItem> List()
        {
            var cmd = _db.CreateCommand("SELECT * FROM todo_items");
            var items = new List<TodoItem>();
            var reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                var item = new TodoItem();
                FillItem(reader, item);
                items.Add(item);
            }
            return items;
        }

A code duplication was also found. A TodoItem was filled with data from a IDataReader in both Get and OnFillData. OnFillData was renamed to Filldata and used in both places.

All code can be viewed at codeplex.


TodoApp – Part 3: Fix that data source.

Let’s continue with the refactoring. What are the main window really doing?? Well.

  1. Displaying todo list
  2. Loading and saving stuff to the database

That’s one thing too much. We’ll implement a Repository. imho, Fowler is wrong in his explanation. The most important goal with the Repository pattern is the following line: “Repository also supports the objective of achieving a clean separation and one-way dependency between the domain and data mapping layers”. That’s what the pattern is all about, period. We do not want our domain to have any knowledge about the data source.

In later versions, the data source will be a REST web service publishing stuff as JSON. By implementing a Repository now, we get the bonus that we do not have to do that many modifications in later versions. All we need to do is to switch implementation class from one to another (since we are using an interface and not a class in our code).

The new class is called ItemRepository. The application is a bit more readable now than the first version, right?


Extension methods to simplify database handling.

Two extension methods used to simplify database handling.

    public static class DbExtensionMethods
    {
        /// <summary>
        /// Create a new database command.
        /// </summary>
        /// <param name="connection">Connection used as factory.</param>
        /// <param name="commandText">SQL query.</param>
        /// <returns>Created command</returns>
        public static IDbCommand CreateCommand(this IDbConnection connection, string commandText)
        {
            var cmd = connection.CreateCommand();
            cmd.CommandText = commandText;
            return cmd;
        }

        /// <summary>
        /// Add a new parameter to the command
        /// </summary>
        /// <param name="cmd">Command</param>
        /// <param name="name">Parameter name, without prefix such as '@'.</param>
        /// <param name="value">Parameter value, datatype should be the same as in the database column.</param>
        public static void AddParameter(this IDbCommand cmd, string name, object value)
        {
            var parameter = cmd.CreateParameter();
            parameter.ParameterName = name;
            parameter.Value = value;
            cmd.Parameters.Add(parameter);
        }
    }

Usage

The following code:

            var cmd =
                new SQLiteCommand("UPDATE todo_items set title=@name, description=@description WHERE id = @id", _db);
            cmd.Parameters.Add(new SQLiteParameter("name", item.Title));
            cmd.Parameters.Add(new SQLiteParameter("description", item.Description));
            cmd.Parameters.Add(new SQLiteParameter("id", item.Id));

becomes

            var cmd = _db.CreateCommand("UPDATE todo_items set title=@name, description=@description WHERE id = @id");
            cmd.AddParameter("name", item.Title);
            cmd.AddParameter("description", item.Description);
            cmd.AddParameter("id", item.Id);

Best of all, the code becomes driver independent. (You can switch between SQLiteConnection, SqlClientConnection or whatever without any code modifications).


TodoApp – Part 2: Single responsibility is what we need.

In our journey towards hardcore we need to refactor the shitcore into a bit more softcore =) I’m not going to show all source code in this blog entry. You can look at the code here.

It will take some iterations before the code is quite usable. In this iteration we will focus giving each method a single responsibility, which means that each method should only contain the logic for one thing. The constructor is a kick ass example of that. Lets look at it.

First of all, it’s responsible of connecting to the database.

public MainWindow()
{
    InitializeComponent();
    _db = new SQLiteConnection("Data Source=todomachine.db;Version=3;DateTimeFormat=Ticks;");
    _db.Open();

then, it’s also verifying that the table exists in the database.

    //create table if it do not exist.
    if (!DoesTableExist(_db, "todo_items"))
    {
        SQLiteCommand command = new SQLiteCommand(_db);
        command.CommandText =
            @"CREATE TABLE todo_items(
id INTEGER PRIMARY KEY AUTOINCREMENT,
title VARCHAR(40) NOT NULL,
description text NOT NULL
);";
        command.ExecuteNonQuery();
    }

and finally it’s loading stuff into the list box.


    // load all todo items.
    SQLiteCommand mycmd = new SQLiteCommand(_db);
    mycmd.CommandText = "SELECT * FROM todo_items";
    var reader = mycmd.ExecuteReader();
    while (reader.Read())
    {
        lbTodos.Items.Add(new Item { Id = (long)reader["id"], Title = (string)reader["title"] });
    }
}

Let’s fix that and write a little bit of documentation for each method.

btnNew_Click

Next we have btnNew_Click which is used to save a new item:

private void btnNew_Click(object sender, EventArgs e)
        {
            var frm = new TodoItemForm();
            frm.ShowDialog(this);

            var cmd =
                new SQLiteCommand("INSERT INTO todo_items (title, description) values(@title, @description)", _db);
            cmd.Parameters.Add(new SQLiteParameter("title", frm.tbTitle.Text));
            cmd.Parameters.Add(new SQLiteParameter("description", frm.tbDescription.Text));
            cmd.ExecuteNonQuery();

            lbTodos.Items.Clear();
            // load all todo items.
            SQLiteCommand mycmd = new SQLiteCommand(_db);
            mycmd.CommandText = "SELECT * FROM todo_items";
            var reader = mycmd.ExecuteReader();
            while (reader.Read())
            {
                lbTodos.Items.Add(new Item { Id = (long)reader["id"], Title = (string)reader["title"] });
            }
        }

It has two responsibilities: Saving an item into the database and refreshing the listbox.
Fortunately, we have already created a method for the listbox in the constructor refactoring. Let’s just add that the listbox should be emptied before adding all items.

lbTodos_MouseDoubleClick

lbTodos_MouseDoubleClick is used to edit an item.

        private void lbTodos_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            Item item = (Item)lbTodos.SelectedItem;

            SQLiteCommand mycmd = new SQLiteCommand(_db);
            mycmd.CommandText = "SELECT * FROM todo_items WHERE id=" + item.Id;
            var reader = mycmd.ExecuteReader();
            reader.Read();

            var frm = new TodoItemForm();
            frm.tbDescription.Text = (string)reader["description"];
            frm.tbTitle.Text = (string) reader["title"];
            frm.ShowDialog(this);

            var cmd =
                new SQLiteCommand("UPDATE todo_items set title=@name, description=@description WHERE id = @id", _db);
            cmd.Parameters.Add(new SQLiteParameter("name", frm.tbTitle.Text));
            cmd.Parameters.Add(new SQLiteParameter("description", frm.tbDescription.Text));
            cmd.Parameters.Add(new SQLiteParameter("id", item.Id));
            cmd.ExecuteNonQuery();

            lbTodos.Items.Clear();
            // load all todo items.
            SQLiteCommand cmd3 = new SQLiteCommand(_db);
            cmd3.CommandText = "SELECT * FROM todo_items";
            reader = cmd3.ExecuteReader();
            while (reader.Read())
            {
                lbTodos.Items.Add(new Item { Id = (long)reader["id"], Title = (string)reader["title"] });
            }

        }

Responsibilities:

  1. Load item from database
  2. Populate item form
  3. Save stuff from the item form into the database
  4. Populate list box

Here we’ll refactor the item form to use the Item class, and we’ll therefore make the item class standalone (instead of being a private class inside MainWindow). That should take care of #2.

#4 have already been fixed thanks to the previous method refactorings.

We’ll move the item loading into a separate method.

Done

The first refactoring is now done. The goal of this post was to help you understand what Single responsibility really means, although we are not quite done with the guideline yet. The MainWindow form still have many different responsibilities. But first let’s explore exception handling in the next post.


TodoApp – part 1: From shitcore to hardcore

The easiest way to learn how to improve ones coding is by examples. I’ve therefore created an example application which is really crappy written application. It’s a todo app where you can enter your todos (but not delete them ;)). The idea is to take this basic winform application and turn it into a client/server app utilizing different open source libraries for logging, IoC and web services.

The sourcecode is available at codeplex, each check in will represent a blog post. (Check each diff to see what I’ve refactored each time).

Read the source code and check the next blog entry for the first refactor iteration.


Everyone know what it is, but no one have used it?

I must confess that I’ve never used the northwind database, despite that I’ve been developing using Visual Studio for more than 10 years.

I’m going to try Entity Framework 4 due to a request from a colleague of mine. The tutorial that I found is using Northwind database. I though that the DB was included in vstudio, but I didn’t find it anywhere. Therefore I downloaded it from Microsoft.

I really hope that the POCO implementation is well done. I’ve never used EF before since it couldn’t keep its hands of my POCOs.


My name is More, Docu More!

Are you one of those people that thinks that code is self explainable? Still thinking that when you go back and try to fix code that you did a year ago? Yes? Good for you.

Documentation is a tool that is quite underrated. If used in the right way, it can improve your coding skills. Seriously!

I got a few guide lines that I try to follow when coding. (Sure, sometimes I don’t give a sh!t. We are only humans, right?)

Rule 1: There are no rules

If you do not intend to follow your rules, don’t make them. It’s quite easy to make a lot of rules that will, if you use them, improve your code quite a lot. But you need to use them, right?

If you feel that you have too many rules, simply remove those that you break most often. When you have started to follow all your rules, add another one (if necessary).

Rule 2: Describe the purpose

When documenting projects and classes, ALWAYS motivate why you created them. If you can’t write a clear and concise motivation to why a class was created, you have probably done something wrong. Refactor.

Rule 3: AND is evil

Do not write a lot of AND in your code documentation. If you do, read about single responsibility principle in a previous post.

Example:

This method will save the user, email the admin and save a blog entry into the database.

Rule 4: Explain what parameters do, not what they are

I quite often see documentation which just describes what parameters are (their type), but not what they are used for or what business rules they are validated against.

Coding contracts will be a big help here, since they are also imported into the documentation.

Rule 5: Return values are not obvious

Return values are not obvious. Can null be returned? What is no users are found, is null or an empty list returned? Always describe the return values.

If you find yourself describing more than two different type of return values, check if you should refactor the method.

Example of a good description (for the method GetUser): The requested user if found; otherwise null.

Rule 6: Exceptions

Are you always throwing/catching Exception instead of more specific exceptions? Stop. Read here and here

Ohh. We are talking about DOCUMENTING exceptions, not about how to use them. Well. Just document them….

Final words

Have you ever started to work out? You create a wonderful exercise program and decide to go the gym four times a week. It looks really good on paper, but how long do you keep it up? It’s the same with documentation. Start small. Download GhostDoc (see below) and start describing the purpose of each project/class/method. Do that for a week or two. Feels good? Do more.

Tools

GhostDoc helps you document your stuff in Visual Studio. When done, use Sandcastle to generate the docs. You might want to wrap sandcastle with a more user-friendly GUI.


Code smells

Found the following article when writing my last post. Read it, you don’t want your code to smell. Do you?


DRY KISS, SR!

omg! wtf?! Nahh, this ain’t a porn blog. The title is three coding principles that I try to follow when I code. And this blog is going to be all about them.

You’ll find code refactorings, insights and such that I discover during my days as a software architect/developer.

As you might notice, no entries will be elaborate or poetic. They will be short and concise: HARDCORE!

DRY – Don’t repeat yourself.

Most of you have probably heard of this principle. You can read more about it at wikipedia.

Code duplication is evil since you:

  1. can get the same bug in a lot of different places
  2. refactoring becomes hard (try finding all the places you have the duplicate code in)
  3. larger programs -> more code to maintain
  4. your application design is most likely bad as a rotten apple

Let’s focus on the last entry. Sorry, but it’s true. If you need to duplicate code, you have done something wrong. Go and take a coffee. Go through your code and try to refactor it. Ask a colleague of yours. DO NOT CONTINUE UNTIL YOU SOLVE THE PROBLEM. Trust me. You’ll regret it later.

KISS – Keep it simple (and) stupid

I have a really active brain. It comes up with all sorts of cool stuff and solutions when programming. That’s a BIG problem when coding. Coding is not about having the coolest solution or the most fancy features. It’s about doing as little as possible to get the job done. I do not mean that you should take shortcuts or writing shit code. I’m talking about doing a simple solid solution which get’s the job done but nothing more.

Time estimation is still one of the hardest thing to do when developing software. How long have we been coding? 40 years? And we still can’t do proper time estimations. El oh el! Do you know why? Because most programmers do not keep it simple! We love to learn new stuff and do cool solutions.

Finish the application first! Then do the fancy stuff.

Read more about KISS at wikipedia.

SR – Single responsibility

Have you ever seen a cop (Mr. Police) mow a lawn when on active duty? (If you have, please give him this link). I thought not. Why? Because doing a lot of different things would make him a bad cop. It’s the same with your classes, methods and projects. Don’t let a class both fetch the users from the database and present the info to the user. Do not let a method both send an email and eject the CD tray.

If a class is called UserReporsitory it should not do anything else than fetch/save you users from/to your data source. That’s what single responsibility means.

Why?! you ask. Well, letting your method/class/project doing a lot of stuff will make it hard to understand what your application does. It will also make it harder to understand. But the most important thing is: It will make it hard to test your application. (unit tests). And you don’t want that. Unit tests are a life saver when your application grows. All those green dots that says that the tests have passed will give you a warm fuzzy feeling inside when your application is 5M lines long. Imagine how hard it would be to test an app that large when all your classes do a lot of different stuff. Imaging a cop mow a lawn.

Read more about single responsibility @ objectmentor || oodesign

That’s it

Again. Welcome to my blog. Leave a comment or two.