Thursday, March 25, 2010

window.postMessage for cross domain communication

There are security concerns when communication between different HTML windows or frames occurs, that is why the communication is one way (from the child to the parent) and only if both windows are from the same domain.

Enter postMessage, an HTML5 feature, that allows sending messages that will be received as message events. Checking the origin (very important) and using with care the event parameter data, a simple string, is all that is required for a good relationship between friendly parties. window.postMessage is or will be implemented in Firefox, Opera, Safari, Chrome and even IE8.

Here is a link that describes the feature: Cross-Window Messaging.

Also, check out the jQuery cross-browser plugin that uses hashes to send data back and forth (naturally, the same mechanism should be implemented at both sides)

Infragistics, SnapToDevicePixels and Utilities.SnapElementToDevicePixels

I was trying to add some content to Infragistics WPF controls and some of the images used were blurry. I have tried setting SnapToDevicePixels, but to no visible effect. I did stumble upon a property in the Infragistics.Windows.Utilities class, called SnapElementToDevicePixels. I didn't know what it does, but I tried it anyway. Voila! The image got crisp and clear.

This is the comment from the property in the Infragistics WPF sources:

/// <summary>
/// SnapElementToDevicePixels Attached Dependency Property
/// </summary>
/// <remarks>
/// <p class="body">The SnapsElementToDevicePixels is meant to be used on elements such as an Image that
/// does not currently support SnapsToDevicePixels.</p>
/// <p class="note"><b>Note:</b> The RenderTransform of the element is used so you should not set the RenderTransform
/// on the same element on which you are setting SnapElementToDevicePixels to true. You may set the RenderTransform on
/// an ancestor element. Also, you should not set this property on an element that is an ancestor of one or more
/// elements that have this property set to true. In such a case the results are undefined since the child element's
/// RenderTransform could be calculated before that of the ancestor element. Since this property should be set on
/// discrete elements such as an Image, this scenario should not be required.</p>/// </remarks>

In order to use it, make sure you load the Infragistics.Windows namespace in your XAML:


and then set the Windows:Utilities.SnapElementToDevicePixels property to True.

Saturday, March 20, 2010

Using NetCat (nc) running in the background

Short version: use nc -dl portNumber instead of just -l

Netcat is a nice little tool that is very useful in all kinds of networking problems. Basically it listens on a port and it sends to ports via TCP/IP. Using the piping mechanism of Linux, one can send anything, from files compressed on the fly in the network stream to telnet sessions and back doors.

Today I was trying to copy a few files from a computer to another, therefore I did something like this:
tar -c -C /source/folder file1 file2 file3 | nc theOtherComputer portNumber
on the second computer I did this:
nc -l portNumber | tar -x /destination/folder

And it worked perfectly. I made all kinds of cool stuff in the bash scripts and then, wanting to execute the "server" in the background I did:
serverApp &

From then on, nothing worked. The sender would report success, the received file would always be truncated. After trying all kinds of things, I stumbled upon the -d switch of the nc tool. The man page says: -d' Do not attempt to read from stdin.. It appears the application is trying to keep a reference to the input of the starting environment. It makes no sense for a listening scenario, but it does it anyway. Failing to find one (since it is runnning in the background), it just exits earlier than expected.

So, whenever you want to use NetCat listening in the background, don't forget to use the -d switch.

Monday, March 15, 2010

Reaper's Gale by Steven Erikson

Book coverReaper's Gale, the seventh book in Steven Erikson's series called The Malazan Book of the Fallen made me feel all kinds of things. There was boredom a lot of times, there was uncomprehension in others, there were moments when tears flowed from my eyes as well as great moments of tension. At the end of it, I feel unqualified to actually discuss it. It is still a great book, it ends with a convergence of paths, as all the others have, but it somehow felt different from the previous six books.

I believe that Erikson fell into a well known writer trap. He was so caught in his own world, that he forgot most readers are not, and cannot be unless with great effort. Therefore the characters got out of control. They did things as they pleased, regardless of the reader's need. That is why I think this book was weak compared to the others.

The plot is too complex to expand here. Enough said that Icarium, Karsa Orlong, Quick Ben, Mael, The Errant, Fiddler and Hedge, Bottle and Beak, The Adjunct and Lostara Yil and all the Bonehunters, they all meet in Letheras. Even after reading the book you don't get to know why all that buildup was for, why in the last 50 pages all the characters acted so strangely, where Karsa and Icarium went and, most of all, why did a woman Seguleh have such a small part! The dragons (all of them) are beaten senseless, the Sengars have the worst of luck and the t'Lann Imass are just peripheral characters.

As did the sixth book, but at a larger scale, more avenues are opened than closed. I can barely wait reading the eight book, but I feel cheated a bit. Hope lives on, though :)

Thursday, March 11, 2010

The collapse of capitalism

Yesterday I was talking with friends of a weird situation near my home: there are 3 pharmacies in the same building and 3 others very close by. Well, pharmacies and banks have the same business model, if you think about it, so no wonder there. What felt a bit strange is that in the building there was the pharmacy that I have been buying medicine from my youth and recently it was bought by one of the larger pharmaceutical chains and converted into a flashy, colorful and very expensive venture. The same happened to a company called Plafar, a Romanian company opened in 1999 with state capital which specialized in natural remedies, infusions and so on. In 2007 it was purchased by a pharmaceutical chain that loses its origin in the vagaries of stock exchange. Now all they sell is terribly expensive as well.

So yes, I think that is strange as seen from the naive view of free market in capitalism. You have a competitive segment of the market, providing no bullshit service at low price, being bought and replaced by the people that gain at least half of their money by overpricing. It's like a virus (A virus enters a bar. The bartender says "We don't serve viruses in here". The virus replaces the bartender with a copy of its own and says "Now you do") and it spreads especially fast in a low immunity environment like a freshly "liberated" country like Romania.

What is going on here? Well, since we are in the medical/pharmaceutical context, let's address the notion of economic health. At they say The value of stock market indices seem to be the barometer many use for the health of the economy.. Well, that is not what I had in mind. What I think is health in an economy is how fresh growth is not hindered, but nurtured. Just as in the human body, disease impedes growth and disables functioning mechanisms that are vital to life. Are other countries healthy? No! They are in the same kind of crap, only there it is harder to suffocate others.

Is there a solution? I don't know. But a full ecosystem is needed to promote health. When only predators remain, the land dies.

Making Internet Explorer load lightning fast

I have been using Internet Explorer as my main browser since IE 3.0 and usually I have no problem with it. I know the rendering engine is a piece of crap, but I got used to the feel of it and the developer tools in IE8 are nice and FireFox just rubbed me the wrong way, so that was that.

But since Internet Explorer 7 upwards, and especially with IE8, the first loading of the browser got slower and slower. So slow, in fact, that I have to wait several seconds for the browser to allow me to use the address bar. No wonder I have been slowly using Chrome for searching and reading the news and all that.

Today I got kind of annoyed with it and started looking into the Internet Explorer options. An advanced one was Enable third-party browser extensions and I removed it, just to see what it would do. Suddenly I had no Google toolbar (but I don't use it anyway, since I enter all my searches in the address bar), Flash worked, the pages worked, the internal IE8 developer tools worked. The only difference is that Internet Explorer would load instantly!

Ok, that would work as a last option, but I got intrigued so I enabled the option again and went into the Manage Add-ons section. I haven't being paying attention before, but each add-on in the list also has displayed the loading time. I looked around and I found Groove GFS Browser Helper that loaded in ... 8.2 seconds! Disabled it: almost instant browser loading. Two other addons had over one second load time, both of them from Sun and related to Java (which almost no one uses anymore in web pages). Disabled them and now I have my browser back! Just for the sake of it I googled for Java Applet and went to a site with a Java on it. Amazingly, the applets all worked! So the addons themselves were not responsible for loading Java, they were just useless junk.

But what is this Groove thing? Is it some malignant Microsoft rival that purposefully makes its browser addon load slower as to sabotage Internet Explorer (hint! hint!). It appears not. As it usually happens, the greatest enemy of Microsoft is Microsoft itself: Groove comes from Microsoft Office 2007!

What does Groove Syncronization do? Microsoft Office Groove was designed for document collaboration in teams with members who are regularly off-line or who do not share the same network security clearance. In other words: nothing useful. Even better, the whole groovy thing can be easily uninstalled, which I also did.

To uninstall Groove go to Add or Remove Programs, look for the Microsoft Office entry, click on Change, remove Groove. That's it!

Wednesday, March 10, 2010

Sunday, March 07, 2010

Css LESS jQuery plugin

I've heard about LESS yesterday so I thought about how I would use it in my projects. Using a .NET http handler is just fine, but I was thinking of a simpler approach, so I created jQuery.cssLess, a jQuery plugin that reads the css and interprets it. You can find it at Github.

Current version supports variables, mixins and nested rules. I am wondering if it is even worth it to implement operations. It may bloat the plugin too much. What do you think?

Little did I know, someone else was trying a js centric approach to this. The project is called less.js and it's made by cloudhead. You can find it at GitHub.

If you are using LESS and decide to use jQuery.cssLess, please leave me a message about it and whatever your opinions are.

Tuesday, March 02, 2010

WPF Binding expression that depends on a parent that might or might not be there

I had this control that functioned as a textbox. The request was that it behaved differently when used as an editor in a grid and was in the "add new record" line. I agree that the best solution would have been for the grid to set a property to the editor when placing it somewhere or at least when adding to the grid, but that is not relevant.

The solution was, of course, to add a DataTrigger that would check a property of the parent grid row object, by using RelativeSource and FindAncestor. However, that approach resulted in an ugly binding error in the Visual Studio debug view window when the textbox was being used stand alone. It didn't break execution, but I kind of disliked it.

The solution, at first, was to use a Converter. However, the converter class does not apply to the RelativeSource, but to the referenced property. The binding would first look for the parent row, find nothing, then return a null reference exception when trying to access the path property.

Another solution would be to look for the parent in the LayoutUpdated event (only the first time) then look for the trigger and enable or disable it. Yet another is to reference a property that the textbox would set depending on the parent found above. Both solutions would be cumbersome if you don't have ownership of either control.

It appears that there is no way to determine the way a relative source is found. I don't know if they changed that in the WPF4 implementation, but it would have been a nice touch. That being said, I believe one can create a custom Binding object to take care of this. I will update the post with some sources when I get to working with WPF again.

Update: I've reached the conclusion that the problem is the question, not the answer. In order to make an element have a certain behaviour when a child of another element, a style should be added to the resources of the parent. This way, the problem is solved. I agree that sometimes it is cumbersome to do so, but the alternative is that your control will always search for a parent that might not be there. So, the solution is to make the parent make the child do what you want.

Monday, March 01, 2010

Javascript's eval Scheme

This weekend I participated in an advanced Javascript training (and workshop, as it turns out) gratiously offered by Frontend Force, a company specialised in professional Javascript code (not web design). That means they do stuff for browsers, for cell phones and even (if you didn't already know) for the server-side platforms running on Javascript. At this moment they are hiring for positions in Berlin (no remoting) and are looking for true IT professionals, preferably with strong Javascript knowledge. So contact them... now! They also do consulting.

The trainers were Dawid de Rosier and Piotr Zwolinski, both from Poland, more the former than the latter, and I have to say that I've learned quite a few new things and understood better things I already knew, just from Dawid's 6 hour presentation. The training was great also because it happened in the weekend, so I didn't have to feel guilty for skipping work from my regular job or to feel bored doing nothing in the weekend. I say 6 hour presentation because the next day we did an application in typical agile manner, working in teams and applying the things we've learned. The project can be found on the net, it is open, and it is a ... shopping cart. I know, terribly boring subject, but the code was the focus and the code was cool (at least my part, of course... :) ). The link for the project is this: 3F Commerce. But enough of that, after all the coding experience cannot be translated into a blog post, I will talk mostly about the presentation in the first day and the things I've learned there.

It should be interesting enough to get your attention that the training was about the Javascript programming language not its use in the browser. After all, Javascript is a stand alone language and, as you will see to the end of the post, used in a lot more contexts. Its roots stem from Lisp, Scheme (hence the title of the post), Self and a bit of Perl and the syntax is C like because it was cool at the time (and it still is, maybe the Perl guys should have thought of that). The name Javascript itself was used as a marketing ploy because Java was all the rage back then.

As a dynamic language its most proeminent features are the protoype based inheritance and the closure/lambda approach to variable scope. One of the most important things, if not the most, that I have learned is that each function remembers the context in which it was created. For procedural style of programming in Javascript, the context is the global one, so many people don't know or care about it. Short example:

function createMyFunction() {
var x = 11;
return function () {
Now if you execute var f=createMyFunction(); f(); you get a message box with a value of 11. The x variable is remembered, even if in the scope of a function that is not longer in execution. I will show you later how you can create truly private members of a class or function. Well, in Javascript there are no classes, only functions, but they have a different meaning from, let's say, functional programming.

First of all, we talked about the variable scope. Javascript does not have block scope. That's important. It means that if you do something like

if (condition) {
var x = 10;
you will get an alert with the value 10. The only scope is function scope in Javascript, meaning that to get the same effect as a block scope, the previous example should have looked like this:

if (condition) {
(function () {
var x = 10;
and now you would get undefined.

Then we delved into apparently obvious stuff like

var x = 'true';
if (x) alert(x == true);
The code above would display false. Why? because there is an equality between different types and they are both converted into... numbers! true gets an internal representation of the true value, while 'true' gets the value NaN, as it is not a number. And they are not equal. The condition itself is satified, because x is not empty.

With these two things explained (better than I can here) it was concluded that global variables should be avoided, while in order to do equality one should use the triple equal sign === which compares not only the values, but also the types. It is also much faster, as it doesn't try to convert anything. One good use of the normal operator == is when comparing to null. Let me exemplify:

null == null //true
undefined == null //true
0 == null // false!
This is better than using a variable as a condition of 0 would not execute an if block.

The next bit was about functions and how you can use them as classes. Here it was explained how functions remember their environment. This kind of functions are called closures. An interesting thing you need to understand in Javascript is that the closer the variable is from your execution scope in the execution hierarchy, the faster its access is. Let's take a very common function: document.getElementById. Here is a faster version of it:

var byId = (function () {
var D = document;
return function (id) {
return D.getElementById(id);
This is faster because byId is a closure and it gets a reference to the document (slow global variable) at its creation and remembers it in the environment. Every time you execute it, it will use the closest scope to find the variable and it will be faster. On my Internet Explorer 8, byId is faster than document.getElementById with 22%.
A very important thing to see here is that D is not accessible anywhere outside the function. Not even byId.toSource would show where D is created. So, indeed, it is a private member of the function!

A lot of stuff was discussed about random but important quirks of the language.
  • There are two main categories of types in Javascript: primitives and objects. For example '5' is a string primitive, while new String('5') is an object. The String object has methods, like toLowerCase. Yet '5'.toLowerCase works, because the primitive is automagically converted into the corresponing object.
  • The instanceof operator checks if a certain object is of a certain type. Kind of useless, since each object can have whatever members one defines dynamically and implemented in whatever way. Needless to say '5' instance of String is false. Or maybe not so needless :)
  • Each function has a special local variable called arguments, which represents an array of arguments passed to the function (no matter how many were defined in the function signature). This object has some special members like arguments.callee, which represents the function being executed. See how it is used to create an anonymous recursive function:

    var x = 10;
    (function () {
    if (x > 0) argument.callee();
  • Another fun thing is that there is a default undefined object. You can compare something with undefined: if (x === undefined). Unfortunately, undefined is not a reserved word. So this code is valid: undefined=10;. Just compare the type to the string 'undefined': if (typeof(x)==='undefined').
  • Most Javascript coders are familiar with the in keyword that is used to create foreach like loops: for (var key in hash) do(hash[key]);. Very few know that 'in' is also an operator: if ('x' in a) { do (a.x); doAgain(a['x']); }. It checks for the existance of a property in an object or its prototype. If you want to know if the property if of the object or of the prototype chain, use the hasOwnProperty method. Prototypes will be explained shortly.

I've spoken a little about private members, but now I will tell you about inheritance! Yes, it is possible in Javascript, who would have thought? :) Only it is a prototype inheritance.

What are prototypes? Each function has an object that would be used to return default values for any of its instances called prototype. It's kept as a reference, so only one prototype object for any number of instances. This prototype, as almost anything in Javascript is writable, replaceable, extendable. Let me give you a short example:

function MyClass = {};
var m = new MyClass();
MyClass.prototype.someProperty = 'set';
m.someProperty = 'overwritten';
delete m.someProperty
This code defines an empty function called MyClass. You use it as a type and create instances of it by using the new operator. The first alert will show 'undefined' because the instance has no someProperty member. We then set it in the prototype and so it will be seen in any of the instances of MyClass, so the second alert will show 'set'. Then we set the actual value directly in the object. The third alert will display 'overwritten'. Delete the value (unset it) and the fourth alert will display 'set' again.

So what about inheritance? Let me give you the short story:

function MyClass(msg) {
// optional
// ParentClass.apply(this,msg);
var F = new Function();
F.prototype = Parent.prototype;
MyClass.prototype = new F();
MyClass.prototype.constructor = MyClass;
Here we create a MyClass object that inherits from ParentClass. In its constructor we apply the ParentClass function in the context of the MyClass instance (if we want to), then we create a new temporary F function in order to copy the prototype, but not whatever values are set via the constructor and we set an instance of it as the prototype for MyClass. Then we recreate the constructor of MyClass in its prototype, since it was overwritten.

Too fast? Let's examine what would happen when a new MyClass instance is created:
var m=new MyClass(msg);
  • the instance of the F temporary class which holds any and all of the members in the prototype of ParentClass is the prototype of MyClass
    the MyClass prototype is different from the ParentClass prototype, so any changes done to it are not reflected to the ParentClass prototype
  • the constructor of MyClass (itself) is executed in the context of the new instance which executes the constructor of ParentClass in the same context and thus sets anything that the parent class would set to its own instances

Now the new instance has all the default members an instance of the ParentClass would have and its own members or overwrites of the existing ones. Inheritance!

To end this over long post, I will give you a piece of code of a class that inherits another class, has private members, setters, getters, etc.

(function () {
// base class
Animal = (function () {
// private member
var _version = '0.9';
return function () {
// priviledged getter (public, with access to the private member)
this.getVersion = function () {
return _version;
// priviledged setter
this.setVersion = function (value) {
_version = value;
// prototype public method (only one referenced in all instances of Animal)
Animal.prototype.MakeNoise = function () {
throw "Abstract animal class must be inherited";
// prototype public method
Animal.prototype.getType = function () {
throw "Abstract animal class must be inherited";

// child class inherits from Animal
Duck = (function () {
// private member
var _type = 'Duck';
return function () {
// call the base constructor;
// priviledged getter (no setter for _type!)
this.getType = function () {
return _type;
// set version using base class method
// hide base class method (emulation of protected methods.
// of course, one can use delete a.setVersion
// and then access the base method)
this.setVersion = function () {}
// copy the base class prototype
var F = new Function();
F.prototype = Animal.prototype;
// set it as the parent prototype
Duck.prototype = new F();
// prototype public method
Duck.prototype.MakeNoise = function () {

var a = new Animal();
alert(a.getVersion()); // 0.9
try {
alert(a.getType()); // error, abstract getter
} catch(e) {
alert("error! (" + e + ")");
try {
a.MakeNoise(); // error, abstract method
} catch(e) {
alert("error! (" + e + ")");
a = new Duck();
a.setVersion('999'); // no effect, since setVersion was replaced with empty function
alert(a.getVersion()); // 1.0
alert(a.getType()); // 'Duck'
a.MakeNoise(); // 'Quack!'

Some more information about tools that one can use in javascript programming:
Aptana - standalone js IDE and also Eclipse plugin
Rainbow9 - javascript IDE as a web application
QUnit - unit tests for javascript
JsLint - checks the validity of your javascript code online - reformats javascript code
Closure Compiler - minimize javascript code
JSA - obfuscator (it's an untranslated Chinese site, just use the last button)
Xmake or Rmake - code builders
NodeJS - javascript powered server side framework
jsDocs - makes documentation (specific comment formats are required)
JS TestDriver - unit testing and integration
Persevere - makes the connection between javascript fron ends and server side databases