Tuesday, 15 January 2019

Nullable References

Reading about the new features that C# will delight us with I felt a bit surprised with the Nullable References one. If you enable the feature, references will be considered as not nullable, unless that you explicitely state the contrary by defining it like this: MyType? mt;. Trying to assign a null value to a reference not declared as nullable will cause the compiler to throw a warning. There are no runtime verifications, it's all at compile time, and it won't prevent your code from being compiled, as I say it will just throw a warning. This warning should be enough to make you review your code and save you many potential problems at runtime.

I pretty much liked the feature and it seemed like something totally new to me, but indeed something almost identical exists in TypeScript since version 2.0. Non-nullable types can be enabled with the --strictNullChecks compiler option. Using this feature will make the compiler throw an error (but well, it's TypeScript, so the code will still get transpiled into JavaScript) each time you try to assing a "null like value"m that is, null or undefined. If when using the feature you want one reference to accept any of those values you'll have to define it like this:

let y: number | undefined;
let z: number | null | undefined;

Notice that this TypeScript feature has nothing to do with the ? optional properties that you can define in types and that so nicely play with the TypeScript structural typing nature.

Monday, 24 December 2018

TypeScript, async and Return Type

The other day when writing one TypeScript async method I got into some doubts that made me revisit the last part of this post, the one about the wrapper Promise that the compiler creates for an async method and how this won't be resolved until the internal Promise is resolved. Basically I have one async method that invokes to async methods to return a Person object.


class Person {
    constructor() {
        this.name = "";
        this.city = "";
    }
}
function getFirstId() { //returns a Promise of a string after 1 second
    return new Promise((res, rej) => {
        setTimeout(() => res("1AB2"), 1000);
    });
}
function getPerson(id) { //returns a Promise of a Person after 1 second
    return new Promise((res, rej) => {
        let p = Object.assign(new Person(), {
            name: "Francois",
            city: "Paris"
        });
        setTimeout(() => res(p), 1000);
    });
}

In JavaScript (ES2017), I know I can write the client code in 2 ways:

Doing a return await

async function getFirstPerson() {
    let id = await getFirstId();
    return await getPerson(id); //this return happens after 2 seconds
}

let per = await getFirstPerson(); //all in all we wait 2 seconds

Doing a return

async function getFirstPerson2() {
    let id = await getFirstId();
    return getPerson(id);  //this return happens after 1 second
}

let per = await getFirstPerson2(); //all in all we wait 2 seconds

The first case is pretty clear, return await getPerson(id); returns a Person, that resolves the wrapper Promise that was created and returned when the function was first invoked. The second case is what I explained in that previous post. return getPerson(id); returns a Promise of a Person, and the wrapper Promise won't be resolved until this one is resolved. So for most aspects both codes are equivalent.

The doubt for me when writing equivalent code in Typescript was with the return types. For the second function I was writing:

async function getFirstPerson2(): Promise<Person>{
    let id = await getFirstId();
    return  getPerson(id);  //returns really a sort of Promise>
}

let per = await getFirstPerson2();
    

The TypeScript compiler allows this and compiles it to the JavaScript above. The return is not returning a Person, but a Promise of a Person, with joined to the wrapper Promise created by the runtime gives us a sort of Promise of a Promise of a Person. Anyway, as the external await will wait for the resolution of the inner Promise, the TypeScript compiler is happy with the Promise function signature.

As I explain in the comments to the JavaScript code, depending on whether we do return await or return the return happens 2 or 1 second after the invokation. Anyway, the external await waits for 2 seconds since the method call is launched. There's one more difference related to this that could be important, exception handling. Let's say the Promise returned by getPerson were rejected. In the return await case, a try-catch in getFirstPerson will catch the exception, I mean:

async function getFirstPerson(fail: boolean): Promise<Person>{
    try{
        let id = await getFirstId();
        return await getPerson(id, fail);
    }
    catch{
        console.log("exception caught in getFirstPerson");
        
    }
    return new Person();
}

async function main(){
    console.log(Date.now() + " before calling getFirstPerson");
    //no need for a try-catch here, the one in getFirstPerson catches it all
    let p = await getFirstPerson(true);
    console.log(Date.now() + " person: " + JSON.stringify(p));
}

In the case of return we are just returning the Promise, so we'll need the try-catch for the outer await also, I mean:


async function getFirstPerson2(fail: boolean): Promise<Person>{
    //only catches the getFirstId rejection, but not the getPerson
    try{
        let id = await getFirstId();
        return getPerson(id, fail);
    }
    catch{
        console.log("exception caught in getFirstPerson");
    }
    return new Person();
}

async function main2(){
    console.log(Date.now() + " before calling getFirstPerson");
    //we need a try-catch here for the getPerson rejection
    try{
        let p = await getFirstPerson2(true);
        console.log(Date.now() + " person: " + JSON.stringify(p));
    }
    catch{
        console.log("exception caught in main2");
    }
}

Saturday, 22 December 2018

Tour Perret, Amiens

There's a belt of 'department capital cities' surrounding Paris conveniently placed at little more than 1 hour by train (Rouen, Amiens, Reims, Orleans, Troyes) from the magical city, that seem perfect for a day trip. Years ago I did it with Rouen, and lately I had thought many times of going on with exploring some of these cities, but in the end the idea of wandering around Paris always ended up winning over this kind of day trip. Last week I was lucky to spend a few days in Paris again, and finally decided to go for something new and do a day-trip to Amiens the capital of the historical territory of Picardy.

Amiens is mainly known as Jules Verne city. Hey, but Nantes also claims that title, right? Well, indeed he spent his life in Nantes, Paris and Amiens... a smart guy I have to say. Amiens is a lovely city, at least its city center (I did not go any further). Having been in Lille some years ago I already knew that the beautiful architecture of Northern France is very similar to what you find in Belgium, but what quite surprised me is that Amiens has quite of a Brugges feeling. The small canals and the beautiful single-family houses in the St Leu neighbourhood (and the rain, cold and humidity...) brought me many memories of my autumn trip to Brugges years ago. All the city center is really beautiful and is well worth a visit, and the massive gothic cathedral is just gorgeous, but there's an architectural element that I found particularly striking, and that grants the city the right to be in modern Architecture books, the Tour Perret.

The Tour Perret was built in the early 50's and with its little more than 100 meters height it was for some time the tallest building in Western Europe (quite funny to find that in a small city in a country where for good part of the population the irrational hatred for buildings higher than 8 stories makes up one essential part of their identity...), but this kind of past ranking is not particularly interesting to me, what seduced me (mesmerized me almost) is its architecture. The tour is amazingly thin, a square base with 4 windows on each side (becoming 3 in the upper levels). Made of grey reinforced concrete, when seen from the distance one could almost think of it as the belfray of some gothic church, so it's really amazing how nicely it fits in the city scape. A perfect reference point that makes an amazing contribution to the beauty and charm of this small city.

This building is just opposite the main train station, gare du Nord, that was built at the same time also by Auguste Perret in a similar style. It looks pretty massive and interesting (even more with the carefully placed Christmas lights)

Sunday, 16 December 2018

FIC Xixón 2018

One of the first posts in this blog, back in December 2009, was about that year's edition of the first posts in this blog, back in December 2009, was about that year's edition of the Xixon Film Festival (FIC Xixon). For the next 3 editions I continued to post my impressions on that year's edition, until 2013, when I was no longer in town during the festival. After a 5 years gap, this November I was in town again during part of the festival, so it was time for me to return. In these five years the festival has gone through some hard times I think. The funding has been reduced (which has forced to cutting its length 1 or 2 days), the director that started in 2012 was questioned for most of his time leading it (I won't add anything to that debate, just say that the only edition under his command that I could experience, 2012, seemed excellent to me) until being replaced for the 2017 edition, and the hardest hit for me (that indeed made me doubt about the survival of the festival) was the closing of the only private cinemas in downtown (that were where most of the films were screened).

Last year I read on the local newspaper an interview to the new director where he was rather positive about the outcome of that edition. The guy seemed pretty modest and sincere, and explained how in spite of all this difficoulties, they had managed to host a pretty decent festival increasing the attendance and the interest of young locals. Currently the festival is held in 3 locations in downtown: Teatro Jovellanos (the beautiful public theatre that has always been the festival's main site), a small, uncomfortable, screening room in "Antiguo Instituto" (this is not new), and a new screening room in the renovated "Escuela de Comercio" (I've never been there, so I can't say how it looks). There's another location in a cultural center quite far from downtown (CMI Pumarin Sur) , that is not new either, and another one in "Teatro de la Laboral", a nice theatre in an amazing, massive complex, but very far from the city center. Finally, 3 rooms in one cinema (Yelmo Cineplex the only commercial cinema in town) located in a mall quite far from the center. With this in mind and being pretty busy with work lately, I was only interested in films screened in "Teatro Jovellanos". I attended to 2 of them.

Saturday 17, The Load, Serbia, Ognjen Glavonic. I pretty enjoyed this fictional work based on a true, little known, dirty event of the Serbia-Kosovo war. A truck driver (before the war he had another job, but now it's the way he's found to put food on the table) has to drive a load from Kosovo to the outskirts of Belgrad. The trip is not particularly exciting but has some odd situations and is good at showing us how in the middle of war people try to go on with their lives, couples get married, teenagers behave as tennagers... As the film develops we (and the driver) will find out that he's carrying the corpses of Kosovar civilians killed during the war, that will get secretly buried in a mass grave in Serbia far from international view. The final part of the movie is poetics and fantastic. Our driver goes through a sort of catharsis talking to his son about how his grandfather had fought against fascism in WWII and decides to document somehow what is happening. The director was present in the cinema and there was a general discussion with him at the end of the film. I could also exchage some impressions with him at the exit. All in all, the guy was an antifascist that had gone through the very difficoult process of doing a work like this in such a nationalistic country like Serbia in order to fight fascism. Absolutely praiseworhty, even when I felt a bit like he was falling too much in the typical European self-demonization. For sure telling this story to make public a hidden and hideous event is important, but we should not forget that Kosovars did as bad, if not worst crap during and after the war, than Serbians. By the way, I absolutely loved the HxC Punk song that closes the film.

Monday 19, One Day, Hungary, Zsofia Szilagyi. Honestly, I did not plan to attend to this film, but one friend of mine wanted to go to 1 session and this one came fit. I have to say that it's been quite a surprise. The plot did not seem to appealing, a day in the life of a Hungarian worker, wife, mother of three and married to an unloyal husband, but it shows masterfully how stressful and painful normal life can be. The film is intense, and at some moments becomes oppresive, immersing us in the little hell in which life has turned for this ordinary woman. One could say that it is disgusting to try to make look the normal life of a European woman with good health as a calvary of pain and suffering, but (have no idea if this was the intent of the director) it works pretty well to remind us of how good we can be at drowning us in misery with our little problems, forgetting how others have to deal with real shit day after day.

Sunday, 2 December 2018

Post and No DTO class

Working on an Asp.Net project I've come across a problem that reminded me of an old post. I have one action in one controller that just expects a simple value (a string) as parameter. The action is not for querying data, and though we are not doing a real REST API, at least I wanted to use a POST and not a GET, and pass the value in the post body (not as a querystring).

When passing multiple values the normal thing is just creating a sort of "DTO" object with those values as fields, send it as JSON and let the ModelBinder do its work. But for a single value (or a couple of them) it felt bad to me to create a class with just a single field. This seemed a perfect case for using dynamic. I mean:

//Client side code
  addItem(item: string): Observable {
    return this._remoteService.post(this.url,
      {
        item: item
      });
}


//server side code
        [HttpPost]
        public HttpResponseMessage AddItem(dynamic dto)
        {
            //wrong, myService receives a "null" value
   return Request.CreateResponse(HttpStatusCode.OK, this.myService.AddItem((dto.item as string)));
        }

The thing is that the myService.AddItem was receiving a null value. Checking with the debugger I could see that the dto object with its "item" field was reaching fine the controller. The model binder was using Json.Net and deserializing it to a JObject. JObjec and "dynamic" are designed to work together, so why was I receiving null when passing over the dto.item???

Here is where that old post of mine comes into play. In my code I'm using the as operator to tell the compiler that dto.item is a string, dto.item as string. The problem is that such statement is false, dto.item is a JValue (containing a string we can say), so when the runtime finds that we don't have a string but a JValue (you can read more here), as fails and returns null. So in this case we have to use the cast operator, (string)dto.item, that here does not behave as just a "hint", but performs a explicit conversion from JValue to String. If you are confused, read my old post, where this thing of cast vs as and the 2 different behaviours of the cast operator (hinting vs converting) are well explained.

//server side code
        [HttpPost]
        public HttpResponseMessage AddItem(dynamic dto)
        {
            //works fine
   return Request.CreateResponse(HttpStatusCode.OK, this._virtualDocument.AddFavoriteToCurrentUser((string)dto.item));
        }

Of course I could be using Content-Type: application/x-www-form-urlencoded as explained hereand the ModelBinder should work fine, but there are some differences depending on the ASP.Net version, and I prefered to just follow the json route.

Friday, 30 November 2018

The Sea of Trees

I've never considered myself a particularly smart or cultivated person. I should read/have read many more and better books, travelled more and earlier, interacted much more with people that had things to teach, all in all learn much more from everything... cause I've always wanted to have a good understanding of our world. Anyway, and particularly taking into account how the cultural level of our society has dropped in the last decades, I try to think that I could be placed in the "not too idiotic" group of people. However, from time to time something happens that makes me think that maybe I'm much more of a redneck that I would like to think and accept. It has happened lately with my reaction to one film "The Sea of Trees" as it happened more than one year ago with The Last Face, another excellent film.

I watched The Sea of Trees a bit by chance. It was available in the "videotheque" of the multimedia device in the bus carrying me to Madrid. I had plenty of films in my own tablet, but decided to give this one a chance without even checking the wikipedia review. Wow, I loved this film. It felt really powerful to me. One Western middle age guy runs into a Japanese counterpart in The Japanese Suicide Forest where both intended to put an end to their lives... Little by little the story that has brought the Western guy here is revealed. A lost wife, a lost chande for happiness, a lost chance to express feelings, to repair what was not really so broken... and all the remorse that comes with it... A constant reminder of how nothing in our lives can be predicted: falling sick, overcoming it, and suddenly, an abrupt end just when you thought life was showing you its sweet face again... A story of how a real pain can help to erase an unnecessary, self-inflicted past pain and dream of a future... This is a very emotional film, a film to learn from for sure (or more specifically, to study again what I tought was a lesson learned for me and indeed I was starting to forget), a film that hurts, seduces and in the end provides hope, where remorse for the past ends up providing light for the future, easing the wounds that seemed ready to bleed forever...

So well, after watching it I decided to check some reviews, expecting to read how much this work had moved and touched others... but to my surprise most comments were really negative, bordering the insulting... Pretentious, sappy, empty... well, all those are calificatives that could not be further from my experience with this film... then, it's up to you to decide, believe what some cool Cannes critics say, or believe what this boring, uneducated moron says.

Saturday, 17 November 2018

Capharnaum

I watched Capharnaum in the American Cosmograph some days ago. When I decided to attend the session I was not particularly excited. The review in the monthly program was good, but not particularly outstanding, but as Lebanon and its chaotic society is always an appealing topic for me I thought I should watch it (also, Toulouse is no longer my primary residence and when I'm there I pretty much feel like going for some indy cinema).

I was just blown away by this masterpiece. Maybe this is the best film that I've watched since Incendies. It's amazing how a handful of artists (this film is ART in uppercase) can transform misery and suffering into beauty and hope, because the daily fight of the SURVIVORS portrayed in this masterpiece is so inspiring. This film is so profoundly humane that really helps us keep alive the humanist inside us. When many of us are fed up of many of those so called refugees that are not escaping from any war (is there a war in Morocco or Albania? ), that were persecutors rather than persecutees (all those that helped the Islamists in Syria and are now fleeding cause hopefully they've lost their bloody war), and just come here with the intent to take as much as they can from our society without providing anything (anything positive I mean) in exchange... it's really good to show the lives of real refugees, people who have lived in the shit for decades (I won't enter to discuss the so difficoult Israel-Palestine affair, but Palestinian refugees living in Lebanon experience a life of misery and hopelessness like few others), and how they fight day after day for their subsistence. It's also good to be exposed to the fair amount of dignity in those migrants like the Ethiopian or Filipino women that work so hard to try to build a better life in such a harsh country like Lebanon. With this kind of migrants there is no doubt about how fucked up their previous lives had to be in order for them to choose such an uncertain path. They are not doing it hoping to live on social benefits for the rest of their lives... like some of those coming to Western Europe in the last years.

The refugee/migrant kids and women in this film are the personification of courage, dignity and solidarity, a solidarity among the poorest where religion, skin color or ethnicity do no exist, just human beings fighting together for survival. These are the migrants that I would love to see replacing all the Islamoracaille that is tearing apart our societies from inside at the same time that they steal from it as much as they can.