Thursday, 25 November 2010

jQuery Debug Console

Years ago it was rather frequent to implement your own JavaScript debug console, a pop up window (this was before draggable divs where so common) where you could send your "printf debugging" messages.

In the last years, Firebug, Chrome's JavaScript console, and others have come to replace these home made debug consoles, making them unnecessary for many people.
Well, in general it's also that way for me, but sometimes I feel like an old style home made console could be useful. One of the reasons is that at times it could be interesting to have more than one console.

So, I've prepared my own debug console. It's nothing far too interesting, I've just glued together some wonderful jQuery functionality (it depends on jQuery and jQuery-UI) and come up with something useful to myself (and maybe to a few others, that's why I'm sharing it here). The UI structure of the console is created through the usage of jQuery DOM manipulation magic, and the look and feel (including size) depends on a css file.

It's just a JavaScript "class", debugConsole, with a few obvious methods (log, clear, close). You can create instances of this class and keep the reference around, or you can use a "global console", through debugConsole.instance(), this way you don't need to create the console and keep a reference to it.

//create a console, keep the reference, and use it
var console = new debugConsole("console 1");

//use the default console

you can see it at work here.

Check the JavaScript "class" here.

and if you think it can be of any use to you, download it, improve it and please drop me a comment here.

Friday, 19 November 2010

Linq (IQueryable) providers

When all the Linq thing started a few years ago, there was something that confused me quite a lot, and that still today we can find in some articles.

There are articles that claim to explain how to implement a Linq Provider. This is not completely accurate, they usually explain how to implement a Linq IQueryable Provider. If we do a google search for "implement linq provider" we get a list of mixed results, many of them add "IQueryable<T>" to the title, but some of them not.

The IQueryable word is important, because it's in that case when we have to go through the (complex) process of implementing an IQueryProvider<T>. This IQueryProvider<T> implementation is who contains the querying logic-magic. This is how Linq to Sql works:
The DataTable<T> objects in our System.Data.Linq.DataContext do implement the IQueryable<T> interface. So, when we call the Where method, we're invoking the System.Linq.Queryable.Where method, that calls into the CreateQuery method of the IQueryProvider referenced by our DataTable<T>, that I think is:


However, for other "Linq systems" like Linq to Objects (I used to call it Linq to Collections) there's not an IQueryProvider<T>. The querying logic is scattered over multiple classes. Using Reflector we can see that calling to System.Linq.Enumerable.Where<T> returns an instance of WhereIterator<T>. This class implements IEnumerable<T>, and it's the MoveNext method where all the querying logic lies in.

The most important point of all this is that making our classes "Linq friendly" does not necessarily involve implementing an IQueryProvider<T>, in many cases all we need is doing our classes implement IEnumerable<T>, so that all methods in System.Linq.Enumerable can be applied to them.

You have a good sample here for querying AD users.

Another sample would be making a CSV document queryable via Linq (so, a very basic form of Linq To CSV, there are several real implementations over there, this is just a read only toy sample). We could just have a GetEntries method returning an IEnumerable, and then apply our querying logic (I'm not taking headers into account here):

public IEnumerable> GetDataEntries()
using (FileStream fs = new FileStream(this.path, FileMode.Open, FileAccess.Read))
using (StreamReader sr = new StreamReader(fs))
while (!sr.EndOfStream)
string curEntry = sr.ReadLine();
yield return curEntry.Split(this.separator).ToList();

so, given some data like:

we could do queries like:

myCsvDao.GetEntries().Where(row => row[0] == "Germany").OrderBy(row => row[1])

A nice feature here is that the IEnumerable<T>-IEnumerator<T> created by our iterator block (yes, it's rather odd to have a class that is both Enumerable and Enumerator, check out this article) is not loading all the lines into memory, but keeping the file open and reading-loading one by one, which can be pretty useful for performance considerations (and pretty shitty if we also had implemented write access and we could have concurrent operations on it...)

Update: I've found this good recent article that is pretty related to this and to my previous post.

Thursday, 18 November 2010

AsEnumerable, IQueryable, IEnumerable

Some Basic stuff that I guess is only useful to me...
The other day while digging into some code I came across the AsEnumerable extension method. It's a pretty important one. Let's say we have an IQueryable and we're chaining queries on it (that is, the extension methods in System.Linq.Queryable). Everything works fine while those queries can be expressed as expressions (the methods in Queryable expect Expressions) and the IQueryProvider associated to our IQueryable object is is able to deal with them (transform them to Sql in the case of Linq To Sql).
If we have one query that can not be expressed as a Expression or that our associated IQueryProvider is not going know how to process, we'll need to resort to Linq to Collections (that is, the extension methods in System.Linq.Enumerable).
So, how do we force the compiler (extension methods are static, so no dynamic VTables polymorphic magic, just static binding) to invoke the right method?. We just convert it to IEnumerable using AsEnumerable, and then the compiler will bind to the Linq.Enumerable methods.

Everything fine so far, but what sounded a bit odd to me about all this is that given that IQueryable inherits from IEnumerable (IEnumerable -> IQueryable), and as aforementioned all this is static binding, isn't it enough with just upcasting from IQueryable to IEnumerable?
Of course it is (as confirmed by the answer by David B in this good entry in StackOverflow), so it seems it's just a matter of style, AsEnumerable fits better in all the method chaining.

Copy and paste from David B answer:

IEnumerable orderQuery = dataContext.Orders
.Where(o => o.Customer.Name == "Bob")
.Where(o => MyFancyFilterMethod(o, MyFancyObject));

IEnumerable orderQuery =
(dataContext.Orders.Where(o => o.Customer.Name == "Bob")))
.Where(o => MyFancyFilterMethod(o, MyFancyObject));

Saturday, 13 November 2010

Morocco, murderous kingdom

I guess it should be clear to anyone reading regularly this blog that I have a rather strong sense of belonging to both Asturies (and Galiza in a lesser extent) and Europe, and no feeling at all of belonging to Spain. In fact, I feel uncomfortable when being abroad and having to show my Spanish passport or identify myself as Spanish in any other way. I come from an Atlantic land with an Atlantic culture, and almost everything people tend to identify with Spain are Mediterranean elements that have quite little to do with me or my family (neither the negative nor the positive ones).

The thing is that from time to time something happens that makes me not just uncomfortable, but purely ashamed of having a Spanish passport, and we're right now in the middle of one of those situations.

In 1975 Spain took one of the more contemptible steps in her recent history, the handing over of her last colonial territory, Western Sahara to the blood thirsty Moroccan kingdom. This means that in an unprecedented move and unlike the rest of the European powers, Spain did not carry out a process of decolonization of a territory that had been exploiting for over 1 century, but gave it away to a new oppressive power, Morocco (and also Mauritania at first). So, the Sahrawi people changed hands from a European dictatorship that had not treated them too bad (thought a dictatorship, being part of the Western world makes you accept some minimum moral laws, if only to avoid criticism from your neighbours) to the brutal, bloody Moroccan dictatorship (well, they prefer to call themselves a kingdom, it sounds more nice...)

What all this has meant for the Sahrawi people has been 35 years of brutal exploitation of their mineral resources, discrimination in favor of the new settlers sent by Morocco to replace the autoctonous population, constant attempts to destroy and replace their culture and identity... all in all, there's a clear name for this GENOCIDE.

In the last weeks, the GENOCIDE has entered a new phase, and the Moroccans are killing the Sahrawis in their own homes before the indifference of the European Union, the UN and worst of all, the main culprit of all this, Spain.

If Spanish government had a minimum of dignity, if Spain had any sort of international prestige or recognition, if Spain were not a joke country that can be looked down on by anyone, even by a shit country like Morocco... The Spanish Army (backed by the EU, that would have to support the legitimate actions of one of its members) would have been sent to Western Sahara to protect the population and heal the wound that was opened in 1975. Western Sahara could be turned temporaly into the 18th Spanish Autonomous Community, waiting for a future referendum of self determination, once the International Community were able to guarantee that the disgusting Moroccan dictatorship would never put their dirty hands on the territory.

But not, 40 years of dictatorship and 35 years of misgovernment by corrupt, ignorant politicians, in addition to the historical backwardness when compared to other European countries, have made of Spain a fucking puppet that has no other option that kneeling before the Moroccan dictator to protect some dubious economical interests...

And still some Spaniards do not understand why Basques, Catalans, Galicians, Asturians seek for independence... who in their right mind would want to be part of this joke country that can not be taken seriously by anyone?

Sahrawi people and Polisario Front RESIST!!!