Tigraine

Daniel Hoelbling-Inzko talks about programming

jQuery.validate and multiple forms on one page

I like generic, convention based approaches to infrastructure so in most of my projects you'll find something like this in the main javascript file:

$('form').validate();
There is only one slight problem: jQuery validate doesn't work like most jQuery plugins and won't operate on the matched set, but rather only on the first element.

So if you want to validate multiple forms you have to call each form individually through each

$('form').each(function () {
    $(this).validate();
});

jQuery.validate and Microsofts unobtrusive validation don't play well together

I was banging my head against the wall for more than three hours, reading jQuery.validate's code, trying to figure out why my supplied errorPlacement or highlight callbacks where not called.

The code in question looked perfectly fine and came pretty much straight out of the docs:

$('form').validate({
    debug: true,
    errorPlacement: function () {
        console.log("errorPlacement", this, arguments);
    },
    highlight: function () {
        console.log("highlight", this, arguments);
    },
    success: function () {
        console.log("success", this, arguments);
    }
});

As you can see I was still stuck in the "let's see what we can do from these callbacks" phase of implementing my own automatic validation scheme for a project. Guess what the above did? Nothing! And I mean really nothing. The validation worked as expected with my validation classes, but none of my callbacks got ever called (meanwhile supplied arguments like messages etc worked like a charm).

After 3 hours I finally came onto something when I couldn't find the validation classnames that where put on my elements inside the jQuery.validation code I was looking at. Turns out: Microsoft's jquery.validation.unobtrusive.js cripples jQuery.validation so that most of it's configuration options simply don't work any more. Neither with the $.validate.setDefaults() nor with the $('#element').validate() methods.

Needless to say that I almost broke into tears when my stuff was working fine once I removed the unobtrusive script from the page.

I do like the unobtrusive stuff - it serves it's purpose inside the MS MVC niche. But in this case I was not using unobtrusive on that form at all! So I simply did not expect the library to mess with jQuery.validate in any way as there was no unobtrusive validation stuff going on.

Localized Fullcalendar options

I usually try to avoid using too many jQuery plugins, especially for rather simple stuff like this. But displaying a calendar is pretty tricky (believe me - I wrote one using GDI+) and Fullcalendar has saved me countless hours so far.

One issue that cropped up now is that we needed our Fullcalendar to be localized in German. As with most things I came across so far, Fullcalendar already supports it - but the documentation is a bit cryptic on the issue so here is my localized options hash:

var localOptions = {
	buttonText: {
		today: 'Heute',
		month: 'Monat',
		day: 'Tag',
		week: 'Woche'
	},
	monthNames: ['Jänner','Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'],
	monthNamesShort: ['Jän','Feb','Mär','Apr','Mai','Jun','Jul','Aug','Sept','Okt','Nov','Dez'],
	dayNames: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
	dayNamesShort: ['So','Mo','Di','Mi','Do','Fr','Sa']
}

$('#calendar').fullCalendar($.extend({ ... your options ... }, localOptions));

Don't commit when you rebase

One common mistake and my team seem to be doing at times with Git is that we routinely commit after resolving a merge conflict during a rebase.

The idea is simple: Instead of doing thousands of merges (thus cluttering the timeline of the project) whenever someone wants to check something into the central repository he fetches the remote changes and applies his local changes onto the remote ones.

Thanks to Visual Studio and it's way of having every source file referenced from the .csproj files (I hate that btw), we routinely get merge conflicts on the project files that need to be manually resolved. During a rebase this means the rebase will stop on the commit that caused the conflict and you have to fix it.

After you are done with fixing the conflict (usually it's just removing the conflict markers Git inserted) you then have to add the now merged file to the index (aka staging area) and hit git rebase --continue. Problem is: Since it's just a special state of a repository you can just as easily do the following:

git add -A git commit

Good job you just put your repository into limbo mode and your merge is gone .. You recorded a commit onto your rebase-HEAD and you can't continue the rebase because the rebase head is no longer where it belongs to.. So once you try to do git rebase --continue git will tell you: "No changes - did you forget to use 'git add'?" And when you run git status you'll see: "Not currently on any branch. nothing to commit"

Your only avenue here is:

git rebase --abort git checkout master git rebase origin/master ... redo the merge git rebase --continue

Filed under programmierung, git

jQuery.Stepy select callback

I just stumbled upon a little issue while using jQuery.Stepy wizard plugin: There are callbacks for navigating, but there is simply no callback that gets fired when the current step is actually displayed. As it happens there are a number of things you may want to do once a wizard  step is shown like start animations or maybe initialize something. (And next/back get fired before validation happens so they don't actually work in case validation fails)

Thank god JavaScript is almost by definition open-source so I fixed this with the following pull request.

The select callback works just like the back/next callbacks:

$('#wizard').stepy({
  select: function (index) {
     //your code goes here
     //index is 1 based - not zero based
  }
});

Filed under programmierung, jquery

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

Restful-Authentication on Rails 3.1 RC1

While working on a small side project I decided to go with the bleeding edge and use Rails 3.1 RC1. One issue I ran into with this though is that they changed the generator scripts so the most instructions for the restful-authentication plugin didn’t work.

First of all the original plugin isn’t yet working on Rails 3 so there is a fork by vinsol that you can use instead.

After running: rails generate authenticated user session I did try to load /signup and was greeted by the following error:

uninitialized constant ApplicationController::AuthenticatedSystem

Looking throuhg sessions_controller.rb and users_controller.rb i found that both include AuthenticatedSystem with instructions to move that into application_controller.rb

Doing so unfortunately doesn’t work out of the box since rails apparently changed search-paths for libs so make sure to include the following in your application_controller.rb:

require File.join(Rails.root, 'lib', 'authenticated_system.rb')
include AuthenticatedSystem

At first I only tried require, but as it turns out require only loads a file and executes it (like include does in C) while include actually copies methods from another module to the current one.

Both are required for restful-authentication to work obviously, or your sessions_controller will throw errors like this one: undefined method `logout_keeping_session!' for #<UsersController:0x8fc409c>.

Hope this helps, it took me some time to figure this out, but I guess this is mostly because I am a total stranger to the Rails platform.

Filed under programmierung, rails, ruby

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

My Photography business

Projects

dynamic css for .NET

Archives

more