Monday, 30 August 2010

Duck Typing and C#

The dynamic keyword in C# 4 (and the underlying DLR machinery making it possible) is amazing and powerful. Some people tend to get confused with Object, var and dynamic... but differences should be rather obvious:

  • var has nothing to do with dynamism, it's just compile time type inference (aka wrist friendliness).

  • Object is just that, everyone's ancestor that can be downcasted (with all its risks and inconveniences) to whatever we need

  • dynamic is pure dynamism, compiler assumes you know what you're doing when you declare something as dynamic and does not interfere. At runtime it will try to find the Method or Property that you're invoking-accessing, either using that object's implementation of IDynamicMetaObjectProvider, or resorting to Reflection. This is what we're used in languages like JavaScript, Python and so on... and is called Duck Typing

So dynamic and DLR are incredibly powerful, allowing us to mix the dynamic and static paradigms in the same language, but anyway, there are some limitations for which we'll need some extra help.

Let's say we have two compatible types (same public methods-properties) but while one of them implements an interface defining those semantics, the other one, for whatever reason (comes from a different code base for example) doesn't. Say we would like to use instances of both types in a piece of code. That's fine while that piece of code is dynamic, I mean, we're passing the object of one of the compatible types to a method expecting a dynamic parameter, but what happens if that method was implemented in a static fashion, expecting typed parameters (an interface)?
We would need to create a new class that implements that interface and redirects calls to the methods with the corresponding name in the initial class. Well, that's what dynamic proxies are for, intercepting and redirecting calls!.

For some odd reason, even in .Net 4, dynamic proxies are not part of the Framework (while Java has had them since the 1.3 times), so we would have to resort to one of the third party implementations out there (Castle, LinFu).
Castle DynamicProxy seems to be the most widely used, but I was already aware (I had toyed with it a bit some years ago) of the problem with its lack of documentation. Hopefully, this excellent tutorial encouraged me to jump onto it again.
Castle DP is arguably a powerful beast, but at first sight it didn't seem to provide out of the box support for what I needed (in principle you normally use it to intercept classes that already implement the common interface).
Googling for "C# and Duck Typing" I found a good article that explains how to accomplish what we want and shows me that I had read too fast the Castle samples.
He's using the CreateInterfaceProxyWithoutTarget. This is an interesting Proxy Generation method, as it does not need a class that already implements the interface, all the magic is in the interceptor. For this case Mauricio creates an interceptor that holds a reference to the proxied object, so we can invoke the corresponding method.

Proxy without target. This one is tricky. You don’t supply target implementation for the interface. Dynamic Proxy generates it for you at runtime, using interceptors to provide behavior for its methods.

The usage:


is very similar to the usage of this nice library that I had found some time ago (by the way, it also provides other useful functionalities like conversion between compatible delegates)
Note that this library has its roots in the pre-Extension Methods times, so that's why the syntax is uglier:

ICanAdd adder = DuckTyping.Cast<ICanAdd>(myAdder);

Back in 2008 the author (David Meyer) wondered if the advent of C# 4 would turn the library obsolete, as we've seen above, some parts of it are still useful, so I'll keep it in my programmer's toolkit.

You can see a usage sample here.
In order to compile it you'll need the DeftTech.DuckTyping.dll Assembly. You can get it all in this zip.

Saturday, 28 August 2010

There will come soft rains

I've just come across by chance this beatiful poem expressing how much Nature would enjoy a world without humans.

There will come soft rains and the smell of the ground,
And swallows circling with their shimmering sound;

And frogs in the pool singing at night,
And wild plum trees in tremulous white;

Robins will wear their feathery fire,
Whistling their whims on a low fence-wire;

And not one will know of the war, not one
Will care at last when it is done.

Not one would mind, neither bird nor tree,
If mankind perished utterly;

And Spring herself when she woke at dawn
Would scarcely know that we were gone.

The most astonishing thing is that this poem dates back to 1920!
At first it surprised me a bit finding someone that almost 100 years ago had the idea of the extinction of mankind revolving around his head. I think that nowadays, due to the many issues that we're facing now (climate change, globalization of the economy, oil depletion, fish depletion, religious fanatism, moral decline of Western society and above all, overpopulation) this idea of humanity being wiped out is not so strange for a certain percentage of the population, but wouldn't have expected such thoughts in that time.
Well, thinking it twice, I guess that after having witnessed in WWI how much the destructive power of humans had increased, thinking of the "total annihilation" was a pretty natural thought.

This idea of how great it would be for the planet to get rid of us (the architects of the Sixth Extinction) is rather clear to me, and is pretty well set out by Michael Boulter in that great documentary "Dodo's Guide to surviving extinction", but it's something that I don't think is understood by most of the population (when thinking about the many challenges that humanity will confront in the near future people tend to think about the end of the world, but no guys, it's not the end of "the world", it's just the end of humanity). This is normal due to our terribly anthropocentric view of everything, an anthropocentrism that will be one of the main causes of our self destruction...

I watched a documentary some years ago where Sir Martin Rees stated that the probability of extinction of Human race by the end of this century was around 50%, well, if we think in terms of a partial destruction (getting to an apocalyptical world like the ones depicted in The Book of Elli or The Road) I bet those chances are much higher...

By the way, "there will come soft rains" was the title of the E150's last track in their split 7" with Ivich (buff... that was 1997...). It was a beautiful melodic electronic song composed by their drum player (Carlos) that had little to do with the fast and furious music usually distilled by these BCN Punks.

Friday, 20 August 2010

Floods, Shock and Profit

At this point in time I guess everyone is aware to a greater or lesser extent of the terrible floods that devastated Pakistan last month.

In the last days media have warned of the attempts of Fundamentalist Islam to proselytize in the refugee camps, trying to gain supporters among these people who have lost it all...
What these bastards are trying is what Naomi Klein describes so brilliantly in her splendid book The Shock Doctrine, exploiting a chaos situation where people are weak, confused and terryfied, to make them accept a wicked and oppressive ideology...

I wonder if these repulsive fanatics will be trying to blame us (Westerns, Kafirs, infidels...) of the floods... of course they could resort to some Conspiracy Theory and say that we're using weather as a weapon through HAARP or something similar... or maybe, they'll be telling the victims that Allah has sent the rains to punish them for not being devote enough muslims...

During the floods part of the rescue services already took care of discriminating those who were not muslims

...were not rescued from their homes because rescuers felt that Muslims must be given priority...

Parallel Programming

An fast write up mainly to share a couple of links (and a reminder of things I'd like to go more in depth in the near future)

In these times when multi-core processors are ubiquitous (even for smartphones in the near future) it's clear that parallel programming is more and more important. .Net framework has tried to address this doing Parallel Extensions mainstream by including them in .Net 4 framework.

Parallel Extensions look exciting and promising to me, so finding this free book (Patterns for Parallel Programming: Understanding and Applying Parallel Patterns with the .NET Framework 4) has been really good news. I've only gone through the first pages and I've already learnt some interesting things about dynamic partitioning, oversubscription...

This reminded me about another excellent free book (Threading in C# by Joseph Albahari) that I had been reading some months ago. It's great news to see that it's been updated for .Net 4, including a full new chapter on Parallel Extensions (and many updates to the previous chapters to reflect other MultiThreading improvements to the Framework).

We tend to think of Parallelism just in terms of Threads or Processes, but there's more to it, for example:

  • SIMD instructions (that's SSE for x86 architecture). These instructions leverage Data Level Parallelism, performing the same instruction on multiple data, for example if we want to add different pairs of points, an only Add instruction could run in parallel over the different pairs. There's a good explanation here
    Mono has added support for SIMD instructions, which can be really useful for Multimedia applications doing heavy use of matrices and vectors. It's contained in an independent assembly that can be used both from Mono and from Microsoft's implementation.

  • GPGPUs. The programmability of GPUs has gone a long way since the initial vertex, pixel shaders. These shaders are used for graphic tasks, so while advanced and interesting, do not seem so revolutionary as being able to run "normal calculations" on the GPU and use the results from the code running on the CPU.
    So far, there are main technologies in this field:

    • CUDA. This is the first one I was aware of. I remember how surprised I was when I saw some code a couple of years ago showing how dynamically compile and load into the GPU some code embedded in a Python script

    • OpenCL (Update, 2010/09/27): I've just read a very interesting entry on InfoQ about using OpenCL via pure Java (code written in a Java subset gets translated to OpenCL code at runtime). It's pretty interesting what the author says on current usages of GPUs in common programming:

      Looking at the OpenCL side, I have seen everything from financial services to energy exploration (I used to work in that field). I also know folk that are looking at GPUs for seismic data analysis. Applications that have the potential to see major benefits of using the GPU for computation include the big-data analytics domain.

    • Direct Compute. Thought it's Microsoft Centric there don't seem to be direct bindings from .Net, but there are some articles out there on how to make them work together.

  • By the way, back to the shaders, it's really amazing being able to run Shaders in your browser via Silverlight!!!

Saturday, 14 August 2010

Windows Uptime

It's a bit odd that Windows does not provide an uptime command whose sole purpose were that, telling us the Uptime of our machine, but well, we have different options to get it:

  1. net statistics server
    as this command will display a bit more of information than just the uptime, we can trim it to just our desired line by using the grep equivalent provided by the Windows Resource Kit, qgrep:
    net statistics server | qgrpe -e "Statistics since"
    As you can test, it returns when the the computer was last booted.

  2. SystemInfo
    this command provides a lot of information about our system, but because of that it can take some seconds to run, so it's less useful for this task. Again, you can refine the results with qgrep:
    SystemInfo | qgrep -e "System Up Time"
    Again, it returns when the computer was last booted.

  3. WMI and WSH
    WMI is one of those wonderful Windows technologies of which potential not everyone is fully aware. I'm used to work with it from WSH (another underrated Windows technology), so I've prepared a script that uses WMI for either getting when the computer was booted:

    var wmiDate = WScript.CreateObject("WbemScripting.SWbemDateTime");
    var wmiObj = GetObject("winmgmts:\\\\" + strComputer + "\\root\\cimv2");
    var aux = wmiObj.ExecQuery("
    Select * from Win32_OperatingSystem");
    //WMI queries always return a collection, so get the first element (the only element in this case)
    var osInfo = new Enumerator(aux).item();
    wmiDate.Value = osInfo.LastBootUpTime;

    or obtaining how many seconds have elapsed since then:

    var wmiObj = GetObject("winmgmts:\\\\" + strComputer + "\\root\\cimv2");
    //returns a collection with an only item
    var aux = wmiObj.ExecQuery("
    Select * From Win32_PerfFormattedData_PerfOS_System");
    var osPerfInfo = new Enumerator(aux).item();
    UpTime: " + osPerfInfo.SystemUpTime + " seconds");

    As you can see in the full source for this second case I had to add some extra code to turn the seconds into weeks, days, hours... this made me think that with .Net I just would need to create a TimeSpan object from those seconds, and it would already provide me the Days, Hours, minutes... so, why not to use the successor technology to WSH, one with full access to the .Net power? this takes us to:

  4. WMI and Windows PowerShell
    After playing for a while with the PowerShell console (If you have PowerShell installed, it should be here: C:\WINDOWS\system32\windowspowershell\v1.0)
    I realized this would involve several lines and I would better write a PowerShell script, so I came up with this uptime.ps1 file (it's my first PowerShell script, so please, be understanding):

    $perfObject = gwmi Win32_PerfFormattedData_PerfOS_System
    $seconds = $perfObject.SystemUpTime
    write-output ($seconds.ToString() + " seconds uptime")

    $timeSpan = new-object System.TimeSpan -argumentlist ($seconds * 1000 * 1000 * 10)
    write-output ($timeSpan.Days.ToString() + " days, " + $timeSpan.Hours.ToString() + " hours, " + $timeSpan.Minutes.ToString() + " minutes, " + $timeSpan.Seconds.ToString() + " seconds")

    in order to run it from the console you'll need to set permissions for running .ps1 scripts (yes, I agree it's weird that it's not enabled by default, but MS is taking security really serious), so type:

    Set-ExecutionPolicy RemoteSigned

    then, if you cd to the folder containing the script, just type:


    and that's all.

Friday, 13 August 2010

Developers will have their say

I guess I'm not the most appropriate person to do predictions about the PDA-smartphone market (I'm using this now almost forgotten word, PDA, as my personal homage and because it's the Multimedia-PDA functionality what is really interesting to me, the Mobile Phone functionality has little interest for someone that some months spends less than 1 euro in calls), I just have my own very limited experience with a few of these gadgets and some theoretical knowledge.

Being a rather pro-Microsoft guy (that also loves open source, I don't see any contradiction on this, but it would be long to explain...), it would be natural that I felt rather attracted to Windows Phone 7, but that's not the case because my rather lame experiences with Windows Mobile 5 and 6 have made me quite reluctant to any Microsoft offerings in this sector.

Currently I have a jailbroken (thanks black rain!) iPod Touch 2G, that for 180 euros seems absolutely unbeatable value for money to me. My main problem with it is that my specific model only admits tethered jailbreaks, and well, that the idea of being forced to resort to jailbreaking for having a really useful gadget is shitty, if I'm paying for the hardware, why don't you fucking Apple give me full control over my legitimate purchase???

Because of this I've been following with growing interest the evolution of Android, waiting for the release of affordable (prepay card is an absolute must for me given my minimum consumption) gadgets, and it seems we're almost there, with some models around 300 euros that seem rather acceptable. I was dreaming of Android as some kind of open source iOS, that as such would be fully accessible to tech-aware users.
These dreams have almost vanished as I've realized that with regards to Freedom, Android is little better than my Iphone OS. I mean, you get an open source OS, but tainted by each manufacturer so that in the end you need to root it (sort of jailbreaking) to get full access to it...

So, when I found this excellent article today, I could only add new variables to the equation that sooner or later I'll have to solve before buying a new toy...
I absolutely agree with almost everything said in that article, Microsoft has been treating us (developers) really (and increasingly) well. Things like Linq, C# 4 and the DLR, COM (using it, not creating it) should be in the Tate Modern of Software Development... and programming for the Windows Phone could end up being so fun that would make us (developers, wow, it's good to feel as if we had power over those masses of programming-unaware poor sheeps) change trends...

The article reminded me of this crazy video of Steve Ballmer gone nuts (I think I had first watched it on this interesting Swedish documentary against consumerism).

This Ballmer's video is also great :-D

Saturday, 7 August 2010

Los turistes qu'Areces nun quería

Hai dellos años (nel 2006 creyo recordar) cuando hebía un ciertu maltar na población porque'l desgobiernu d'Asturies nun yera quien a trayer pal nuesu aeropuertu más vuelos baratos aparte del de EasyJet a Londres, el bandidu Areces dixo que los vuelos baratos nun yeren bonos p'Asturies porque namás traíen turismu de "baxa calidá". Esi sinvergoña quedóse tan anchu (que nel so casu ye bien, bien anchu...) ya otra miembra de la piara sociata, Migoya, añadió que colos vuelos baratos los asturianos dexaríen de dir a les cases rurales pa colar fuera, ya diba perxudicanos... en fin, declaraciones d'una baxeza intellectual que si nun mos afeutaren direutamente sedríen pa mexase de risa.

Per un lláu, los vuelos baratos nun yeren vistos por Areces como un serviciu a los ciudadanos asturianos, demientres que los ciudadanos d'otros países europeos sí tienen drechu a percorrer Europa a precios asequibles, los asturianos nun ñecesiten d'eso, o meyor dicho, hai torgaselo tolo posible, nun seya que si salen d'Asturies a otros países más civilizaos dense cuenta de lo qu'Asturies podría ser ya nun ye por culpa la Mafia ppsoE. Que viaxen a Benidorm, como "bonos españoles", pa tomar el "solecito" ya mediterraneizase bien...
Per otru lláu, paez como que'l turista européu que fai usu de los vuelos baratos ye un probetón que diba venir Asturies a poco más que xintar pinchos de baldre nos chigres, ya nun diba dexar ganancia dala...

Ye curiosu que yo escriba sobro'l turismu n'Asturies, cuando pa nada quiero que la economía asturiana sostengase sobro'l turismu. Como Asturianu que quier lo meyor pal so país prestaríame una Asturies reindustrializada, una economía productiva ya innovadora, que xenere trabayu de calidá... les economíes basaes nel turismu son xusto l'antítesis d'eso...
Pero bien, yá qu'el ppsoE, nel so paletismu ya incapacidá neuronal, anecia ya anecia en convertinos nuna "potencia turística", taba bien que polo menos supieren de lo que falaben...

N'Asturies nun hai turismu de fuera la península, nun hai más que dase una vuelta peles cais pa decatase que lo único qu'hai ye xente la meseta, ye dicir, xente de una de les economíes más probetayes d'Europa.
Fasta l'otru día pensaba que sedría dalgo común a tola Cornisa Cantábrica, pero non, nun ye asina. Santander, colos sos vuelos baratos a Alemaña, Irlanda, Bélxica... taba estráu de turistes europeos (de países toos d'un poder alquisitivu bien superior al español). El avión nel que vine dende Frankfurt venía fasta arriba d'Alemanes con botes de montaña ya mochiles que diben a Cantabria (l'antigua Asturies de Santillana) a esfrutar de les montañes que na so zona nun abunden. De verdá quedéme plasmáu cola cantidá de turistes estranxeros, n'Asturies en tol branu nun llevo vistos los que ví ellí nuna hora...
Nun sé, a lo meyor son los míos prexuicios, pero fuera yá de la tema de la so capacidá alquisitiva, paezme abondo más enriquecedor esti turismu proveniente de sociedaes más avanzaes que la nuesa, qu'esi otru turismu que vien equí (afortunadamente hai honroses exeiciones) a mamase nes vinateríes ya ver les corríes de toros sufragaes col dineru los asturianos.
Cuando menos, igual fasta pa poder atendelos la xente la hostelería deprendía un poco d'otros idiomes, envede tener qu'avezase a dicir "cafetito" ya "sidrita"...