Wednesday 28 December 2011

Emulate Java Enums in C#

Enums are a really useful and simple programming construct. In C, C++ and C# an enum type is little more than a set of restricted numeric values that we can assign to a variable declared as such. In C#, there are 3 main static methods that we'll need when working with enums:
Let's say we have a Planet Enum:
enum Planet{ Mercury, Venus, Earth }

  • Get the string value from an enum:
    Enum.GetName
    Enum.GetName( typeof(Planet), mode)
  • Convert a string to an enum type
    Enum.Parse
    Planet myPlanet = (Planet)Enum.Parse(typeof(Planet), "Venus");
  • Retrieve an array of the values of the constants in a specified enumeration. Enum.GetValues
    Planet[] planets = Enum.GetValues(typeof(Planet));

So far so good, but sometimes it's not enough. Something rather common is the need to assign some extra string values to the enum (something beyond the name itself), for example a description. The common solution in C# for this is using a custom Attribute.

That should seem enough, and it used to be, until Java got enums in version 1.4, and we learnt from there that enums could provide a much richer (and more OOP) experience. The Planets sample is really interesting and mind opening. As you can see, an enum in Java is just a normal class, with data fields, properties and methods, the only special thing is that it has a limited number of possible values. Besides the infrastructure provided by the base Enum class, the Java compiler does a nice job for us, generating a class for our enum, inheriting it from Enum and adding some methods to it like valueOf and values (diassamble the .class for your test enum and check the bytecodes, do something like: javap -v MyEnum.class > MyEnum.bytecode)

One work around in C# for simple cases would be adding behavior to a normal Enum through Extension Methods (we can also add data by placing it in the helper class containing the Extension Methods, this way avoiding the Attributes approach that I pointed out before):

public enum Planet
{ 
 Mercury, 
 Venus, 
 Earth 
}

public class PlanetData
{
 public double Mass
 {get;set;}
 public double Radius
 {get;set;}
 
}

public static class PlanetHelper
{
 private static Dictionary planets = new Dictionary()
 {
  {Planet.Mercury, new PlanetData(){Mass = 3.30, Radius = 2.43}},
  {Planet.Venus, new PlanetData(){Mass = 4.86, Radius = 6.05}},
  {Planet.Earth, new PlanetData(){Mass = 5.97, Radius = 6.37}}
 };
 
 public static readonly double G = 6.67;
 
 public static double GetRadius(this Planet pl)
 {
  return planets[pl].Radius;
 }
 
 public static double GetMass(this Planet pl)
 {
  return planets[pl].Mass;
 }
 
 public static double GetSurfaceGravity(this Planet pl) 
 {
  return G * pl.GetMass() / pl.GetRadius() * pl.GetRadius();
    }
 
    public static double GetSurfaceWeight(this Planet pl, double otherMass) 
 {
        return otherMass * pl.GetSurfaceGravity();
    }
}

You can check the source here

Something like the above should be enough for most cases, but anyway, what if we want to simulate as much as possible the Java case?. Reading this StackOverflow discussion is a must

. The solution given there is pretty good, but why not to try to go the Java way and generalize as much functionality as possible to a Base class.

Before showing my solution here, I'd like to note that Java enums have another very interesting feature that I found out when reading this excellent article. One method can vary across instances, I mean, each enum value can have a different implementation for one method. Well, hopefully, in the .Net arena delegates come to our rescue, making it very simple to add that extra feature

All in all, this is what I came up with:

public abstract class AdvancedEnum
{
 public Enum InternalEnum;
 //notice that this Name (as Java's Name) is similar .Net's Enum.GetName()
 public string Name
 {
  get
  {
   return this.InternalEnum.ToString();
  }
 }
 
 //notice that this ValueOf (as Java's ValueOf) is the equivalent to .Net's Enum.Parse()
 public static T ValueOf(string name)
 {
  return (T)(typeof(T).GetField(name, BindingFlags.Public | BindingFlags.Static).GetValue(null));
 }
 
 public static IEnumerable Values()
 {
        //this is really weird, for some odd reason you need to use "+" instead of "."
  string tpStr = typeof(T).Name + "+" + typeof(T).Name + "Enum";
  Type tp = Type.GetType(tpStr);
  //notice that .Net warranties that values are returned in the same order as they were declared
  foreach(var item in Enum.GetValues(tp))
  {
   yield return ValueOf(Enum.GetName( tp, item));
  }
 }
}

public class Planet: AdvancedEnum
{
 //naming is important here, we use as a convention that the internal enum must be named thus: className + "Enum"
 public enum PlanetEnum
 {
  MERCURY,
  VENUS
 }
 
 //"method" that will vary across instances
 public Action Live;
 
 public static readonly double G = 6.67;
 
 private double mass;   // in kilograms
 public double Mass
 {
  get
  {
   return this.mass;
  }
 }
 private double radius;
 public double Radius
 {
  get
  {
   return this.radius;
  }
 }

 private Planet(PlanetEnum internalEnum, double mass, double radius, Action liveAction)
 {
  this.InternalEnum = internalEnum;
  this.mass = mass;
  this.radius = radius;
  this.Live = liveAction;
 }
 
 public static readonly Planet MERCURY = new Planet(PlanetEnum.MERCURY, 3, 2, () => Console.WriteLine("living in Mercury is impossible for humans"));
    public static readonly Planet VENUS = new Planet (PlanetEnum.VENUS, 4, 6, () => Console.WriteLine("living in Venu would have been possible for humans milleniums ago"));
 
 public double GetSurfaceGravity() 
 {
  return G * this.Mass / this.Radius * this.Radius;
    }
 
}

You can check the source here

I plan to experiment a bit with enums in JavaScript, but for the moment, you can check this article I came across with

Monday 26 December 2011

The Debt

The Debt is an absolutely impressive film. I had read very good critics about it, but I don't think they praised it enough. Maybe it's because it brings together many different elements that I pretty much like: the state of Israel, the Holocaust, Berlin, Revenge...

But above all this is a film about lying and fleeing. A past lie shapes the life of 3 (well, many more) Israeli who deal with it very differently. It's a justified lie, a lie I think I would have been happy to tell and would have no had problems to live with, but that's not the same for one of the characters, who has been unable to deal with it, being haunted with it for the ensuing 30 years of his ruined life. In the end, that allegedly buried dramatic event of the past is about to come back to life, casting its shadow over a fairly increased "public", and the 3 characters will try to come to terms with it following very different approaches.

These 30 years have been a continuous flight for our 3 characters, and also for the Nazi butcher. Now they'll have to decide whether to continue the flight or put a painful end to it. The same doubts they were confronted with in an old flat in Berlin 30 years ago will assault them now in Tel Aviv and in a Ukrainian hospital.

Not much more to add, just to remark how excellent the interpretations by both Jessica Chastain and Helen Mirren are. That's all, now just go and watch it!

Wednesday 14 December 2011

Some interesting stuff

Just a compilation of links of interesting programming stuff that I've come across with in the last days and that I would like to note down for future reference

  • I think it's commonly accepted that C# is a much more expressive language than Java, I've already written indirectly about it in some other posts, but given that I try to be as language agnostic as possible, and try to learn lessons from all languages I know, I think it's good to acknowledge some of the strong points of Java. I don't miss Anonymous classes in C#, but Java class-like enums are something that I've been pretty jealous of since I first heard about them, and the Method return type covariance really caught me by surprise.
  • Continuing with Java, I was rather interested to see how the long awaited invokedynamic thing has improved the overall Java experience. Long in short, it's a great addition to the JVM platform, but for the Java language itself it adds quite little. If you were expecting something similar to C#'s dynamic keyword, forget about it. However, contrary to C# dynamic that just comes down to a lot of compiler magic, the JVM has been enhanced to deal with invokedynamic. This old post is a great source of information.

    The biggest changes in Java 7 are not related to the Java language at all. Sure, there's the "project coin" enhancements to the Java language, which add some exception-handling shortcuts, new literals for numbers, arrays, hashes, the oft-requested "strings in switch" support, and a few other things. But they're modest incremental changes; the real revolution is at the JVM and JDK level.
  • After reading this excellent interview in InfoQ discussing the new Groovy candies, one of the things that really caught my eye is passing closures to annotations. That would be the equivalent of passing delegates to attributes in the .Net world. This feature does not exist, but it's interesting to see how some people were requesting it some time ago. The AST transforms seem quite in line with some of the things that Roslyn has to offer or with Boo's Syntactic Macros
  • As I said in a recent post, time seems to fly, and much more when we talk about technology. Last time I had tried to create a bootable flash drive it was still rather troublesome, so when last week I stumbled upon this site and found out how easy it's to create a multiboot flash drive, I felt delighted.

Monday 12 December 2011

Atomised/The Elementary Particles

Another excellent German film. At first sight this hilarious work could seem quite apart from my common tastes (horror, dystopias, social unrest...) but I've had a really enjoyable time with it, well, in fact it ends up being a very human film, maybe it's because I'm right in the age group to get some sort of identification (hey, don't take me wrong, I'm not such a loser as Bruno)

This is the story of two brothers with very different lives: Michael is a scientific genius, Bruno is a frustrated everything (teacher, writer, father, play boy...) but a common problem, their (lack of) sexuality, and quite different approaches to tackle it (remove the need for sex by developing cloning techniques vs harass teenager students and join a free love camp...) Bruno (the frustrated writer, by the way he portrayed Baader in The Baader Meinhof Complex) has the main role in this film, as the funniest moments (and also the harshest ones) gravitate around his pathetic adventures (his racist prejudices, his bonobo like attitude, his dramatic attempts to gain other's simpathy...). Maybe his character was so fun to me cause in some of his actions I could try to put faces that I know in real life :-)

Be warned that there's more to this film that all this fun, while the 2 first thirds of the film will mainly make you laugh like hell, the last part will make you reflect about the tough situation presented there and about life in general, mainly if you're at that age when you still see yourself too young for some "für immer" decisions, but too old to continue wandering aimlessly

A must see film that I would leave in store to ease a bad day

Tuesday 6 December 2011

And time goes by

I think I tend to be rather aware of how fast time passes, how our precious minutes get consumed, but even with this in mind, sometimes something comes up that makes me even more conscious of this fact.

Yesterday, one piece of news that probably will have gone unnoticed for many people (that increases that feeling of time running away), clearly reminded me of it. Napster is over. Napster, the first P2P application, the one that opened a new world of unlimited access to music to many of us, is no more. I remember getting late to a Saturday night meeting with friends cause I was eagerly waiting to see if I managed to finish the download of a much desired disc (through my old good 56 kbits modem with flat rate connection only from 18:00...). It's been 11 years since that, and many, many things have changed. Drawing up from Napster's success many other P2P sharing applications flourished (and rapidly faded away): Kazaa, WinMX, AudioGalaxy, eMule... BitTorrent seems to be one of the few that is still in pretty good shape.

I would say we've almost reached the point where we're not aware of how things (in the technological world, unfortunately other areas have not nearly seen this level of evolution) have improved, how now we take for granted things that just 5 years ago were unthinkable. We're in the middle of an Accelerating Change, just think for a moment:

  • Online video (YouTube, DailyMotion and so on...) in 2003 the common perception would be that there would be no bandwidth enough (not at home, but in the internet itself) for transmitting all those bytes.
  • Free WiFi in almost every coffee shop in town (well, I'm talking about my town, oddly enough, it's harder to find a Free WiFi in London or Berlin that in Xixón)
  • Dual core 1GHz processing monsters weighting just 200 grams and living in your pocket. It's funny when I look to the heavy and bulky old desktop PC lying in a corner of my room, with 392 MBs of RAM and a 800MHz processor and think of how well it served me as my main Programming and "multimedia" platform until 8 years ago.
  • With those 1 and 2 TBs external disks sitting on your desktop, do you remember the last time you burnt a data DVD? Did you ever use your old PCs as "storage server" in your local network? It seems like an odd occurrence now
  • Do you remember those times when owning a laptop was only for wealthy guys or for the "important people" of the company?
  • Internet everywhere thanks to affordable 3G data connections. This is something that left me astonished 2 months ago when I switched to my new Mobile phone operator. They have a monthly flat rate data plan (even for pre pay users like me) for just 9 euros. I don't need that service, it would be useful to me only when I'm abroad (I guess that's one of the pending things that we'll see changing in a short time, flat rate data access everywhere, at least in Europe) but if you need it, it's rather affordable.
  • GIS for the massess!!! Google Maps, Bing... and one million applications based on them
  • Home bandwidth. I've got now a 15 Mbits (download) connection at home. This is how my bandwidth (download) has evolved ever since I have internet at home:
    • 2000: 56 Kbits Modem (I think there's a generational gap between those who are familiar with the noise of a Modem when dialing and those who aren't)
    • 2001: 128 Kbits with my Cable operator (the only one I've had so far)
    • 2004 (August), 160 Kbits
    • 2005 (May), 640 Kbits
    • 2007 (February), 1Mbit
    • 2009 (June), 10 Mbits
    • 2011 (May), 15 Mbits (not an advertisement trick, you can see below that you really get that speed )

The other day I was chatting with a friend (a C++ guru, not a "humanities" guy) and he told me with his brand new smartphone on his had "I'm fed up with 3G, it's so slow that I have to use WiFi when I'm at home". I was astonished, we've grown so accustomed to the marvels of technology that we expect more and more from it, and dare to think that 3G should be as fast as our home WiFi!!!

I can't close this post without saying a clear and loud THANKS NAPSTER!!!

Friday 2 December 2011

FIC Xixón 2011

One more year has passed, and this odd Autumn (almost no rain, summer like temperatures... shit, I love my normal dark, rainy Asturian autumns... bloody climate change) has brought us a new edition of Xixón's Film Festival. This year I could attend to 9 films, and my perception was pretty good, there are only 2 of them (well, maybe just 1) that were not worth my time (and I already suspected these films would not fit my taste, but had nothing more to choose for that session), all the others ranged from entertaining to excellent.

  • Viva Riva by Djo Tunda Wa Munga, Congo/France/Belgium (sounds like colonization revival :-), Rellumes section (Friday 2011/11/18)
    I think this is my first African movie, and it's pretty good. A story full of violence, sex and action, Kinhasa has almost run out of gas, and that turns Riva, a gas smuggler, into one of the big men of the city. He chases after an African beauty, and a bunch of ruthless criminals chase after him and his gas. It's interesting to see how even in these times of global everything... attitudes towards, sex, violence, money, and life in general are still rather different depending of our geographical location.
  • Take Shelter by Jeff Nichols, USA, Official competition (Saturday 2011/11/19)
    Excellent film. Some people could had been misled to think that this would be one more apocalyptic film (that's neither good nor bad for me, there are some "end of the world scenario" films that I really like), but not, this is not one of those films. Well, in fact maybe it is, but a different kind of apocalypsis. It's not a natural disaster or man made threat what the characters are really presented with, but a personal disaster, one of the worse that one can imagine, losing control of your mind and being aware of it. The hell descends upon an Ohio family when the householder, whose mother has been suffering from schizofrenia since her thirties, starts to suffer from delusions, paranoia and terrible nightmares. There's a very interesting situation here, while he's pretty aware of the severity of his case and the high chances of him going crazy, he just can't avoid to carry out some plans based on what his delusions and paranoias tell him. I would consider this a very harsh film, a drama that almost turns into horror, internal horror. It grows in intensity as it moves forward, reaching some devastating moment at the end. A must see film.
  • Unfortunately I could not attend to any film on Sunday, as I was selected (it's a draw where any Asturian (well, any Spaniard) older than 18 can be selected, no volunteers here...) to waste the whole day working for the electoral system (you're seized by democracy to collaborate with it under threat of prison if you refuse, no matter if you're an Anarchist or are fed up with their System)
  • Essential Killing by Jerzy Skolimowski, Poland/Norway/Ireland/Hungary, Generos Mutantes section (Monday 2011/11/21)
    Rather interesting film. It's not the masterpice that the guy that introduced the film praised, but certainly a rather good one. One Taliban is taken from Afghanistan to Europe and manages to scape, wandering through a forest in in the middle of Polish winter. A harsh depiction of the fight for survival in a very hostile environment enriched by the empressive natural landscapes (the Afghan mountains first and the European forest then). Some people try to do a sociopolitical reading of the film, the director has denied it, and I'm on his side, I don't think he would have chosen a Taliban shithead as main character if he wanted people to feel identified with him.
  • Faust by Alexander Sokurov, Russia, Official section (Tuesday 2011/11/22)
    Long in short, I didn't like it. Well, I quite liked some visual passages, but the development of the story was quite uninteresting. I've not read the book by Goethe, but given its masterpiece status I'd like to think that a much better film adaptation could have been done. During the first hour I had to strive to not fall asleep, then things got better, but it was just only the excitement of thinking how the end was getting closer...
  • Hors Satan by Bruno Dumont, France, Official section (Wednesday 2011/11/23)
    Terribly boring film, the plot lacks of any interest (well, there's hardly any story being told) and it's just a few sequences along the film mixing violence, sex and oddity what prevents you from falling asleep. By the way, this film presents us with one of the most disgusting sex scenes that I've seen in a long while...
  • Punk's not dead by Vladimir Blazevski, Macedonia, Rellumes section (Thursday 2011/11/24)
    I pretty much enjoyed this my first Macedonian film ever. The synopsis really caught my attention, some 40 something punks in the ramshake city of Skojpe intending to relive their old band. Once in the cinema the story turned out to be pretty good, many fun moments, and an excellent way to show us different tough aspects of the life in Macedonia (that can apply to a good part of the ex-Yugoslavia). The director could have slapped us with each of those aspects: ethnic conflicts, lives and social networks broken by the Western sponsorized civil war, alienation, escape from reality through fucking chemicals... but instead, he preferred to show all this in a soft way, more like a pinch, but one of those which stinging remains with you for a long while. This was the only "meeting with the director" session I could attend this year, and it was outstanding. Vladimir Blazevski gave an introduction that really shocked me, he told us how special and touching this film had been for him, after a 17 year hiatus due to the state of shock in which the break up of Yugoslavia, the fall of the socialist system and the devastating civil war had left him. Once the film finished and excellent discussion with him followed. There he explained (slowly, with a discourse full of details and in a sad and reflective voice) that he had never been related to the Punk counterculture, but that he chose it for this film because of their condition of outsiders, of people that do not seem to fit... just how he felt after Western democracies and the Vatican decided to destroy Yugoslavia.
  • The Stoker by Alexei Balabanov, Russia, Rellumes section (Friday 2011/11/25)
    One entertaining film by Balabanov, indeed I liked it quite more than his other 2 films that I'd previously watched. This said, I don't understand why he has gained the cult status that he seems to enjoy, to me he does entertaining violent films, just that, nothing more. At least this time he shows signs of some social awareness, thing that I absolutely missed in his stupid "Russian Rambo in Chechnya" (War) film. This film (same as Cargo 200) reflects the state of disgrace in which Russia lives after the fall of the Communist State, but I don't think Balabanov has any kind of political intention (OK, yes, I have to admit it, I feel some aversion for this guy because of his stupid antiChechen film)
  • Michael by Markus Schleinzer, Austria, Official section (Saturday 2011/11/26)
    A great surprise. Based on the synopsis I had many doubts about this film, but it was the one that better suited my schedule. It could be a masterpiece or it could be an unbearable "experimental" piece, hopefully it turned out to be an excellent film. Based on a very harsh situation (a kid that's been kidnapped for year by a correct, intrascendent clerk that happens to be a pedophile) the director creates a very convincing work, where while avoiding explicit displays of "horror" he shows enough to make us feel uncomfortable and keep us glued to the screen. There's a very interesting portrait of another terrible situation, members of a family dividing the properties of their deceased loved one, as a fundamental part of the process of getting over the tragedy.
  • Miss Bala by Gerardo Naranjo, Mexico, Géneros Mutantes section (Saturday 2011/11/26)
    An excellent finale for this edition. This is a very convincing and well done radiography of Mexican society, so you know what to expect, violence, gratuitous violence, at any moment, by any (no) reason and exerted by anyone. And also, corruption, plain corruption pervading it all, anyone, any social construct... a broken society suffering a sort of civil war. If it makes it to normal cinemas, go and watch it!
You can check my reviews of past editions here and here.

Sunday 27 November 2011

Parallel Ajax requests

In our last Web project (rather rich jQuery UI + Asp.Net MVC) we had one page where we needed to do several async Ajax calls to load different screen items (combos, jqGrid, several lists in one Accordion...) just on page load. All these calls were independent from each other (results from one of them were not needed in another of the calls). This led us to some interesting head scratching about which was the best approach:
  • Just launch them sequentially. Each call is started when the previous one finishes. This basic approach seems rather wise if the failure to retrieve some data means that the whole page turns invalid, in that case you stop you sequence of calls and show the error message.
    For this you just can queue your calls just by passing them as callbacks to the success event of your previous call. This is fine for a few calls, but for many of them it ends up being rather messy. A better approach here is the use jQuery's deferred objects to create your queue. You would use a chain of calls to the pipe method (the documentation is a bit confusing to me, but that's the way to go for chaining calls with deferred).
    Of course, you can always create you own Queue.
  • Just launch them all in parallel. Pretty simple from a code perspective (I would reccomend to wrap your "Loading..." modal dialog in some helper class with a counter that increases-decreases with each show-hide call, that way you don't need to care of when all calls have completed to turn the page operative, each call just calls to the Dialog show-hide and that's all)
  • Keep a limit on the number of concurrent calls. I mean, maybe you have to do 5 calls but don't want to have more than 2 concurrent calls. So you would start launching 2 calls and queuing the rest, and each time one call is done you would launch the next call in the queue. To my knowledge jQuery's deferred does not have an out of the box way to do this, so you would have to implement your own system.

So, what's the best way to proceed? I don't have a firm answer to that, so I'll just outline some of the many things that we should take into account.

  1. HTTP persistent connection. Almost all browsers and servers use this technique, so one same http connection is reused for requesting different resources. OK, good, but, what about requesting those resources in parallel? Let's move to point 2.
  2. Number of allowed concurrent requests in modern browsers (notice that though he's asking about Ajax requests, this applies to any kind of request). Seems like this ranges from 2 to 6. The number of concurrent Http connections to the same domain needs to keep a balance between what is good for the client (more connections) and what is good for the Server (don't flood it with too many connections, you know, the C10k problem...).
    From these 2 points, let's think that we have 3 persistent http connections open to the server, each one requesting data, does each request have to wait for its response, or we could send several requests in parallel through the same connection? This is called Pipelining (similar to processor pipelining, when several instructions in different steps run in parallel in the same processor core), so, jump to point 3.
  3. HTTP pipelining Long in short, unfortunately this interesting feature is scarcely supported by most major browsers.
  4. Your server technology also plays a role here. For example, when using Asp.Net, any request that make use of the Session object will get serialized, so, it'll be just the same as if we had done the requests sequentially. This is so because concurrent access to the Session object should be avoided, and the Framework is doing just that locking for us. With Asp.Net MVC it's assumed that all actions make use of the Session, and that means that we can't have 2 actions running in parallel (so forget your concurrent Ajax requests from being really parallel, you'll see them both running in firebug, but on the server side they'll run sequentially). Hopefully this can be changed at the controller level, by means of this attribute: SessionState
    Read this article thoroughly for a much better explanation

Tuesday 15 November 2011

Some musings about Roslyn

There's been quite a lot of excitement in the last weeks around the first preview of the "Compiler as a Service" technology to be added to .Net 5 (aka Project Roslyn).

I have mixed feelings about this. On one side, I can't share all that much excitement, cause for the most part I don't see it as a revolutionary feature (as I see the DLR or even Linq), but as a rather needed feature that should not have taken so long to make it into the Framework. Furthermore, something similar has been present in Mono for a long time (one of the main reasons I always hurry up to install Mono on any new machine is the wonderful C# REPL console that comes with it). On the other side, having full access to the compiler pipeline means that I think very interesting things can be built on top of it, this made my imagination fly, but it suddenly hit the wall of reality. One of the fist and more obvious things that I could think of was adding your own new custom keywords and constructs to the language (turn it into an open language...), but unfortunately, seems like that's out of the scope for now

Actually, it isn't true that you can use Roslyn to extend C# with additional keywords. – Dustin Campbell Oct 21 at 19:35
thanks... corrected... although not in the first release I am pretty that this will be possible... – Yahia Oct 21 at 19:36

@DustinCampbell, What if you handled whatever compiler error that the pseudo keyword caused by generating code? – Rodrick Chapman Oct 21 at 20:17

You'd need to do a rewrite before passing it to the compiler. First, parse code with your special keywords. The code will parse and, unless the parser couldn't make heads or tails of it, the invalid keywords will show up as SkippedTokenTrivia in the resulting tree. Then, detect the skipped keywords and rewrite the tree with valid code (e.g. AOP weaving). Finally, pass the new tree to the compiler. This is definitely a hack though, and it's not guaranteed to work with future versions of Roslyn. E.g. the parser might produce not produce the same tree for broken code in future releases. – Dustin Campbell Oct 21 at 21:59

Anyway, I guess (even over Anders Hejlsberge dead body) compile time AOP will turn much more prevalent in the .Net world thanks to this.

Reflection is something that has always deeply appealed to me, from basic introspection to the full beauty of runtime code generation. The way to generate code at runtime in .Net has evolved over the years. Already in the first version we had 2 ways to do this:

  • write some C# code, write it to a file, invoke the compiler (launch the csc.exe process) to create an Assembly and load that assembly
  • use CodeDom to generate C# code and compile it (under the cover this also invokes csc.exe)
  • use System.Reflection.Emit
By the way, we've got a good discussion of CodeDom vs Reflection.Emit here.

These options above have the drawback of having to create a new assembly for each new code that we want to run, which adds some overhead. Later on, (.Net 2.0) things got improved, allowing us to create new code by using LCG (Lightweight Code Generation) aka Dynamic Methods. No new assemblies are created/loaded, and the new code can be referenced from a delegate (using DynamicMethod.CreateDelegate). The main drawback is that we're not writing C# code here, but IL... and thought going low level in these times of higher and higher abstractions can have much appeal for the Geek inside us, you get a feeling of being brought back to the times of C and inline assembler :-)

.Net 3.5 came with new Code Generation candy in the form of Expression Trees, candy that got extra sugar in .Net 4, where Expression Trees can be used for creating statements, not just expressions.

In .NET Framework 4, the expression trees API also supports assignments and control flow expressions such as loops, conditional blocks, and try-catch blocks.

This gives us full power, but again, at the cost of a non trivial, not much natural syntax.

All this said, I think a common wish for many of us would be something that cute as JavaScript's almighty eval function. Finally, Roslyn seems to bring something similar to the table, but well, will have to see how it evolves, cause right now there seem to be some limitations

Can we now take a piece of code in a string, and compile that to a DynamicMethod?
We don't have this feature implemented yet, but it's definitely something on our radar.

One interesting topic here is, why Mono seems to have been some steps ahead in the "Compiler as a Service" area? Well, Mono has had a managed compiler since its early steps, while C# has been burdened by a native compiler so far. I think that's a big difference that we tend to overlook. Even contrary to what we could think based on how the native JavaScript interpreter (jscript.dll), Xml Parser (msxml.dll)... work (COM component in a dll that this way can be reused by IE, WSH, HTAs...), the C# compiler logic is not implemented in a separate dll-COM, but just in the csc.exe executable. This means that any C# to IL compilation involves spawning the csc.exe process. Even now I'm still amazed when I see the w3wp.exe process launch a csc.exe instance to compile some Razor view or .aspx page...

Tuesday 1 November 2011

C# Params and MethodInfo.Invoke

I guess everyone will agree that the params keyword in C# is pretty useful, but probably many of us will have never thought too much about how it works.
As I had a issue with it recently, I had to give it some extra thinking...

I was trying to call via MethodInfo.Invoke a method that was expecting a params object[].
MethodInfo.Invoke also expects a params object[].
And I was getting a nasty:
System.Reflection.TargetParameterCountException: Parameter count mismatch.

public static void WriteParams(params Object[] myParams)
 {
  foreach(Object param in myParams)
  {
   Console.WriteLine(param.ToString());
  }
 }

object[] myValues = new object[]{"hi", "man"};
  MethodInfo method = typeof(App).GetMethod("WriteParams");
  //runtime error: Parameter Count Mismatch
  try
  {
   method.Invoke(null, myValues);
  }
  catch (Exception ex)
  {
  }

If we have a look at the bytecodes generated for a call to a method expecting params where we're passing several arguments to the call, we'll see that there's some compiler help involved. The compiler takes care of wrapping those parameters into an array, that is what will be passed to the method. If we were already calling the method with an array, the compiler does not do any extra wrapping. This is rather well explained here

The params parameter modifer gives callers a shortcut syntax for passing multiple arguments to a method. There are two ways to call a method with a params parameter: 1) Calling with an array of the parameter type, in which case the params keyword has no effect and the array is passed directly to the method:
object[] array = new[] { "1", "2" };
// Foo receives the 'array' argument directly.
Foo( array );
2) Or, calling with an extended list of arguments, in which case the compiler will automatically wrap the list of arguments in a temporary array and pass that to the method:

In my case, as I was already passing an Object[] to MethodInfo.Invoke, this was not getting an extra wrap, and then, the Invoke method was passing the items in that array as individual parameters to a method that in this case also expected an array of parameters... (I guess that the Invoke method does not do any checking to see if the target method expects a params object[], remember that it's something done by the compiler).
so the Solution is just doing the extra wrapping myself when calling Invoke

//we  have to wrap the array into another array
  method.Invoke(null, new object[]{myValues});

We find the same problem with other dynamic invocation scenarios, like calling Delegate.DynamicInvoke.

Delegate deleg = new Action (WriteParams);
  try
  {
   deleg.DynamicInvoke(myValues);
  }
  catch (Exception ex)
  {
  }
  deleg.DynamicInvoke(new object[]{myValues});

All this brings to my mind another issue with params with a similar response. What happens if we have a method that expects a params object[], and we want to pass to it an only parameter that happens to be an object[] ?
By defaul, the method will be treating that object[] that we're passing as a params object[], so it would be as if we were passing n parameters to it, instead of an only parameter.
Again the solution is to wrap our Array in another Array. We can do it ourselves, or cast our Array to Object, so that the compiler itself does the extra wrapping for us.

You can check the source here

Thursday 27 October 2011

64 bits

I used to be a hardware freak back in time, with some good knowledge of processor architectures and so on. As time went on I preferred to focus just on programming, and at the same time, programming has been going higher and higher level to such extent that for most programming tasks coders do not need to be much aware of the details of the hardware on which their software runs.

That said, when this week we experienced some problems with an Asp.Net MVC application running on a 64 bits server failing to load a 32 bits COM component, I felt (as the rest of the team) a bit lost. Hopefully, this issue has turned into a rather fast and interesting learning experience.

First of all, some definitions:
  • IA32, x86-32, i386 or just x86 refer to the 32 bits architecture that was common on most computers until 3 years ago. Intel, AMD...
  • x86-64 is the 64 bits evolution of the former architecture. AMD, Intel...
  • IA64 has nothing with the above, it was a completely new 64 bits architecture developed by intel and that had little success.
  • WOW64 is the technology used by MS to run 32 bits applications on a 64 bit system (Operating System and Processor).
and some tips:
  • When on a 64 bits system, we can check whether a given Native process is 32 or 64 bits by launching ProcessExplorer and checking whether it has the wow64.dll loaded
  • We can check if a .dll is 32 or 64 bits by means of the binary dumper that comes with Visual Studio. Open the Visual Studio Command Prompt and type:
    dumpbin /headers myDll.dll |find "machine"
    you'll get: 14C machine (x32) 8664 machine (x64) My first idea was to check the 32-64 bits using the almighty PEBrowser, but oddly enough I couldn't find where to check this.
  • We can check under what option (x86, x64, Any CPU...) (more on this 2 paragraphs below) an assembly was compiled by using the corflags tool provided with the SDK

One of the first things I found is that you can't load a 32 bits dll in a 64 bits process. WOW64 only works at a whole process level, but not for independent dlls. I mean, if you're running a 64 bits process and you try to load a 32 bits dll there (or COM object) WOW64 won't get into play, you either compile the process to 32 bits or the dll to 64 bits, of course, if you don't have the source code, you're fucked.

Another interesting point, I used to think of .Net assemblies as unrelated to the processor details, just a bunch of bytecodes that get compiled to 32 or 64 native instructions by the JIT compiler, just as would happen with Python, Javascript or so... This is not completely true, and we get a hint if we notice that the CSC compiler allows us to compile our assemblies as x86, x64 or Any CPU... As explained here what those actions do is to indicate the JIT compiler how it should compile our bytecodes, 32 bits, 64 bits or "as the process on which I'm being loaded". The reason why we could need this level of control is because .Net allows us to go rather low level using unsafe code and calling into Native Code (PInvoke...).

That said, if you intend to use a 32 bits native dll from your .Net application, you'll need to compile your app with the x86 option. That means that if running on a 64 bits system the WOW64 system will be loaded and everything should be fine.

When working with Asp.Net there's something else you need to take into account. Your Web application (a bunch of dll's, not a .exe) gest hosted by the w3wp.exe process spawned by IIS. There's a w3wp.exe process for each IIS Application Pool (this means each application pool is independent from each other, thanks to that we can run Asp.Net 2, Asp.Net 4... apps on the same machine, they just need to run on different App Pools so that each pool loads the corresponding Framework version). By default, w3wp.exe is launched as a 64 bits process, so, how do I load my 32 bits assemblies + Native dll there?

Hopefully, the solution is damn easy, we just need to mark the Application Pool where we plan to load our Web Application as a 32 bits (IIS -> Advanced Properties of the Application Pool -> set Enable 32 bits applications to true)

Friday 21 October 2011

Murder of a brave man

Well, I guess everyone knows the big news of the day, colonel Gaddafi has been murdered today by the NATO-paramilitar "rebel" forces joint venture... I don't intend to praise Gaddafi as a "good guy", as in the 70's he funded a good bunch of armed organizations that committed all sort of violent acts in the Western world. Some of these organizations had a left wing revolutionary ideology and meant to create a new and better society, but were pretty confused as to how to spread marxism and liberate the "working class", others were just a gang of criminals, islamists and other crap...

I'm not Lybian and I've never been to Lybia (and I guess I'll never be, as I have serious doubts that after the NATO bombs have taken the country back to the stone age... it willl ever be a place worth a visit...), but I think to know enought about recent history and about how our current world drowns in NeoLiberal poison to firmly believe that Lybia is much worse now than it was 1 year ago. I already expressed my views about the invasion of Lybia in this previous post, now, not only do I reaffirm those opinions, but even more, I dare to claim that Lybia will never reach again the same level of development (high quality public education system, health system, per capita rent) that it enjoyed under Gaddafi's dictatorship. The new regime, consisting of Islamists and greedy puppets of the Multinationals, will bring no good to Lybians, that I'm sure will end up remembering the old times when their kids could attend to the University for free and their natural resources were used to develop the country instead of filling foreign pockets...

These 2 videos clearly align with my understanding of the "Lybian conflict":

The images of the "rebels" murdering Gaddaffi and dragging his body is that repulsive as the images of the NATO leaders cellebrating this public execution as a triumph of liberty and Human Rights... fucking hypocrites...

As a final point, whatever one's opinion about Gaddafi is, what I think everyone will have to concede is that Gaddafi has died like a brave man, someone that firmly believed in his role as the leader of his people and that as such, chose to die fighting instead of fleeing to Algeria, Russia or some other country where his money, old friendships and "business secrets" would sure have bought him a secure location under the protection of the local government with the only condition of keeping a low profile.

Sunday 16 October 2011

When We Leave

Another great German film dealing with the problems of a multicultural society. Being set in Berlin, it's pretty easy to figure out that it will revolve around Turkish in Germany.
What I pretty much like of this film is that it focuses on problems inside a multicultural family, but not a family with people coming from different cultures, but a family which members have developed different cultures. This way, the main character in the film is a westernized German-Turkish twenty something woman with traditional Turkish parents and older brother, and half traditional younger brother and sister.

Our young lady, Umay (the incredibly beautiful Sibel Kekilli) flees with her child from her violent husband in Turkey and returns to her family home in Berlin. Her family does not accept her breaking her marriage and try to force her to return to her husband. When this says that he's no longer interested in "a German whore" they try to take Umay's child and take him to his father. Umay has to escape from her family and keep away from them, this is emotinally devastating for her, but all her attempts of reconciling with her family (that blindly believe that she has brought shame and ruin upon them with her "horrible" action) painfully fail.
The story develops harsher as it slowly gets on, with some really tough moments, but also with some moments where we're drawn to believe that hope still exists.
As I've said, the film is rather slow (contrary to Head-On the film that gained Sibel public attention), but it's deeply intense and powerful, and profoundly beautiful. I think this is in good part thanks to the excellent performance of Sibel, well, it's not just because I consider her terribly attractive, it's because her skinny body and her "Modigliani face" can convey sadness, pain and even happyness in such a convincent manner.

This film is a must, and is one more wake up call on how Europe needs to deal with the topic of integrating not just immigrants, but the second and third generation ones.
Umay is the perfect example of integration, her best friend is a German girl, she starts a relation with a German guy, she picks up her studies with the intent to go to the University... so she's a German woman with Turkish background. On the other hand, the rest of her family seem barely integrated (either because of their obsession with tradition, or for the acceptance of the submissive role of women, or just because they don't seem to relate to non Turkish people in the whole film).

I guess Sibel had to feel really comfortable in her role, as in the real life she's a very solid example of integration, she has even criticized Islam for being inherently violent
I have experienced myself that physical and psychological violence is seen as normal in Muslim families. Unfortunately violence belongs to the culture in Islam."
My hat off to you lady :-)

Sadly enough, the film seems to be inspired by real events. Forced marriage and honour killings in Western Europe in the XXI century... shit, we've done something terribly bad in the last decades...

By the way, I guess Berlin's Tourist Office had nothing to do with this film, cause we have very few scenes where some landmark of the city is shown (you could think that it's set in any other large German city). This said, it's curious to say that I think I know one of the localizations, the place where Sibel gives her little brother a letter for Mum seems like the "50 faces" in Kreuzberg to me (you just see a small graffiti there and it's not a face... but anyway I would bet it's located there).

Update March 2012: from my last trips to Berlin I think I can also confirm that the scene from which I captured the image below is set on the Warschauer Strasse S-Bhan station.


Monday 10 October 2011

Run Lola run

This German film from 1998 has come as a beautiful surprise to me.
As I'm preparing my next visit to Berlin (I love the Prussian Metropolis, one of those places where regardless of how many times you've been there you ever have one million things to do), I've decided to watch some films set in Berlin, just to whet my appetite even more. Somehow I stumpled upon this film, and the fact of having Franka Potente playing the main role (I absolutely love her performance in Bourne), obviously increased my interest.

What we get here is a vibrating story, where a woman has 20 minutes to obtain a huge amount of money to save his boyfriend's life. She desperately runs through Berlin trying to obtain the money and take it to her boyfriend. The idea sounds good, but what is better is that what I've just told is used as the baseline to develop 3 different stories, where the characters take different decisions and the outcome is devastatingly different. The frantic soundtrack (pretty good electronic sounds) is another plus for this film, and reminds me of the soundtrack of another good film set (partially) in Berlin, Hanna

The film works also as sort of a Berlin tour, which is always good, but don't try to follow on a map the route traced by Franka in her anguished run, cause it makes no sense. She starts in Mitte, and suddenly she's in Kreuzberg crossing the Oberbaumbrücke to Mitte again... so Berlin's geography has been fairly altered.

Well, I think there's not much more I can add, just watch it and enjoy.

Tuesday 4 October 2011

The aesthetics of your code

For better or for worse I'm someone that can spend awful amounts of time pondering on things that many (if not most) would consider irrelevant. Many of those "wasted?" brain cycles are related to programming issues that I still consider important like:

  • Initialize in the constructor or inline?

  • Should this go to a separate class? (how strictly to adhere to the Single Responsability Principle is a constant source of doubt for me)

  • Add another parameter or create a separate method (think and rethink semantics...)

  • This method should go here or there?



So when finding just by chance the excellent reflection of a StackOverflow folk on the Aesthetics of Programming and its intrinsic individual nature I could not resist to copy-paste it here:
Original source

Look at the things that are important: your project, your code, your job, your personal life. None of them are going to have their success rest on whether or not you use the "this" keyword to qualify access to fields. The this keyword will not help you ship on time. It's not going to reduce bugs, it's not going to have any appreciable effect on code quality or maintainability. It's not going to get you a raise, or allow you to spend less time at the office.

It's really just a style issue. If you like "this", then use it. If you don't, then don't. If you need it to get correct semantics then use it. The truth is, every programmer has his own unique programing style. That style reflects that particular programmer's notions of what the "most aesthetically pleasing code" should look like. By definition, any other programmer who reads your code is going to have a different programing style. That means there is always going to be something you did that the other guy doesn't like, or would have done differently. At some point some guy is going to read your code and grumble about something.

I wouldn't fret over it. I would just make sure the code is as aesthetically pleasing as possible according to your own tastes. If you ask 10 programmers how to format code, you are going to get about 15 different opinions. A better thing to focus on is how the code is factored. Are things abstracted right? Did I pick meaningful names for things? Is there a lot of code duplication? Are there ways I can simplify stuff? Getting those things right, I think, will have the greatest positive impact on your project, your code, your job, and your life. Coincidentally, it will probably also cause the other guy to grumble the least. If your code works, is easy to read, and is well factored, the other guy isn't going to be scrutinizing how you initialize fields. He's just going to use your code, marvel at it's greatness, and then move on to something else.


My 2 cents with respect to the question that sparked such a nice text is that I always use "this". On one side it seems more clear to me, on the other hand, in some brilliant languages like Python or JavaScript(well, the mechanism and semantics are quite different from C# and Java and it's not something optional, you could not do withou it) you have to use it, so what is good in JavaScript is good in the rest of the Coding world :-)

By the way, do not miss this impressive ellaboration by the same author on how to get some sort of Class Loader equivalent in C#

Saturday 1 October 2011

Last months interesting stuff

Well, it's being a long while since the last of my posts summarizing interesting items that I came across lately, so time for one of those.

As I've been doing tons of JavaScript lately, I found these 2 posts pretty useful. I was aware of most of what is stated there, but anyway it's good to get you assumptions confirmed

jQuery performance rules

JavaScript and Ajax performance

That said, even when I'm pretty interested in any sort of performace trick (in whatever language I'm using) mainly because those things help you understand how things work internally (I've ever been a rather curious person), I tend to favor semantics and clear code over performance (I guess that's the right decision for the kind of applications that I develop, that are far from having any kind of high peformance requirements). Some weeks ago I had one discussion with one colleage and couldn't help throwing this classic sentence: premature optimization is the root of all evil

Thought the most commonly used JSON serializer in the .Net ecosystem (JavaScriptSerializer, the one used by default by Asp.Net MVC) leaves much to be desired, JSON has turned into my preferred serialization format, thought having to declare C# classes for the JavaScript objects that you want to deserialize seems like boring and time consuming, so, with all the dynamic magic in C# 4, couldn't we just deserialize to a dynamic object? Good reading here (JSON to ExpandoObject)

I'm really longing to have some time play a bit with some NoSql stuff (ok, you can call me "fashion victim") mainly CouchDB, so this thing seems pretty promising
UnQL query Language for Document Databases

Even when you think you're rather fluent in one technology, there are always things that you miss, mainly due to some initial decisions that turn into habits. In my case, I've always used classic castings and type comparisons, so I hardly remembered that C# provides the as and is operators
x is T returns true, if the variable x of base class type stores an object of derived class type T, or, if x is of type T. Else returns false.

x as T returns (T)x (x cast to T), if the variable x of base class type stores an object of derived class type T, or, if x is of type T. Else returns null. Equivalent to x is T ? (T)x : null


This excellent article about Asp.Net MVC extensibility, makes me look forward to the next installments in the series.

This good article about a new .Net collection (the Exposing a limited read-only window of a list seems rather useful), took me to this interesting research project made in Danmark, a new set of advanced .Net collections. The events on collection changes thing seems pretty interesting.

Sunday 25 September 2011

From Resistance to Revolt

After several attempts over the last years, finally last month I managed to find for download the 2 CDs that make up the whole discography of one of my favorite hardcore bands of the 90's, Manifesto.

One million thanks to this blog for making them both available for download here

  • Un mundo que ganar, unas cadenas que perder (A world to be won, some chains to be broken)

  • De la Resistencia a la Revolución (From Resistance to Revolt).


Manifesto was a socialist hardcore band from Barcelona, active I think roughly between 1994 and 1999. Most of their work should be classified as what at the time we called New School Hardcore (I've been so cut off from that scene in the last decade that I don't know if this term is still much in use), something in the vein of Earth Crisis, but their best songs (well, at least my total favorites) are some very fast tracks that appeared in their 7 inch "El arte de la insurrección", rather reminiscents of Man Lifting Banner. These songs also have some of their best lyrics.

Some of their uncompromising socialist (of course we're talking about Marxism/Communism..., not about socialdemocracy) statements are now more relevant and up to date than ever, even when I rather disagree with all the "class fight" stuff (just because on the contrary, it seems like a pretty outdated concept in our world of Megacorporations, outsourcings...)

My favorite song in terms of sound is also my favorite one in terms of lyrics, "En este Sistema/In this System"
Here's my broken translation from Spanish:

Free Market, economic anarchy, cut after cut. Accumulate is the new Bible. Production that ignores human needs. Profit is their only sacred law. Health System, Education System, social services. Always questiones, always under attack. We have no control over what we create. We can't decide what to use it for. Judges, parliament, structures designed in this System. Army, Police, created to protect their profits. In this System we ever lose.

As you can see, in our current Europe, where all sort of funding cuts are being conducted, those lyrics seem more relevant than ever, and make us realize how the foundations of our Western civization (universal health system, education system) seem to crumble.



A fun note now, the cover for this CD seems a bit odd for such a political band. I mean,Casa Milá is a superb building, but neither the building nor the architect have any political significance, so how does it match with the Socialist ideology of the band?. Well, it's pretty fun, one of the band members told us back in time that there was a huge demonstration due to pass by the building, so they hired a photographer to take a pic from one of the buildings across the street. The thing is that they got too late and the demonstration had already passed... but anyway they took the picture of the empty street and used it for the cover :-)

Lyrics for "De la Resistencia a la Revolución":



Saturday 24 September 2011

Destructuring Assignment

I've been keen of Rhino since the first time I knew about it, many years ago. At that time JavaScript was not by far the popular language that it's now, and being able to run a JavaScript shell and do some of your normal coding tasks with it was not in most people's agenda (for example just think that 95% of the WSH samples that you find on the net are VB instead of JavaScript).

Today I paid a visit to their site to see if there was something new, and to my delight I found version 1.7R3 there. I immediately jumped to the "What's new" section, and from there to the JavaScript 1.8 section. And there I found one of those brilliant ideas that once you come across them think how it is that humanity has lived for so long without them :-)
Changes in destructuring for..in

I've known the concept of destructuring assignment since the times I used to do some Python coding, it's a simple and powerful idea that I though only applied to function returns and swapping values

var [a, b] = function(){
return ["val1", "val2"];
};


so when I found this destructuring for..in thing it really caught my eye. I was not completely sure of what it mean, so I've done a couple of tests, and it's amazing, you can write code that elegant like this:


var ar = ["a", "b", "c"];
for (var [i,v] in ar){
print (i + ": " + v );
}

var ob = {
name: "Iyan",
age: 30
};
for (var [k,v] in ob){
print (k + ": " + v );
}


If you change "print" for "console.log" and try it in firebug you'll see that it works fine for objects (second sample) but not for arrays (first sample), which appears odd to me as this seems to be part of JavaScript 1.8 and modern versions of Firefox seem to implement it...

Update, 2012/11/25 With the functional style additions to ES5, both cases above can be easily rewritten with the new forEach method in the Array object:

var ar = ["a", "b", "c"];
ar.forEach(function(item, index){
console.log (index + ": " + item );
});
 
var ob = {
name: "Iyan",
age: 30
};
Object.keys(ob).forEach(function(key){
console.log(key + " : " + ob[key]);
});

Sunday 4 September 2011

Passing Anonymous Types as parameters

It's been a long while since my last C# post, so time for a short one.
Some days ago, I'm not sure why, it came back to my mind a question done by a colleague some months ago "hey, I can't pass Anonymous Types to another method?" and my simple answer, "no, you can't".

Well, my answer was rather simplified and outdated, what I really meant was that you can't pass Anonymous types around in a useful way. As the type is anonymous, when you pass it to another method, all you can put in the signature is Object, so in order to get access to any of its properties you would have to use Reflection, and that's verbose and slow.

public static void PrintPersonAnonymous(object p)
{
PropertyInfo propName = p.GetType().GetProperty("Name");
string name = (string)(propName.GetValue(p, null));
Console.WriteLine(name);
}

PrintPersonAnonymous(new
{
Name = "Iyan",
Age = 40
});


Hopefully, with C# 4.0 things are much better. You can declare the parameter as dynamic in the method signature, and then you can access its properties normally. The only problem is that the access is still done via Reflection, but it's the compiler who generates the code instead of you.

public static void PrintPersonDynamic(dynamic p)
{
string name = p.Name;
Console.WriteLine(name);
}

PrintPersonDynamic(new
{
Name = "Iyan",
Age = 40
});



Of course, we all know that dealing with Dynamic objects can be pretty fast if we're using objects that take care themselves of the property access - method invocation by implementing IDynamicMetaObjectProvider, like for example ExpandoObject does.

With what I've just said, an idea comes to mind, converting an anonymous type into a ExpandoObject, something that is pretty trivial (probably the most interesting thing here is that we can get access to a Property of the ExpandoObject using its string name by leveraging that it implements IDictionary<String,Object>)


public static dynamic AnonymousToDynamic(object ob)
{
IDictionary d = new ExpandoObject();
foreach(PropertyInfo property in ob.GetType().GetProperties())
{
d[property.Name] = property.GetValue(ob, null);
}
return d as dynamic;
}


This way we can convert our anonymous object to an ExpandoObject to improve performance.

The source code

Ah, while writing this I found this post where they explain a rather different approach to this same problem.



Saturday 27 August 2011

Looting begins (in the name of democracy)

While his fate is unknown at this point (public or hidden retirement, being taken on trial, being behaded by the "rebels" with the smiling approval of the "civilized" world...), what is clear now is that Gaddafi is over.

What a beautiful world, thousands of peoples have been murdered by NATO bombs and the NATO sponsored "rebels", the infrastructures of a modern country completly destroyed (and waiting for reconstruction, what a yummi cake!), a harsh division of the country between pro and anti-"rebels" that sure will burden the country for many years... but hey, they've got ridden of the dictator and democracy is waiting. Once again the Global powers have done their duty, spreading democracy and freedom to one more "dark corner" of the world. "Freedom", a pretty depreciated concept.

For Global powers Freedom means Democracy, and that's pretty easy to understand, Democracy nowadays is such a convenient form of government... it's the easiest way to keep masses "happpy", silent, calm and conform. There's not better way to prevent someone from seeking something than making him believe that he already has it. "You're free", you're allowed to choose your government, you're allowed to represent you community by entering the political system, and bla, bla, bla...
Yes, you're allowed to choose between the political parties, but only those that the Global powers fund, you're free to choose between the different lies spread by the Mass Media owned by the Global powers, you're free to receive decent education and decent medical care if you can afford it...

It wouldn't have to be that way, sure democracy could be a good system of government, but the problem is that in the last decades, every new place that has been "awarded" with democracy has received it with one more extra gift, "Brutal Capitalism". Yes, since a long while Democracy comes hand in hand with Neoliberlism and capitalism, so Democracy has turned out being a poisoned gift for so many countries.
Take a look at Soviet Union, is the average Russian better now (not being able to send his kids to the University, spending half of his income in the rent of a dilapidated flat...) than in the Soviet times?, take a look at Serbia, take a look at Ukraine or Romania, think about those young Eastern women forced to leave their country (so democratic now) to sell their bodies in some mafia owned brothel in one of our so democratic countries...

If democracy is so important for "our leaders" it's odd that it has taken them 40 years to come to the realization that Libya should be democratized by any means (like Irak...), and it's even more strange that Syrians do not deserve that brilliant fate (or what to say about Somalia, where if Islamists had been wiped out and a functional government established it would be a bit easier now to deal with the current famine)...
Of course, there's a clear difference, profit, or let's put it clear booty. Same as Iraq was, Lybia is a wealthy country, and as such, a highly desirable prey for global capitalism. It's not just taking over the oil deposits, it's the reconstruction process. How many millions will be spent in rebuilding all the infrastrutures destroyed by the NATO forces? Libya has a huge flow of petrodollars, so let's suck it dry!

There's an important point to notice about the NATO war on Libya:
Contrary to what happened with Iraq, there's been hardly any visible opposition to this war among the different "progressist" groups in the Western world. Sounds odd, cause I still have fresh in my mind the images of the huge demonstrations against the invasion of Iraq... So what?, well, Global Powers learned a lesson from the "Weapons of Mass Deception" thing. For many people solidarity is above fear, so trying to terrorize people with an imminent threat (biological weapons, nuclear weapons, terrorism...) does not work when they know that the "remedy" to that unlikely threat means dragging millions of people into the very certain horrors of war. But there's an easy workaround, let's put the victims on our side. Let's create a group of "freedom fighters" (the so called "rebels") and let's say that these honorable freedom advocates are being slaughtered by the dictator (yes, that's true, Gaddafi was getting rid of the "rebels" with violence, as he had always done, but the same violence that they had started off with). The trap is ready, and most "progressist" Westerns will take the bait, who could oppose the helpful actions of the "Keepers of peace" trying to help "freedom fighters" and civilians against the awful dictator...?
There's been no questioning among the mass, few people seemed to care about who the "rebels" are, about what would come next if they seized power... Well, the "rebels" are a mix of Radical Islamist (wahhabists, salafists... all that scum that hates us, Westerns, so much), monarchists, some progressist pro-Western Lybians (but don't worry, they'll have little to say in the future government, probably as the Iranian Ayatolah did with the Communists after the "Islamic Revolution", they'll get smashed by the "beardies") and finally, a wide group of opportunists initially on Gaddafi's side that switched sides as they realized that the Regime had little to do against all the NATO machinery...

Please, watch these videos for some insight into this:
http://rt.com/usa/news/al-qaeda-libya-commander-escobar-269/
http://rt.com/usa/news/pepe-escobar-libya-iraq-132/


Well, at least we can think of the positive things of this senseless destruction:
the economies of those more involved in this shameless war: France, USA, UK, Spain... will get a boost with all the contracts to sign to rebuild Lybia. Anyway, sure they'll tell us that boost is not enough to stop the cutbacks to the Education System, Health System... well underway in most of Europe...
I bet it'll take just a few months to have the first Hollywood Blockbuster telling the story of the "heroes of Tripoli"...

World of shit... well, I better end this here and go to sleep...

Friday 19 August 2011

Riots in UK

I truly admire this man since the first time someone (thanks Gus!) sent me a link to one of his videos: Free Speech in Eurabia. Ever since I regularly check his web to catch up with his new videos, and I've never been disappointed, just the contrary, such is my admiration that I've even "paid him a beer" via Paypal.

Even living in the country that is undergoing probably the sharpest process of Islamization in Europe, he's not afraid to fiercely criticize Radical Islam, unveiling the facts of this demonic threat with an astonishing sense of humor. Hopefully, he does not stop there, and also attacks Radical Christians, brainless "suicidal leftists" and NeoNazis alike (by the way, it's fun to notice, reafirming how trendy and brainless these shitheads are, that while now most NeoNazis tend to be antiIslam, just a few years ago they used to be rather proIslam)
We could consider Pat a Heroe of Western liberties, someone that with each of his speeches reminds us that we have a responsability to keep and improve this our civilization, one that our ancestors built by rebelling against feudal lords, kings, bishops and dictators, and that we can't remain with our arms folded, prisoners of "Political Correctness" while a bunch of illiterate zealots attempt to destroy it.

This time Pat is particularly angry (and it's not surprising, my feelings, being someone that has only been to Britain as a visitor, were also really strong in view of the shameful events happening last week), and he does a glorious speech against all those lame, ungrateful bastards that tried to terrify and bring to its kneels a whole society.
I absolutely share his views and I think to know enough about England to be pretty certain that most of those vandals were not "victims of society" like some "PC media" try to portray them, but just the contrary, lazy bastards living off this society, taking advantage of all sort of social aid: housing, wages...
the others are just hooligans or normal idiots wanting to feel bad an rebellious.

Something interesting in this episode of violence and that I think is rather specific to UK is the lack of power on the Police side. I'm not talking about the lack of materials (thought I have to admit that not being allowed to carry guns really shocked me), but about the inability to properly confront criminals cause any sort of physical "contact" with them would almost certainly end up with the policemen in court.
That's not the same here, just the contrary (and that's not for good either, cause in Asturies-Spain policemen are known for their violence and impunity, mainly when they act against workers or left wing people).
What I think is common to all of Europe (at least to all those countries living under the Political Correctness Dictatorship) is that common citizens are not allowed to defend themselves. Confronting a criminal, either a common street robber, a NeoNazi or a Latin Gang (both equally stupid and xenophobic) or someone entering your home and attacking you and your family, is not allowed in any way in our weak societies where any sort of self defense causing any harm to your aggressor would end up in serious problems for you. If you're lucky, that will just mean paying a huge compensation to the criminal (and a bitter feeling of helplessness on your side), but that well could end up for you in a prison sentence much more severe than anyone ever served by your attacker.

Shit, all this absurdity is sickening, so no better way to sort it that finishing this write up with some sentences by Pat Condell that ever manage to make me smile:

Multicultural fascism
PC totalitarianism
Post Imperialist Guilt
Islam dominates, not integrates
pathetic, pompous human vermin

Friday 12 August 2011

Technology Radar

After reading the Thoughtworks Technology Radar for July I could not help dropping a few lines to praise this statement:

GWT is a reasonable implementation of a poor
architectural choice. GWT attempts to hide many of
the details of the web as a platform by creating desktop
metaphors
in Java and generating JavaScript code to
implement them. First, in many ways, JavaScript is
more powerful and expressive than Java, so we
suspect that the generation is going in the wrong
direction
. Secondly, it is impossible to hide a complex
abstraction difference like that from event-driven
desktop to stateless-web without leaky abstraction
headaches eventually popping up
. Third, it suffers from
the same shortcomings of many elaborate frameworks,
where building simple, aligned applications is quick and
easy, building more sophisticated but not supported
functionality is possible but difficult, and building
the level of sophistication required by any non-trivial
application becomes either impossible or so difficult
it isn’t reasonable.


Wow, even never having done any development with GWT I think I can fully endorse those claims without fear of being wrong. When I first heard of GWT some years ago I thought it was a huge step back.
My boss in one of my first development projects was a real "guru", a visionary that had developed an impressive RIA framework in the early 2000's, using tons of beautiful Object Oriented JavaScript (both on the client and on the classic ASP server), CSS, Active X (it was for intranet applications that only needed to run on IE), an excellent debug console and tons of XHR (at that time JSON was almost unknown, so it was sending/receiving needlessly verbose XML). The first versions even used iFrames instead of XHR.
Well, I'm telling all this because thanks to that (and to an old o'reilly JavaScript book where I first read about prototypes) I've been pretty aware of the power of JavaScript and client side coding from rather early, and that's why GWT smelled like crap to me since the first moment.
Translating Java to JavaScript seemed absolutely ridiculous to me (I could even say insulting), and it can only be justified by wanting to do life easy to sloppy programmers that are not willing to learn a new language and paradigm. It appears to me a terrible mistake, similar to the error of keeping VB around by morphing it into VB.Net, instead of forcing developers to learn the beauty of C#...

The idea of hiding the Web particularities under a "desktop metaphor" was first implemented in Asp.Net WebForms, and I would say that with terrible results (don't get me wrong, it can be OK for some kind of applications, but not for the kind of applications that we need today, well, hopefully now we have the almighty Asp.Net MVC) that were hardly improved with the addition of "Update panels". Shit, I remember the pain of trying to make some basic JavaScript DOM manipulation in an Asp.Net 2.0 Web application (with tons of update panels, puff...) that we developed 4 years ago... the hacks that we had to devise to work around all the limitations imposed by "the Web as the Desktop" nightmare...

Web Developers have had excellent DOM, Ajax, effects, "language enrichment" libraries since a long while (jQuery, mootools, dojo...), so what we now need are JavaScript frameworks pushing and helping us to write more maintainable JavaScript intensive applications. It seems like backbone.js and JavaScriptMVC could be good steps in that direction. Unfortunately I haven't had a chance to play a bit with them, but I'm longing to get my hands dirty with them :-)

Saturday 6 August 2011

Centurion

The last work by the almighty Neil Marshall is, as one could expect, another masterpiece.
From my review of The Descent 2, it's clear that I love both installments of The Descent.
As for Doomsday, I've been about to write a review several times, but in the end I've never got to it, the thing is that is an amazing film drawing from different excellent influences, though maybe it's a too crazy mix at times and probably I would have dismissed a few parts.

Centurion will keep you stuck to your screen for 90 minutes. The story is pretty interesting, more if like me you're pretty interested in history, early inhabitants of Europe, the Atlantic Arc...
It wisely uses one of the possible explanations to the disappearance of the Roman Ninth Legion as background for a story of escape, revenge and survival. If you add to it the stunning Scottish landscapes, the Picts (the misterious ancestors of the Scottish people that were able to put to halt the (until then) unstoppable advance of the Roman empire (not even my ancestors had managed to stop them), and the captivating beauty of Olga Kurylenko you have a sure winner.

The general feeling can seem similar to Van Diemens Land or even Valhalla Rising, but I prefer Centurion over these films.

Well, I think I need some sleep, so nothing more to write here, just watch it!

Sunday 31 July 2011

Ecstasy

Ecstasy is an excellent HARSH Canadian film that uses drug consumption as the vehicle to explore loneliness, fear, despair, beliefs, friendship... If you think "Requiem for a dream" is a tough film, be warned that it seems like a comedy when compared to "Ecstasy".

Apart from drugs, the other main topic in the film is Religion, and both of them serve a similar function: escaping from reality. The drugs induced escape lasts just for a short time before turning against the escapists and devouring them, the negative effects of the religious flight are not shown in the film, really, there's not an anti-religion stance in the film, except for the fact that the priest tries to keep up his audience by putting drugs in the wine used for the communion!!! the idea is interesting (reminds me of some old stories about food in Hare Krishna restaurants... well, I've been in several Govinda restaurants throughout Europe and I've never left there in an "altered state") and it fits pretty well with the idea of Religion as a collective hallucination...

I don't feel like writing anymore about the plot, you just should watch it and enjoy (or maybe suffer) it, so I will only add that the soundtrack is pretty good, both the "danceable electronic" themes and the "depressive introspective" ones.


Thursday 28 July 2011

Latvian Non citizens

A history-geography-politics freak like me needs to digest tons of information about any place he plans to visit in order to feel OK when he sets foot there (I understand travelling as a form of personal enrichment that goes far beyond the experiences lived in the few days that I can afford in whatever place I go), so as I'm planning a trip to Latvia and Lithuania I've started my search for all sorts of information, and I've come across this pretty interesting documentary about Latvia.

Well, I've said that it's pretty interesting, but first and foremost I need to warn you that it is terribly biased towards Russian interests. The hosting website rt.com (pretty interesting by the way) was formerly known as Russia Today, so it's easy to expect some proRussian stance...

Not that I want to show off, but I should say that few things in the video were new to me (apart from my general interest in European affairs, I paid a visit to Estonia in 2008, and learning about any of the "Baltic states" necessarily means learning about the other 2...), so I already knew about the Non citizens, the tensions between ethnic Latvians and ethnic Russians (and their huge percentage there, even larger than in Estonia), the economic difficulties that the country is going through, the Latvian SS thing, the Latvian NeoNazi scum... but what it seemed to me is that everything appeared like a bit distorted.
Well, what I had not a clue about was that the Latvian government had returned the previously "collectivized" properties to their old owners (even people living abroad).

The documentary does not explain how the 28% of Russians living there (not 50% as the documentary constantly claims) ended up in Latvia, probably they are skipping that in order to avoid inconvenient references to the occupation of the Baltic States. They do not explain either that the percentage of Russian population was also increased by the deportation of a 10% of the native population, as part of the population transfers conducted by the Soviet government.
They pay much attention to the disgusting Latvian NeoNazis, I guess they do this intending to demonstrate how ultraNationalistic and xenophobic the whole Latvian society is... but in doing so, they should also mention the huge number of NeoNazi shitheads in Russia itself, but well, following that logic that should lead us to think that the Russian society as a whole is the most nationalistic and fanatic in the world...

I don't want to sound antiRussian, I can understand part of the feelings of both communities,
from the Latvian SS member (that in most cases was not a blood thirsty fanatic, but a guy that had to choose between the Soviets, which brutality alredy knew pretty well after the initial occupation, and the Nazis, that in principle could seem more "Baltic friendly", after all, Nazis did not regard Baltic people as an "inferior race", and Germans had dominated the Baltic economy for centuries with no need of blood baths or brutal oppression of the natives
to the Soviet veteran that after being forced into the army was about to die in the Great Antifascist War, and that finally got relocated to an unknown land as a "prize" (better, as the following step in the construction of the perfect (and impossible) society)...
Sure it's hard to swallow that after having lived in a country for many years you are suddenly a second class citizen there, but it's also hard to swallow that you're not willing to do the effort to learn about the history and culture of the place that after all those years you should love.
Furthermore, at first sight it doesn't seem so complex to get naturalised.

So well, all in all, good stuff to further investigate and think about, and sure a great topic to discuss before a coffee with some ethnic Latvian and some Latvian Non-citizen (and preferably young single females :-D
but so far I'll have to resign myself with the comments below the video, that provide pretty different takes on this topic and are well worth a read.