Thursday 31 March 2011

Draggable items in Accordion

In the next months I'll be helping out part-time on a new project at work using Asp.Net Mvc 3 with a rich, jQuery based, UI. We'll be migrating-evolving an existing Flex application, so the User Interface we'll need to be rather smooth, and allow things like dragging items on some pageable-editable-sortable Ajax based Grid.
So, I've been playing around a bit in the last weeks to see how different jQuery based controls, plugins play together.

This is how I found out, to my horror, that the jQuery UI Accordion and the draggable functionality don't mix well together.
If we have an Accordion where each "button" (the h3 element) has a list of items (li's inside the sibling div), doing those items draggable does not work as expected, and dragging them results in an horizontal scroll being added to the div, not being able to drag the items outside.

Some searches on the net brought up some unanswered questions on some forums, which led me to think that it could be a fun and good idea to do my own accordion. The code for a basic accordion is rather simple (I'm using a closure to save as state the current expanded item):


function accordionize(containerId) {
//the eventhandling function is a closure that will trap the "expanded" variable, that is the only state we need to keep
var expanded;

var $headers = $("#" + containerId + " h3");
//notice that h3 and div elements are siblings here, that's why given a h3 element I use next() to refer to its corresponding div.
//use toggle for showing/hiding, instead of show-hide, the animation effect is better
$headers.each(function (index) {
$(this).click(function () {
if (index != expanded) {
var $cur = $(this);
//the callback function is only called once, not one time for each item being animated
$cur.siblings("h3").next().toggle("slow", function () {
printf("hidden");
$cur.next().toggle("slow");
expanded = index;
});
}
});
});

//initial display, hide all excepting the first one
$headers.not(":first").next().toggle();
expanded = 0;
}


The behavior is OK, and I guess that if I exerted myself for a while with CSS I would manage to give it a decent look. At first the dragging was working fine, but when I added a overflow-y: auto (you know, making it scrollable), to the div containing the list, the same issue I had with the jQuery accordion sprung up... Checking the jQuery UI accordion I noticed that the styles applied to it by the CSS framework were also adding the overflow-y:auto, so that's where the issue seems to lie. That looked almost like a dead end to me, cause it's rather likely that I'll need the scrolling functionality.

Hopefully, after some more and more internet reading, I've finally found the 2 draggable options that make it play (apparently) fine with the accordion:

appendTo: "body",
helper: "clone"


You can view it here

It seemed promising, but after having this entry almost ready I've realized it has a huge problem. In my case, if the item is not dropped, it gets replaced in the original position by a cloned element that is not draggable (examining it with some DOM explorer shows that it lacks the "ui-draggable" class that items acquire when done draggable. I've tried several things and none seems to work... but I guess the solution will be using the helper:function(){} option.

Update, 2011/04/14:
I was right in my assumption above, if we change the helper option to something like this:

helper: function(event){
return $("").html(event.target.innerHTML).css("border", "1px solid black");
}

(we return there the DOM element that we want to see dragging around the screen)

it works great!!!
Well, all of this has been a rather unfortunate and very time consuming issue...

Departing a bit from the main topic of this post, adding the fails-works radio buttons on top came useful to refresh a bit my memory on how these things work:

  • You group them by giving them the same value to their name attribute.

  • To handle them with jQuery you'll use the change() function-event, and the .attr("checked") function.

  • Furthermore, selecting an item based on it's value can be pretty useful:

    $("#accordionSelection").find("input[value='correct']").attr("checked", true);



  • As for the "changing" message that I show/hide when the radio button changes, it's just some very simple jQuery magic:


    var $changedItem = $(this);
    $changedItem.after($("").text("changing")
    .addClass("messageTag"));
    setTimeout(function(){
    $changedItem.next().remove();
    }, 2000)

Wednesday 23 March 2011

Collection was modified; enumeration...

Well, it's been years since I first stumbled upon this, but still today it sometimes gets my by surprise, I'm talking about this exception:
Collection was modified; enumeration operation may not execute

This happens when you're enumerating an IEnumerable, do some modification to it, and try to continue enumerating (do another MoveNext). Many times this happens in a foreach loop (that of course under the covers makes use of Enumerators...)

You can find good information on the net explaining why IEnumerables have been designed this way, and as pointed out there, MSDN says it clear:

An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and its behavior is undefined.

What is important here is that there's no way to force us to implement this part of the interface contract in our own classes, I mean, someone could program his own IEnumerables without following this rule, either deliberately of by mistake, but the expected behavior of a .Net IEnumerable should be that, and all should play by those rules.

How do the classes implementing IEnumerator and IEnumerable play together so that the former knows that the latter has been modified?
Well, sometime ago I had disassembled some code to take a peek, and found the same that is stated in the link above, the class implementing IEnumerable has a version field, that is increased by each method that involves a change (Add, Remove...). The class implementing IEnumerator also has a version field, that at creation time is filled with the version value in the IEnumerable. Each time MoveNext is executed it checks that the version values in the IEnumerator and the IEnumerable are the same, launching an exceptions if the condition is not met.

Taken from StackOverflow:

Internally, most of the base collection classes maintain a version number internally. Whenever you add, remove, reorder, etc the collection, this version number is incremented.

When you start enumerating, a snapshot of the version number is taken. Each time around the loop, this version number is compared against the collection's, and if they are different then this exception is thrown.


Today I got this same exception with some code modifying a Dictionary while traversing its Keys collection, which at first surprised me a bit


foreach (string key in this.columnsMap.Keys)
this.columnsMap[key] = columns.IndexOf(key);


Well, I'm iterating the Keys collection, not the Dictionary itself, but of course, modifying the Dictionary should change the Keys collection invalidating it... and that's just what's happening.

Disassembling with ILSpy (I think this is going to be a great replacement for Reflector), we can see how the KeyCollection.Enumerator checks the Dictionary.version against its own version field:


Monday 21 March 2011

C# literals

Well, I guess this is something that should almost have become automatic actions not needing any further brain cycle wasting... but it's not the case, and every now and then I need to search the net for references and samples, cause I tend to get confused with what can be omitted and what not, so good point to write my own reference in an easy to locate place:

C# literals:

  • Array Declaration and Initialization:


    //the long way
    int[] numbers = new int[5] {1, 2, 3, 4, 5};

    //shorter
    int[] numbers = new int[] {1, 2, 3, 4, 5};

    //the shortest, more friendly way:
    int[] numbers = {1, 2, 3, 4, 5};




  • Object Initializers


    //Object, (well, this is so obvious, but anyway I add it here to have a complete reference)
    myPerson p = new Person(){
    Name: "xuan",
    Age: 30
    };



  • Collections initializers:


    List<int> myList = new List<int>(){1,2,3};

    List<Cat> cats = new List<Cat>
    {
    new Cat(){ Name = "Sylvester", Age=8 },
    new Cat(){ Name = "Whiskers", Age=2 },
    new Cat(){ Name = "Sasha", Age=14 }
    };


    And now, the one that I tend to have more doubts with, thinking that I'm just borrowing it from other dynamic languages, but not, this short nice syntax for Dictionaries is perfectly valid C#:



    var data = new Dictionary<string, string>
    {
    { "test", "val" },
    { "test2", "val2" }
    };


Saturday 19 March 2011

The Killing Room

I've rather enjoyed this North American film. The main idea is nothing too new: some people locked in a room, shocked and fearful undergo a series of mysterious tests, and failing means dying.
Sure you're thinking now of Cube, Fermant's Room... (another very good film springs to my mind, but I can't remember the name now), and you're damn right, but there are some elements here that sure gives it a special touch.

This film makes it rather clear since the beginning (to us, not to the prisoners) who are the guys behind the experiments, the American Secret Services are conducting this crazy thing (well not too unusual), and they're doing it as part of the MKUltra project. Yes, this is an interesting take, imagining a world where MKUltra did stop only at an official level, but where some dark government agency has kept it going under the covers all these years, is something that makes good sense to me.

Spoiler warning starts here
What I liked most of this film is the final part, when the aim of the "research" is unveiled. They're trying to select people willing to sacrifice their own lives for the others, people that would have the psychological basis for being trained into "martyrs", "suicide bombers"... Well, when you have nuclear weapons why do you need "human weapons" you could ask... as nuclear weapons have sort of a global effect their damage would end up reaching your own people, the effect of "human bombs" can be better focused though...
Spoiler warning ends here

Casting the film aside now and focusing on the pieces of reality that got declassified by the USA government, and that unfortunately can only allow us to barely scratch the surface of what was going on during those years of "human behavior investigation and manipulation"....

In 1973 CIA Director Richard Helms ordered all MKULTRA files destroyed. Pursuant to this order, most CIA documents regarding the project were destroyed, making a full investigation of MKULTRA impossible. A cache of some 20,000 documents survived Helms' purge, as they had been incorrectly stored in a financial record building and were discovered following a FOIA request in 1977.

MKUltra was both fascinating and terrifying. Given the minimum knowledge about the human brain that was held at that time, that some high ranks of the military thought that it would be possible to develop techniques for fully reading and manipulating the humand mind sounds like rather arrogant.

One of the most astonishing facts is that the investigations crossed the USA borders to the North, funding the atrocities conducted by the crazy psychiatrist Donald Ewen Cameron in Montreal. There are some pages in that mandatory reading (if you happen to want to understand a bit how our current world works) called The Shock Doctrine where the barbaric experiments conducted by this beast are explained. He aimed to reprogram humans by completely wiping out their memories, a process he called depatterning. The means used to achieve this werer this were sleep deprivation, massive doses of electroshock and different cocktails of drugs... Unfortunately he was rather successful with his experiments, meaning that he managed to destroy the lives of a good number of unwitting patients that had turned to him seeking out help for common problems like anxiety or mild depression.

There's a very good documentary dealing with all the MKUltra madness, Mind Control, America´s Secret War

Saturday 12 March 2011

jQuery Animation Matrix

Ever since I first played with Flash a long while ago (in those old Macromedia times...) I've had an interest in basic animation, making objects move around the screen. I guess the experiments by Robert Penner were responsible for getting me into this. Of course, I've never achieved any too interesting thing regarding this, just some lame effects... but anyway, I've lost my time (and had plenty of fun) from time to time over the years doing basic animations with Action Script, GDI+, PyGame, WPF and lately with jQuery.

So what I've been up to lately has been an "Animation Matrix". It's just a Matrix of div elements (well, jQuery objects wrapping those divs) that get added, removed, shown and hidden in different ways. All the animation work is done with jQuery's animate method. As we're animating objects one after another, we have to chain animations, so that once the .animate() for the current object is done it calls a new .animate() on the following object. I do this by having "private" methods that animate the current object by calling its .animate() method and passing to it as a callback this method itself again. I'm keeping the state of the animation (next item to animate) in a private field of the Matrix object, I could have avoided this by using closures, but at a first moment I thought it would turn it more complex. The matrix has some events that are consumed both internally and externally (for the "matrix Orchestrator").
Another point of interest is that for operations where I randomly choose the next item to be actioned, I use a separate array of available items, otherwise, if I were choosing the next item from the normal matrix, once we have fewer and fewer elements left to be animated, I would need tons of attempts to find the next random one... and it would ruin the whole system.

In addition to the matrix, I've also coded a "matrix Orchestrator" class, that receives a sequence of animations to execute on the matrix and runs them n times. It's not much different from what I talk about in this post.

Update, 2011/03/19 After having played around a bit with the Html5 Canvas and its Image Drawing features, I've updated the code so that if you're using a canvas enabled browser (Firefox, Chrome, IE9) you'll see the matrix filled with tiles taken from the image on the right (that's Munich, my next trip destination :-) So, in that case, instead of a Matrix of divs, we have a matrix of canvases, that got filled with this:

myCanvas.getContext("2d").drawImage(img, sx, sy, width, height, 0, 0, width, height);

You can see it in action here

The matrix and matrixOrchestrator classes are in this file.

Tuesday 8 March 2011

.Net 4 Oddities II

I'll post here some additional information to this old post.
Today I finally could put my hands on a Windows 64 bits system (Windows Server 2008 R2). Yes, it sounds odd, but all my home PCs and my work laptop are 32 bits systems.

After installing the .Net 4 runtime, I went to the C:\Windows\Microsoft.Net folder to make sure that I had a v.4 folder there. First unexpected thing was finding 2 folders there: Framework and Framework64. Obviously one contains 32 bits executable files and the other one 64 bits, but why is this necessary?. I did some web searching and this is what I found:

You do need both the 64 and 32 bit versions of the frameworks on your system. There are a lot things you can only do when the app is run as 32bit. For example most activex controls are 32bit, you can not open an access database when running in 64 bits, etc

That well, does not clarify much to me, for example, I don't see that ActiveX controls play any roll in having 2 csc.exe files.

Then, having a look into the C:\Windows\Microsoft.Net\assembly (this is the GAC location for .Net 4) I got another surprise, finding there 3 folders, GAC_32, GAC_64 and GAC_MSIL. My first thought was that 32, 64 folders would contain those assemblies that have been Ngened, but a glance there didn't show any .ni (native image) file, so seeking some more shared knowledge on the net came up with this:
The GAC_MSIL cache contains assemblies that can be run in either 32-bit or 64-bit mode, and are JIT compiled to the required word size as needed.

The 32/64 directories contain assemblies that are specific to either 32-bit or 64-bit mode, either because they contain native code or because they make specific assumptions about the word size.


That makes good sense to me, and one point that helps us to corroborate this is that the mscorlib.dll assembly (that contains some native code for the MethodImplOptions.InternalCall thing) is in the 32 and 64 folders, and not in the MSIL one.

Thursday 3 March 2011

Last month Interesting Stuff (February 2011)

Last month I was mainly active reading about some generic client side-server side items:

  • Inheritance in JavaScript is a recurrent and controversial topic (should we adapt a Prototype-based language to our, at for most people, Çlass-based background, or just the contrary, leverage our brain plasticity to adapt ourselves to the language?). Anyway, this article and this one, are really helpful.

  • I already knew JSONP was a mechanism to bypass the Same origin policy limitation, but as I'd never needed to use it I'd never investigated any further.
    This article clearly explains how it works, the nice job done by jQuery injecting the needed <script> tags and an extra function, and how the server needs to return the requested data wrapped on an invocation to that function generated by jQuery.

  • Time ago I had glanced through several articles explaining how to develop high performance servers, so coming across this article in infoq brought to my mind some other discussions like this and this. All in all it's a matter of not creating a new thread for each new incoming request, and it's used for some real world servers that tackle the so called CK10 problem.



and learning Asp.Net MVC 3:

  • Asp.Net MVC 3 is a really extensible/customizable beast, and the new IDependencyResolver centralizes much of that. This article provides tons of information about it.

  • Thought based on an earlier version, this article about testing is also a good read.

  • I didn't know you could have different methods responding to the same Action, and instruct the runtime which one to use by means of attributes. This article rather amazed me.

  • With the right settings it's easy to debug the MVC source code from Visual Studio. That way VS downloads all the needed files on the go, and you don't need to download the MVC source code and change the MVC assembly references as explained on other articles.
    As of now, the Framework Source Code, though being available here, is not available on the Symbol Servers, so to debug the Framework Source Code you need to download and extract that huge 1GB file, as explained here.
  • debugging:


Well, mission accomplished, I've put together in an easy to reach page a partial dump of my brain activity for the last month :-)