Khebbies blog

I blog about .net development, Ruby on Rails and some Christian stuff

Migrated Blog

I just migrated my blog to octopress hosted on heroku Heroku is a free hosting (for small scale sites) for Ruby and octopress is a blogengine based on Jekyll, which is a static page blog engine.

I migrated from blogengine.net using xslt and perl, which is a perfect match for this. There are some posts that are not migrated perfectly, but I’m not bothered enough to fix it yet…

[the perl code]
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
use XML::LibXSLT;
use XML::LibXML;
use XML::XPath;
use XML::XPath::XMLParser;

sub getOutputFilename
{
  my $filename =  $_[0];
  my $xp = XML::XPath->new(filename => $filename );
  my $date = $xp->find('post/pubDate')->string_value();

  my $title = $xp->find('post/title')->string_value();
  $title =~ s/ /-/g;
  my $filename =  substr($date , 0, 10) . "-" . $title . ".markdown";
}



opendir my $dir, "blog/posts" or die "Cannot open directory: $!";
my @files = readdir $dir;
closedir $dir;

foreach $file (@files) {

  if( $file != "." or $file != "."){

    my $filename =
    'blog/posts/' . $file ;

    my $outputFilename = getOutputFilename($filename);

    my $parser = XML::LibXML->new();
    my $xslt = XML::LibXSLT->new();

    my $source =
    $parser->parse_file($filename );
    my $style_doc = $parser->parse_file('convert.xslt');

    my $stylesheet = $xslt->parse_stylesheet($style_doc);

    my $results = $stylesheet->transform($source);

    my  $resultsREplace = $stylesheet->output_string($results);

    $resultsREplace =~ s/>/>/g;
    $resultsREplace =~ s/&lt;/</g;
    $resultsREplace =~ s/&amp;aelig;/æ/g;
    $resultsREplace =~ s/&amp;oslash;/ø/g;
    $resultsREplace =~ s/&amp;aring;/å/g;
    $resultsREplace =~ s/&amp;quot;/"/g;
    $resultsREplace =~ s/&amp;nbsp;/ /g;
    $resultsREplace =~ s/&amp;ldquo;/"/g;


    $outputFilename = "converted/" . $outputFilename;

    print $outputFilename;
    open(MYOUTFILE, ">$outputFilename");
    print MYOUTFILE $resultsREplace;

    close(MYOUTFILE);
  }
}

It’s been ages since I last wrote perl but it’s pretty easy for doing quick stuff like migrating a blog. The XSLT is not perfect, actually It generated some whitespace stuff that I fixed by hand…

[the xslt code]
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
use XML::LibXSLT;
use XML::LibXML;
use XML::XPath;
use XML::XPath::XMLParser;

sub getOutputFilename
{
  my $filename =  $_[0];
  my $xp = XML::XPath->new(filename => $filename );
  my $date = $xp->find('post/pubDate')->string_value();

  my $title = $xp->find('post/title')->string_value();
  $title =~ s/ /-/g;
  my $filename =  substr($date , 0, 10) . "-" . $title . ".markdown";
}



opendir my $dir, "blog/posts" or die "Cannot open directory: $!";
my @files = readdir $dir;
closedir $dir;

foreach $file (@files) {

  if( $file != "." or $file != "."){

    my $filename =
    'blog/posts/' . $file ;

    my $outputFilename = getOutputFilename($filename);

    my $parser = XML::LibXML->new();
    my $xslt = XML::LibXSLT->new();

    my $source =
    $parser->parse_file($filename );
    my $style_doc = $parser->parse_file('convert.xslt');

    my $stylesheet = $xslt->parse_stylesheet($style_doc);

    my $results = $stylesheet->transform($source);

    my  $resultsREplace = $stylesheet->output_string($results);

    $resultsREplace =~ s/&gt;/>/g;
    $resultsREplace =~ s/&lt;/</g;
    $resultsREplace =~ s/&amp;aelig;/æ/g;
    $resultsREplace =~ s/&amp;oslash;/ø/g;
    $resultsREplace =~ s/&amp;aring;/å/g;
    $resultsREplace =~ s/&amp;quot;/"/g;
    $resultsREplace =~ s/&amp;nbsp;/ /g;
    $resultsREplace =~ s/&amp;ldquo;/"/g;


    $outputFilename = "converted/" . $outputFilename;

    print $outputFilename;
    open(MYOUTFILE, ">$outputFilename");
    print MYOUTFILE $resultsREplace;

    close(MYOUTFILE);
  }
}

Three Aspects of Software Projects

The way I see it there are three aspects of a software projects that are worth noting, (or at least that I will focus on in this blog post):

1. The technical aspect

2. The process aspect

3. The meta techincal aspect

The technical aspect are all the aspects that every developer (hopefully) knows, like the programming language, the framework, the application servers etc.

The process aspect is the stuff like scrum, kanban ,lean etc.

The meta technical stuff is what I’ll zoom in on now.

First of all I’m not sure this it the best term, and probably someone has coined a better one…

However the way I see it these three aspects has to be in place for a project to suceed. The first two are usually in place, the first handled by the developer and the second by the project manager or scrum master or someone in similar roles.

However I see the last aspect often being neglected.

The meta technical aspect is about the framework of doing the technical stuff. so I would say it is for instance:

-TDD (BDD)

- SOLID

- IOC

So I would describe it as all the technical stuff that many hardcore developers do not care that much about, but that makes the quality of the code higher, and makes the code more maintainable.

The problem is that many people going into software development care about technical stuff, and care about breaking that small technical problem. But they don’t find the meta technical stuff as interesting.

Khebbie Build Notifier

I created a tool that I use at work for watching my solution, and running the unit tests. It is very much inspired by a tool that I saw for ruby on rails, and can&#39;t remember the name of.

The tool is created in boo, and this is my first encounter with boo so probably the code is very C#&#39;ish.

It definetly isn&#39;t ”Clean code”.

With all of this set aside, let me introduce khebbie build notifier, it&#39;s not packaged nicely or anything, so you have to install sharpdevelop in order to use it.

You also need to install Growl for windows, since this is whats used for notification.

Then you need to have your tests organized so that the tests reside in assemblies called xyx.tests.dll (where xyz.dll is the dll you are testing).

Then install SharpDevelop

Change the source code of khebbie build notifier so that it points to your installation of NUnit (yes it only runs NUnit tests)

Change the source of code khebbie build notifier so that i points to where your source reside

This should all be moved to configuration… someday

Start khebbie build notifier and whenever you compile a dll or its corresponding test dll, the tests will run.

I have changed Growl for windows so that failures are displayed in red and success are displayed in green.

Growl can not break a long assembly name, but that too will be changed… someday

Just Did the String Calculator Kata

I just did the string calculator kata, here is the output
&#160;
[TestFixture]
    public class CalculatorTests
    {
        readonly Calculator _calc = new Calculator();
        [Test]
        public void Add_WhenGiven1_ShouldReturn1()
        {
            int result = _calc.Add("1");
            Assert.That(result, Is.EqualTo(1));
        }

        [Test]
        public void Add_WhenGiven15_ShouldReturn15()
        {
            int result = _calc.Add("15");
            Assert.That(result, Is.EqualTo(15));
        }

        [Test]
        public void Add_WhenGiven1comma5_ShouldReturn6()
        {
            int result = _calc.Add("1,5");
            Assert.That(result, Is.EqualTo(6));
        }

        [Test]
        public void Add_WhenGiven115comma23_ShouldReturn138()
        {
            int result = _calc.Add("115,23");
            Assert.That(result, Is.EqualTo(138));
        }

        [Test]
        public void Add_WhenGivenAlphaCharacter_ShouldThrowArgumentException()
        {
            Assert.Throws&lt;ArgumentException&gt;(() =&gt; _calc.Add("jens"));
        }

        [Test]
        public void Add_WhenGivenAlphaNumericCharacterWithNumericAtTheEnd_ShouldThrowArgumentException()
        {
            Assert.Throws&lt;ArgumentException&gt;(() =&gt; _calc.Add("jens1"));
        }

        [Test]
        public void Add_WhenGivenAlphaNumericCharacterWithNumericAtTheBeginning_ShouldThrowArgumentException()
        {
            Assert.Throws&lt;ArgumentException&gt;(() =&gt; _calc.Add("1jens"));
        }
    }

&#160;

&#160;

public class Calculator
    {
        public int Add(string s)
        {
            if(!Regex.IsMatch(s, @"^\d+(,\d+)?$"))
                throw new ArgumentException("s");

            var numbers = s.Split(',');
            int returnValue = 0;
            foreach (var number in numbers)
            {
                returnValue += int.Parse(number);
            }
            return returnValue;
        }
    }

My (Non-thread Safe) Wrapper for Castle Windsor IoC

I have a small wrapper API that I use around Castle Windsor, and thought I would share it. You could probably use it to wrap an IoC of your own choice.

First please note that this library is not checked for thread safety, secondly there is nothing original in what I do, it’s just my take on what’s already been done.

Here is how I configure the IoC container:

private static void SetupIOC() { Bind&lt;HTTPClientWithBasicAuth&gt;.To&lt;IHTTPClient&gt;(); Bind&lt;TwitterClient&gt;.ToAbstraction&lt;ITwitterClient&gt;(); }

Here is how I resolve an object:

ITwitterClient twitterClient = ResolveType.Of&lt;ITwitterClient&gt;();

Here is how you bind an instance to an interface or class:

Bind&lt;UsernamePassword&gt;.ToInstance(new UsernamePassword(args[0], args[1]));

&#160;

Here is the class I use to resolve an object. This code is tightly coupled to the Windsor container, and for my pet project it is fine, but you might want to couple loosely to the container.

public static class ResolveType
{
private static readonly IWindsorContainer _container;
static ResolveType()
{
_container = new WindsorContainer();
}
public static T Of&lt;T&gt;() where T : class
{
if (typeof (T).Equals(typeof (IWindsorContainer)))
{
return new WindsorContainer() as T;
}
return _container.Resolve&lt;T&gt;();
}
internal static void AddComponent(string key, Type serviceType, Type classType)
{
_container.AddComponent(key, serviceType, classType);
}
internal static void AddComponentInstance&lt;T&gt;(object instance)
{
_container.Kernel.AddComponentInstance&lt;T&gt;(instance);
}
}

The two AddInstance methods are internal since the Bind class lives in the same assembly.

Here is how i configure the IoC container:

&#160;

public class Bind&lt;T&gt;
{
public static void ToAbstraction&lt;S&gt;()
{
ResolveType.AddComponent(typeof (S).ToString(), typeof (S),
typeof (T));
}
public static void ToInstance(object instance)
{
ResolveType.AddComponentInstance&lt;T&gt;(instance);
}
}
You can find a small solution using this here 

Edit:

Renamed Bind.To to Bind.ToAbstraction, but not in the downloadable solution.

[Dk] Om Aspergers

Jeg har en søn med aspergers syndrom og en af de ting man tit møder er det at folk ikke opdager at han har et handicap.

Udtalelser som “Han fejler da ikke noget” er ret normale at støde ind i, og de sårer, da det jo samtidig siger at de problemer og udfordringer man som forældre til et barn med aspergers har, ikke er reelle - de bliver ikke anerkendt.

Så det folk tit vel-ment udtaler ligesom for at trøste kan i virkeligheden virke sårende.

Aspergers er det man kalder et usynligt handicap, hvor man ikke ved bare lige at møde folk med handicappet kan gennemskue at man står overfor en handicappet person.

Jeg har klippet et citat fra en pdf om hvad aspergers egentlig er:

Anita Hummelshøj:
“Det, værste jeg ved, er folk, som siger: “du fejler jo ikke noget. Du ser da helt normal ud.
Du får jo nogle gode karakterer. Der er nok slet ikke noget galt med dig. Du er blot
påvirket af de oplevelser, du er blevet udsat for gennem din barn- og ungdom. Og det kan
man da godt blive &lsquo;lidt anderledes&rsquo; af. Hvis du ellers kan slippe ud af den bås, som de
såkaldte eksperter har placeret dig i… Det kan du sagtens lære dig. Du skal bare øve dig!&rdquo;
Det er meget hårdt at tvinges til at argumentere for, at jeg er Asperger! Man forsøger da
ikke tilsvarende at lokke sukkersyge børn med slik: “Du vokser nok fra det&rdquo;, at skælde ud
på ordblinde: “du skal blot have opmærksomhed&rdquo;? at fortælle ordblinde, at det blot er
indbildning: “du skal bare tage dig sammen&rdquo;? at bilde døve ind, at “det hjælper med b-
vitaminer&rdquo;? at sige til en epileptiker: “Det er dine forældres skyld&rdquo;?

Taget fra http://asperger-holstebro.dk/?download=Froejk_hvad-er-aspergers.pdf

[Dk]uncle Bob Om Software Projekter (Min Formulering)

Uncle Bob om software projekter:
“Tit haster vi igennem for at blive færdige til tiden, og sjusker for at gøre det hurtigere.

Men når vi sjusker os igennem opdager vi tit, at det sjusk vi lavede for at blive hurtigt færdig,

er det der forsinker os og gør at vi bliver forsinkede.”

[Dk]sådan Forstår Jeg Udi Dahan’s Intentions & Interfaces Making Patterns Concrete Fra Teched

Hvis jeg&#160; skal hente data fra en database i forbindelse med en ordre, så kan jeg i nogle tilfælde have brug for at hente ordren med ordrelinjer, og i nogle tilfælde kan jeg have brug for kun at hente ordren selv.

I stedet for at hardcode dette i forretningslaget eller i repository, kan jeg lægge det ud for sig selv.

Bemærk venligst at dette er mit forsøg på at forstå en metode, det er ikke “production ready”

Det gør jeg ved først at definerer et interface:

public interface IFetchingStrategy&lt;T&gt; where T : IEntity
{

</span><span style="background: #f9f4f2; color: blue">void </span><span style="background: #f9f4f2">Fetch();

}

Dette interface tager så en IEntity, som er rollen.

Rollen kan være IOrder (hent kun ordren) eller IOrderCalculator(Hent også ordrelinjer) eller IOrderInfo(Hent ordren i readonly tilstand)

public interface IOrder : IEntity
{
}

public interface IOrderCalculator : IEntity
{
    Money CalculateCost();
}

public interface IOrderInfo : IEntity
{
}

Nede i mit repository spørger jeg min DI container om en FetchingStrategy

class Repository&lt;T&gt; where T : IEntity
{
  public static T FindOne(int id)
  {
    IFetchingStrategy&lt;T&gt; fetchingStrategy =  ResolveType.Of&lt;IFetchingStrategy&lt;T&gt;&gt;();
    fetchingStrategy.Fetch();
    return default(T);
  }
}

Alt efter typen af T, får jeg en forskellig fetching strategy:

public class OrderService
{
    public virtual Money CalculateCostForOrder(int orderId)
    {
        IOrderCalculator order = Repository&lt;IOrderCalculator&gt;.FindOne(orderId);
        return new Money();
    }

    public virtual void DisplayOrder(int orderId)
    {
        IOrderInfo order = Repository&lt;IOrderInfo&gt;.FindOne(orderId);
    }

    public void LoadOrder(int orderId)
    {
        IOrder order = Repository&lt;IOrder&gt;.FindOne(orderId);
    }
}

Disse fetching strategier har jeg lagt ud for sig, så de kan ændres flydende (Open / Closed principle)

public class OrderCalculatorFetchingStrategy : IFetchingStrategy&lt;IOrderCalculator&gt;
{
    public void Fetch()
    {
        Console.WriteLine("Fetch the whole bunch - do eager loading");
    }

}
public class OrderFetchingStrategy : IFetchingStrategy&lt;IOrder&gt;
{
    public void Fetch()
    {
        Console.WriteLine("Fetch only the order");
    }
}

public class OrderInfoFetchingStrategy : IFetchingStrategy&lt;IOrderInfo&gt;
{
    public void Fetch()
    {
        Console.WriteLine("Fetch in read-only mode");
    }
}

Her konfigurerer jeg min DI Container:

IWindsorContainer container = new WindsorContainer();
container.AddComponent("OrderCalculatorFetchingStrategy", 
                typeof(IFetchingStrategy&lt;IOrderCalculator&gt;),
                typeof(OrderCalculatorFetchingStrategy));
container.AddComponent("OrderFetchingStrategy", 
                typeof(IFetchingStrategy&lt;IOrder&gt;),
                typeof(OrderFetchingStrategy));
container.AddComponent("OrderInfoFetchingStrategy", 
                typeof(IFetchingStrategy&lt;IOrderInfo&gt;),
                typeof(OrderInfoFetchingStrategy));
ResolveType.Initialize(container); 

Kort sagt kan man vel sige at det er en implementation af Strategypattern, hvor man bruger sin DI container til at hente strategien på runtime.

Jeg vil gerne henvise til Udi Dahans blogposts om emnet:

Fetching Stratey Design

Better Domain Driven Design implementation

Ayende har også en god blogpost om emnet:

Adaptive Domain models with Rhino Commons

Currying in C#

I recently listend to Deep Fried Bytes on functional programming in C#.

In the show notes, there is a code sample of doing curring in C#, I worked a bit further on it.

This is what came out of it:

First I did a delegate, that would take a delegate:

Func&lt;Func&lt;int, int, int&gt;, int, Func&lt;int, int&gt;&gt; MyCurry =                

(dele, x) =&gt; z =&gt; dele(z, x);

Then I made three functions, that would adhere to Func&lt;int, int, int&gt; :

Func&lt;int, int, int&gt; add = (x, y) =&gt; x + y;
Func&lt;int, int, int&gt; sub = (x, y) =&gt; x - y;
Func&lt;int, int, int&gt; mul = (x, y) =&gt; x * y;

Then I made three curried functions, that used the first delegate:

var add9 = MyCurry(add, 9);
var sub9 = MyCurry(sub, 9);
var mulBy2 = MyCurry(mul, 2);

And lastly I used the curried functions:

int result = add9(5);
result = sub9(10);
result = mulBy2(5);

And it actually works!

This way it is really easy to curry functions together…

&#160; kick it on DotNetKicks.com