Tigraine

Daniel Hoelbling-Inzko talks about programming

New team member on dotless: Luke Page

You may have noticed that my blog is filling itself slowly with stuff about Ruby and Unix in general. This has to do with the fact that for now 3 months I am working on Rails full time with very little to no .NET work in between.

While this is awesome for me and I am really enjoying it - it also means that I don't have a .NET dev environment available at work and quickly merging in a pull request and testing it has become quite a hassle. So dotless has had quite some open tickets that where already fixed but where not yet merged into the mainline due to me lagging behind on responding to pull requests.

Fortunately, most/all pull requests have come from our very active Luke Page who has been busily fixing bugs and contributing features - so adding him to the dotless core team is a logical choice to cut down on the lag I or James where inducing into the process.

Since James felt the same we are happy to announce that Luke Page is now part of the dotless team with commit access and everything. So, welcome onboard Luke! Thanks for being part of dotless :)

What I've been up to

I just noticed that I started a new job almost half a year ago and didn’t mention it on my blog.

So it’s probably time I share what interesting stuff I’ve been doing lately.

New job

I now work for Life a software development company in Klagenfurt that’s situated inside the Lakeside Park. We focus on R&D in areas like ERP systems, natural language processing and other business solutions.

Although I still believe Lakeside Park is one of the ugliest buildings ever designed, from the inside it’s not that bad. It’s also located right next to the University, so I can attend courses in between work (a huge plus).

While I am mainly developing a CQRS-style business application I also did a lot of smaller projects for customers like WWF/AI.

CQRS

CQRS is a new architectural style coined by Greg Young that makes use of a few older patterns like Event Sourcing and CommandQuerySeparation as described by Fowler and Meyer. The style has been around for some time in the .NET space and Greg Young did a wonderful job of explaining it in a lot of screencasts and documentation he put up on his CQRS site.

The main idea behind CQRS is an eventually consistent architecture that does not rely on a big entity-relationship datamodel but rather on EventSourcing. EventSourcing means that you are storing every state transition inside your Domain as a distinct business event. So any model can be generated off this string of events that represents the currenct state. The benefit is rather huge because you can use heavily de-normalized models to read data from, while always issuing well-defined commands to mutate state.

I’ll blog on this in the future, but I strongly urge you to read up on cqrsinfo.com.

Still, it’s not an easy style to grasp and I had to let it sink for a few months before I could make heads or tails of it. In essence it’s so simple that you can explain it rather quickly, but it requires a pretty fundamental shift away from the CRUD style architecture you might be used to and finding out how to effectively work with this new “style” while being productive doing it takes some time.

Fortunately, just when I started to get into the right mindset for this way of working a project came in that required almost exactly the kind of traceability and flexibility Event Sourcing would give us, so I decided to go with a full CQRS stack.

CQRS in itself has worked out quite nicely so far. There is a lot of infrastructure I had to create, although fortunately Jonathan Oliver has created the EventStore project that at least spared me the work of rolling my own EventStorage system.

Since I’ll be working on this project for the rest of the year you can expect a few posts on the internals of the system and my thoughts on CQRS and eventual consistency in web applications.

JavaScript

Although I hate to admit it, I was always a web developer. I still suck at design as much as anyone else, but I was writing web applications all along, trying to convince myself that I was doing back-end stuff while hacking together the occasional HTML input form.

No more, I finally gave in and acknowledged the browser as the one platform I am probably targetting 80% of my work for, so I decided it’s time man up and really learn JavaScript.

I kind of knew JavaScript, it’s C based after all.. And I kind of knew my way around jQuery but never took the time to properly learn what makes this language so great.

So I got myself the brilliant book JavaScript: The Good Parts by Douglas Crockford and took a few nights to watch his great presentation Crockford on JavaScript that made a lot of things about the language clearer.

Funny thing: Right after I started getting a firm grasp around JavaScripts/EcmaScripts quirkyness I had to help out getting a project out the door that was entirely done in JavaScript as it was using the Sencha Touch JavaScript library to run on the iPad. (Note: ExtJS/Sencha are really incredibly ugly JavaScript frameworks – Use jQuery whereever possible)

Ruby and Rails

This goes hand in hand with the last point. After realizing that I’ll be doing MVC for a pretty long time I decided it’s time to really take another look at Rails and how it’s been doing while I was following ASP.NET MVC.

While I had looked at Rails earlier, I usually had given up trying to figure out how to install it on Windows and had just looked at the samples to conclude: “Same as .NET but with a bit of code-gen”

And oh boy was I wrong! While ASP.NET MVC really manages to get a lot of things right (at least for a MS framework), Rails3 is simply lightyears ahead.

And it’s not so much the core functionality I was usually looking at. It’s the subtle little things you don’t see in the samples but really learn to appreciate while working.

It’s the empty folders everywhere that give your code a very clean structure. Everything has it’s place.

And it’s the simplicity of it’s helper methods and little things like respond_to that are so incredibly hard and noisy to do in .NET land. Or the way helpers simply work whereas helpers in MVC usually make me want to tear my hair out (at least if you are working with dynamic models they simply fail).

Or another example of things that are simply there and nobody managed to get off the ground in 3 versions of .NET MVC is the asset bundling that’s been going on in Rails forever. Rails bundles all your javascript assets into one application.js file together to reduce browser load times, while .NET in MVC3 still references 2 seperate javascript library files in it’s default project template.

Rails is doing all the things right that I’ve been struggling with on the ASP.NET MVC platform for years whenever I was writing a simple business app, and it’s damn elegant all the way. It’s solving the CRUD application part so perfectly and with such simplicity that I am pretty sure I’ll be doing a lot of simpler applications in Rails in the future.

Vim and Visual Studio

Part of working with a lot of JavaScript is that you start to feel the limitations of Visual Studio as a JavaScript IDE. It’s simply inadequate and besides some syntax highlighting the whole editor simply falls down when writing JavaScript (not to mention the indentation screwups it does all the time).

So I ended up learning Vim and must say that I really enjoy it.

With the right plugins Vim is one hell of a powerful editor that does not require 600 mb of Ram and 40+ seconds to start up.

Having you editor boot in milliseconds instead of seconds has also had a huge impact on my work, and I have to say it annoys me every day when VS decides to hang up on me for 15 seconds only because I did hit save twice.

New home and cute mammals

I heard conclusive evidence that all blogposts are better with pictures of little furry mammals, so this one has to have them too.

To make that happen I moved into a new apartment with my Girlfriend and got myself two little baby cats that are called “Schrödinger” and “Marie Curie”.

Schrödinger:

schroedinger

Marie Curie:

curie

Sinatra vs WCF WebAPI

Yesterday I decided that there has to be a better way to expose data through JSon than to spin up MVC applications and abuse it to write a JSon returning service.

Since I was listening to Glenn Block on Hanselminutes talk about the WCF WebAPI I decided to give it a try and followed the hello-world article on codeplex to see what all the fuss is about.

It took about an hour to make the example work on my machine, and I completely failed in returning a clr-object as JSon. So after two hours of trying I gave up and decided to go to bed.

Today I had a few minutes of free time so I decided to have a look at Sinatra. 35 seconds later and I had a working “Hello World” running on my machine, with no configuration in 4 lines of code!

I then spent another 2 minutes figuring out how to return JSon from Sinatra (another 2 lines of code) and then decided to write this blog post.

Even though WebAPI is still a work-in-progress (that’s why it took so long to figure stuff out), it’s obcene that a WCF WebAPI “Hello World” requires more lines in web.config than Sinatra requires to do the whole sample.

In Sinatra the WCF sample literally boils down to these 10 lines:

require 'sinatra'
people = []
get "/hello/" do
	"Hello #{people.join(", ")}"
end
post "/hello/:person" do
	people << params[:person]
end

It’s tragic that you need to reference 6 .NET assemblies to achieve the things other platforms can do in 10 lines of code.. And the ruby code is also cleaner.

Filed under net, programmierung, ruby

Mappin Sql-Time to TimeSpan with NHibernate

Funny how long you can use NHibernate + Fluent NHibernate on greenfield applications and not use all of it’s mapping features. But one little project that needs to talk to a legacy database and you run into all kinds of troubles.

Today I had to map the time datatype present in MsSql2008. According to official Microsoft documentation the preferred clr-type for time is TimeSpan.

Unfortunately, by default NHibernate believes that the best way to map TimeSpan is to transform it to a bigint.

Fortunately the solution is rather trivial:

Map(p => p.CreatedOn, "CreationTime")
.CustomType("TimeAsTimeSpan");

Filed under net, programmierung, nhibernate

NHibernate Composide-Id mapping gotcha

I am currently working on a new system that populates a legacy database, so I am knee deep in relational SQL weirdness, trying to fight it with arcane NHibernate mappings.

This gem just cost me over an hour of work:

//Inside a ClassMap
CompositeId()
    .KeyProperty(p => p.Id)
    .KeyProperty(p => p.POSITION);
Map(p => p.Id, "Id");
Map(p => p.POSITION, "Position");

Trying to save this entity results in a Exception stating: Invalid Index 3 for SqlParameterCollection with Count=3

What happens here is that not even NHibernate Profiler can detect that you are doing something wrong because NHibernate fails to construct the SqlCommand to send to the database before any profiler can pick up on this.

What happened here is that I was mapping Id and Position twice, since the ComposideId already counts as one mapping.

So in order to make this work I had to remove the Map() instructions and specify the column name in the KeyProperty of ComposideId:

CompositeId() .KeyProperty(p => p.Id, "Id") .KeyProperty(p => p.POSITION, "Position");

Hope this helps.

Filed under net, programmierung, nhibernate

View localization with dynamics in MVC3

I ended up doing a good bit of Javascript and Ruby development lately and whenever I go back doing .NET afterwards I feel like things are getting in my way..

For instance the way localization is handled by .NET is a major pain point in all things I’ve been doing lately. WPF is probably the shining example of how not to do it (LocBaml? Serious?), but MVC3 also throws stones your way.

Problem is, that Views are not compiled – so you don’t get access to the static Resources.XXX properties from your Views. This is unfortunate and there are ways around that like using Helpers etc.

But I really grew fond of dynamic in C# for so I decided to simply use that to wrap the usage of my resources so I can write code like this in my Views:

@App.L10n.Product.Name

This is done by hanging my custom dynamic ResourceWrapper onto the dynamic ApplicationContext in Global.asax.

protected void Application_Start() { Application.Add("L10n", new MultiResourceWrapper()); … }

And my MultiResourceWrapper is simply wrapping all Resources existing in the MVC application on startup, and allows access to them through their name:

public class MultiResourceWrapper : DynamicObject { private readonly Dictionary<string, object> resources = new Dictionary<string, object>(); public MultiResourceWrapper() { var assemblyNamespace = this.GetType().Assembly.GetManifestResourceNames(); foreach (var s in assemblyNamespace) { var manager = new ResourceManager(ExtractResourceFullName(s), GetType().Assembly); var name = ExtractResourceName(s); resources.Add(name, new ResourceWrapper(manager)); } }

string ExtractResourceFullName(string s) { var regex = new Regex(@"(.*).resources$"); return regex.Match(s).Groups1.Value; }

string ExtractResourceName(string s) { var regex = new Regex(@"([a|A-z|Z]*).resources$"); return regex.Match(s).Groups1.Value; }

public override bool TryGetMember(GetMemberBinder binder, out object result) { result = resources[binder.Name]; return true; }

public class ResourceWrapper : DynamicObject { readonly ResourceManager manager; public ResourceWrapper(ResourceManager manager) { this.manager = manager; }

public override bool TryGetMember(GetMemberBinder binder, out object result) { result = manager.GetString(binder.Name); return true; } } }

As you can see all I need to do now to have localized strings for something is to add a Resource somewhere in my MVC application and then access it through it’s name from within the View.

One important thing though: I intentionally omitted any error handling code for the case where you mistype something. Nothing is more annoying than WPF bindings that simply don’t work because of typos, so having the app blow up with a YSOD is to me preferrable to a silent failure you have to spot later in deployment. But feel free to expand this to your liking.

The code is also available as a Gist from GitHub: MultiResourceWrapper.cs

Filed under net, programmierung

Troubleshooting project type not supported in Visual Studio

I was tasked with fixing an old legacy component that has been developed for Windows Mobile. Although the source code was available, I was unable to open up the solution due to my Visual Studio not supporting the project type.

Initially I spent hours downloading and installing SDKs for Pocket PC hoping to fix the issue, but after exhausting every SDK from Windows Mobile 2003 through 5 to 6.5.3 I finally gave up.

I took a closer look at the .csproj file, trying to determine how to find out what project type I am missing.

Turns out the project type is saved as a GUID in your .csproj file and you can simply google for that project type to find out what tool/sdk it’s associated with.

Turns out, my Visual Studio was missing a 3rd party designer component, preventing me to open up the whole project in VS.

Anyway, in your .csproj search for the <ProjectTypeGuids> – You should see GUIDs seperated by semicolons that specify exactly what project types have to be present in your Visual Studio.

This clearly goes into the category named: “Stuff I wish I knew 5 hours ago”

Filed under net, programmierung

Required files to bin-deploy ASP.NET MVC3

I’ve been awfully busy writing a MVC3 application for a customer over the last month. Suffice it to say that there is a great deal of goodness in MVC3 that I really like. Especially the addition of some dynamic sugar to the overly strict and rigid MVC stack is a welcome change.

Anyway, when it came to bin-deploying MVC3 I was scratching my head a bit until I found Scott Hanselman’s post on what files are required. This has changed since beta so here is an updated list:

  1. Microsoft.Web.Infrastructure.dll
  2. System.Web.Helpers.dll
  3. System.Web.Mvc.dll
  4. System.Web.Razor.dll
  5. System.Web.WebPages.Deployment.dll
  6. System.Web.WebPages.dll
  7. System.Web.WebPages.Razor.dll

All of these files can be found in the following locations and can simply be copied to the /bin folder of your deployment output.

  1. C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\Assemblies
  2. C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 3\Assemblies

Although I really like what the guys did with MVC3, this sort of deployment is pretty sub-optimal. Having that many late-bound assemblies that you just need to deploy while not having any reference to it is a problem for me. That requires me to write custom deployment scripts that copy that stuff over, and I really don’t like that.

Let’s hope they include something in Visual Studio SP1 that lets the deployment wizard copy these files for you to the output directory.

Filed under net, programmierung

Eliminating SELECT N+1 in NHibernate without getting duplicate root entities

NHibernate makes it easy to do a lot of things in a natural and OO way without having to constantly think about tables and rows.

It just falls short on some occasions when you do something in your domain model that is fine from a design and OO standpoint but kills you in terms of database performance.

I ran into this problem with a fairly common use-case: Iterating over a list of orders and calling a method on them that operates on their OrderLines collection. Everyone knows: you don’t do that. Whenever you run that method, NHibernate knows you haven’t fetched the OrderLines collection yet and will issue a single SELECT query to get them for you so you can do your calculation.

In traditional systems this is the perfect place to use a stored procedure and push the calculation logic into the sproc. It’s just not something I fancy doing. You end up with your code scattered around the system, and at times your calculations simply don’t work inside the database.

Putting code in the database also makes it even harder to deploy the application because you have to think about deploying the database code too.

Well, now back to topic. If you run the following query on a Order table that has many OrderLines NHProf will warn you that you are doing a SELECT N+1.

var orders = session.CreateCriteria(typeof (Order)) .List<Order>(); foreach(var order in orders) { order.DoSomethingWithOrderLines(); }

The way to prevent this is to tell NHibernate explicitly to fetch all OrderLines through a Join.

session.CreateCriteria(typeof(Order))
    .SetFetchMode("Lines", FetchMode.Eager)
    .List<Order>();

This works, but you’ll end up with duplicate orders being returned by NHibernate. This is due to the query you are running that will join each OrderLine with it’s order, resulting in one Order per Orderline (with a lot of duplicates).

But NHibernate is smart, and the information you are getting from the query is enough to construct the right objects, although some unnecessary data is coming over the wire. As with most things, you only need to tell NHibernate how to do it right. In our case that’s to only return distinct orders instead of duplicates through a result transformer:

var orders = session.CreateCriteria(typeof(Order)) .SetFetchMode("Lines", FetchMode.Eager) .SetResultTransformer(new DistinctRootEntityResultTransformer()) .List<Order>();

The result-transformer will eliminiate all duplicate root elements (in our case Order) while populating the child-collection accordingly. Resulting in only one query being run.

Filed under net, programmierung, nhibernate

Displaying different screens with ContentPresenters in Silverlight

In WPF you can use a ContentPresenter with DataTemplate to display different Views for different ViewModels. And although writing those DataTemplates gets old pretty quickly (and you resort to frameworks or roll your own code to alleviate that problem), I do like to use them in small demo apps at times.

Silverlight does not support DataTemplates with types on them, so you can’t use ContentPresenters like you would in WPF.

But in this case it helps to understand what a DataTemplate is doing in WPF to easily replicate that behavior in Silverlight. DataTemplates (in this case) are little more than Converters that take objects and supply a template that is then used to display that object to the screen.

Once you know that, it gets rather simple: Simply implement IValueConverter and return a Silverlight UserControl in the Convert method.

You can even write something as simple as this:

public class ViewConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value.GetType() == typeof(NewCustomerViewModel))
        {
            return new NewCustomer();
        }
        if (value.GetType() == typeof(CustomerListViewModel))
        {
            return new MasterDetail();
        }
        return null;
    }

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } }

Once your Converter can translate ViewModels (or any object) into Views you can then bind your ContentPresenter to use that Converter:

<ContentPresenter Content="{Binding ActiveScreen, Converter={StaticResource ViewConverter}}" />

You would obviously not want to use the code above, but rather hook your ViewConverter into your Inversion of Control container or something similar (or just use Caliburn.Micro).

There are a number of UI frameworks out there that make writing complex MVVM applications a lot easier. Caliburn, Caliburn.Micro and Prism. I tried some of them and I really liked them, but I found that you should really learn how Silverlight/WPF works before you resort to these Frameworks, as most of their features only start making sense once you start understanding the problems those frameworks set out to solve.

Filed under net, programmierung, wpf

My Photography business

Projects

dynamic css for .NET

Archives

more