#programmierung

Posts tagged programmierung

DRY Guard clause performance

Brad Wilson left me an inspiring comment on my post about his Guard class that I immediately tried out:

If you target 3.5, you could write a guard which used expressions, and then you could evaluate the expression in order to fill things out. Unfortunately, the syntax ends up a little wonky, but at least you’re not repeating yourself:

Guard.ArgumentNotNull(() => username);

You could also do the same thing with complex expressions:

Guard.Precondition(() => username.Length > 10);

and when you throw the exception, it can even contain the actual condition code, extracted from the expression.

I went off to implement this using an Expression and ended up with the following ArgumentNotNull method:

public static void ArgumentNotNull(Expression<Func<object>> action)
{
    var result = action.Compile()();
    if (result == null)
    {
        //TODO: Extract memberinfo name from expression
        throw new ArgumentException();
    }
}

One thing to keep in mind is that guard clauses usually end up being in production code, and not in test code. So performance isn’t neglect able. Since action.Compile() clearly indicates that some compiling overhead happens to retrieve the value, I thought it might be interesting to benchmark it. Just in case it might still be neglect able.

So, I wrote the following tester:

using System;
using System.Diagnostics;
using System.Linq;

public class Program {     private static int passes = 10000;

    private static void Main(string[] args)     {         var runs = 5;         Console.WriteLine("{0} ms to run normal", AverageExecutionTime(RunSimple, runs));         Console.WriteLine("{0} ms to run with expression", AverageExecutionTime(RunExpressions, runs));         Console.ReadLine();     }

    private static long AverageExecutionTime(Action delegateToWatch, int runs)     {         var lapTimes = new long[runs];         for (var i = 0; i < runs; i++)         {             lapTimes[i] = GetExecutiontime(delegateToWatch);         }         return lapTimes.Sum(p => p)/runs;     }

    private static long GetExecutiontime(Action delegateToWatch)     {         var stopwatch = new Stopwatch();         stopwatch.Start();         delegateToWatch();         stopwatch.Stop();         return stopwatch.ElapsedMilliseconds;     }

    private static void RunSimple()     {         for (int i = 0; i < passes; i++)         {             string user = "test";             Guard.ArgumentNotNull("user", user);             GC.Collect();         }     }

    private static void RunExpressions()     {         for (int i = 0; i < passes; i++)         {             string user = "test";             Guard.ArgumentNotNull(() => user);             GC.Collect();         }     } }

As you can see, I rerun the test 4 times doing the NotNull test only 10000 times (always running the non-exceptional path), always forcing garbage collection between passes.

The results were stunning:

image

I ran the test on my 2x3.16 Ghz Intel with 8gb Ram running Windows Vista x64 with no debugger attached and it turned out the expression tree compilation took almost 1 ms per pass. (Without garbage collection normal runs took 0 ms)

Now one could argue, no sane person would place those guards inside some tight loop. But once you run into recursive method calls you may end up creating a performance bottleneck.

Now, since I’m a lazy guy, I ended up writing a Resharper Live template that saves me the repetitive typing:

Guard.ArgumentNotNull("$parametername$", $parametername$);
$END$

Read more →

Component Lifestyles and Fluent Interface for Pandora

I just finished refactoring Pandora to have a much cleaner configuration and also to enable lifestyles for certain components.

Until now, Pandora was not able to save one service after it’s initial activation. Every call to container.Resolve() would instantiate a new service with new dependencies etc. It may be of interest to some of you that this is the exact opposite of the default lifestyle Windsor sets for it’s components. So I obviously wanted to change that.

[Fact]
public void ActivationHappensOnlyOnceForSingletonComponents()
{
    var store = new ComponentStore();
    var registration = store.Add<IService, ClassWithNoDependencies>("test");
    registration.Lifestyle = ComponentLifestyles.Singleton;

    var container = new PandoraContainer(store);

    var service = container.Resolve<IService>("test");     var service2 = container.Resolve<IService>("test");

    Assert.Same(service, service2); }

All “logic” concerning a lifestyle is completely enclosed in the Lifestyle classes so creating a new lifestyle for Pandora should be rather simple in the future.

But the real big news (and the real big change) is the changed configuration.
At first I tried to bake a fluent interface into the Registration (the class Pandora uses to represent one registered service) to allow nice parameter syntax.

The idea was good, but it led to some problems with the interface and also made it much harder to consume those registrations inside the container.

I then decided to rip everything out and revert the registration to a dumb value type that only holds information that can be easily serialized/deserialized if needed.
So that the fluent interface would generate a value type, instead of trying to be one with all it’s faults. Doing so opened up a whole lot of new possibilities in terms of API for me, and so I ended up with a quite pleasant interface like this:

store.Register(p => p.Service<IService>("db.service")
                        .Implementor<ClassWithNoDependencies>()
                        .Parameters("hello").Set("world")
                        .Lifestyle.Transient()
                        .Parameters("foo").Set("bar"));

As before, this looks intentionally familiar to Windsor users, since I believe Windsor’s interface is really good and makes a lot of sense when reading.
What I improved upon (at least, I believe so) was to get away from the static Component class Windsor uses to bootstrap the Fluent registration, but to use a closure that provides Intellisense right from the beginning.

Meaning, in Windsor there is no Intellisense when you Write: container.Register() .. From the signature you can only see that you need an array of IRegistration while nobody tells you that you need to use that static class that’s buried down in Castle.MicroKernel.Registration, while writing p. instantly brings up all registration options in Pandora.

Next in line is improving the fluent interface even further to allow for auto-configuration (eg. take Assembly A and register all Types in there).

Another challenge I want to tackle with Pandora is externalizing the configuration. Fluent interfaces are awesome for developers (since they allow easy refactoring), but the real power of a DI container also comes from the ability to change the configuration without recompiling the app. Usually all containers solve this through XML, so I’d like to try a new approach here and am currently thinking about making Pandora read the configuration from a IronPython script. That would allow me to consume the Fluent Interface without recompiling the application and paying the XML bracket tax while retaining the flexibility of just opening up a text file to change my configuration.

As usually, you can find the source to Pandora at the project website on Bitbucket.

Read more →

Common Service Locator adapter for Pandora

In case you haven’t heard. Some time ago Microsoft sat with most authors of leading IoC containers and defined a common interface for Dependency Injection / Service Location. You can get all the relevant information about the Common Service Locator through reading Glenn Block, Ayende Rahien or Chris Travares and you can download it from it’s Codeplex site. There is a comprehensive API reference in their wiki too.

Ayende sums the purpose of the CSL up pretty well:

The idea is based off a post that Jeremy Miller had about a month ago, having a common, shared interface across several IoC implementation. That would allow library authors to make use of the benefits of a container without taking a dependency on a particular implementation.

The alternative for that is to each library to create its own abstraction layer. A good example of that is NServiceBus' IBuilder interface, or ASP.NET MVC's IControllerFactory. That is just annoying, especially if you are integrating more than a single such framework.

In Pandora I aimed for CSL compliance from the beginning, and the CSLAdapter class has been there for quite some time now. But since Pandora only recently got the named lookups feature I never finished it.

Until now. Today I finally implemented the CommonServiceLocatorAdapter that (for me) somehow “verifies” that Pandora supports most mandatory lookup features needed from a DI container.

On the implementation side: I first tried to implement IServiceLocator directly, until I discovered the abstract ServiceLocatorImplBase class that wraps all of the overloads and generic/nongeneric stuff, saving you a bunch of boilerplate code.

Coming up next in Pandora will be component lifestyles, forwards and then maybe DLR configuration.

Read more →

Named dependency lookup &ndash; Pandora

One rather essential feature for a DI container is to be able to lookup components by some key. For example retrieving a specific IController class based on the controller name specified by the request.

So the usual use case for the above looks like this:

var store = new ComponentStore();
store.Add<IRepository, MemoryRepository>("memory.repository");
store.Add<IRepository, SqlRepository>("db.repository");
var container = new PandoraContainer(store);

var service = container.Resolve<IRepository>("db.repository");

Now, there is another thing too: What if I want one controller to use one special repository out of the registered ones:

var store = new ComponentStore();
store.Add<IRepository, SqlRepository>("db.repository");
store.Add<IRepository, MemoryRepository>("memory.repository");
store.Add<Controller, Controller>()
    .Parameters("repository").Eq("memory.repository");
var container = new PandoraContainer(store);

var controller = container.Resolve<Controller>();

Well, yes Pandora can do those kinds of things too.

If you know Windsor’s Fluent interface .Parameters().Eq() may sound familiar to you. That’s intentionally. I like the Windsor Fluent syntax.

What I really underestimated was how to do the fluent interface. It’s not terribly hard, but it’s takes some tinkering ;).

You can find the source to Pandora at the project website on Bitbucket.

Read more →

Essential tools for .NET Developers

I always thought that I am up and running the moment Visual Studio is installed on a machine.
Unfortunately, life isn’t that easy any more and I thought it might be interesting to share what I consider essential from my toolbox.

IDEs

  1. Visual Studio 2008
  2. Resharper 4.5
  3. Notepad++

Although some people say they can work with other IDEs in .NET, I consider Visual Studio a absolute necessity. Not so much for the Studio itself but as a shell for Resharper, the very best tool I have yet come across. It’s so damn convenient and increases productivity by such a margin that I simply can’t use Visual Studio without it any more. Although Resharper isn’t free, I strongly suggest you try it out for 30 days. I feel it’s a good investment.

And Notepad++ is one of many great simple editors that make editing and reviewing of files easy.

Source Control

If you plan on working with open source tools, be prepared to bring their tools to the party. Nothing is worse than needing some source and not being able to access the SCM.
I usually install the following:

  1. TortoiseSVN - Subversion right from the Explorer right click menu. Very good and very mature SVN client.
  2. SlikSVN - Unfortunately TortosieSVN doesn’t install SVN binaries, so if you want to be able to run SVN from the command line you better get the conveniently packed SlikSVN subversion binaries.
  3. TortoiseHG - Same idea as with TortoiseSVN but for Mercurial, but it installs the hg binaries so you can use hg from the command line.
  4. msysGit - A GUI for git together with a custom git command line that emulates a *nix shell for git operations. Not so convenient as HG, but Fluent Nhibernate and most tools by Jon Skeet use git.
Build tools

Getting the source is usually not enough, sometimes you need to be able to build it too.
While most projects can be built by simply starting up Visual Studio and building, others require you to run a build script like NAnt.

  1. NAnt - NAnt is a free .NET build tool. In theory it is kind of like make without make's wrinkles. In practice it's a lot like Ant.

Download the latest NAnt release and unpack the zip to some convenient folder. Then create a file called nant.bat in your C:\windows folder with the following content:

@echo off
"C:\Program Files\NAnt\bin\NAnt.exe" %*

(Obviously you should change the path to your NAnt executable).
Now whenever you encounter a project with a *.build file you can simply start a command line window and type nant to start building the source (that’s how you build the the Castle Project and NHibernate).

  1. Rake - I don’t use rake, but I sure know Fluent NHibernate does. Rake is the build tool used for Ruby projects, but it’s gaining popularity. On windows installing it was rather simple, just get the Ruby One-Click Installer from their downloads page and install it with gems (gems is used for installing extensions and libaries).

If none of the above apply, usually every project has a howtobuild.txt that instructs you on how to run the build.

Database

Hugely depends on what tools you use. But it never hurts to have the following:

  1. Sql Server 2008 Management Studio Express - It’s free, and allows you to run queries and create databases. Nothing fancy as reporting or real server administration, but what developer really wants to do a DBAs job?
  2. NHProf - If you are using NHibernate for your data access needs (and I believe you should), you will find this tool well worth it’s money. It’s by no means cheap, but it will watch all your database queries, analyze them and point out possible performance bottlenecks for you.

Others

  1. Sourcegear DiffMerge - A very good and free diff tool in case the ones in TortoiseSVN don’t cut it.
  2. .NET Reflector - Sometimes you don’t have access to the source code, or you don’t want to get the source just to look at one file.


    .NET Reflector allows you to look at all the types inside an assembly, and if it’s not obfuscated it allows you to decompile it into your language of choice and look at the code (you could decompile VB programs into C# for example).

  3. Please note that there are myriads of other tools lists out there, and if your are a web developer you’ll need some more tools for debugging HTML/JS. The above are the ones I consider essential to do .NET desktop/backend development when using open source libraries as Castle or NHibernate.

Read more →

Moving to Mercurial

I feel like I’m constantly falling behind on stuff I want to post about but don’t get around to. One of which is the version control system Mercurial I have been using now for almost 4 months and loving ever since.
Since Google just decided to enable Mercurial on Google Code I figured it’s a great time to write about it.

What is Mercurial?
I’ll quote the getting started article from Bitbucket:

Introduction

Mercurial is a distributed version control system, or DVCS for short. It is in the ranks of Git and Bazaar, leading a new paradigm of working with version control.

Philosophy

This new paradigm of distributed versioning allows for several things that centralized development does not. Specifically, it provides:

  1. Allows commits/logs even when working offline
  2. Drastic increase in speed for most operations
  3. Ability for anyone to have their own copy of a project, and continue work without explicit "commit access"
  4. No requirement to publish changes
  5. No need to set up a server for version controlling things (self-contained)

So, it’s like your  own private version control system. Nobody can mess with it, you own it.
Which is great, I mean: How often has a fellow coworker submitted something to your tree that made your code break? Or how often did you update before a commit just to see that the update breaks something (and your changes weren’t commited, so you’re at the mercy of merges)?

What also rocks is it’s simplicity. Mercurial needs no server, so even on my little pet projects I can leverage the power of a SCM system without the headache around setting up something in a central place.

What most people though fail to understand is that the centralized model does also mean that you need to share your private changes with the world at some time.
And while doing so on a shared filesystem is very easy (when sharing with a coworker for example), doing so over the wire is non-trivial as it would require you setting up a server somewhere.

And that’s how I learned to love Bitbucket:

Bitbucket's aim is to compensate for this while maintaining the flexibility and benefits of DVCS. It does this firstly by providing a centralized location for a repository which provides a sharing-point for one or more developers to grow their code base. Secondly, it provides a set of tools that ease development and sharing of a code with the rest of the world.

Bitbucket is free and gives you 150mb of disk space, an issue tracker and a wiki for each of your projects. While the limitation is that only one project/repository per account can be private (not open source), there is no limit on how many public repositories you can create.

I suggest reading the guides on Bitbucket (or the book) on how HG differs from SVN and how the usual workflow looks like.
Also I suggest installing TortoiseHg, this will install all the hg command-line as well as a nice shell integrated GUI like we are all used to from TortoiseSVN.

Read more →

Fluent NHibernate gotchas when testing with an in memory database.

What I love most about programmatic configuration is that it’s close to the test.
While we were carrying dozens of XML files around for testing before, now with DSL based configuration everywhere the configuration is usually pretty near to the test fixture, instead of residing in some arbitrary XML that only insiders can associate with the test.

The standard sample for using SqlLite and Fluent NHibernate usually looks like this:

return
    Fluently
        .Configure()
        .Database(SQLiteConfiguration.Standard.UsingFile("mydb.db3").ShowSql())
        .Mappings(m => m.FluentMappings.AddFromAssemblyOf<SessionFactory>())
        .ExposeConfiguration(SaveSchema)
        .BuildSessionFactory();

Where SaveSchema is a method that does a database rebuild.

Now, Fluent Nhibernate has in-memory databases built into the API. Just remove the UsingFile directive and you replace it with:

.Database(SQLiteConfiguration.Standard.InMemory().ShowSql())

Charming isn’t it? Now the only problem is that you won’t be able to do anything with that DB since there is no schema present.
The in-memory database exists per session, so once you close the ISession the db is gone. Since the schema export from most samples operates in it’s own ISession the subsequent queries will still hit a blank database, and you’ll get an error stating there is no such table.

So my SessionFactory implementation had to change, since I needed to keep the configuration around for doing the schema export:

public class SessionFactory
{
    public static ISessionFactory CreateSessionFactory()
    {
        return
            Fluently
                .Configure()
                .Database(SQLiteConfiguration.Standard.InMemory().ShowSql())
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf<SessionFactory>())
                .ExposeConfiguration((c) =>  SavedConfig = c)
                .BuildSessionFactory();
    }

    private static Configuration SavedConfig;

    public static void BuildSchema(ISession session)     {         var export = new SchemaExport(SavedConfig);         export.Execute(true, true, false, false, session.Connection, null);     } }

And my tests then use a another factory method to construct the ISession object:

public static ISession CreateSession()
{
    var factory = SessionFactory.CreateSessionFactory();
    var session = factory.OpenSession();
    SessionFactory.BuildSchema(session);

    return session; }

Hope this helps, quite an annoying problem and imo a far from perfect solution. Someone on the FNH mailing list suggested looking at the OneToManyIntegrationTester class but I couldn’t really extract any terribly useful information from there.

Read more →

Dependency chain lookups with Pandora

Almost a week ago I introduced Pandora my own take on Inversion of Control. So I’m back to report some news.

New features:

  1. Multiple registrations of one service type
  2. Graph splitting
  3. Dependency chains of own service

Before only one service registration was possible, preventing you from doing all sorts of cool things.
For example it prevented you from registering a class like this one:

public class ClassWithDependencyOnItsOwnService : IService
{
    public ClassWithDependencyOnItsOwnService(IService service)
    {
    }
}

This class would typically be some sort of decorator that covers the IService interface with a thin layer of concerns (like logging/errorhandling/caching). Now, you can just register more than one IService and it will walk the graph for you:

[Fact]
public void CanResolveDependencyChainOfSameService()
{
    var store = new ComponentStore();
    store.Add<IService, ClassWithDependencyOnItsOwnService>();
    store.Add<IService, ClassWithNoDependencies>();

    var container = new PandoraContainer(store);

    var service = container.Resolve<IService>();

    Assert.IsType(typeof (ClassWithDependencyOnItsOwnService), service);     var ownService = (ClassWithDependencyOnItsOwnService)service;     Assert.IsType(typeof (ClassWithNoDependencies), ownService.SubService); }

Also now there is the possibility to split the graph at some point like this:

image

You don’t need three registrations for this, only one since every subresolving of IService will happen on it’s own. Something that isn’t really practical actually since we still lack the ability to influence the resolve process. Both IServices will be populated by the same registered type, it just won’t be the parent IService again.

I also spent almost the whole day refactoring the resolver code since I felt that it became quickly unreadable.

Next:

I still feel like the resolver needs some more refactoring, and I also want to improve the error messages. After that, I’d like to return my focus back to much needed features like lookup strategies and after that auto-configuration.

You can check out the code on the project site on bitbucket.

Read more →

Rant: Interface violation inside ASP.NET MVC

I’m amazed about how bad the ASP.NET MVC code really is. Why? Because something as trivial as redirecting the output of a View to another TextWriter shouldn’t take more than 5 lines of code and certainly not be impossible!

But from the start, here’s the scenario. ViewResult should not be written to HttpContext.Response but to some arbitrary TextWriter.
So, for me the most obvious choice was to alter the ViewResult to write to somewhere else. So redirecting should be as easy as:

public ActionResult Index()
{
    ViewData["Message"] = "Welcome to ASP.NET MVC!";
    TextWriter writer = Console.Out;
    return new RoutedViewResult(writer);
}

Now, nothing left to do but override the ExecuteResult method and call View.Render() with another writer:

image

So, what do you see here? A method that takes a ViewContext (containing ViewData, TempData, HttpContext etc..) and a TextWriter. 
Any normal person would now jump to the conclusion, that if I build a ViewContext and pass in my TextWriter, I’m set and all is well.

So, I spent almost 30 minutes trying to find a way on how to construct the ViewContext (without copy/pasting the code from within the framework, btw. forget it – they married ViewContext creation with View rendering, so no way to separate those) just to find out that my output was still written to HttpContext.Response.

That’s when I looked at the WebFormView class that implements the IView interface, but does so badly.
Let me explain:

public interface IView
{
    // Methods
    void Render(ViewContext viewContext, TextWriter writer);
}

The interface clearly states that there should be a TextWriter passed to the View.
Imagine my face when I saw the implementation in the WebFormView class:

public virtual void Render(ViewContext viewContext, TextWriter writer)
{
    if (viewContext == null)
    {
        throw new ArgumentNullException("viewContext");
    }
    object obj2 = this.BuildManager.CreateInstanceFromVirtualPath(this.ViewPath, typeof(object));
    if (obj2 == null)
    {
        throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture, MvcResources.WebFormViewEngine_ViewCouldNotBeCreated, new object[] { this.ViewPath }));
    }
    ViewPage page = obj2 as ViewPage;
    if (page != null)
    {
        this.RenderViewPage(viewContext, page);
    }
    else
    {
        ViewUserControl control = obj2 as ViewUserControl;
        if (control == null)
        {
            throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture, MvcResources.WebFormViewEngine_WrongViewBase, new object[] { this.ViewPath }));
        }
        this.RenderViewUserControl(viewContext, control);
    }
}

Do you see the problem? Writer is NEVER used. They violate their own interface in their own code. What a mess.

Something similar has been done with the EmailTemplateService in MVCContrib, but it’s very email specific and works with using a MemoryStream as filter to the HttpContext.Response (not happy with that either, but apparently the only way).

Read more →

Rails with obstacles

Important: Most of the information in this post about outdated MonoRail docs is now also outdated since I submitted a patch to the castle documentation project to fix the issues raised in this post.

Yesterday I decided to build a website with Castle.Monorail to learn another take on the MVC (besides the Microsoft one). Since the last official release of Monorail is quite outdated I just compiled the trunk version to start from the current release.

Doing so is very simple, just do a:

svn checkout http://svn.castleproject.org:8080/svn/castle/trunk

Some time ago Roelof Blom made an effort to make the build more user-friendly, so you don’t need any tools installed besides .NET to compile all castle assemblies. Just run ClickToBuild.cmd and it will invoke nant (also in SVN) etc, run a complete compile of all projects and place the output in

build\net-3.5\release

(Did I mention this is awesome? Building the trunk before was a nightmare!)

I then followed the Monorail getting-started samples from the website and was quite frustrated with how outdated that documentation really is.

Please read through the original documentation as it usually still applies, I’ll just list the things that I had to adapt for the trunk version to work:

Creating the Project Sceleton:

Registering Assemblies:

The list of assemblies to register is pretty outdated, I failed because I didn’t reference the DictionaryAdapter.
Instead you need to reference:

  1. Castle.Components.Binder.dll
  2. Castle.Components.Common.EmailSender.dll
  3. Castle.Components.DictionaryAdapter.dll
  4. Castle.Components.Validator.dll
  5. Castle.Core.dll
  6. Castle.MonoRail.Framework.dll
  7. Castle.MonoRail.Framework.Views.NVelocity.dll
  8. NVelocity.dll

HttpModule registration

Register the HttpModule is no longer needed. If you try to add

<httpModules>
  <add
      name="monorail"
      type="Castle.MonoRail.Framework.EngineContextModule, Castle.MonoRail.Framework" />
</httpModules>

to your config things will break. The EngineContextModule has disappeared from the source and is no longer needed.

Bringing ActiveRecord to the party

The configuration has changed since RC3 and you no longer need to prefix all keys with a hibernate. Things will break if you do. You’ll get a exception stating:

Could not find the dialect in the configuration

Kind of an misleading exception, once you remove the leading nhibernate. from your config values you’ll be set.

That’s all as for now, I decided to not go with a “real” database like MsSql during development but to go against a SqlLite database. To do so I changed the AR configuration to this:

<activerecord isWeb="true">
  <config>
    <add
        key="connection.driver_class"
        value="NHibernate.Driver.SQLite20Driver" />
    <add
        key="dialect"
        value="NHibernate.Dialect.SQLiteDialect" />
    <add
        key="connection.provider"
        value="NHibernate.Connection.DriverConnectionProvider" />
    <add
        key="connection.connection_string"
        value="Data Source=nhibernate.db3;Version=3" />
  </config>
</activerecord>

You then need to reference the System.Data.SQLite.dll and you’re set (grab the release from SourceForge).

Update: In case you try the SqlLite database I found SqlLite Administrator very useful for looking at the database.

Read more →