Tigraine
Daniel Hoelbling talks about .NET

The fastest way to install dotless : nubular (nu)!

August 25th, 2010 . by Daniel Hölbling

Did you know that dependency management in the .NET open source space really sucks? For a long time have we been looking at Ruby Gems in envy of the ease of use and simplicity, spawning projects like Horn or  Bricks. And while some of these projects were promising, none really took off in a big way, so here comes another take at it: Some clever guys just talked to the RubyGem people about (ab-)using their existing infrastructure for .NET assemblies. And hey, they agreed to let us use their Gem system to distribute .NET assemblies just the way Ruby people can get Rails and all other Ruby projects.

And behold there it is: nubular (nu)

I won’t go too deep into what nu does and why it’s awesome, read Rob Reynold’s article and you’ll see the light pretty soon. Suffice it to say that nu is to assemblies what apt-get and gems is to Linux people. You just drop to the command line and tell nu you need assembly X, and if a package exists with that name it will automagically pull it down and with it all dependencies and install it to your /lib folder. Best of all, it also allows you to install binaries with it, a feature that turned out to be really cool for dotless.

Anyway, I promised you a really fast way to install dotless. Well, it can’t get any simpler than this, just drop to the command line and type (install instructions on nu are further down in this article):

nu install dotless

And now nu goes out to the gem server and just fetches dotless for you:

image

The installation just took 3 seconds, and we have the dotless.Core.dll now sitting neatly in our <currentdir>/lib/dotless folder alongside all other libraries we got through nu.

What this install also gives you is a shortcut to the dotless.Compiler.exe. Nu will install a dotless.bat in your C:\Ruby\bin (that should be in your PATH) that you can now use to compile .less files from anywhere:

image

That’s pretty cool I dare say. And now the best part: Updating dotless just got a lot easier too. Whenever we publish a new version to nu you can just hit

gem update dotless

Installing nu

So far I’ve shown you how to get dotless installed once you already run ruby gems + nubular, but for that all to work you need to install Ruby on your machine first.

Doing so is probably the simplest thing in the world right now, just hit http://rubyinstaller.org/ and you are almost set. You just need to install the nu gem afterwards and you are done installing (takes together under 2 minutes). (Note: Make sure to let the installer add Ruby to your PATH or the whole exercise is futile)

To install the nu gem just type:

gem install nu

It can’t get any simpler than this does it? Oh and btw: Ruby is completely xcopy deployable and will leave no traces behind on your machine. No services are being run and no bad things can happen to you, so there is really no excuse for a developer out there to no just go ahead and install it.

Oh, and after you’ve installed nu you can then go ahead and fetch a complete Fluent Nhibernate + Castle Windsor stack in a matter of seconds, disregarding all dependency issues since nu is handling that for you. And people are putting more stuff there by the minute: Rhino.Mocks, Fluent Nhibernate, Nhibernate, Castle Windsor, Castle DynProxy, Automapper.. etc etc.. Look at the full list and see for your self how much easier you life can become by a simple installation!


Don’t rely on exception messages

August 20th, 2010 . by Daniel Hölbling

Since the dotless 1.1 release we are finally able to present you with good error messages, telling you what line/column the problem was encountered etc. This has led to some tests like this one:

public void DivisionByZero()
{
    AssertExpressionError("Attempted to divide by zero.", 5, "20px / 0");
    AssertExpressionError("Attempted to divide by zero.", 14, "1 + 2 - 3 * 4 / 0");
    AssertExpressionError("Attempted to divide by zero.", 6, "1 + 2 / 0 - 3 * 4 / 0");
}

Usually you just check the exception type, but in this case it’s a generic ParseException that has the additional line/column  info on it and does not wrap the DivideByZeroException in it’s InnerException. Obviously the above failed on my machine due to my German locale and I was getting a different exception message.

I first tried to set the thread’s culture to en-GB but this only changes how formats are handled, there are no English exception texts installed on a German Windows machine.

The obvious solution then was to not hard-code the exception message but retrieve it from the DivideByZeroException:

[Test]
public void DivisionByZero()
{
    var divideByZeroException = new DivideByZeroException();
    AssertExpressionError(divideByZeroException.Message, 5, "20px / 0");
    AssertExpressionError(divideByZeroException.Message, 14, "1 + 2 - 3 * 4 / 0");
    AssertExpressionError(divideByZeroException.Message, 6, "1 + 2 / 0 - 3 * 4 / 0");
}

Takeaway: Make sure you tests run on all locales if your tests rely on exception messages. Smile


C# Object Initializers are Expressions!

August 14th, 2010 . by Daniel Hölbling

Object initializers got introduced into C# as part of .NET 3.5 and allow you to define properties through a nice concise syntax that makes code easier to read. Here’s an example:

var daniel = new User()
                    {
                        Username = "Tigraine",
                        Age = 25,
                        Email = "tigraine@tigraine.at"
                    };

In a .NET 2.0 environment the above code would have looked like this:

var daniel = new User();
daniel.Username = "Tigraine";
daniel.Age = 25;
daniel.Email = "tigraine@tigraine.at";

The funny thing here is that the .NET 2 code is not thread safe. If daniel is a public field or static field anywhere, the scheduler could interrupt the Thread right after setting the age, leaving you with an empty email field. This is also the reason why I’d call object initializers expressions: Expressions do by definition yield a value. And if we look at the code the compiler generates for an object initializer you will see this:

User <>g__initLocal0 = new User();
<>g__initLocal0.Username = "Tigraine";
<>g__initLocal0.Age = 0x19;
<>g__initLocal0.Email = "tigraine@tigraine.at";
User daniel = <>g__initLocal0;

The compiler does emit code that constructs the new object in a local variable that gets discarded right afterwards, and only the completed object, with all properties initialized will then be assigned to the variable. This makes this code thread safe. But, you’ll say it doesn’t yield a result thus it’s not really an expression.

Well, rewrite it a bit and you get a expression:

Func<User> expr = () =>
                    {
                        var user = new User();
                        user.Username = "Tigraine";
                        user.Age = 25;
                        user.Email = "tigraine@tigraine.at";
                        return user;
                    };
var daniel = expr();

It’s essentially a function that the compiler generates inline to save the cost of a method call, but it’s semantically a function, thus it yields a value and is a expression.


NHibernate removes items from Many-To-Many upon Update of Entity due to Model Binding

June 19th, 2010 . by Daniel Hölbling

Imagine the following scenario:

nh

Townships has two m:n collections mapped to Region. My Controller has special actions for updating these collections, while there is a generic Edit method that takes care of updating normal properties on Township. The code in question looks quite innocent:

[HttpPost]
public virtual ActionResult Edit([Bind]T item)
{
    if (!ModelState.IsValid) return View(item);
    using (var trans = session.BeginTransaction())
    {
        session.Update(item);
        trans.Commit();
    }
    return RedirectToAction("List");
}

Well, the problem is quickly found using NHProf:

image

Whenever I updated the Township entity all it’s associated Regions where cleared.

Turns out, the problem lies with the ModelBinder in MVC2: Since it reconstructs a new Township item and populates it with values from the request, there is no way for MVC to fill the WinterRegions and SummerRegions collection. So NHibernate got empty collections and assumed I removed all items from them and decided to persist that removal to the database, resulting in a DELETE.

There are two solutions to the problem: a) turn off Cascade.All b) Fill the collections before the update.

Since I already used the Cascade Behavior in other places I decided to go with b and select the entity prior to updating it. The resulting code looks like this:

[HttpPost]
public override ActionResult Edit([Bind]Township item)
{
    using (var trans = session.BeginTransaction())
    {
        var township = session.Get<Township>(item.Id);
        session.Evict(township);
        item.WinterRegions = township.WinterRegions;
        item.SummerRegions = township.SummerRegions;
        session.Update(item);
        trans.Commit();
    }
    return RedirectToAction("List");
}

Notice that it is important to first evict the fetched entity from the session, otherwise you’ll get an Exception stating that the same identified is already associated with this session cache.

To be honest: I don’t feel particularly fond of this solution, if anyone can point out a better solution please leave a comment or email me. While at it, it would be nice to be able to change the cascade behavior of entities for one session (like FetchMode for one criteria).


dotless Version 1.1 Released!

June 16th, 2010 . by Daniel Hölbling

logo

After a lot of work we finally released a new version of dotless. And this release is really sweet. We switched parsers from the troubled PEG parser we had to an all-new implementation of the less.js parser that gave us a ton of room for improvements and little tweaks.

Here’s a rundown of the most important features:

New Parser

New parser also means we finally have meaningful error messages and if there are syntax errors we tell you what line the error occured and what went wrong. So that’s a huge improvement for all the people who saw empty .css files trying to figure out what broke the compilation.

Parameter passing

One thing users have  been asking us for are parameters to be passed to the scripts. We finally found a good way to implement this and now it’s in.

If you use the HttpHandler you can simply pass parameters through the querystring. Let’s say you have a basecolor you want to pass to your .less file you simply call it from the site like this:

http://www.myserver.com/site.less?basecolor=#34679a

and the variable @basecolor will be set to #34679a for you in your script. This is especially handy if you are using the HSL functions where you can modify saturation, lightness etc.

If you are using the console compiler you can also leverage this new functionality through a very Ant like parameter syntax:

dotless.Compiler.exe test.less –Dbasecolor=%2334679a

Note: Parameters in querystrings have to be URL encoded or some browsers will act up.

Improved Caching

We also made sure that the cache works properly with parameters, so if two requests have the same parameters the cache will be used. If not, dotless will insert for every parameter/file combination one cache entry. Since parameters are by no means user-input values but usually limited to a set of values the designers specify this should still give you very good performance. Behind the scenes we are still using the ASP.NET cache infrastructure.

While at the topic of caching, we also improved cache invalidation. The old version did not watch all imported files for changes but only the main .less file. This has changed, you should now never have to think about disabling the cache during development.

The same change was also applied to the console compiler, if you start it with –watch the compiler will regenerate the CSS whenever any of the imported changes or the main file gets changed.

Runnable in medium trust

Well, nothing really exciting here, but you should now be able to run dotless in a shared hosting environment.

Other improvements

  1. Cleaner output
  2. better support for CSS3
  3. Many more..
    A big thanks goes to James Foster who did most of the heavy lifting involved with bringing you this new release. You can download the new version from our website at http://www.dotlesscss.com. Remember, dotless is open source and released under the Apache License, Version 2.0, the source can be easily found on GitHub.

ASP.NET MVC2 – Make Custom ControllerFactory less painful

June 4th, 2010 . by Daniel Hölbling

When starting a new project on ASP.NET MVC2 I noticed something very annoying. When used with a custom ControllerFactory the framework will throw a HttpException whenever a browser requests a file that is not present on the file system or not mapped by a route.

That means you’ll hit an exception about once per page-load just because Google Chrome is requesting the favicon all the time unless it finds one.

The solution to this is to make the Debugger just step through your CreateController method so no Exceptions will be visible to Visual Studio there:

[System.Diagnostics.DebuggerStepThrough]
public override IController CreateController(System.Web.Routing.RequestContext requestContext,
                                                string controllerName)
{
    return base.CreateController(requestContext, controllerName);
}

This works reasonably well for me right now, at least the pain of hitting F5 every 10 seconds while debugging has gone away. It’s still not perfect since it makes it impossible to actually debug the method if something really goes wrong, but you’ve always got the yellow screen of death to figure out what’s wrong.

Hope this helps!


Git Source Control Provider for Visual Studio 2010

May 30th, 2010 . by Daniel Hölbling

During my presentation at Barcamp Vienna today I got asked what GUI to use with Git. My plain and simple answer was: “Use the command line, its just better that way.. “. Well, after the talk Andreas approached me and raised a very good point: Mainstream adoption of tools (like Git) often depends on GUIs to help people during the transition phase.

Besides the obvious Guis like TortoiseGit or GitGui there is now one more tool aimed at .NET developers to make the transition easier: Git Source Control Provider for Visual Studio 2010. It looks like Microsoft got VS2010 extensibility right this time, and someone managed to implement Git integration right into the VS2010 solution explorer:

Git Source Control Provider

The Plugin is available through Visual Studio Gallery and seems to be Ms-Pl licensed and free, although I couldn’t find the code anywhere, it’s still worth checking out: Git Source Control Provider.


Never assume! Stack iterators in Java

May 12th, 2010 . by Daniel Hölbling

I spent almost 2 hours of debugging Java code yesterday due to one assumption that proved fatally wrong: I assumed a Stack, by definition a LIFO data structure would iterate over it’s elements from the top of the stack to the bottom.

So inserting 1, 2, 3 the resulting order when iterating through the stack should be 3, 2, 1.

Well, at least that’s what .NET does. Java is different. Look at the following Java code:

Stack<Integer> stack = new Stack<Integer>();
stack.push(1);
stack.push(2);
stack.push(3);

for(Integer i : stack) {
	System.out.println(i);
}

And this C#:

var stack = new Stack<int>();
stack.Push(1);
stack.Push(2);
stack.Push(3);

foreach (var i in stack)
{
    Console.WriteLine(i);
}

Well, they look exactly the same, but Java will return 1,2,3 while C# will honor the Stack’s special semantics and return 3,2,1. Great stuff isn’t it?

The workaround was quite simple, yet it had cost me 2 hours of my life trying to hunt a bug in my code, never thinking the bug could lie in a simple foreach iteration through the stack..

Lesson learned: Never assume you know anything about data structure semantics unless you have checked that your assumptions are indeed true. Implementations differ and sometimes this will bite you.

Oh and did I mention that the way Java does it is simply wrong?


Useful Resharper Live Template for WPF development

April 29th, 2010 . by Daniel Hölbling

While doing some work in WPF for a customer project I found myself writing far too often code like this:

private bool isSelected;

public bool IsSelected
{
    get { return isSelected; }
    set
    {
        isSelected = value;
        OnPropertyChanged("IsSelected");
    }
}

Auto-properties simply don’t work with INotifyPropertyChanged so you have to do all the grunt work over again .. Thank god there is Resharper!

It’s said lazyness is a virtue on a programmer, so I made this little Live Template that will create all that code with you only having to fill in type and name of your property:

image

Download it here: wpfprop.xml


Keep away from regions!

April 23rd, 2010 . by Daniel Hölbling

Well, I’m currently digging a bit deeper into WPF and the thousand little things you can do with it. Naturally I’ve been looking through my fair share of demo apps and tutorials too. And that’s where I stumbled upon this little gem of information hiding:

image

Exactly, that is what you get to see of a 200 LoC file when opening it up in Visual Studio. And the author did that for every single file, so whenever I opened a file I had to hit “Toggle all outlining” (Shortcut by default is CRTL+M, L).

Now, I’m all for clean code and tidy classes. But there are one thing fundamentally flawed with regions:

Once you need regions – Your code is simply too long.
My most successful (and biggest) project to date had no class that exceeded 100 lines of code, and you simply can’t imagine what a joy it was to work with that codebase. You simply can’t put enough logic into 100 LoC to make it hard to test, just by limiting the length of a class  you also lower the possible complexity of test and maintenance by a huge amount. Nice side effect: 100 LoC almost fit onto one screen so you understand the code without having to scroll through 3 pages of code to look up the name of a field.

Fix the root problem, not hide it!

What again reminds me of Jeff Atwood and he is totally right:

image


« Previous Entries