Monday, 30 August 2010

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:

duck.As<IQuack>().Quack();

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

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

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...

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.

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 hereMono 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.

Saturday, 14 August 2010

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:

net statistics serveras 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.

SystemInfothis 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.

WMI and WSHWMI 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:

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:

WMI and Windows PowerShellAfter 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):

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:

Friday, 13 August 2010

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...