Tigraine

Daniel Hoelbling talks about programming

RSS Feed

Archives for Coding

jQuery: Execute once animation finished

0 Comments

Good JavaScript almost forces you into learning async programming and jQuery animations is no different. Everything in jQuery supports callbacks because the stuff you do is in most cases done on the background while your script continues to run.

But as with most stuff, there are many ways of going about this:

Completed Callbacks

    $('#item').fadeOut('slow', function () {
        console.log('animation finished');
    });

The problem with this approach is that it gets rather tedious to queue stuff together if you want to do say three things in order.

Let’s say you want to a fadeOut animation then add a cssClass, start another animation and once that one is finished remove the cssClass again. Using callbacks this looks rather ugly:

    $('#item').fadeOut('slow', function () {
        var foo = $('#foo');
        foo.addClass('myclass');
        $('#item2').fadeIn('slow', function () {
          foo.removeClasS('myclass');
        }
    });

As you can see, two nested callbacks is really not that readable and almost confusing.. That’s why there is a better way to do this:

The fx Queue

jQuery uses a queue for all it’s animations. That’s the magic behind this nice syntax:

    $('#item').fadeIn().fadeOut();

If you run this code it will first fade the item in and only once it’s completely visible it will start the fadeOut animation.

Problem with this is that it looks nice in it’s syntax, but can’t be mixed with the regular jQuery methods. Something like

$('#item').fadeIn().removeClass('active').fadeOut();

will not work simply because you removeClass will be executed instantly while fadeIn and fadeOut will be queued for later execution by the effects (fx) queue.

In that case you can hook into the queue yourself by using the .queue() method:

    $('#item').fadeIn().queue(function (next) {
        $(this).removeClass('active');
        next(); //Important to continue running the queue
    }).fadeOut();

Hope this helps!

Filed under JavaScript, jQuery
Aug 21, 2011

dotless v1.2.1 released

0 Comments


Remember dotless, the awesome little framework that makes writing CSS a enjoyable and nice experience? Well, it’s time to announce a new major/minor version!

Major? Yes – James in all secrecy tagged a v1.2 without me putting out a formal NuGet package. So v1.2 has been available for quite some time but only to the few interested souls that follow us on GitHub and those who got it to compile.

So it’s been about time we formally push out v1.2 (and me writing about it). But, as with all software 1.2 had some open issues that got patched by the community and that’s why we are calling it 1.2.1 :)

The binaries are now available through NuGet with a simple:

PM> Install-Package dotless

Or you can simply grab the binaries from GitHub . If you care to build the code yourself from source: knock yourself out

Hope you enjoy writing lesscss – I for sure do.

Filed under dotless, Projects
Aug 20, 2011

Don’t commit when you rebase

0 Comments

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 Coding, Git
Aug 10, 2011

jQuery.Stepy select callback

0 Comments

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 Coding, jQuery
Aug 2, 2011

What I’ve been up to

0 Comments

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

Jun 11, 2011

Restful-Authentication on Rails 3.1 RC1

1 Comment

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 Coding, Rails, Ruby
May 28, 2011

Sinatra vs WCF WebAPI

0 Comments

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, Coding, Ruby
May 16, 2011

Mappin Sql-Time to TimeSpan with NHibernate

9 Comments

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, Coding, NHibernate
May 12, 2011

NHibernate Composide-Id mapping gotcha

0 Comments

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, Coding, NHibernate
May 11, 2011

JavaScript scope and how to leverage it

0 Comments

Care to guess what this will output?

function() {
var x = 1;
	if (x < 5) {
		var y = 3;
	}
	console.log(y);
}

If you expect y to be undefined you fell for the same trap as everyone who comes from a more traditional background.

The output is of course y = 3

JavaScript has no block scope

I’d suggest you tattoo that on the inside of your eyelids since it’s so important to remember..

Whenever JavaScript behaves totally irrational for you, take a hard look at your code and make sure you are not using block scope like you would in most other languages.

But how does JavaScript scope then?

JavaScript is a really nice functional language someone threw a lot of Java ugliness on to make it appeal to the unwashed masses.

But at it’s core it remains this beautiful functional language, so naturally: JavaScript scopes by functions

And since functions are objects, you can leverage this scoping to create your own little hidden namespaces whenever you like.

(function () {
var x = 1;
}());
console.log(x); //undefined

Since functions in JavaScript are objects, you can define one and immediately call it afterwards, thus creating a block that hides everything inside from the outside. This becomes very important when you try to avoid naming collisions with other libraries when writing your business logic.

Since it’s advisable to group your logic, you can use the above function syntax to create objects with their own little shared namespace you can then call from your page:


var util = (function () {
var x,y; //private variables nobody sees
	return {
		method1: function() { return x; },
		method2: function() { return y; },
	};
}());

util.method1() //returns value of x

Interesting here is that although we used a function to define util, since that function was executed right on the spot, util now points to the return value of that function. In this case an object with two methods on it.

And now things get weird: Closure.

If may strike you that at the time we call util.method1() the function that created util has already returned (a long time ago), so in theory we should not be able to access x and y.

But like it would with block-scope in a traditional language, JavaScript also looks at it’s parent scopes if it can’t resolve an identifier inside it’s current one.

And in functional scoping this means it has to look in it’s parent scope that is a already returned function.

In short: JavaScript keeps the scopes around as long as there are references to them, so even if a function returned in the past, it’s scope is still available to functions that can access it’s scope.

This also means you can do cool stuff like this function that allows another function to be executed exactly once:


var once = function ( fn ) {
var callCount = 0;
	return function () {
		callCount += 1;
		if ( callCount > 1) {
			throw "Function can only be called once";
		}
		fn();
	};
};

var f = function() { alert("hi"); };
f = once(f);
f();
f(); //this call will throw

Did I mention that programming JavaScript is totally addicting?

Filed under Coding, JavaScript
May 5, 2011

Projects

dynamic css for .NET