Book Review: The 3 Pillars of personal effectiveness

Your ads will be inserted here by

Easy AdSense Pro.

Please go to the plugin admin page to paste your ad code.

Last week I went to the GOTOCon in Aarhus, Denmark. When I arrived and collected my registration badge I also got a bag (now have 4…) with some merchandice inside. Beside all the usual stuff from all the exhibitors, there also were two small books, “The 3 Pillars of personal effectiveness” by Troels Richter and Priming Kanban by Jesper Boeg.This review is about the first of them, later I’ll review the second.

Today I happend to have some time off from kids and all the usual housework, so why not focus on this one book “The 3 pillars of personal effectiveness”. As the title says the book has 3 main areas Focus, Importance and Value. Troels does a good job to explain every one of them in an easy to read easy to understand language, and combined with especially value, he also adds some level of implementation details to it, with his own tool Kanbana. As he describe the importance of visualization throughout the book, as an important aspect to better understand  “ your work effectiveness” so does he also illustrate with this little tool. But depending on your induvidual needs, another tool might fit as well.

In the “Focus” topic Troels writes a lot about The Pomodoro Technique. I think that everybody who haven’t tried this technique yet should just do it right now, or after reading the rest of this blog post :) . From my personal expirence this is a very powerful technique to stay focused, and not feeling tired at the end of the day. I also tried it with pairprogramming sessions which tend to very intense, and by the end of the day I was not as tired as the other pair programming days. Just use the clock on your phone, Focusbooster, or the one Troels integrated into to his own Kanbana tool, just get started now, the ROI is right around the corner. Everybody really need this, think of how many times a day you just say to somebody, I’ll help you in just 2 sec.  What if the person saw that you actually measured your “Focus” time, what could happen? He might adopt the same technique, the next time he might just look at your “Timer” before asking and you wouldn’t even notice his presence, until you actually had a break, cool right?

The last pillar Value has for me added some new thought, to the definition of Done, Done Done of as some ought to say Done Done Done, Well it is not a matter of how many D’s you get, what do you mean? As Troels explains feedback and evaluation is needed before you have Done whatever you are doing. The example from the book is great, send  someone an email, well are you done or do you expect a reply? well when are you actually done? I think he narrows down the key point of Done, look at when your task has added value or else why are you even working on it.

As the book explains how to set daily goals, one of mine was to read this book. And so I did, maybe not Done until this blogpost is released…… But I really enjoyed reading the book and I might have spend 1-2 hours of reading, but the value was great. I really like the non US style where every first 10 pages of a chapter explains what I’ll be reading in the next pages. It is precies, easy to read and adopt. I would recommend this book to everyone, not only in the IT business, but everybody who cares about their effectiveness and ain’t afraid of changes Kaizen.

Posted in Uncategorized | Tagged , | Leave a comment

WPF #1 Markup Extension

Your ads will be inserted here by

Easy AdSense Pro.

Please go to the plugin admin page to paste your ad code.

During the last two weeks I’ve been working on a small project with a WPF client. Until I started the project, I’ve only written a small amount of xaml in silverlight, and I’ve kept a distance to WPX/XAML.

Now, after two weeks of xaml xaml xaml xaml and some more xaml, I actually started to get the feeling of the framework. First off I was a bit scared and thats why I’ve haven’t touched the framework that much before, its huge!

To get a good infrastructure inside the project structure I’m using the Galasoft MVVMlight toolkit, really cool stuff! and also available for Silverlight. Just grab the package from Nuget

Markup Extensions as the topic says whats that? Normally I would make a view and viewmodel to serve as a DataContext for the view. The viewmodel will serve the view with behaviour and data, but which data? I needed to show the hours from 0 to 23 like this.

markupextension

Well when using the MVVM pattern one could easy achieve this by exposing an ObservableCollection from the viewmodel but? If you think of the view as an html page, you would properly not let the serverside serve fill the combobox with the numbers, why not make use of the client? And this is what is possible with markup extensions.

First create a Markup Extension by inherit from…… MarkupExtension

class HoursExtension : MarkupExtension
    {
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return Enumerable.Range(0, 24);
        }
    }

Next make the new extension available in the view by adding it as a static resource to the window and finally create a staticresource binding in the combobox’s itemssource with a key to the new resource.

<Window x:Class="ViewExtension.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:ViewExtension="clr-namespace:ViewExtension"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <ViewExtension:HoursExtension x:Key="hours"/>
    </Window.Resources>    
    <StackPanel>
        <TextBlock>Select Hour</TextBlock>
        <ComboBox ItemsSource="{StaticResource hours}"/>
    </StackPanel>
</Window>

Download ViewExtension Sourcecode

Posted in Uncategorized | Tagged | Leave a comment

Unittest with C# 4.0 Optional And Named Parameters

Your ads will be inserted here by

Easy AdSense Pro.

Please go to the plugin admin page to paste your ad code.

Just wrote a very simple unittest and started to wonder how I could optimize it? Then came optional and named parameters in c# 4.0 to the rescue. A feature of the language I didn´t know how to use, but now a found one place where it can be done.

The test is quite simple. I have a registration form with the usual “email”, “repeat email”, “password”, “repeat password” etc. and a method with the following model object to receive the registration from the form

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Registration
    {        
        public string Firstname { get; set; }
        public string Lastname { get; set; }
        public string Email { get; set; }
        public string RepeatEmail { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
        public string RepeatPassword { get; set; }

        public bool IsValid()
        {
            throw new NotImplementedException("Remember to write a test first ;) ");
        }
    }

Then I went to test it at wrote the usual test fixture to validate that I would return false if the emails were not equal. But hey then the rest needed to be valid……
To solve this I could create a factorymethod that let me pass all the parameters and write something like this.

1
2
3
4
5
6
7
8
9
10
11
12
[Test]
public void EmailsMustBeEqual()
{
      // arrange
      var registration = Create("John", "doe", "john@somemail.com", "john@error.com", "johndoe", "thesecret", "thesecret");

     //act
     var valid = registration.IsValid();

     //assert
     Assert.That(valid, Is.EqualTo(false));
}

The downside with this solution is to consider and make a valid combination, in each and every testfixture for the parts that are not being tested.
To solve this “named and optional parameters” can be used. Simply create a factorymethod that creates a single valid Registration by setting the default values to something valid.

1
2
3
4
5
6
7
8
9
10
11
12
13
public Registration Create(string firstname = "firstname", string lastname = "lastname", string email = "email", string repeatEmail = "email", string username = "username", string password = "password", string repeatPassword = "password")
{
    return new Registration
    {                
        Firstname = firstname,
        Lastname = lastname,
        Email = email,
        RepeatEmail = repeatEmail,
        Username = username,
        Password = password,
        RepeatPassword = repeatPassword
    };
}

Now the test fixture above can be refactored to:

1
2
3
4
5
6
7
8
9
10
11
12
[Test]
public void EmailsMustBeEqual()
{
    // arrange
    var registration = Create(email: "john@somemail.com", repeatEmail: "john@error.com" );

    //act
    var valid = registration.IsValid();

    //assert
    Assert.That(valid, Is.EqualTo(false));
}

I think it is clean and simple solution to keep each testfixture clean.

Posted in Uncategorized | Tagged , | 1 Comment

ASPNET MVC 3 Simple NHibernate UnitOfWork using Global Action Filters

One of the tools I’ve used for the last couple of years in severeal projects has been NHibernate. When using NHibernate for web projects the big question is always, how should the ISession be handled? There are severeal posts about this, and I want to show a small example of how this can be even more simplified using ASP.NET MVC 3 Global Action Filters.
For more detailed infor about setting up NHibernate see this earlier post

The Goal

We want every request to a controller / action to create a new instance of a session, to work inside an Identity Map unique to this request. To make it just a little more abstract I will state that we want a unique UnitOfWork for every request.

The Challenge

When should a new NHibernate Session be created for an incoming HrrpRequest? How do you filter the request for an image *.png, a stylesheet *.css or MVC action e.g.? How should the session for the request be comitted or rolledback between the Identity Map and actual datastorage, what if an exception occurs?

The strategy

First of all I want to create a new instance of a session when making a new httprequest. It doesn’t matter if the request is only a GET and we are only pulling out data. The creation of the session is very cheap and this should not be the first performance bottleneck to address. If it should be a issue later, when you really needs to scale your project, go change it. For now and a lot of the future it will work just fine.

But by creating a new session for every httprequest I only mean “Action” requests, not requests for images, stylesheets, scripts e.g. So there needs to be some kind of filter to avoid these requests will create a new session. Last thing to handle is a simple rollback, what should you to do if for some reason the session needs a rollback?

When I first started using NHibernate for web projects I used a HttpModule for controlling the creation of a new session. This works quite well and it is quite simple to turn the module on/off from the web.config.
The downside is the filtering you need to check the type of request. Is it a request for a stylesheet or is this actual a request for an action to perform some operation? So how could this be performed even more simple?
I’ve seen some examples of this, but never really liked the concept.

The Mission

Starting from ASPNET MVC 2, action filter were introduced and let you intercept a request for an action, by using ActionFilters like in Aspect Oriented Programming. A filter could either be added to actions one by one or applied to a controller by apply it as an attribute to the action or controller. Adding it to the controller is a shortcut for adding it to all actions inside a controller.

1
2
3
4
5
 [UnitOfWorkFilter]
 public class CustomerController : Controller
 {
     .....All your magic goes here
 }

Creating the UnitOfWork Filter
So lets start by creating the UnitOfWork Filter, details will follow.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class UnitOfWorkFilter : ActionFilterAttribute, ICustomActionFilter
{        
        private ISessionContainer sessionContainer;        
        public UnitOfWorkFilter(ISessionContainer container)
        {
            this.sessionContainer = sessionContainer;
        }
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);
         
            if(filterContext.Exception != null)
            {
                sessionContainer.Abort();
            }            
            sessionContainer.Dispose();
        }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            sessionContainer.OpenSession();            
        }
}

First the new filter must inherit from ActionFilterAttirbute. Next it implements a marker interface. This interface makes it easy for me to register and install custom actionfilters. This is explained later
The contructor of the filter gets an ISessionContainer injected. This is the level of session encapsulation I normally uses. The benefits of doing it this way, is first of all the abstraction against the actual implementation and further more the possibility to encapsulate the logic for how transactions is created e.g. but still offer some control of when to do stuff, OpenSession bind to current request and Dispose e.g. And finally Dependency Injection :)
The filter shown above handles before and after action behaviours. When an action is invoked, a the session container is told to open a new session. When an Action ends, the current session is disposed. But notice the extra lines with check for exception. This is one possible way to abort and rollback a transaction. If an exception were thrown inside the action this is where it would be handled.

From Local to Global ASPNET MVC filter
The filter we just created is one that should be used at every controller in the application. So should be just start to add it to all the controllers inside the app? This is where we welcome ASPNET MVC 3 global filters.

Inside the Global.asax file the following method is found, with its default implementation.

1
2
3
4
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
        filters.Add(new HandleErrorAttribute());
}

So inside here I could just add the new UnitOfWork filter. But the problem is that is requires an instance of an ISessionContainer….
Of course the answer to this is dependency injection. First thing to to is make an installer for all CustomAction filters. Notice the ICustomActionFilter marker interface as used above.

1
2
3
4
5
6
7
8
9
10
public class FilterInstaller : IWindsorInstaller
{
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            container.Register(AllTypes
                           .FromThisAssembly()
                           .BasedOn<ICustomActionFilter>()                          
                           .Configure(c => c.LifeStyle.Transient));
        }
}

Remember to add this to the Install of the Windsor container

To finally register the filter as global extend the default registration method with the following

1
2
3
4
5
6
7
8
9
10
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
            filters.Add(new HandleErrorAttribute());

            var actionlFilters = Container.ResolveAll<ICustomActionFilter>();            
            foreach (var actionFilterAttribute in actionlFilters)
            {
                filters.Add(actionFilterAttribute);
            }            
}

This will resolve the customfilters from the container, and make sure that their dependencies ISessionContainer e.g. are satisfied too.

And that’s it!

Posted in Uncategorized | Tagged , , , | Leave a comment

ASPNET MVC 3 Dependency Injection With Castle Windsor

This post is not a post about what dependency injection is. Its about how you can make it work in ASP.NET MVC 3 with its new dependency feature. Why use it? Dependency injection is a great help when doing TDD and also saves a lot of “hardcoded” plumming code in programs also known as maintainability.

Preparing the MVC framework for dependency injection
There are some basically dependency registration steps that needs to be done. As the subject describes this is about castle windsor, so first of all go grap it, and why not from NuGet.

Register dependencies
Next thing is a strategy for how you want register your dependencies. The goal here is to make constructor injection an option. I prefere to have one strategy for MVC controllers and another for all other dependencies like repositories e.g. I many samples, Windsor registration is done in a handcrafted way where every registration is listed line by line. As this is not very maintainable and effective (this is an infrastructure you need to rely on). The solution is WindsorInstaller.

1
2
3
4
5
6
7
8
9
10
public class ControllerInstaller : IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            container.Register(AllTypes
                                   .FromThisAssembly()
                                   .BasedOn<IController>()
                                   .Configure(c => c.LifeStyle.Transient));
        }
    }

First up is the installer for Controllers. What Windsor will do when this installer is executed, is to look in this assembly for all implementations of IController, and register each one by its type.

1
2
3
4
5
6
7
8
9
10
11
public class DependencyInstaller : IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            container.Register(AllTypes
                .FromThisAssembly()
                .BasedOn<IDependency>()
                .WithService.FirstInterface()
                .Configure(component => component.LifeStyle.Transient));            
        }
    }

Secondly is the installer for all other dependencies. I use a marker interface named IDependency for dependencies. As one would see from the above I expect all dependencies to implement an interface for what they represents. A dependency could be like the one below. Notice that the marker interface is last and the interface this type would be registered by is the ICustomerRepository.

1
public class CustomerRepository : ICustomerRepository, IDependency

Executing installers
To run the installers above, Global.asax.cs is the answer as shown below:

1
2
3
4
5
6
private void BootstrapContainer()
        {            
            Container = new WindsorContainer();
            Container.Install(new DependencyInstaller(), new ControllerInstaller());                      
            DependencyResolver.SetResolver(new CastleDependencyResolver(Container));
        }

First an instance of the container is created. Next the container is told to run the specified installers and thats it! Simple and effective. The third line is explained later.

Wireing it all up with ASP.NET MVC 3
With the introduction of version 3 of the ASP.NET MVC framework dependency injection is one of the new highlighted features. The framework introduces two new interfaces to facilitate this feature: IDependencyResolver and IControllerActivator.
The IDependencyResolver tells the framework how to resolve dependencies as the name describes and are instantiated as shown above in the Global.asax description.
In our case the implementation could look like below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class CastleDependencyResolver : IDependencyResolver
    {
        private readonly IWindsorContainer container;

        public CastleDependencyResolver(IWindsorContainer container)
        {
            this.container = container;
        }

        public object GetService(Type serviceType)
        {
            try
            {
                return container.Resolve(serviceType);
            }
            catch (Exception e)
            {
                return null;
            }        
        }
        public IEnumerable<object> GetServices(Type serviceType)
        {
            try
            {
                return (IEnumerable<object>)container.ResolveAll(serviceType);
            }
            catch (Exception e)
            {                
                return null;
            }
        }
    }

Quite a simple implementation and according to the mvc documentation, if its not possible to resolve a dependency then null should be returned.
The implementation of IDependencyResolver is enough if controllers did not rely on injection. But to get all the value for money you can, these must support dependency injection too. To make the controllers support it, an implementation of IControllerActivator is needed. The implementation relies on the IDependencyResolver so there is not much of implementation here, just what easy and simple.

1
2
3
4
5
6
7
8
 public class ControllerActivator : IControllerActivator, IDependency
    {
        public IController Create(RequestContext requestContext, Type controllerType)
        {
            return DependencyResolver.Current
               .GetService(controllerType) as IController;
        }
    }

To hook this up with the framework, I use the technique shown earlier,the marker interface IDependency.

And thats It
You now have a fully Windsor supported edition of the ASP.NET MVC 3 Framework. Compared to the earlier version 2 of the framework, The two interfaces IDependencyResolver and IControllerActivator wasen’t available. Even though some of the same code could be used. You just needed to implement a custom controller factory. It might have been a few less lines of code, but with the new interfaces Single Responsible Principle comes to its power. Enjoy!

Posted in Uncategorized | Tagged , | 1 Comment

NHibernate Loquacious configuration goodbye NHibernate.cfg.xml?

For the last couple of projects I been working on, NHibernate has been the ORM used mapping Entities with the storage backend, Both for Oracle and MSSql databases. NHibernate does both well and by first look the only difference is the dialect you specifiy in the nhibernate.cfg.xml configuration file, which has been the way it has been configured in all the projects I’ve seen so far.

1
2
3
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>

This will work in most projects most of the time, but not always and have you ever thought why you are configuring NHibernate this way?

Do you offer selfhosting?
If you are making a product that people can buy and host them self, you obviously can not make a strict configuration they must fullfill. The one thing that will 99% (Windows integrated security might be the 1%) of the time be different is the connectionstring. First thing to do is to make it part of the app/web.config by specifying the following:

nhibernate.cfg.config

1
<property name="connection.connection_string_name">dbcon</property>

app/web.config

1
2
3
  <connectionStrings>        
    <add name="dbcon" connectionString="data source=.\SQLExpress;Integrated Security=true;Initial Catalog=northwind" providerName="System.Data.SqlClient"/>
  </connectionStrings>

This will move the connectionstring to a central place. Next thing to consider is how resistance is your application for different storage providers? What happens if your customer changes the dialect from MSSQL to Oracle e.g.? And to Oracle9 or 10 dialect, what will happen? Is it supported?

For a small and auto mapped application this might work, and if this is where your application lives, then you are good to go. Well have you considered the change you did time ago in the mapping of your entities? When you started using the new MSSQL Datetime2 datatype instead of the “old” datetime? This is a DB specific mapping and will properly breake your application sometime. To avoid issues like this you wrote a testcase for providers ypu claim to support didn’t you….

Selfhosting
All of the above is also important if you host the application backend yourself and your customers are only using some frontend application that integrates to your backend.
After upgrading to NHibernate 3.0 and looking at the new Loquacious fluent configuration I suddenly realized I could change my normal nhibernate configuration setup code (nhibernate.cfg.xml). I had code looking for the configuration file, appdomain lookup messy code…. building a configuration and sessionfactory based on it. But why? the only thing I would change would be the server hosting the database so why would I need this extra file on disk?

By the introduction of NHibernate Loquacious you can and should write the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void BuildSessionFactory()
        {
            if (SessionFactory == null)
            {
                configuration = new Configuration();                
                configuration                    
                    .Proxy(p => p.ProxyFactoryFactory<ProxyFactoryFactory>())
                    .DataBaseIntegration(db =>
                                             {
                                                 db.ConnectionStringName = "myconnectionstring";
                                                 db.Dialect<MsSql2008Dialect>();
                                             })
                    .AddAssembly(typeof(MyEntity).Assembly)                      
                    .CurrentSessionContext<WebSessionContext>()                                                            
                SessionFactory = configuration.BuildSessionFactory();                                
            }
        }

After this “small” fluent change the NHibernate.cfg.xml file can be permanently and safely deleted. The above could also have been written by using FluentNHibernate, but as of NHibernate 3.0 Loquacious is a part of NHibernate so why introduce a 3rd party package for this?

So for your current project try consider the above and what risk you might introduce to your application by having a seperate configuration file. If you at some point in time have to change storage provider after all, you still need to test your application and this could the be a new release after all so the change in your Loquacious configuration would not be a problem after all.

Posted in Uncategorized | Tagged | Leave a comment

Welcome By Passion.dk

Finally after a long time without blogging, I’ve decided to start blogging again, Why? Well to me blogging is also a kind of  memory online, note to one self. I often have many thoughts during my daily life as a professional softeware developer. Thoughts and expirences about how I see some of all the principles for software development, agile development and entrepeneurship You read about in all the textbooks Meets Real Life, when is comes to practical experience.

Hopefully it will remove some of my post-its off my desk, and be helpful for you reading this blog.

Enjoy!

Posted in Uncategorized | Leave a comment