Monday 29 April 2013

Careful with the new .NET overloads of String.Join when moving to .Net 4.0

I was trying to figure out an issue with our product and, in order to understand what was going on, I copied a class from the project into a small sandbox project to see how it would work. Lo and behold, a problem occurred in one of the utility functions that would have made the entire feature unusable. Yet the feature worked fine, except the little detail I was working on. What was going on?

Let me show you the code first (simplified for your pleasure):
Dim al As New ArrayList
al.Add("A")
al.Add("B")
Dim result as String = String.Join(":", al.ToArray(GetType(String))))

What do you think the result will hold?

In our production site the result was "A:B". In my sandbox project the result was "System.String[]". It took me a little to understand what was going on. You see, the sandbox project was .Net 4.0 while the production site still worked with 3.5. New to .Net 4.0 are overloads for the String.Join method, including one that receives a params array of objects. Since ArrayList.ToArray(Type type) returns Array no matter the type boxed inside, this is the overload that is chosen. The list of strings is taken as the first parameter, stringified, and the result is what you saw.

Conclusion: be very careful of the types you send to methods. Even if Visual Basic automatically casts method parameters, you never know for sure which type it will choose to transform into. And if you want to upgrade a VB project from .Net 2.0-3.5 to 4.0, be careful of the new overloads that have appeared.

Sunday 21 April 2013

Dune Messiah (Dune 2), by Frank Herbert

Book cover Dune Messiah is the second book of Frank Herbert's Dune saga. It is two and a half times smaller than the first book and it feels almost completely different. Paul has been emperor for some time, not much, but enough for his jihad to bring the death of tens of billions. The government of the universe is now his, a combination of religion and bureaucratic despotism that he foresaw, but could not have prevented. The house of Ix and the Bene Tleilaxu make their appearance. There are conspiracies against Muad'dib and his family from every corner and, if the first book was of his victory over his enemies, however painful, the second book is all about his defeat at the hands of the future. He walks the edge, loses almost everything, all in the name of a better future for human kind. All the characters are weaker, more human, some less human but still weak.

All in all, it is a nice book, well written and interesting, but it felt like a kind of bridge between Dune and the next two books, which have their focus on Paul Atreides' children. We are certainly looking forward to brilliant stories and great writing, but Dune Messiah seemed a little too melodramatic, less focused, with less work done on it. Compared to its predecessor, it seems a disappointment; compared to most other books, it is still great.

Thursday 18 April 2013

Visual Studio 2010 restarting after loading a solution

This has happened to a colleague of mine: when trying to open a solution file with VS 2010 the program would start, it would successfully load the solution, open the few files that were open when last closed, then suddenly restart. No fancy dialog prompting for action, no message of any kind, just a total silent fail. He tried using the /log filename option of Visual Studio to gather more information, it did not help. He tried using the /SafeMode switch to load only the essential bits of Visual Studio, to no avail. The only useful information was in the Windows Application log (run eventvwr.exe in the command line) which pointed to the module cslangsvc.dll failing.

The Windows Application log entry for the crash:
Faulting application name: devenv.exe, version: 10.0.40219.1, time stamp: 0x4d5f2a73
Faulting module name: cslangsvc.dll, version: 10.0.40219.1, time stamp: 0x4d5f3b95
Exception code: 0xc0000005
Fault offset: 0x00249be1
Faulting process id: 0x1af8
Faulting application start time: 0x01ce3c253d1db9e5
Faulting application path: C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe
Faulting module path: C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC#\VCSPackages\cslangsvc.dll
Report Id: f3522e88-a818-11e2-a285-14109fd5a416


The bit of the Visual Studio log that is relevant:
<entry>
<record>437</record>
<time>2013/04/18 11:17:35.042</time>
<type>Information</type>
<source>VisualStudio</source>
<description>Unexpected system error mode before loading package [Visual Studio XML Editor Package]</description>
<guid>{87569308-4813-40A0-9CD0-D7A30838CA3F}</guid>
</entry>

At this point, we thought that it was a problem caused by Visual Studio trying to parse the open files, probably related to Intellisense, which means we need to make the solution open ignoring the files open when using it last time. That means deleting the file with the .suo extension associated to the solution.

This is a common issue, as the first Google search item when looking for cslangsvc.dll is this: Visual Studio 2010 Crashing on Solution Load. The thing is the guy does claim he deleted his .suo file and that the problem was still reproducing. There are also some Microsoft Connect items logged (Vs2010 crashes on cslangsvc.dll) that have no resolution.

Well, deleting the .suo file associated with the solution worked. This, of course, removes more than the last opened files, like the source control associations of the solution, various custom options for said solution, etc, but it shouldn't be a problem.

There is a bit of information in the Visual Studio log which points to the XML Editor Package. This means it could be caused by XML files or aspx/ascx files. However, it might not. We did not pursue the issue any further. Hope it helps other people looking for a resolution.

Tuesday 16 April 2013

Dune, by Frank Herbert

Book cover, featuring the worm of Arrakis Dune, a mega-classic of sci-fi books, written in 1965 by the ecology obsessed Frank Herbert, tells the story of a future world that is dependent on the substance known as spice, of a vast stellar empire led by an emperor and the noble houses and shaped by religion. Dune is the first in a series of six books, each one increasing the level of "epicness" of the story. There is no way I can do justice to the book in my review, it is that good and that complex. All I can say is that I've read it every ten years from the time I was 15, and every time I read it, I interpret it differently. This also shows how different we are at various ages.

Anyway, I was saying that Frank Herbert was obsessed by ecology. I am saying this after reading all of his books a while ago and noticing the pattern. The Dune Wikipedia article claims that this book was the result of events that started Herbert's interest in ecology, while he was working for the Department of Agriculture, trying to stabilize sand dunes using plants. Herbert is also the author of brilliant books like the Pandora series or like Hellstrom's Hive, which for many reasons, I consider a masterpiece as well. However most of his books and short novels feature some interest in ecological systems.

The story is set twenty millennia into the future. As it was written in the sixties, it had to solve the problem of exponential technological advancement that was obvious even then. How can one write a book about the future, when the future moves so fast? Herbert solved it in a simple way: he imagined a world where humans rebelled against the use of intelligent machines, for religious reasons, thus removing computer advancements from the equation. Also, in order to solve the issue of ever evolving weaponry, he imagined a world where energy shields were cheap and small and could be used personally or on buildings or ships; these shields would stop any object or energy moving fast enough. This reduces battles to hand to hand combat, with knives and slow needles that can penetrate the shield. It's not like Herbert had all the answers: there are obvious technological devices that would have rendered this version of a shield useless, as well as clear reasons while perfect control over technology could not have been enforced. But the way he envisioned this future world, where everything important was the human being - as a thinking, feeling, believing creature - made it close to timeless.

Now, the plot is vast and the beauty of the book is in its minutiae, not in the overall story. This has been proved, I think, by the way people have received the 1984 David Lynch film adaptation versus the 2000 version. The first took "poetic licence" to change the story and make it more script like, but preserved the feel of the book, with the interior dialogues, the epic scenes and careful attention to minor details. The 2000 adaptation was completely faithful to the book in the way of following it scene by scene, but the lack of attention to punctual details made it unappealing and bland. There is a project called Dune for 2014, maybe that will give us another point of reference. So I will not talk about the plot and let you discover it for yourself. Enough to say that it is a great book.

It is important for me to talk about the difference between my personal interpretation of the book at different ages. When I was 15 I thought it was a glorious story of personal achievement, where Paul Muad'dib and Leto II were becomes gods by the sheer power of their thoughts and feelings. At 25 I thought it was a deep analysis of human interaction, of how logic, emotions and belief clash to mould our beings. And now, at 36, I feel like the book is brilliant, but I can read between the lines, see how the structure of the story was created from various sources; a bit of the mythos has lost its power, but gained more respect. If at 15 I was identifying with Paul and at 25 I was dreaming to become Leto II, now it's easier to me to identify with the likes of Gurney Halleck or even Feyd Rautha Harkonnen. I am not saying that I like them more, I just feel I gained more insight into the other characters. I say it again: Dune is a book of details (without being boring with them).

I cannot end this review without mentioning the Dune video games. I spent many an hour playing the adventure game Dune and many a day playing Dune II, the real time strategy game that was to inspire all others in the future. The game was so primitive that the controls were not designed for ease. Each unit was controlled individually and had very little autonomy, the result being that one rarely had time to blink when many units were constructed. This prompted my father to take me to a mirror and show me my own eyes. They were red and irritated. "Oh", I said, " it's from the spice!".

Thursday 11 April 2013

The Rise of the Dead

The last few years have been great for (un)dead people. Vampires have taken over the screens, even werewolves, the ridiculous people that in their greatest moments turn into mangy canines, have had their fair share of screen time and now it's the turn of zombies to have their days. Not that zombies were not done to death, so to speak, the same idea reinvented and rehashed, but basically unchanged. It was only fair that zombies become "mainstream" by appearing in a TV series: The Walking Dead. And they were not even the modern, raging running rabid type of zombie, but the slow and mindless, yet highly infectious kind. But hey, it's about supernatural monsters, a step away from sci-fi, so it is cool, even if it reiterates the same tired story of people that love drama too much and can't help fight each other and getting in the way of the undead when their emotions run high (which must invariably do so, else the characters would he boringly successful in avoiding any danger).

You might think that I am criticising the new zombie uprising because I am the kind of movie critic asshole that thinks everything sucks unless done my way, but it is not so. I have solid evidence that the undead genre can be awesomely innovative and deep in meaning. I give you three examples, all of them European, not because I am some sort of continentalist, but because the American stuff just sucks ass! I've decided to pointedly single out these three TV series and discuss them outside my "TV series I've Been Watching" section, because they prove without a shred of a doubt that TV can be for smart people, they are just not that many of them and it's not feasible economically.

Here it goes:
  • The Fades - this British series had dead people that could not go to Heaven turn on the living and becoming zombies, only smart, feeling ones, that just consider death is treating them badly and are lashing out. A brilliant take on the whole undead concept that went unexplored because the series got cancelled after a season. By far the best supernatural TV series of the decade, though!
  • In the Flesh - new British show that features actual zombies, the kind that eat on people. Unlike their American counterparts, they place the action of the film after the rise, when the undead are being "treated" and returned to their families. PDS (Partially Deceased Syndrome) sufferers have to deal with the reactions of small town people used to shooting undead on sight and being proud of it. Typical British thing to take a zombie idea and turn it into a deep exploration of social issues.
  • Les Revenants - last, but certainly not least, a French series about people coming back from the dead. They just come back, not remembering how they died and not knowing they did. People have different reactions to them and many have noticed the "Twin Peaks" feel of the series. Dark and psychologically violent, as only the French can make them, this is as far from La Horde as In the Flesh is from The Walking Dead. There was also a movie on which this series is based, which in English was translated as "They Came Back".

I highly recommend you watching these series. I don't care what the audiences were. In my view low audience to a movie or TV show can mean only two things: it was really bad, or it was really smart. I believe these three examples fall into the smart category.

Wednesday 3 April 2013

The big Wibyia screwup and the Google Drive refactoring

There was a web toolbar at the bottom of the blog called Wibyia. Damn if I know where these web startups get their names, but it is as good as any other, I guess. Anyway, the bar stuck at the bottom of any page and offered some tools, addons like chat and who is online, and a welcome message to new users. So here I am, pretty snug about my little blog, when I get an email from Wibyia: upgrade for free to the new version of Wibyia! So I click on it, I log in, Bam! a completely new design (a crappy "social" a brightly colored big and ugly thing), less features, a ridiculous admin interface and no way to revert to the previous functionality. At this point I got mad and removed the bar from the blog. If you somehow found it useful, let me know, I will write my own version.

But this prompted some research on the net on how to host files for the blog and I found that I can use Google Drive (in a rather convoluted way) to store the additional js and css I added on the blog. And so here is the new version of the blog, which should work the same, but hopefully load a little faster due to caching of the 50k js and css files.

Oh! And congratulate me for reaching the beautiful round number of 1024 blog entries today! >:-)

Monday 1 April 2013

Detecting if an URL can be loaded in an IFrame

I was trying to solve a problem on this blog, where the opening of links in their own fancy javascript window would fail if the server did not allow opening their pages in frames. The result would be an ugly empty black window and an ugly javascript error in the browser console in the form of Refused to display '[some URL]' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.

So I started looking for a way to detect these pesky URLs. First attempt was using jQuery.Ajax with method 'HEAD', which inquires the HTTP headers only from a given URL. There is no reason I can see to deny access to 'HEAD' requests, but the browser does it anyway based on... HTTP headers! Not to mention that this solution fails for more links than a frame because of Ajax cross-site scripting issues.

Second attempt: use an adhoc hidden iframe to detect if the URL can be opened. This worked, but at a cost that prohibits me using the solution in the blog. I will publicize it, though, maybe it works for other scenarios. It uses jQuery, so you will have to translate it yourself into the raw Javascript version or to make it use your favorite framework.

The code first:
var Result={
CouldNotLoadUrl:1,
UrlLoadedButContentCannotBeAccessed:2,
UrlLoadedContentCanBeAccessed:3
};


function isAvailable(url, callback, timeout) {
if (!+(timeout)||+(timeout)<0) {
timeout=5000;
}
var timer=setTimeout(function() {
ifr.remove();
callback(Result.CouldNotLoadUrl,url);
},timeout);
var ifr=$('<iframe></iframe>')
.hide()
.appendTo('body');
ifr.on('load',function() {
if (timer) clearTimeout(timer);
var result;
try {
var iframe=ifr[0];
var doc=(iframe.contentWindow||iframe.contentDocument).location.href;
result=Result.UrlLoadedContentCanBeAccessed;
} catch(ex) {
result=Result.UrlLoadedButContentCannotBeAccessed;
alt=ex;
}
ifr.remove();
callback(result,url,alt);
});
ifr.attr('src',url);
}
You use it like this:
isAvailable('http://siderite.blogspot.com',function(result,url,alt) {
switch(result) {
case Result.CouldNotLoadUrl:
alert('Could not load '+url+' in an iframe (timeout after '+alt+' milliseconds)');
break;
case Result.UrlLoadedButContentCannotBeAccessed:
alert(url+' loaded in an iframe, but content is innaccessible ('+alt+')');
break;
case Result.UrlLoadedContentCanBeAccessed:
alert(url+' loaded in an iframe and content is accessible');
break;
}
},10000);

You will need to have jQuery loaded and to have a html body loaded in the DOM (so if you copy these into an empty html file to test, make sure you add <body></body> before the script or execute isAvailable on the DOM Ready event.

And now the explanation.
First, it is imperative to first append the iframe element to body before binding the load event. That is because jQuery creates the element in a document fragment and this process fires a load event by itself! Then, different browsers act differently. Google Chrome does not fire a load event for an iframe with an URL that has this problem. Internet Explorer does fire the event, but the iframe's content document is not accessible (and this can be caught in a try/catch block). FireFox does fire the event, but only the leaf properties of the content document throw an exception, like the href of the location. In order to fix all of these, I used a timeout for Chrome, to return a false result after a time, then an access to ifr[0].contentDocument.location.href to make it throw an exception in both Internet Explorer and FireFox.

Finally, the reason why I cannot use it on the blog is that it would force the browser of the viewer to load all the URLs completely in the background in order to add a silly click event on the links. I have one more idea in mind, though, and that is to detect the frame loading problem when I open it and in that case to create the content of the iframe manually to contain a link to the URL. I will attempt it sometime soon.

Update: I found a solution that seems reasonable enough. When creating the iframe in which I want to nicely load the page that the link points to, I am not just creating an empty frame, but I also add content: a link that points to the same page. The SAMEORIGIN problem is still there, so the link opens the URL in target="_blank" and has a click handler that closes the dialog 100 milliseconds later. Thus, when changing the frame src, if the content of the frame does not change, the user will have the option to click the link and see the page open in a new tab/window.