Friday, 18 August 2017

Covariance and Contravariance in Delegates

Delegates covariance and contravariance is a rather confusing topic and I'm not going to put any theory here, you can check any MSDN or stackoverflow response for that, I'll just put here a fast, personal reference. For an excellent approach to Variance in Programming languages, you should read this.
Short ago I talked about Converting from one delegate type to another different delegate type with the same signature. Covariance and contravariance in Delegates is a different topic, but we'll see that in one case it saves us having to do that conversion.

Since C# 2.0 covariance and contravariance applies to the rules that dictate that you can create a delegate of a certain type that points to a method of a certain return type and signature. We no longer need a perfect match between return types and the signature. You can read about it in Variance in Delegates.

What C# 4 brought to the table was covariance and contravariance between related generic delegates. Basically, now you have a relation between Func<Animal> and Func<Cat> and between Action<Cat> and Action<Animal>. It's explained in Variance in Generic and Non-Generic Delegates

I'll put some examples here for easy reference

Delegate Covariance (for return types)

If we have these custom delegate types and method:

  public delegate Animal CreateAnimalDelegate();
  public delegate Cat CreateCatDelegate();
  public static Cat CreateCat(){
   return new Cat();

Since C# 2.0 (one MSDN article mentions 3.0, it's wrong) we can do this, bind a delegate type (returning an Animal) to a method returning a more derived type (Cat):

CreateAnimalDelegate animalCreator = CreateCat;

If we are using generic delegates we can do the same (this is not related to the out keyword introduced in C# 4), here this continues to be delegate binding.

Func<Animal> animalCreatorFunc = CreateCat;

C# 4 brought something new, you can point a variable of a certain delegate type to an instance of a delegate of a different but related type. From MSDN

In .NET Framework 4 or later you can enable implicit conversion between delegates, so that generic delegates that have different types specified by generic type parameters can be assigned to each other, if the types are inherited from each other as required by variance.

//so thanks to C# 4 I can do this assignment of a different delegate type, there is no conversion it's just type compability
Func<Cat> catCreatorFunc = CreateCat;
Func<Animal> animalCreatorFunc = catCreatorFunc;

//so in C# 4 there is type compability, but not really inheritance ("is" works, but "IsSubclassOf" does not)
Console.WriteLine("catCreatorFunc " + ((catCreatorFunc is Func<Animal>)? "IS" : "IS NOT" ) + " Func<Animal>"); //IS 
Console.WriteLine("Func<Cat> " + ((typeof(Func<Cat>).IsSubclassOf(typeof(Func<Animal>)))? "IS" : "IS NOT" ) + " Func<Animal>"); //IS NOT!!!

As you see in the example I can point a Func<Animal> to a Func<Cat>, it's as if they were in an inheritance hierarchy, but it's not really the case, cause while the is operator will tell us that Func<Cat> is a Func<Animal>, the IsSubclassOf will tell us that no inheritance exists.

All in all Covariance for return types seems pretty natural, same as we can do Animal an = new Cat(); , we can do Func<Animal> fAn = new Func<Cat>...;

Delegate Contravariance (for arguments)

Delegate Contravariance seems a bit less natural, cause basically we can do: Action<Cat> aCat = new Action<Animal>.... So it seems we are reversing the way we use type compability (a Cat is an Animal for sure, but here we seem to say that an Animal is a Cat). If we think that this applies to parameters it makes total sense. We invoke aCat passing a Cat to it. aCat points now to a function that expects an Animal, so if it receives a Cat it will behave nicely.

I'm putting here the equivalent contravariant samples for the ones above

public delegate void ManageAnimalDelegate(Animal an);
public delegate void ManageCatDelegate(Cat cat);
public static void ManageAnimal(Animal an){

Bind a delegate type (expecting a Cat) to a method expecting a less derived type (Animal):

ManageCatDelegate catManager = ManageAnimal;

If we are using generic delegates we can do the same (this is not related to the out keyword introduced in C# 4), here this continues to be delegate binding.

Action<Cat> catManagerAction = ManageAnimal; //this one looks a bit odd cause we are sort of doing Cat = Animal;

And what was added in C# 4

Action<Animal> animalManagerAction = ManageAnimal;
Action<Cat> catManagerAction = animalManagerAction;

Console.WriteLine("animalManagerAction " + ((animalManagerAction is Action<Cat>) ? "IS" : "IS NOT" ) + " Action<Cat>"); //IS
Console.WriteLine("Action<Animal> " + ((typeof(Action<Animal>).IsSubclassOf(typeof(Action<Cat>)))? "IS" : "IS NOT" ) + " Action<Cat>"); //IS NOT!!!

To finish this article, I'll mention that while return type covariance applies to delegates, unfortunately (in C#) it does not apply to overriden methods in a derived class (Java has support for this since a long while). For contravariant arguments, again it applies only to delegates. The feature is not available for methods in hardly any language.
To my surprise, I learn that Eiffel supports Covariance in method arguments

Thursday, 17 August 2017

After the Wedding

When I first watched After the Wedding some years ago, I quite liked it, but it was last week, when watching it for second time, when I really realised how excellent this film is. Susanne Bier is such a great director and (notice that I have not watched all her films, I particularly miss Open Hearts) this is so far my favorite.

The story (co-written by Susanne) is rather imaginative and becomes more and more powerful as it develops. It's always amazed me that citizens of happy and well-functioning societies like Denmark or Sweden have such a capacity to create dark and compelling dramas (the Scandinavian Noir of Camilla Lacberg and Asa Larsson particularly delight me due to those characters living sad, complex, tormeted existences). In After the Wedding we have these 2 characters meeting again "as if by chance" after 20 years of neglect. First there's some anger, then those old feelings that will never disappear and the maturity that time gives us as such a beautiful present, will heal the pain and make things move on. This short conversation (it's not a literal transcription) describes with such sharpness how easy it is to spoil our lives:

  • - Why didn't you come back?
  • - Cause I thought you would end up following me
  • - Why didn't you follow me?
  • - Cause I thought you would come back

The most impressive moment in the film is when the husband, this strong and succesful man that had kept his terminal illness hidden from his love ones and seemed to be putting up with it so well finally crumbles. At the moment when the physical damage starts to show and the end of the "game" (our only game) becomes a too close certitude, the strong man collapses in tears, embraced to his loving wife and crying "I don't want to die". A powerful reminder of how temporal all we have, all we are, is. A reminder of how precious every second is, of how costly any unsaid word or unexpressed feeling is.

The leading actor, Mads Mikkelsen is sort of a must in most of popular Danish films. His facial expression is pretty astonishing, sometimes it's difficult to know if he's laughing, crying or both. I've recently watched another rather good film of him, The Hunt.

Monday, 31 July 2017

Delegate Types Conversions

The (non) equivalence between different delegates with the same signature can be a source of confusion. I'm not going to talk in this post about another related source of confusion with delegates, Covariance and Contravariance (pointing delegates to methods with "similar" signatures), probably I'll dedicate another short post to that topic.

Since the advent of the Func and Action generic kind of delegates, it's quite unusual (and advised against) to create your own delegate types, but you will still find them, mainly coming from old code. So let's say that you want to assign an instance of a custom delegate type to one of the generic ones, like this:

delegate string FormatterDelegate(string st);
class Formatter
  private string formatItem;
  public Formatter(string formatItem)
   this.formatItem = formatItem;
  public string Wrap(string st)
   return this.formatItem + st + this.formatItem;

var formatter = new Formatter("--");

FormatterDelegate formatterDeleg = formatter.Wrap;

//this line won't compile
Func<string, string> formatterDeleg2 = formatterDeleg;

The last line will not compile. Though their signatures are the same (receive a string an return a string), Func<string, string> and FormatterDelegate are completely different types and you can not assign one to another. So the obvious solution is to create a Func<string, string> delegate that calls to FormatterDelegate. I used to do this:

Option 1:

Func<string, string> formatterDeleg2 = (st) => formatterDeleg(st);

Somehow the other day I came across some discussions ([1] and [2]) on this topic and there are other similar ways to address this issue.

Option 2

Func<string, string> formatterDeleg2 = new Func<string, string>(formatterDeleg);

Option 3

Func<string, string> formatterDeleg2 = formatterDeleg.Invoke;

Option 3 made quite sense to me, but I have to admit that option 2 pretty surprised me. I didn't know that the compiler allowed to pass a delegate to a delegate constructor. In the end the compiler generates the same IL code for option 2 and option 3.

Both cases are similar in performance terms to Option 1. In all of them the call to the code in the original delegate goes through an additional level of indirection. This is clear for Option 1, where you are invoking an anonymous method that in turn calls to the original delegate. In Options 2 and 3 the MethodInfo of the Func delegate will point to the Invoke method of the original delegate, so you also have a "double hop". Option 1 creates a closure to hold the reference to the first delegate, so in the end will have some extra (but minimum) cost.

Option 4

. In the discussion they came up with a different technique that avoids the extra level of indirection:

formatterDeleg2 = (Func<string, string>) Delegate.CreateDelegate(typeof(Func<string, string>), formatterDeleg.Target, formatterDeleg.Method);

With Option 4 you directly assign the method referenced from the original delegate to the new delegate, so the indirection is avoided. Notice that they mention that this will cause problems with multicast delegates.

I was going to put up some test code as a gist in github, but it is down.

Friday, 28 July 2017

Enmerable/Iterable Comparison

I've been revisiting the way C#, JavaScript and Java approach Iteration (Enumeration in C# jargon), so I'll dump here a short summary.

The basis is the same for the 3 languages. In C#/Java you have a class that implements the IEnumerable/Iterable protocol providing you access to an IEnumerator/Iterator object that takes care of the iteration. In JavaScript your object implements the Iterable protocol by featuring a [Symbol.iterator] property that returns an object conforming to the Iterator protocol.

The main difference stems from the methods provided by the Iterator (Enumerator) object. Most times you should not be concerned about these differences, as you will be just using the specific loop structure provided by each language:
foreach (it in enumerable)
for(o : iterable)
for (variable of iterable)
But if you are using your iterable differently you should take some more things into account.

C#. You advance your position in the Enumerator by calling the MoveNext method, that returns false if it has passed the end of the collection. To access the current element you use the Current property, that will return "an undefined value" (which is quite an open and confusing idea) if you are either before the first element (you've never called MoveNext) or after the last element (the last MoveNext returned false)

JavaScript. Your iterator just provides you with a next method, that returns a [done, value] pair and moves to the following position.

Java. The iterator provides a hasNext method, that returns false if you are positioned at the last element, and a next method that moves to the next position and returns its value. If you were already at the last element, next will throw a NoSuchElementException.

These iterators present similarities and differences. C# and JavaScript are pretty similar. As we've seen both of them have a method (MoveNext/next) that advances the iterator if possible and returns a boolean indicating if it has reached the end. If the end has not been reached, in C# we access the current element via the Current property while in JavaScript that value has also been returned in the next method. I like the idea of being able to access the current element through a property.

Java is quite a bit different. I find the haveNext method rather strange. It tells you if there is a next element, but does not gather it (in C# MoveNext does not return the next element as such, but is supposed to assign it to the field backing the Current property). So after the hasNext you will have to call next to really obtain the element. On one side, this means that if there are several threads accessing the iterator you have to put hasNext and next inside a critical section, on the other side, depending on your iterator, checking for the existance of a next item and obtaining it could be costly operations, so there is a sort of redundancy. The iterator could internally obtain and cache the value when checking for existence of the value, but maybe the caching is not the intended behaviour. So all in all I find the Java design a bit odd.

InHuman Rights

This week I've been reminded of how stupid some "Human Rights" organizations can be. After the Iraki Army finally managed to liberate Mosul from the Daesh monstrosity, Human Rights Watch denounced that the Iraki forces had mistreated and executed Daesh "militants" (I hate when the media calls these beasts "militants" it's a word that seems to normalize them, they are not "militants", they are fascists beasts). OK, so the Iraki forces have executed some "individuals" that were part of an "organization" that rapes and sells women as slaves, that throws homosexuals from the roofs, that chops people's heads or burn them alive because of being infidels... So what? Should we just put them in prison waiting for them to be rehabilitated? Bullshit, we must punish them in accordance to their crimes, so of course they must be executed, and before that we should make them suffer at least a bit of the pain that they have caused to others. Yes, I'm saying what you think to have understood, I think that Daesh members that have been captured alive should be physically punished (yeah, I'm trying avoid the word "torture" to not sound so "aggressive"), before being executed, "eye for an eye...". This reminds me of the nice treatment given by Nasser to Sayyid Qutb one prominent IslamooFascist that has been a source of inspiration for Islamists worlwide.

The difference between people that like me defend the execution (and previous physical punishment) of these monsters, and Human Rights organizations that decide to defend these beasts, is our conception of Humanity. I consider myself an Humanist, and I think of "Human" as a moral attribute, an attribute that can be lost due to our inhuman actions. Human Rights organizations think of "Human" just as a biological attribute that as such can not be lost (a Human can not be converted into a dog, so he will ever be a Human regardless of his actions and hence will always be granted with Human rights, whatever he has done).

For me, when a Human being commits brutal acts against other living beings (humans or animals), these inhuman actions deprive him of his Humanity, and the moral rules that we use when dealing with other humans (and should be applied also to animals) should no longer apply. At that point that individual must be punished with as much vehemence as those affected by his crimes (or the society in general) decide. This punishment can involve for sure execution, but also different levels physical and/or psycological punishment.

Last year there was an opinion poll in France (I think French people love polls, you constantly find in the news headers like "60% of French people think that...") where a big percentage of the participants said to agree with the idea of torturing Islamist Terrorists to obtain information (this was just after the capture of the Salah Abdeslam bastard). Of course I agree with the idea of subjecting Abdeslam (or any Salafist scum) to very hard physical punishments, but not just for obtaining information, but for the sake of justice. I'm fed up of the idea of "rehabilitation". Sometimes people commit small crimes out of real need, and for sure these people must be helped. Other times people just make "acceptable" errors, that's an essential part of our human condition. In these cases the ideas of rehabilitation and punishment should go together. Be deprived of your freedom for some time as a punishment, and leverage that time to help you make up your mind and choose a different path. But when the crime is too brutal, too cruel, I don't think rehabilitation should play any role, the only thing that matters is punishment.

Friday, 14 July 2017

The Autopsy of Jane Doe

It has passed almost one year since I watched The Witch, and my attitude towards horror films has not changed, I continue to be no particularly interested on "Paranormal" Horror, but again, as with The Witch, The American Cosmograph has given me the opportunity to watch a really good one, The Autopsy of Jane Doe.

One father and son run proudly and professionally an "Autopsy business". One evening the police brings them a new "client", a young, beautiful, unidentified (hence the "Jane Doe" thing) woman found dead in unknown circunstances. They start the examination, and as it advances more an more odd findings stack up until the first paranormal events start. So far, the film was a bit gore, now it turns violent and claustrophobic, with some good jump scares. To round it off they manage to give it a nice source to all this supernatural mess (OK, it's paranormal stuff, don't thik of a rational explanation, but the idea is cool). Indeed, this is one more point that makes me relate this film and The Witch

The acting is pretty good, particularly Brian Cox, and the 90 minutes of the film pass too fast. There is one of those moments of 5 seconds when the screen goes completely black (there's a blackout), that is particularly good when you are watching the film in the huge screen of a cinema.

All in all, a very good cinema, that for sure will be on top ten of 2017 Horror films and that you should watch.

Friday, 7 July 2017

ES6 Proxies and getPrototypeOf

The other day, somehow came to my mind an old post about static methods in JavaScript, and I thought that similar to the "avoid overriding" reason that I mention in that post, another use case would be to prevent operations from being intercepted by a proxy. I immediately thought of key actions like getPrototypeOf as an action that is better to be sure that the real method is being called and not a replacement, so it's much better to have it as a static method than as an instance method. So to my surprise I found out that the Proxy API provides a trap for getPrototypeOf, that indeed intercepts all these operations:

  • Object.getPrototypeOf()
  • Reflect.getPrototypeOf()
  • __proto__
  • Object.prototype.isPrototypeOf()
  • instanceof

Seeing that list I thought, OK, it intercepts all those cases, but will it intercept the case when the runtime is traversing the prototype chain of an object?.

I've done a short test, and seems like the traversal of the prototype chain when the runtime searches for an item is not affected by the proxy trap.

class Person{
 constructor(name){ = name;
  return "Hello I'm " +;
let p1 = new Person("Francois");

let proxiedP1 = new Proxy(p1, {
  getPrototypeOf(target) {
 return null;

console.log("- Operations with proxiedP1");

console.log("proxiedP1 instanceof Person: " + (proxiedP1 instanceof Person));

proto = Reflect.getPrototypeOf(proxiedP1);
console.log("proto is " + (proto === null ? "NULL" : "NOT NULL"));
//proto is NULL

//INTERESTING, proxying getPrototypeOf does not have an effect in how the runtime itself gets access to the prototype chain, so the sayHi method continues to work, even if instanceof is now telling me that proxiedP1 is not a Person anymore
//works fine

So if you run the code above you'll get that the internal prototype [[Prototype]] of proxiedP1 is null and that it is not an instance of Person, but the call to sayHi, that is not directly attached to the p1 object, but to its [[Prototype]], will work fine! So officially you are not a Person, but in fact you are...

I find the existance of this trap like a source of confusion, but well, you can read about some use case here.

This has raised some questions in my head. From the programmer perspective the access to a method in JavaScript is not based on Method Dispatch or Message Sending, it's just a property lookup. That property lookup just returns a function and then it's invoked (if it it does not exist the runtime will follow up the prototype chain to find it). I assumed that at the lower level it would be implemented like that, but this would means that the addition of proxies would have introduced a sort of conditional to any property access in any object in the system. The runtime would have to check if the object is a proxy and has a get trap to invoke that trap or just do the normal access. If this were this way, the introduction of proxies in ES6 engines would have had performance implications for any code (whether it uses proxies or not), so obviously there has to be much more to it.

Saturday, 1 July 2017

Generics and Dynamic

Time ago I saw somewhere a fragment of code that rather confused me. It was a line where a generic method was receiving dynamic as type parameter. "dynamic" is something at the C# compiler level, but at the MSIL level it does not exist, it just gets translated into callsite magic for accessing to its methods and properties. So, if you run this code:

  public static void DoSomething<T>()
   Console.WriteLine("type: " + typeof(T).FullName);
  static void Main(string[] args)
   // type: System.String
   // type: System.Object
   // type: System.Object

You can see the passing dynamic or Object is just the same, in the method you are receiving T as an Object. If you decompile it and check the MSIL you'll see indeed the compiler is just replacing dynamic by Object in the call.

So from the point of view of the invoked method "dynamic" has no particular meaning, it's from the caller side where it can add semantic value to write DoSomething<dynamic> rather than DoSomething<Object>.

Another related case is when a method returns generic type of dynamic. For example, in Dapper we have this method:

public static IEnumerable<dynamic> Query (this IDbConnection cnn, string sql, object param = null, SqlTransaction transaction ...

Again, at the MSIL that dynamic is just an Object, you can check the MSIL:

Here the semantic value of using dynamic is particularly powerful. It's telling you that the method is returning an object that whatever its type, contains all the fields that you expect and so you can access them without a problem. You can consume it like this:

var rows = connection.Query(...); 

If they had just signed the method as returning IEnumerable<Object> you could write something like this:

IEnumerable<dynamic> rows = connection.Query(...); 

But obviously it's pretty much more semantic to have expressed this "duck typing" in the signature.

By the way, this Query method indeed returns DapperRow objects (a class implementing IDynamicMetaObjectProvider). One could think why they don't just return an anonymous type (then it's going to be accessed via dynamic anyway). One reason is performance, with an anonymous type the dynamic access would be using a Reflection (with a cache mechanism, so it works faster than normal Reflection, but it's Reflection anyway), a type implementing IDyamicMetaObjectProvider implements itmself the access and dispatch rules, so it should be faster. But there is another more fundamental reason, based on what you can read here

Anonymous objects are internal, which means their members are very restricted outside of the assembly that declares them. dynamic respects accessibility, so pretends not to be able to see those members.

Notice that when you use Reflection you can decide to ask access to non public items, but dynamic uses Reflection "as a good guy", trying to access only public items, so for this case where Dapper is in an assembly and your code in another, Anonymous Types + dynamic is not an option. On the contrary, for code living in the same assembly, like the one below, it's a good option.

static dynamic CreateObject()
 return new {Name="Francois"};
static void Main(string[] args)
 dynamic o1 = CreateObject();

Monday, 26 June 2017

Local Functions and Async

Following my previous post on Local Functions and Iterator methods, it's time now to see what I've learnt about async thanks to local functions

When reading the last part of this article, this paragraph was a great finding.

This exhibits the same issue as the iterator method. This method doesn’t synchronously throw exceptions, because it is marked with the ‘async’ modifier. Instead, it will return a faulted task. That Task object contains the exception that caused the fault. Calling code will not observe the exception until the Task returned from this method is awaited (or its result is examined).

So, let's compare these 2 methods:

public static Task<string> DoProcess1(string st)
   Console.WriteLine("DoProcess1method started in: " +  Thread.CurrentThread.ManagedThreadId);
   if (st.StartsWith("throw")){
    throw new Exception("Can not process invalid string");
   Console.WriteLine("string is valid to be processed");
   var t1 = Task.Run(() => {
                      Console.WriteLine("Time consuming operation running in: " +  Thread.CurrentThread.ManagedThreadId);
                      return st.ToUpper();
   return t1;
  public static async Task<string> DoProcess2(string st)
   Console.WriteLine("DoProcess2 method started in: " +  Thread.CurrentThread.ManagedThreadId);
   if (st.StartsWith("throw")){
    throw new Exception("Can not process invalid string");
   Console.WriteLine("string is valid to be processed");
   var res = await Task.Run(() => {
                      Console.WriteLine("Time consuming operation running in: " +  Thread.CurrentThread.ManagedThreadId);
                      return st.ToUpper();
   return res;

Both methods are basically the same, but the second is using await and hence we've had to decorate it with the async keyword. In both cases the first lines of the method (until Task.Run) are executed by the thread from the caller method, but while in Process1, the exception will be thrown immediatelly, in Process2 the compiler generated code will capture the exception and won't throw it until the Result of the returned Task is accessed. Let's see:

    t1 = ProcessingService3.DoProcess1("throw aaaa");
    //we DON't reach this line
    Console.WriteLine("after Process1 call");
   catch (Exception ex){
    Console.WriteLine("Exception: " + ex);
    t1 = ProcessingService3.DoProcess2("throw bbbb");
    //we reach this line
    Console.WriteLine("after Process1 call");
    //exception occurs in the line below, when accessing Result
   catch (Exception ex){
    Console.WriteLine("Exception: " + ex);

This is interesting, in DoProcess1, 0 or 1 Task object is created (depending on whether we throw or not before reaching Task.Run). In a method marked as async, like DoProcess2 the compiler creates at least 1 "main" Task object. This main Task object is always created, it does not involve a particular thread, but is used to hold the Result/Exceptions of the different Tasks created inside the method, and is returned to the invoker of the method. If DoProcess2 does not throw an Exception then it reaches Task.Run, and the compiler will add an invocation to ContinueWith on that second task, and so on for as many "await" calls we could have inside the async method. For the last one the ContinueWith will set a Result in that main Task created at the beginning of the call. If at some point an exeption happens the exception will be added to the Main Task and no more code of the asynchronous method will be run.

OK, the explanation above is confusing and not really accurate, but it helps me to get an approximate idea of what is going on in a method marked as async. If you really want to understand it, check this amazing post.

As you can see in that glorious article, for each method marked as async the compiler will create a class that is basically a State Machine. This State Machine has a MoveNext method that orchestrates the sequence of asynchronous calls. Each await call that exists in the async method is like a step, and where each awaited Task is asked (via ContinueWith) to call into MoveNext once it's done.

It's amazing to see how similar this compiler generated State Machine is to the one generated for an Iterator method. In the end, both things are basically the same, the big difference is that for Iterators is the consumer of the iterator who will be calling to MoveNext, while for the async-await thing it's the asynchronous method who once finished will call to MoveNext. Just as a reminder, in ES6 (while waiting for the await keyword to be introduced in ES7) people have been leveraging generators to sort of simulate await and avoid the callback hell.

Saturday, 24 June 2017

Local Functions and Iterators

In the end I find the introduction of Local Functions in C# 6 really useful, as I have learnt a couple of things reading about their uses. Thanks to them I've got a refresh and improvement of my understanding of how the compiler manages Iterators and Async methods. As explained here, in both cases local functions provide a useful pattern to manage validation in Iterators and Async Methods. This post will focus on Iterators.

I've had since its inception a more or less clear a view of the magic used by the compiler when it comes across an Iterator method. It creates a class implementing both IEnumerable and IEnumerator and moves the code of the iterator method into the MoveNext method in that class (that acts as a sort of State Machine), replacing the "yield" keyword (that does not exist at MSIL level) with assignments to the "Current" support field. No need to enter into more details when you have a perfect explanation here.

The thing is that maybe one could think that when we have code like this:

public IEnumerablet<string> GetMainDocuments(string url)
 if (url == null){
  throw new Exception("Empty!");
 for (var i=0; i<5; i++){
  yield return + "/item/i");

The compiler could put the code that goes before the loop in a separate method, not in the MoveNext. A method that would be executed before we started the iteration with MoveNext, just invoked from the constructor of the state machine for example. This would make sense for certain cases of validation code, where we could want an immediate crash rather than a delayed crash when we decided to iterate. But we have to be aware that one of the basis of iterators is "lazy evaluation/deferred execution". In a way they are a bit like "promises", we have a "promise of a sequence" but each of its items does not materialize until the moment when we ask for it in the next iteration step. Have this in mind, and think that there are many cases where the "pre-iteration" code should be done just at the moment of starting to iterate: maybe it returns values used during the iteration, maybe it's still a validation, but one that depends on dynamic factors and has to be done just at the moment of starting to iterate, not before. So as the compiler can not differenciate those cases, absolutely all the code in your iterator method is put inside the MoveNext of the state machine.

For example think about this case:

public IEnumerable<string> GetMainDocuments(string pattern, DBHelper dbHelper)
 if (pattern == null){
  throw new Exception("Empty!");
 if (!dbHelper.IsDbUp()){
  throw new Exception("DB down!!!");
 IEnumerable<string> documents = dbHelper.GetDocuments("whatever query " + pattern + " whatever");
 for (var i=0; i<5; i++){
  yield return + "/item/i");

For the first contitional it would be useful to do it in a no deferred way, but for the second conditional, it makes more sense to do it just at the moment when data start to be needed. And for the third, again it makes more sense to do it not deferred (or maybe you wanted a snapshot at the moment when GetMainDocuments was called?) Yes, there are many possibilities, and the compiler can not just guess. So just have to adapt to his rules. Anything, inside the iterator will be deferred, so if there is code that you don't want lazy you'll have to separate it yourself

public IEnumerable<string> GetMainDocuments(string url)
 IEnumerable<string> getDocuments(string url){
  for (var i=0; i<5; i++){
   yield return + "/item/i");
 if (url == null){
  throw new Exception("Empty!");
 return getDocuments(url);

I have no idea of how the different JavaScript engines manage generators, but the issue with deferred execution is the same. Nothing of the code in your generator function will be executed until you start to iterate the created generator object.

function* nameGenerator(){
 //this console.log won't be executed until the first call to "next"
 console.log("inside iteration");
 yield "xuan";
 yield "xana";
 yield "iyan";

let gen = nameGenerator();

console.log("generator created\n");

console.log("starting loop");
for(let name of gen){


// generator created

// starting loop
// inside iteration
// xuan
// xana
// iyan

Wednesday, 21 June 2017

A Distaste For Expression Bodied Members

I really like to see programming languages evolve, getting new features version after version. Even if some of those features are not particularly useful or revolutionary, but just a way to make code less verbose, I appreciate them, as I like to see evolution and dynamism, being forced to learn something new. Microsoft has put quite a bit of effort in saving us to type repetitive code and do our code more concise. The introduction of Automatic properties was a huge step, and the improvements done in the last versions (default values for Automatic properties, read only auto properties, and both features combined) are pretty sweet.

//Automatic property with default value
public string FavoriteCity {get; set;} = "Paris";

//Read Only Automatic property (I'll be setting its value in the constructor
public string BirthCity {get;}
//Read Only Automatic property with default value
public DateTime BirthDate {get;} = DateTime.Now;

Another "big feature" in terms of type strokes saving has been Expression Bodied Mmembers. Honestly, this feature feels like a bit irritating to me.

So now you can write a method like this:

public int FormatString(string st) => $"---{st}---";

//rather than like this:
public int FormatString(string st){
return $"---{st}---";

I don't see it particularly helpful, but guess others will find it cool. The problem for me comes when we use it with Automatic Properties. Let's see:

public string FrenchFullName => $"{this.LastName.ToUpper()}, {this.Name}";

//is equivalent to:
public string FrenchFullName 
 get{ return $"{this.LastName.ToUpper()}, {this.Name}";}


//And here an identical method

public string GetFrenchFullName() => $"{this.LastName.ToUpper()}, {this.Name}";

So in the first line I have a property and in the last line a method. At first sight it's not easy to see if it's a method or a property, the only difference is the extra "()". If you follow the correct nomenclature, properties should be nouns and methods should be verbs, there's no room for confusion, but anyway, I feel a bit uneasy with this similarity.

Furthermore, this syntax can be applied to create local functions (added in C# 7). So you can write alocal function in any of these 2 ways:

public static void InternalFunctionTest()
   string applyFormat(int num){
    return $"[{num.ToString()}]";
   string applyFormat1(int num) =>  $"[{num.ToString()}]";

If you use the second way, it looks a bit similar to what we would have done in the past if we wanted to avoid polluting the class with a function that is only used from a certain method, write it as a lambda:

Func<int, string> applyFormat2 = (int num) => $"[{num.ToString()}]";

Under the covers, this is quite different from the expression bodied local function. In this case we are creating a new object, a delegate, while with the local function such object creation is not needed. There are more differences in terms on where the compiler creates the underlying method and the use of closures, but I've read some contradictory informations about this, so I'll have to spend some time to get the complete idea.

The "=>" syntax has been a pretty bad choice in my opinion and probably the source for my distaste for Expression Bodied Members . It's linked in my mind to delegates, so it takes my brain some extra cycles to break that association each time I see this symbol.

Saturday, 17 June 2017

Current Directory

The Current Directory (or Working Directory or Current Working Directoy) of a process is one of those topics that I seem to clearly understand, but after a while I partially forget and have to strive to rebuild it in my head, so I'll do a dump it here after that last build. I'm talking only about Windows, I guess the behaviour in Linux and the different UI Shells will be similar.

Every windows process has an associated Current Directory. This is the folder that the process will use as root for any relative path that it tries to access. You can see it with Process Explorer. So, how does a process get its working directory assigned?

The CreateProcess Win32 API function has a parameter to set the Current Directory. If NULL, the Current Directory of the parent process will be inherited. Higher level mechanisms used to create processes (and that ultimately make use of CreateProcess) will usually give you the option to provide the Current dDrectory (like in .Net with ProcessStartInfo).

OK, the above is good to know when we are writing a program that will launch another process, but how have the writers of common OS components handle this? meaning, how does this work when a program is started from the command line or Windows Explorer?

The Windows command line. cmd.exe has as Current Directory the folder where it is currently located. If you do a cd, the Current Directory will get updated accordingly. When you start a process from the command line, the process will inherit the Current Directory from cmd. This means that if you do this:

c:\Temp>cd c:\myAppFolder
c:\myAppFolder> myApp.exe

myApp.exe will have as working directory c:\myAppFolder

But if you do this:


myApp.exe will have as working directory c:\Temp

Windows Explorer. There are several ways in which you can launch a process from Windows Explorer (explorer.exe). Browsing to the folder containing the .exe file and double clicking on it, or typing the path to the exe in the Windows->Run window, is the same, Explorer will set up as Current Directory the folder where the .exe file is located.

An additional way to launch process from Windows Explorer is through a shortcut. If you check the properties of a shortcut you'll see a Start in field. If filled, that value will be used as Current Directory. If emtpy, Explorer will set the program's Current Directory to the folder where the shortcut is located (quite commonly the Desktop).

A process can easily change its working directory while running, by using the SetCurrentDirectory Windows API function. From .Net you can use the Directory.SetCurrentDirectory method.

As far as I know there is not a public API for changing the Current Directory of another process. The option that I've seen is pretty hackerish, injecting a dll in that process and invoking SetCurrentDirectory from its entry point.

As far as I know, by default Windows Services get as Current Directory C:\Windows\System32\, I guess because they inherit it from services.exe

Finally, there's an interesting quirk to bear in mind with .NET applications. The standard configuration system (the old school System.Configuration.ConfigurationManager, previous to the introduction in .Net Core of the much more advanced Microsoft.Extensions.Configuration) is pretty smart and does not use the Current Directory to locate the myApp.config file that has to be located next to myApp.exe, it will get the folder containing our binary and search the app.config in it, so in terms of configuration you don't care about the Current Directory and whether your app is started via explorer or from the command line or from another process. If you move to using a different kind of config file placed also next to your binary, you'll have to start to consider that the Current Directory could have different values and is not a reliable way to get the file.

Wednesday, 31 May 2017

Intel Fuck Off

Less than 1 year ago Intel announced that they were closing all their research centers in France (the 2 main ones were located in Toulouse and Sophia Antipolis (Nice)). The idea came like a shock, at least in Toulose, as the center here seemed to be working pretty well, and indeed it had grown in the previous months when the employees of the small center in Montpellier were transferred here.

From what I've read the French government provides companies with huge aids to their research efforts. It seems Intel took benefit of this support for a few years and then decided to close as part of their "restructuring efforts". I guess they just found another place where to get more aids... Well, you know, multinationals behave like that, and if their roots are in USA obviously they don't give a shit about "decadent Europeans"

To common surprise, last week a happy ending to this story was revealed. Renault is taking control of both sites, that will make up a new structure in Renault dedicated to connected and autonomous vehicles. This seems to be a pretty good deal for Renault, that expects this will help them to highly speed up their development on these fields. As for the employees, I assume that moving into a French company that keeps in France its main R&D facility, the Technocentre, which hosts around 8000 employees, the change should be rather reassuring.

It's also pretty good for Toulouse and its attempts to diversify its economy beyond the Aeuronautics sector. While the initial bet, the health sector (Oncopole), is moving rather slowly, the sector of technologies around "terrestrian transport" seems to be moving pretty good. In addition to this announcement from Renault, 2 months ago Continental announced that they would be launching here a new facility focused on "connected vehicles".

Saturday, 20 May 2017

Lyon Mural Paintings

I already praised the gorgeous city of Lyon some time ago. The beauty of this city continues to mesmerize me each time that I go there. French classic architecture, the imposing Rhone, the lovely Saone, the hills and their viewpoints (la croix-rousse is such a cute quartier), the "grandour" of Tete d'Or, the smart urban planning, pieces of modernity like the Tour Incity and Confluences... There are so many things to appreciate that I think they managed to distract my attention from an element that in other cities would have caught my eye quite earlier, the amazing mural paintings.

In first term I would not think of Lyon as a hotspot for Street Art, but indeed it is, as it boasts a huge number of astonishing mural paintings. In general these murals follow a more classic style, so I've had some problems to associate them with street art (mainly cause I've usually been more dragged to less conventional works like those of Blu, ROA, Hendrik Beikirch), but classifying something as street art has little to do with the style, but with the intent. Putting up art on the street for others to enjoy (get moved, awakened...) for free is the essence of Street Art, and these mural paintings obviously adhere to it.

In my last visit to Lyon I got delighted by the massive Mur des canuts. It's just beautiful. The explanation given here is pretty complete, so I will not repeat it with different words. I will add one thing that really fascinated me. As the article explains, this piece of art has been redone on 3 occasions. Well, it has evolved, treated as a live scene. The portion of neighbourhood depicted in this work has evolved over time, new shops have opened, the building facades have got revamped and vegetalized... but most importantly, the different characters that appeared in the first installment have also evolved with time, not just by getting smartphones or other modern elements, but by growing, getting older... I'm not sure about the particular changes, but one could think that maybe someone that in the first version was a kid in the second one would have turned into a teenager and in the third into a "family guy". For the occasional visitor this will not have much effect, but for those that have lived with this painting for years, it makes it a living element of their lives.

Sorry for the low quality, I took the pics at night, and I quite don't like using a flash:

Most of these amazing mural paintings have been created by the artists collective Cité-creation. Visit their website, it's just amazing. In this article there is a good overview of their creative path. Reading this paragraph below brings to my mind the words of wisdom written by Banksy 3 decades later in "Wall and pice"

In the early 1970s a group of local students got to discussing the closed nature of the art world, concluding that art was a form or expression largely confined to galleries and museums. Murals, they decided, would bring art to ordinary people. They would be direct, effective in portraying ideas, and free.

Much of the mural work in Lyon follows the Trompe-l'œil technique, trying, very successfully in many occasions, to create a 3-D effect that when seen from a distance really makes you think that you are seeing real buildings rather than a painting. In that sense, this one in Montpellier continues to amaze me each time I pose my eyes on it

Sunday, 14 May 2017

Macron President

Let's start this post with an enormous exclamation of RELIEF.
OK, now let's go on. 20.743.128 (66.10% of valid votes) French citizens saved The French Republic last Sunday by giving their vote to Emmanuelle Macron. Some did it by conviction, others to stop the FN monster, to make sure their plan to destroy the France and the Europe that we know, to throw us into isolation, chaos and misery, could not be carried out. The French Republic has been saved, hopefully we have not followed the path into disaster followed recently by UK and USA voters, and we can look at them with superiority and say "Fuck you, we are cultivated Europeans, you are anglosaxons".

I don't want to devote much time to the 10.638.475 (34.90% of valid votes) idiots, ignorant beasts or whatever that voted for Marine Le Pen. If the catastrophe had taken place and she had won, they would have suffered the consequences of their ignorance or evilness once the French society and economy had got disintegrated. After all these years of dediabolisation, where the FN has made a huge effort to present themselves as "normal folks", I used to think that good part of the vote for the FN came out of the (justified) fear of Islam and criminality, the rejection of the other old and corrupt parties, the confused vision of the EU as a source of evil, and so on... After the electoral debate on May 3rd, where Marine Le Pen drop her mask and behaved like a violent, almost crazy beast, vomiting all sort of insults, lies and unfounded accusations, I can no longer think of any kind of justification for those who voted for her. They are either people with cognitive deficiencies or ultra-nationalist, xenophobic bastards full of hate.

As for the 25% of people that did not vote, and the 4 million people that voted either blank or null, I have basically the same bad feeling and contempt as for the FN voters. I quite understand that some people decide not to do the effort to choose between Sarkozy and Hollande (or between PP and PSOE in Spain). You don't see much difference between having one or another managing the country, so you just don't give your opinion (indeed, I have not voted in the last Spanish elections). But if you are not able to see the difference and make a choice between the Le Pen clan and Macron, you are full of shit. My disdain (well, it's stronger than that, it's hatred) goes in particular to those alleged "lefties" that in the first round had voted for Melenchon's sect (La France Insoumise), or even worse, for the NPA islamo-stalinists, and in the second round decided not to "get their hands dirty" voting for a "banker" (as they call Macron), letting the door open to Le Pen. Those that (in Melenchon's stupid vocabulary) could not choose between the "extreme-droite" and the "extreme-finance". I think these so called "lefties" have also drop their masks. These people have waved the flag of anti-racism, multi-culturalism, open society and so on cause it's part of the "left-culture", but indeed they don't give a shit about it. They have only taken into account the economical dimension to decide between FN and En Marche, and as many of them in their ignorance have judged that the "liberalism with human face" of Macron would be as bad as the senseless economical program of Le Pen (that is indeed not much different from Melenchon's "utopia"), they have preferred not to help us to stop the human drama that the FN would bring about, because as I say, internally they don't really care about xenophobia or discrimination, it was just a trendy piece of clothes that can be taken off and thrown into a drawer. It's particularly painful to think that for sure many of these scumbags will have vehemently accused of "Islamophobia" to anyone critizising radical Islam, but now they would not give a shit about the mispolicies that Le Pen would perpetrate against any Muslim...

These "lefties" are so radical and so "insoumis" that not even the calls to vote against Le Pen launched by most of the progressist media were able to make them change their mind. They do not obey (I mean, they only obey to the Melenchon "comrade")... I'll put here some of the calls to actions that some decent media put up that week, they make up part now of our history:

Charlie Hebdo front page: Is it really necessary to do a design?

Charlie Hebdo last page: Is it really necessary to do a speech?

Le Canard Enchaine: The Canard also advocates for the "ni-ni": Neither Marine nor Le Pen

Liberation: Do whatever you want, but vote for Macron

L'Humanite, the French Communist Party newspaper, (yes, the PCF does not get on well with the Melenchon bastard)
Let's stop her!

Les Echos, an economy magazine: Defeat the extremism

Before closing this writing, I'll share my shocking experience with one of these "I don't give a shit" individuals (I don't know if he voted in the first round or not...). Last Sunday afternoon I was sitting on a train on my way back to Toulouse. It was 20:30, I had no data connection on my phone (I'm not plannig to explain why), SNCF does not provide WiFi on board and obviously I really needed to know the results, to know if our world as we know it was going to shit. I looked around (assuming everyone would be reading like crazy Le Monde, Le Figaro or whatever source of electoral information... but it was not the case). So I chose one twenty-something guy that was reading a comic on his phone. When I asked him if he knew the electoral results he looked at me absolutely surprised, asking me "the presidential elections?" He searched on google and showed me the good news, France (and Europe) was saved. The guy had not looked at the results until that moment and was totally surprised that anyone could have the slighlest interest on them. They guy was indifferent, absolutely unaware of the big difference that it would make for everyone's life (including his life) that Le Pen would win. He showed no emotion at all when he showed me the results on the screen... An authentic "Je m'en fou/I don't give a shit"...

A tous ceux qui ont voté pour battre Le Pen, MERCI

A Melenchon et NPA, allez vous faire foutre, collabos de merde (avec Le Pen et avec les islamistes)

Thursday, 4 May 2017

Macron ou la guerre

We are just a few days far from the most decisive elections in the modern history of Europe, the second round of the French presidential elections. There are many different things that I'd like to express here, I could probably write like 4 or 5 posts, but I have no time for that, so I'll summarize it all together in this chaotic writing.

I don't know to what extent people in the whole of this continent are aware of what is at stake. If Le Pen were to win this Sunday, the European Union is over. I hardly can imagine a world without European Union. A world were I would have to ask for a Visa to go to Berlin or Paris. A world were I could not opt to a job position in one city that I love because I was born in "the wrong place". We are used to other people having to suffer these constraints, to feel pity for them and relief for us, for being so lucky to be Europeans in the XXI century, to be the "easyjet generation"... free to travel and to find a place we like and have the possibility of staying there. All that would be over. That's the first, more direct consequence, but then would come the worse. Countries would withdraw and close on themselves, and us, the citizens, would do so. Nationalism would be back, stronger and more stinky and repulsive than ever, and with Nationalism, sooner or later, would come war.
You think I'm overstating? Just take a look at our history... Alsace-Lorraine comes to mind as a "nice" pretext for a Franco-Prusian war v.3.0. And there would be many more pretexts. Above all, the brutal economical crisis that would come with the death of the European Union would cause such internal turmoil that starting a war would be the best way to distract the population and make them address their hatred to an "external enemy" rather than the internal beasts that caused this disaster. In a multipolar world where our small countries of 80, 60, 40, 10... millions inhabitants are just nothing compared to USA, Russia, China, India, Brasil... what a better way to feel important again and find our new place in the world that trying to beat our neighbour in a senseless war...

Honestly, when the results of the elections of the first round were announced with the good news of Emmanuel Macron arriving on the first position, I thought the problem was almost fixed. I assumed everyone would join on the second round to vote Macron to defeat the Le Pen clan. It's what happened in 2002, when every normal citizen voted for Chirac (even if they had to cover their nose) to defeat Le Pen (the father). To my horror (and the horror of so many normal citizens that can not understand how lost and stupid one part of the population is), this has not happened. This time there has not been a Front Republicain to defeat the FN. Sure the socialist party has called to vote for Macron without any sort of doubt or ambiguity. Most of the main figures in Les Républicains have also done so (Fillon, in an act that manages to dignify a bit such a gloomy individual, Alain Juppé, Sarkozy), but the party itself has not taken an official stance. The serious issue comes with "the radical Left". Jean Luc Melenchon, the LEADER (I put it in uppercase because I sense quite a sort of stalinist personality cult around him) of that new far-left movement called "La France Insoumise" has shamefully opted for the "ni-ni" (neither Macron nor Le Pen). He has not asked to vote for Macron, he has just asked not to vote for Le Pen. This is a disgusting act of irresponsability (at the best) or a meditated, machiavelic political plan for the next elections (make Macron weak for having obtained a minimum victory, or just let Le Pen reach power so that chaos starts and people cry for their 'Left savior") at the worst. Everybody knows that not a single Le Pen sympathizer will fail to put his nauseating vote in the polling box, so abstention or voting blank is not an option at all. Melenchon says to want to keep his vote secret and not to want to force people's vote, but with his continuous critics to Macron "he's the candidate of the banks, he's the candidate of the financial system..." he's indeed pushing the electorat of the France Insoumise to abstention/blank vote (or even worse, bearing in mind that a 10% of these alleged "revolutionaries" intend to vote for Le Pen...). Melenchon has just become a collabo like Pétain in the WWII.

Hopefully, some of the political organizations that make up "la France Insoumise": the PCF and the Front de Gauche, have asked to vote for Macron with slogans like "first let's defeat Le Pen, then let's fight against Macron", but based on what I could see in Paris the other day and what I can read on the news, it does not seem like they are having too much effect... This leads us to the next level in human stupidity, some of the "left radicals" that either voted for "les insoumis" or for other worse political sects like NPA or LO (or that directly did not vote) and are now trying to convince others to abstain. These "saviours of humanity" that in some cases make up the rangs of the infamous "black block" that ruins legitimate demonstrations attacking the police and destroying public property. These "left warriors" that have converted the Antifa movement in France in something close to a terrorist organization. These "freedom fighters" already took to the streets as soon as the results of the first round were announced to protest against Macron and Le Pen likewise (and to take the opportunity to destroy public property and attack the police once again). When these idiots put both candidates at the same level, using phrases like "neither finances dictatorship nor fascist dictatorship", "neither plague nor cholera", "capitalism == fascism", they are putting our society at risk, cause there are other idiots that will believe their crap and decide not to vote for Macron just to feel rebellious and cool, just because it's becoming trendy... These criminals are just planning "to fight Le Pen on the streets" if she wins... cool... Are they plannig to do like last Monday in Paris, setting a policeman on fire??? Interesting that last time I saw someone being burnt alive it had been ISIS the author. Bearing in mind that a certain part of the "far-left" is sympathetic with (when not openly defends) Islamists, it's not so odd that they learn "battle techniques" from them...

If I had the French nationality I would have already voted for Macron in the first round. It's not that I were entusiastic about him, I would have preferred a hard guy like Manuel Valls or Sarkozy (unfortunately both had been kicked out in the respective primary elections of their parties) that would have a harder stance towards Islam and criminality, but all in all I think he can be a pretty good president for this country and a great asset in order to help to put the European project back on track. For sure my political views have changed enormously in the last years. I have nothing to do with the "left radical Asturian nationalist" that I used to be just a few years ago, but I'm pretty sure that even if I were still lost in such ideological nonsense, in a situation like this I would have voted for who I would have considered "the lesser evil".

I belong to a generation that has been lucky to never have lived a war on its territory (and which parents enjoyed also that privilege), and suddenly, these days waiting for the results on Sunday evening, it seems a bit like what other generations had to feel the days before an imminent call to arms or the signature of a treaty that would avoid the conflict. Next Monday, the aftermath of this dramatic election, it's the 8th of may. On this date France celebrates "Victoire", the victory over fascism in the WWII. I really hope this year we'll be able to do a double celebration.

I pretty liked this article by Marjane Satrapi (the author of Persepolis). As someone that found refuge in France after having to flee her birth country to escape a dictatorship she can not understand that people will decide not use their vote as a weapon against horror. I'll reuse the last lines of her post to close this one:

Votez Emmanuel Macron!

Vive la Liberté!

Vive l’Egalité!

Vive la Fraternité!

Et vive la France!

Friday, 28 April 2017

J'adore Femen

Years ago, when I first knew about Femen, I got quite interested on them, but I have to admit that it was more due to the nice view of young women in topless protesting histerically on the streets that because of their feminist agenda. Of course I consider men and women should have equal rights, but living at that time in one of the few parts of Westen Europe where Islam basically did not (and hopefully still does not) exist, I used to think that these equal rights were a reallity (and indeed in some cases: child custody after divorce, parity rules, positive discrimination... women had more rights than men). At the same time, I understood that Ukraine was a much more conservative (backwards) society, and sure things were different, but anyway I was more interested in their "topless attitude" :-)

At the same time, for my Western European mind it was odd that these feminists would protest "with almost no clothes". For me the main problem for women was their reduction to sexual objects and all the social pressure that comes with it (look beautiful and sexy or be a freak and a loser), so showing their almost naked bodies to defend the women's cause seemed contradictory to me. Of course it was a way to gather (a lot of) attention, but anyway it seemed odd and dubious to me.

Over time their protests became more and more interesting. They were confronting the (radical) Orthodox church and the Islamists! At one point one of their main members cut down a cross in Kiev. Over years I've become less and less critical to Christianity (if people need a religion to fill their spiritual needs better that they chose Western style "humanist" Christianity rather than "humanophobic" Islam...) but the ultra-conservative Eastern Europe Orthodox Church (homophobic, nationalistic...) is a different story, so I almost entered in ecstasy with that video :-D

After this the activist Inna Shevchenko, had to search for refuge in France (Tu es la bienvenue chez nous!!!), where she has developed the Femen branch. Their actions in France (at least the main ones I'm aware of) have been corageous and praiseworthy, confronting Islamists and the FN likewise. Seeing 3 bare breasted women burn a salafist flag in front of the Great Mosque of Paris was almost orgasmic to me! With this action they moved from activists to heroines.

I had not thought much of them in the last years, until I read a pretty intesting interview in Charlie Hebdo on the occasion of the release of a book written by 2 of their members, Inna and a French Madeimoselle, "Anatomie de l'oppresion", dealing with the oppresion exerted by religions over women

"A radical and enraged essay, a lawsuit for 'blows and wounds' against religions" - Coco, Charlie Hebdo

In these last years in France I've seen to what extent (one form of) Islam is trying to destroy our freedoms and our mixed society. How it asks its followers to keep away from the infidels prompting them to live in a separate, medieval community until the day they manage to conquer the whole country. How it despises women turning them into worthless objects. There are neighbourhoods in Paris where a normal Arab woman will be insulted (at the least) for not wearing a scarf and will not be allowed into a bar!!! (This form of) Islam is the biggest enemy of humanity, and of women in particular. So suddenly, I've realised how powerful a weapon against these medieval beasts the naked body of a rebellious woman is. It represents all what they hate and fear, a proud woman, shameful, corageous and ready to kick their fucking, hairy balls. In a sense we are back in the 60's, when women would wear a mini-skirt as a symbol of freedom and rebellion against the moral rules of conservative society. This made them dangerous and scary rather than weak objects. Femen has managed to turn the female body into a very threatening object, into a weapon, at a time when because of the reIslamisation of the population of the "quartiers populaires" and the arrival of more Islamist invaders, this is more necessary than ever. We need this courage and determination in both women and men to defend our society and freedoms from the horrors of radical Islam or Nationalism. Notice that Femen's headquarters in Paris have been attacked by neonazis. It's interesting that these bold aryan warriors attack a feminist centre but don't have the bollocks to attack a Salafist indoctrination centre (aka radical mosque) or the conferences of that anti-white, anti-French group of criminals and proto-terrorists kwnon as Les indigenes de la Republique.

I learnt in the interview that a few years ago some designers were inspired by Inna Shevchenko to create a new stamp representing Marianne.

It makes pretty much sense. Almost 2 centuries separate the amazing representation of Marianne (the French republic) in the canvas by Delacroix, "La Liberté guidant le peuple (Liberty leading the Peope)" from the Femen protesters, but one can see in them the modern incarnation of Marianne.

So Femen, please, continue to kick the balls of bearded medieval fascist ("Niqab ta mére - Fuck your mother") and new style nationalists as hard as you can! Vive la République laïque!

Friday, 21 April 2017

Http.sys update

Things have changed a bit since I wrote about self hosted web applications in .net and http.sys 4 years ago, so I'll write a short update.

In the past your (Microsoft based) self-hosting options were based on HttpListener, that relies on the powerful http.sys kernel driver. As you can read here we have now 2 alternatives for Asp.Net core. If we still want to leverage http.sys we'll be using the WebListener embeddable server. This is the evolution (it started as a fork) of the HttpListener. Notice that WebListener has been created just to take advantage of http.sys (by means of the HTTP Server API), so it is only available for Windows, it will not be ported to Linux. If you want to run your application on both platforms you should use the other alternative, Kestrel. Time ago the the Mono folks implemented HttpListener for Linux, which made much sense at that time as there was not any other alternative component, but with the multiplatform Kestrel there's no need to port WebListener.

There's an important general difference between Unix and Windows regarding ports. In Unix you need to be root in order to listen on a port below 1024 (a privileged port), but this limitation does not exist in Windows. So when running kestrel on Linux you'll have to be careful to use a port above 1024 (unless you want to run kestrel as root, that is not a particularly good idea).

On the other side, if using WebListener you'll also be have to be careful about ports and permissions, though this is due to how the underlying http.sys works. This kernel driver is the one that listens for http connections, and your WebListener application has to register with it (hey, listen on this port and redirect anything with this url prefix to me) so that it redirects the incoming connections to your application. If you are running your application as admin you'll be able to register on any port, but if you are not admin things can get a bit more complicated. Registering your application with http.sys for ports under 1024 is protected, so for a non admin user to be allowed to do so you will first have to configure http.sys giving the user permissions on that port/url. It's what you do with the netsh http add urlacl command.

When using Kestrel on Windows there are situations where you still need to be aware of http.sys, particularly if you are trying to run Kestrel on port 80. On some occasions this port will be already taken by http.sys, so if kestrel tries to listen on that port you will get an error. Notice that Kestrel is totally unaware of http.sys, so it does not try to register with http.sys, it just directly tries to take the port. As far as I know http.sys is loaded into (kernel) memory by Windows at start up (as many other drivers), but it will not start to listen on any port until a process asks for it. This is how it looks on my home machine.

Http.sys is loaded into memory and it has a couple of kernel threads running (Process Explorer shows these under a fictitious "system" process. If you check the TCP/IP connections for that pseudo-process you'll see that the http port is not taken, so I have no problem to start another web server on that port.

However, on my office laptop I can see that port 80 is taken by the "system" pseudo-process (hence, it had to be http.sys who is taking it). So some process that I'm not aware of has asked http.sys to listen on that port. In a situation like this, if we need port 80 for another Web Server not relying on http.sys, the best we can do is to disable http.sys as explained here.

Don't be confused by the use of sc to unload it. Http.sys is not a "normal" service (notice that you will not see it displayed on services.msc), but one kind of drivers (like http.sys) can be installed and loaded/unloaded through the sc service interface. This in the end calls into the CreateService function in advapi32.dll, passing as parameter the SERVICE_KERNEL_DRIVER value. So in a sense we could consider these drivers as "Kernel services".

Friday, 14 April 2017

Overriding Extension Methods

The other day I found that there is a proposal to add "multiple inheritance of behaviour" to C#, by means of allowing you to add "implemented methods" to interfaces. This is basically what was done in Java 8 with "default methods". I talked about them some years ago.

So far we could get a limited taste of this by means of Extension Methods (as you know this has been the way to extend IEnumerable with all the Linq methods). So, what's the difference with default methods?

Extension Methods are a bit more like a hack. They are like a limited form of the object expansion (monkey patching) that you do in JavaScript (when you assign a new method to a [[prototype]] or the object itself. I say limited cause there is a main problem with it. It's a static, compile-time artifact, hence it can not be overridden. I mean, let's say I have this code:

interface IPerson
 String Name {get;set;}

static class PersonExtensions
 public static string SaySomething(this IPerson person)
  return "Hello, I am " + person.Name;

So I have an IPerson interface and we sort of expand it by adding the SaySomething extension method. The problem here is that if I have a French class were that method is redefined (it's not properly overriden, as it is not part of the interface itself, just an extension), if I use the interface, I will continue to call the extension method rather than the overriden one. The compiler just sees an interface and a method call not directly in the contract, but in the extension, and statically binds that call to the extension method. With default methods in Java we would get the dynamic behaviour.

public class French: IPerson
 public string Name {get; set;}

 public French(string name)
  this.Name = name;

 public string SaySomething()
    return "Bonjour, je suis " + this.Name;


IPerson iP = new French("Charlie");

// prints "Hello, I am..."
//it calls the extension method (PersonExtensions.SaySomething) rather than French.SaySomething

Could we do something to "fix" this with extension methods? Well, I can think of a rather ugly hack, but it could come handy. We would have to include in those extension methods that we want to make overridable the code that checks if type for the specific instance that we receive in this call is redefining the method. Something like this (just a POC, I'm not checking parameters, only the method name):

 static class PersonExtensions
 public static string SaySomethingOverridable(this IPerson person)
  if (person.GetType().GetMethod("SaySomethingOverridable") != null)
   dynamic aux = person;
   return aux.SaySomething();
   return "Hello, I am " + person.Name; 

IPerson iP = new French("Charlie");
//this one goes through the Extension method that contains the type checking and allows the overriding
//so it prints "Bonjour, je suis..."        

Saturday, 8 April 2017

La Tour d'Occitanie

A few weeks ago the great project was revealed, Toulouse should boast a 150 meters skyscrapper around 2022. The project is absolutely beautiful. A vegetalized tower, a "spiraling garden" overlooking the lovely Canal du Midi, the Central Train Station and a revamped promenade (I refuse to call it "Ramblas" as the city council does, this is proud and beautiful France, not Catalonia...). Furthermore, it'll be the entry point to TESO (Toulouse Euro SudOuest), the future business district surrounding the train station. As someone that pretty loves modern, high quality, high rise buildings, I'm pretty excited with this project, though I'm afraid there will be many obstacles on its way (but it has already overcome a good deal of them!).

This project is conceived as a very much needed signal of architectural modernity in an open and prosperous city in which the mediocre architecture of the last 60 years has not lived up to the beautiful constructions of its past. It's a way to put the image of Toulouse (in modern architectonic terms) in line with those of Lille or Marseille (or even Lyon, but this gorgeous city plays at a different level, it's really like a small Paris). Each of these cities has at least one modern and beautiful "skyscrapper" (in France more than 100 ms can be considered like that) and is building a new one: the existing CGA-CGM tower and the new La Marseillaise tower conceived by Jean Nouvel in Marseille, the existing EuraLille towers and a new planned tower to host some administrative offices, the beautiful Tour Incity in Lyon (that also has some more planned)

In general the local reactions to this announcement have been quite positive, which has been rather surprising for a city so conservative when it comes to architecture, and infested by the kind of stupid "ecolos" that basically are against everything and still think that high-rise buildings damage the environment, when it's absolutely the contrary, modern high-rises are the most environment friendly kind of construction. The socialist party (in the opposition) has embraced the idea, and reminded us that it was them who included in the PLU (urban plan) the possiblity of building a 100 meters tower in Montaudran Aerospace (unfortunately for the moment promoters do not seem to be interested in this project, the crazy French security laws that apply to new buildings higher than 60 meters make them so expensive that only projects in very sought-after areas can be carried out). Many people see this like me, as a necessary architectural signal that will put Toulouse at the level it deservers

As for the negative reactions that we can read online, we have several types. Some of them are totally respectable. Some people do not like high-rise buildings due to their own personal sens of aesthetics. OK, I accept that, each one has a sense of aesthetics, I love gothic but I don't like renaissance that much, I love dark clothes and hate clear ones... So I love (well done) high-rises, but others don't. But most of the negative reactions are so fucking stupid...

  • Who's going to pay?. Well, it's not due to host any public institution, only private entities (Hotel, offices and appartments). It's private inverstors who are in charge of the project, the city council is not putting a single euro. On the other side, the roof top with amazing views over the city (and the Pyrenees in days of high visibility!) will be open to the public. So well, we are getting for free an architectonic landmark that will help to put the city on the spotligt and a public space like no other one in all of Southern France. Seems like a deal to me :-)
  • They better invest the money in improving people's quality of life. As I've said this is 100% private investment, so up to you to try to convince the promoters to invest their money in setting new bike lanes or public parks, I guess they'll consider people's smile and gratitude as a more than enough return of investment...
  • It does not match with the architecture of the city Oh, yes, that's true, it's what usually happens when something completely new is done, it's different from the rest. I guess the first wooden hut would feel pretty "unfitting" to the folks living in caves, and the same later with the first stone houses, the first glass windows and so on. If all these "experts in urban planning" and "ecolos" of today had lived centuries ago gothic cathedrals would have never been built because they didn't fit with the existing buildings and being so high and slim made them look like "phallic symbols"...

The main and recurrent complain (and I fully agree with such complain) is the English name, Occitanie Tower. This is France, and there is absolutely no reason to use an English name for something called to be a symbol of "notre ville". It's clear that Tour d'Occitanie makes much more sense. In Paris, you delight your eyes contemplating Notre Dame, not Our Lady. Furthermore, with the Brexit it's time to rethink the role of the English language in the European Union.