Sunday, 5 July 2015

AD Fast Querying

The other day at work I went through again a issue I had already experienced in previous occasions. Querying the Windows AD for some basic need can be terribly slow. I have no idea about why, but I've suffered this while querying different AD's (from different companies). So this time I've gone through an alternative route.

As far as I know the recommended way to query the AD from modern versios of .Net is using the classes in the System.DirectoryServices.AccountManagement namespace, like PrincipalContext and UserPrincipal, so if you want to get the AD groups a user is member of you would do something like this:

private static List<string> GetGroupNamesBasedOnPC(string userName, string domainName)
 {
  List<string> result;

  using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domainName))
  {
   using (PrincipalSearchResult<.Principal> src = UserPrincipal.FindByIdentity(pc, userName).GetGroups(pc))
   {
    result = src.Select(sr => sr.SamAccountName).ToList();
   }
  }
  return result;
 }

The above code is terribly sloooooowwwwww.

Hopefully, there are alternatives (don't ask me why these alternatives are way faster, I have no clue).

  • You can use the very fast net user command like this:
    net user userName /domain
    notice that it will search the current domain, so the "/domain" string is right that, you don't have to replace it by the domain name, I mean:
    net user francoise12 /domain
    The problem with that approach is that the returned string comes formatted for the Windows Console and some characters can be trimmed. So large group names will be trimmed and this command is not valid for general cases.

  • Another option is using the gpresult command, as along with information about the installed gpo's it will also return the list a groups for the current user, and this time with no odd formatting causing trimming.
    gpresult /user ng3419a /r
    The problem with this is that it only works for the current user, you can't pass the user name as parameter

  • And finally the good one:
    net group groupName /domain
    Here you'll get a listing with just the group names, one per row, so no trimming problems. The windows commandline is not that primitive as many people use to think (and yes, of course with PowerShell is really powerful), so if you just want to verify if a user belongs to a certain group you can pipe the output to the find command like this:
    net group groupName /domain | find /I /C userName
    If you want to run it from a .Net application you just do this (notice that net group is a command, not a program, so the process that you have to start is cmd.exe)
    string command = "/c net group /domain " + group + " | find /I /C \"" + user + "\"";
    Process process = new Process();
    process.StartInfo.FileName = "cmd.exe";
    process.StartInfo.Arguments = command;
    process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    //need these 2 lines in order to read from the stdout
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.Start();
    process.WaitForExit();// Waits here for the process to exit.
    string output = process.StandardOutput.ReadToEnd(); 
    bool belongsToGroup = output[0] == '1';
    

Saturday, 27 June 2015

Simulating await with ES6 Generators

When I first read about ES6 generators I wrote a post about its differences with C# "iterators" (I'll say it again, horrible naming choice by Microsoft). At that time I read how people were taking advantage of them to write code resembling C#s async/await magic. It seemed hard and interesting to me to understand at first sight how both things were related, but I had no time to look into it at that time. These days, after glancing through this thorough and brilliant article I decided to try to understand it.

The first point to consider is that as mentioned in the article, generator objects created by a generator function implement 2 different interfaces: data producers (iterators, the Symbol.iterator thing), that's what you are used to in C#, and data consumers. The latter is pretty interesting as it's the feature that makes the await emulation possible.

The fundamental idea is that generator objects combine the producer and consumer role in a "next" method that receives a value and returns a value. You represent it like this in your generator function:

var b = yield a;

The essential part in that line is that it really means this:

return a to the current "next" call;
read b from the next "next" call;
and execute the following lines until the next "yield" is found and you return a new value from there);

between both actions, the generator function gets "suspended".

This idea of having your code inside a sort of function (in the end it's a kind of illusion, that function is bended by the compiler into a generator object where state is maintained so that this suspension/reentrancy can really work) is the basis of how async/await works in C#. So, if you return from your yield a sort of Task object that when completed would call the reentrant function again passing it its return value, you basically get the same. Calling the reentrant funtion means calling the generator.next from an async loop, so your Task objects will need a reference to the async loop function (that you will call from the continuation (nextStep property in my example) that you have added to the Task), so that they can continue the cycle.

The JavaScript kind of equivalent to C# Tasks are Promises, and it's what is used by the different libraries (like co) enabling this sort of async/await programming. For exploratory reasons, in order to fully understand this whole thing, when writing my "async/await enabling" function, I've decided to use a very basic TaskInfo object rather than Promises, I think it makes easier to understand how the whole think works with no need to know anything about promises. Indeed, seems like co also works with a sort of lightweight alternative to promises called thunks

I've put up the code in this gist.

Sunday, 21 June 2015

OrderBy vs Max

Some days ago I came across a piece of code by one colleague that caught me quite by surprise. He told me it was a performance improvement, and while in that case it was rather unnecessary and made the code less straight forward, it's good to have it in mind for other occasions. The idea is pretty basic, but I had never though about it before.

The example was in C# and Linq To Objects, so I'll stick to it, but it would be the same with JavaScript and underscore.js or whatever.

So we have a collections of City objects like these:

public class City
{
 public string Name {get; set;}
 public int Population {get; set;}
}

var cities = new List(){
   new City(){
    Name = "Xixon",
    Population = 275000
   },
   new City(){
    Name = "Berlin",
    Population = 4000000
   },
   new City(){
    Name = "Toulouse",
    Population = 1250000
   },
   new City(){
    Name = "Paris",
    Population = 12000000
   }
  };

and we want to get the most populated city. So I would just do this:

biggestCity = cities.OrderByDescending(city => city.Population).First();

while my colleage had written this:

var maxPopulation = cities.Max(city => city.Population);
var biggestCity = cities.First(city => city.Population == maxPopulation);

In the first code, regardless of the sorting algorithm used by OrderBy, we can say that you are finding the Max element n times (each time in a smaller collection), while in the second example you are finding that Max only once. Depending on the Sorting algorithm the first case will usually be O(n*log n), while the second case is O(n). As explained here, apart from the speed improvements, with the OrderBy approach you'll run into an Out of Memory exception if your collection is huge enough.

Saturday, 13 June 2015

The void Operator in JavaScript

The other day, while checking the source of underscore.js (I already mentioned time ago that it was a really beautiful code to learn from) it came to my attention some code like this:

return obj == null ? void 0 : obj[key];

That void operator, what is it useful for? (both in general and in this particular case). Checking in MDN, for this particular use you'll find this:

The void operator is often used merely to obtain the undefined primitive value, usually using "void(0)" (which is equivalent to "void 0"). In these cases, the global variable undefined can be used instead (assuming it has not been assigned to a non-default value).

So it's being used to safely assign the undefined value. "safely" means that when we use undefined this way: obj = undefined; you are using the undefined global property, that by default points to the undefined value, but that someone could have changed assigning it another value and breaking your code!

However, if you run this code in firebug:

var a = undefined;
undefined
a === undefined;
true
undefined = "xxx";
"xxx"
a === undefined;
true

You'll see that indeed the attempt to change the value of the undefined property has not worked! As usual, MDN has the explanation:

undefined is a property of the global object, i.e. it is a variable in global scope. The initial value of undefined is the primitive value undefined.
In modern browsers (JavaScript 1.8.5 / Firefox 4+), undefined is a non-configurable, non-writable property per the ECMAScript 5 specification. Even when this is not the case, avoid overriding it.

The reference for the void operator mentions another use case that really confused me:

When using an immediately-invoked function expression, void can be used to force the function keyword to be treated as an expression instead of a declaration.

So they propose creating IIFS's like this: void function(){}();
I see no use at all in creating an IIFE like that. I pretty much prefer the "normal style":
(function(){}());
or
(function(){})();
Using void adds nothing other than confusion and it looks to me as if we were in another language declaring that the function returns nothing.

Trying to understand if I were missing something with this I checked what seems to be the seminal article about IIFE's. There the author mentions some other utterly confusing ways to declare a IIFE, like these:

// If you don't care about the return value, or the possibility of making
// your code slightly harder to read, you can save a byte by just prefixing
// the function with a unary operator.
!function(){ /* code */ }();
~function(){ /* code */ }();
-function(){ /* code */ }();
+function(){ /* code */ }();

As the author says, it makes the code harder to read, for sure. I love how expressive and freak javascript is, but things like this seem utterly unnecessary to me.

Sunday, 7 June 2015

International Brigades 2.0

Volunteers have been joining the fight against the Fascist Beasts of ISIS in Syria and Irak since last summer. First volunteers came from USA and UK mainly, some of them had militar experience and were joining the battle in a Good vs Evil basis, to defend ordinary men and women from being decapitated, raped, tortured and sold as slaves by the Islamist terrorists. Most of them did not have a left wing ideology, and indeed some of them ended up not feeling comfortable being integrated in a left wing force like YPG-JPG and decided to move to other "not red" groups, like some Christian militias or the Peshmerga.

Since the MLKP (a communist Turkish-Kurdish revolutionary vanguard) made a call to join an International Brigade to fight against IslamoFascism and support the Social Revolution in Rojava, a new kind of western volunteers showed up, these ones with a clear left or far-left ideology. It's unknown how many foreigners make up the ranks of this left wing militia (notice that most foreign revolutionaries there are Turkish-Kurdish Communists and Anarchists), but for sure they have had a certain media impact, and have helped a lot to bring to the table of the European left the drama of the Kurdish people and the need of Antifascists to confront IslamoFascism in the same way they confront "White-Nationalist-Fascism".
I already talked about the German revolutionary Ivana Hoffman, sadly fallen in combat against the IslamoFascist scum, and already in February a video was released portraying 2 Spanish Revolutionaries in Rojava, along with German and Turkish ones.

I had not known much of these humanitarian fighters until today, when through the site of the Comite de Solidaridad con Rojava y el Pueblo Kurdo I've found this documentary by a Spanish TV Channel about the Spanish Revolutionaries there. Unfortunately it is in Spanish, but even if you can not understand the language, the images are well worth your time. From this video I learnt that these Spanish guys are members of the Marxist-Leninist organization Reconstruccion Comunista (Communist Reconstruction) a very militant group putting a huge emphasis in the political education of its members. Knowing this, it's clear that these guys have not been drawn into this battle just for a quest of adventure or a youngster impulse, I assume that they are educated left wing militants taking a reasoned and consequent decision. They had previously done some interesting declarations to other Spanish media. As I'm linking an article in "El Pais" I need to clarify that I feel rather little respect for this Paper. It has its own agenda dictated by Spanish oligarchy, which makes it painfully partial when dealing for example with topics related to South America (Venezuela, Cuba) where this oligarchy has neocolonial interests and attitudes. In no way can it be considered at the level of European real papers like "Le Monde".

This is not a fight against Islam, but for peaceful co-existence between different cultures, and not just in favor of the Kurds, but all humanity. We cannot accept simplistic arguments that Islam is to blame. We are not fighting against Muslims, but against the fascism that Islamic State represents, in the same way that people fought in Spain in 1936 or in Stalingrad in 1943.”

By the way, these pictures of their organization, Reconstruction Comunista, quite impressed me. I'm quite far from some of their political positions, as the concept of "class war" is now totally alien to someone like me that to a certain extent has ended up in the moderate, "System changing but not System breaking" left, but the way they parade through the streets of Madrid, baring communist and republican flags in an almost military formation is really captivating. It gives a sense of discipline, organization, power and willingness to fight that is now more necessary than ever. At these times when the fascist monsters carrying the poison of radical islam or xenophobia and racism are more alive than ever in our old continent, the left must be ready for confrontation, a confrontation that goes far beyond dialectic and keyboards.

Honor and glory to Antifascist fighters

Saturday, 30 May 2015

Monuments to Horror

Every time that I say that I'm going to Paris, Berlin, Marseille, London... someone will say: "again? but if you've been there many times". Well, it's a reasoning that I can not understand. If I like a place, I like to go back again and again, both because I want to repeat the experiences and because these experiences are never the same. If you like a certain food or music you want to taste it again, you don't get tired of it unless you taste it too often, the same happens to me with places. Furthermore, cities like the ones I've mentioned have so many things to see and do that I bet you could spend several lifetimes visiting them and you would not get tired (and in this kind of dynamic, ever evolving cities, you'll always find something new).

Last weekend in Paris I came across just by chance with a beautiful sculpture paying homage to the victims of racism and antisemitism during WWII in France.

The words on the monument read:

"The French Republic in homage to victims of racist and antisemitic persecutions and of crimes against humanity committed under the authority of the so-called 'Government of the State of France.'"

You can read more about this topic here. Obviously the different French governments have never had any problem acknowledging and condemning the disgusting role of the Vichy fascist and collaborationist government in WWII, pretty far from what happens with Spanish governments when it comes to admitting and denouncing the horrors of Franco's dictatorship. France is France, and Spain is ...

This monument reminded me a lot (particularly the small girl playing with a toy located right in the center) to the monuments in Berlin's Friedrichstraße Station and London's Liverpool Street Station to the Kindertransport to rescue kids from Nazi occupied Germany. I have particularly fresh in my mind the one in Berlin:

A plaque on it reads: "Trains to Life, Trains to Death". Its portray of kids with their baggages and toys marching towards hope or horror is devastatingly powerful and emotional, and ever that I pass by it I can't help but stopping for a while and plunge into some moments of reflection. You can check these pictures to get a better idea.

Wednesday, 27 May 2015

Expat vs Inmigrant

Words, can be beautiful, can be painful, too often we just use them without really thinking twice about their real meaning, about what they sometimes subtly hide. Expatriate (expat) is like a cool world now. I think I've used it occasionally, even to refer to myself. I think the first time I gained contact with this term was through some friends that had moved to Switzerland and were in an 'expats forum' to find people to meet (seems like many Swiss nationals tend to be a bit 'particular' about foreigners and it's quite unlikely that you will manage to socialize with them). The term has gained a lot of traction, so well, if you move to another country to work, you are an expat.

But, this situation has existed since the first time humans came up with the concept of 'countries', so in the past we used a different word, immigrant. But, hey, we still use this word today, and seems as if for just the same, people that move to a new country. So one could think that they are synonyms, but for sure they are not, we don't use them as such, they are not used interchangeably.

You could say that maybe expat is more like a temporal move, it's false, it's used by people that have been living abroad for many years, and furthermore in many occasions when you move you do not know for how long, life is to complex for that kind of certainties. Also, it has nothing to do with whether you are moving inside the Schengen Area, cause USA and Canadian citizens are expats, but Polish people, Romanians or Bulgarians are usually immigrants. It's not about qualifications either, some European high school drop outs move abroad to be expats, some African, south American, Asian... university graduates are immigrants. So it seems like both words establish a difference, there are 2 types of people that move abroad. It seems like expats are cool, they are there to help the country, they are valuable, they should be welcomed, they should not be randomly questioned for their ID by the police. Immigrants are not so welcome, they 'steal' jobs, they do not integrate, they take advantage of the social system, they scare people. Expats come by plane, immigrants sometimes too, sometimes by bus, sometimes by patera, sometimes die in our coasts or are received with hits and hate from the police. I think all this stinks somehow like racism and xenophobia. Expats are like us, immigrants are different. Us versus Others, the same rotten misconception that has always led us to disaster. I even think expats can be against immigration, both in their own country and in the new one, cause in the end they don't consider themselves immigrants.

So yes, expat is a perverse term, I don't like it. I will never call me an expat again. I am an EU citizen, I'm white (well, Southern Europe 'Olive' skin) and have a University degree, but from now on I am an immigrant, like the Cameroonian or Moroccan people that work with me. We are equally integrated and equally contribute to this country (indeed, they pay French taxes while I still pay Spanish ones).

Actually, I think the (*)migrant term itself is confusing, more properly, it confuses. There's a nomadic nature in human beings. There's a constant (or there should be), change, evolution. You move from one kind of music to another, from one kind of films to another, from one clothing style to another, from one place to another, life should be a journey of discovery in all of the infinite aspects that make up the human nature. Furthermore, when do you stop being an immigrant? If you have lived more time in the new country than in the original one, you are still an immigrant? does it have to do with getting the nationality? Again, I think the term is terribly confusing, we are just nomads wandering in a sea of confusion.