Daniel Hoelbling-Inzko talks about programming

Good ideas worth spreading: SystemDateTime abstractions

I brought this example up a lot on this blog, but while looking at the code of Mark Nijhof yesterday I noticed a rather nice solution to my ongoing problem of abstracting away System.DateTime.Now calls for testing purposes.

As stated before: Don’t make your tests depend on external factors like the current time or Date, and I even had a solution until now that solved the problem rather nicely through a static factory that returns an instance to your DateProvider.
Why a global factory? Simple: having your IDateProvider be a mandatory dependency on all your objects and services will quite simply clutter up your design. IDateProvider is by no means a really important dependency, and modeling it the same way as say IImportantBusinessRule would not only require you to think about that DateTimeProvider in every test that you run against your object, but also reduce the readability of your constructors dramatically.

What I didn’t think about when writing my IDateProvider abstraction almost a year ago was that with C# 3.5 and lambdas, passing around a function is essentially the same as using a strategy class, but with a lot less ceremony. And obviously so thought Mark Nijhof when he wrote Fohjin (a very nice CQRS example you really should check out on GitHub).

public static class SystemDateTime
    public static Func<DateTime> Now = () => DateTime.Now;
    public static void Reset()
        Now = () => DateTime.Now;

So simple yet so elegant. In your tests you hardly have to think about this stuff, but if there is a test that depends on the date you can just go ahead and set it like this:

public void ctor_SetsDateAddedTo_CurrentDate()
    SystemDateTime.Now = () => DateTime.MaxValue;
    var orderLine = new OrderLine(TestData.Product, 1);

    Assert.Equal(DateTime.MaxValue, orderLine.DateAdded); }

It’s just a small touch, but it saves you 2 classes and still solves the problem nicely.

Locking with Linq to SQL&rsquo;s deferred execution

If you have been reading this blog lately you may have noticed that I’m currently working on a project where I chose Linq to Sql as my data-source, inspired by the IQueryable<T> Repository Rob Conery introduced in his MVC Storefront series.

The basic idea of the IQueryable<T> repository is to have the repository return a IQueryable list of C# domain objects that can then be filtered, queried, parsed at higher layers of the application.
So things like paging, filtering etc (all business concerns) can be applied to the query at a later stage instead of having to propagate all of these requirements down to the Repository (Ayende wrote something great on the death of Repository you should check out).

So my business code would call the repository for all objects and then apply logic to it:

var preferredUsers = 
    .Where(p => p.JoinDate < DateTime.Now.AddYears(-1))

I loved it. Not having to propagate concerns like paging and filtering to the DAL was awesome, and since the interface is so damn simple I very quickly came up with decorators that did error handling, caching and logging at the DAL level.

Since I’ve become a dependency injection nut, I then came up with a injectable datacontext so my repositories don’t have anything to do with the data context creation (thus sparing me the configuration concerns in that class).

My concrete repository implementation then looked like this:

public class UserRepository : IRepository<BlogUser> 
    private DataClassesDataContext context;

    public UserRepository(DataClassesDataContext context)     {         this.context = context;     }

    public IQueryable<BlogUser> GetAll()     {         return from u in context.Users                select new BlogUser                           {                               Id = u.Id,                               Username = u.Name,                               Password = u.Password                           };     } }

You see, the context gets injected and besides the query there is nothing in the repository, SRP .. check.

Now, the logical thing to do in my IoC configuration was to have the repositories be singletons, and so every repository has one datacontext attached to it.

And this is where it blew up in my face, having multiple threads access the repository leads to some nasty race conditions for the datacontext, and I found no sane way of dealing with this at the DAL level.
Try this:

public static void main()
    var repository = new UserRepository(new DataClassesDataContext());
    new Thread(() => ThreadStart(repository)).Start();
    new Thread(() => ThreadStart(repository)).Start();

public static void ThreadStart(IRepository<BlogUser> repository) {     const int PAGE_SIZE = 10;     int pageNumber = 1;     var preferredUsers =         repository.GetAll()         .Where(p => p.JoinDate < DateTime.Now.AddYears(-1))         .Skip(PAGE_SIZE*pageNumber)         .Take(PAGE_SIZE);     preferredUsers.ToList(); }

The same query as before, but two threads that share the same repository, therefore sharing the same datacontext. Once started, the whole thing will blow up with a InvalidOperationException stating that the connection is closed.

I didn’t bother to go into the DataContext source and check out why they are closing the connection, but apparently after the query is executed it takes some time for the context to “recover” and be able to accept a new query.

I immediately tried to solve the problem by adding a lock on the datacontext in the repository class (since the contexts are pooled, it was the only thing that made sense since I don’t need to lock all connections, just the one I’m currently using).

public IQueryable<BlogUser> GetAll()
    lock (context)
        return from u in context.Users
               select new BlogUser
                              Id = u.Id,
                              Username = u.Name,
                              Password = u.Password

I intentionally said I tried, because it didn’t work. The lock gets executed alright, but the query isn’t run inside the lock{} but rather at the calling code, in my business class (the power of deferred execution). So the only way to prevent a race condition for my datacontext would have been to add locking to the business code:

const int PAGE_SIZE = 10;
int pageNumber = 1;
var preferredUsers = 
    .Where(p => p.JoinDate < DateTime.Now.AddYears(-1))

Omg right? So, besides the fact that I can’t guarantee that two repositories don’t use the same datacontext (and therefore racing against each other), I just opened the Pandora's box of possible errors (give me a month and I’ll forget the locking at least 3 times).
Also, it’s just painful to see an implementation detail of the data access layer leak into the business code for no apparent reason.

And the only way I found on how to solve that problem was to supply a new datacontext to every query, so I get rid of the whole locking. I did so by injecting a datacontext factory into the repository and call the factory every time I execute a query.

This fixed the issue for now, but I don’t feel too good about the solution. Creating new datacontext object for every query somehow feels wrong, and I’d love to hear suggestions from you on how to change that.

Filed under net, programmierung, patterns

Inevitable leaking of control Information

I’m wondering if anyone of you has a better solution (or thoughts) for this.

Assume I have a business rule that states “If there is already a bill for one special order, the user should be warned when trying to create another bill”.
So, obviously I simply display a MessageBox telling the user he’s about to do something stupid (but he should have the choice).

I see a “leak” of business logic from the Controller to the GUI when I have the GUI question the controller layer if there is already a bill for the Order. The decision about whether to proceed or not has to happen in the GUI since it’s the only layer capable of displaying a messagebox to the user (simply reference wise). But the semantics of this decision actually belong into the controller. And frankly, I can’t really find a viable way to separate the logic from the Gui on this case.

The system is layered as follows:


The root cause of this problem is that I’m not really following the MVC pattern on this one. The GUI always calls down to the controller instead of the controller calling the GUI. This way I often see myself struggling to somehow push logic down into the controller while trying to keep the GUI free from logic. But when it comes to complex interaction I realize now that the GUI is actually driving the whole thing, and that makes this whole thing a pain to re-wire later.

One way to detect things like this is when your controller classes don’t contain actual state. Most of my controller methods are just taking input and applying logic to it, not actually controlling the information flow inside the application (and that should have made me suspicious a long time ago).

So, I guess I can blame myself on this one and will have to try to minimize the damage done until I get time to refactor the system at a later stage.
Still bugs me that I fell for this, but the whole point in failing is to be able to learn from mistakes. :)

What also supports my case is that the controller and repository layers are very well tested, so I may be able to divide the controller layer into multiple strategy classes (logic dumps) while reworking how control flow is handled by the system.

Filed under programmierung, patterns

Windows Forms: Form within a panel

I already blogged about Visual Inheritance as a tool for avoiding DRY violation.

Once you’re through with any better book on object oriented design you should have found another important oo principle:

Favor object composition over class inheritance

But how to do that in Windows Forms?
Well, if you dig with Reflector into the Form class you’ll discover that it’s derived from Control. And every container in Winforms accepts Control as it’s child objects.


Now, this makes it possible to just create a Panel and say:


But after running you’ll get a ArgumentException stating that you can’t add a top level control at this level.

The solution to this is even simpler, you simply need to tell the form to not be top level any more:

form.TopLevel = false;

And you’re done, you just need to set the BorderStyle on your form to get rid of the ugly borders and you’ve successfully embedded a form into another form.

The complete example looks like this:

Form1 form = new Form1();
form.TopLevel = false;

Using Extension Methods as a Factory Method for an Adapter

Sometimes you have existing code you don't want to change. And sometimes you need to write libraries that consume these old legacy objects as input to function.
No need to say that it's usually a bad idea to couple your code to not properly tested and poorly designed legacy code.

So it's generally a good idea to abstract it away from new code and try to mask the old objects through adapters and interfaces from being too tightly coupled to your new code.

Either way, you're trying to put square blocks into round holes. And the adapter classes need to be initialized by your callers every time your class gets used.

    public class LegacyFoo
        public void SomeFoo()
    public interface IFoo
        void Foo();
    public class FooAdapter : IFoo
        private readonly LegacyFoo Foo_;
        public FooAdapter(LegacyFoo foo)
            Foo_ = foo; }
        public void Foo()
        { Foo_.SomeFoo(); }
    public class FooConsumer
        public void DoSomethingWithOldFoo(IFoo oldFoo)
        { oldFoo.Foo(); }

So instead of providing yet another Factory that constructs the adapter object, you could instead just put the factory method onto the legacy object by using an extension method:

    public static class FooExtensions
        public static IFoo GetFooAdapter(this LegacyFoo foo)
        { return new FooAdapter(foo); }

Now your callers can conveniently construct the Adapter object by calling:

LegacyFoo foo = new LegacyFoo();

Filed under net, programmierung, patterns

Anatomy of a pattern: Singleton

Singleton is one of the simplest patterns that does just one thing: Ensure that there is one object to rule them all, one object to bind... (Ok sorry got dragged away).

The idea is simple: Sometimes (especially when writing to disk with open file handles) you need to ensure that there is only ONE instance of a class going on at any time. And that's it. It's so simple, you could turn it into a 1-liner:

public static Singleton _Instance;

But things never are that simple ;). By using only a shared variable you may end up calling the constructor twice, resulting in 2 objects that may get used by two different clients.

To avoid this you'll need to get an exclusive lock of the Singleton to ensure it's really empty before you instance it.
And that's how it's usually done

private static Singleton _Instance;
private static Object __LockObject = new object();

public static Singleton GetInstance() {     if (_Instance == null)     {         lock(__LockObject)         {             if (_Instance == null)                 _Instance = new Singleton();         }     }     return _Instance; }

In the singleton implementation the static Singleton variable holds the reference to the Singleton, and whenever we try to get a reference to this instance we check if it's already set and return the value.

If not, it get's tricky when 2 threads are getting a cache-miss at the exact same time (_Instance == null). If you aren't synchronizing at this point you may end up with two different references of a singleton object being used (and causing problems with resources being consumed twice, causing ). So it's important to perform another check when you have exclusive reign over the shared object (by using a lock object here).

This ensures that no two threads will try to create a new instance to your singleton, while not slowing down your read-performance at all.

Sample code: Singleton.cs

My Photography business


dynamic css for .NET