Thursday 29 September 2016

About the security of online services

Some time ago, I started receiving in my Gmail inbox notifications of purchases from the Playstation Network... the thing is: I neither have a Playstation nor registered an account on that network!

My Gmail account has been protected for a long time with 2-factor authentication; therefore, I was not worried about the security of my account.
Those emails are just the annoying consequence of at least two facts:
- A dumb user who cannot remember or type their email address correctly.
- An online service that does not care to verify the email address during the registration process.

Since I considered it not worth digging into the support pages of PSN to search for a solution, I initially decided to add a filter to Gmail to delete those emails automatically.

Last week, I received a welcome email from Uber and, soon after, a receipt of my very first trip around Philadelphia (US).
Again, even though I suppose it is a lovely place to visit, I have never been to Philadelphia!
And I never registered an account with Uber.

Same as above, someone used my email to register an account (same person? no way to know).

As I got annoyed by these notifications, I have decided to spend one evening trying to find a way to either delete these accounts or disable the notifications.

Uber

After reading throughout their support site, I finally landed on the page to delete an account.
To delete the account, you first have to log in.
You might ask how I can log in if I did not create the account in the first place? Easy: request a password reset!
I reset the password, logged in, and finally clicked on the button to delete the account.
Ridiculous.


PSN

Here the problem is finding the support page. After a good thirty minutes in the forum, I found a link to the US online support live chat.

Being outside the US, a message on the waiting page informed me the service was not available, and I had to contact the Support Team for my country.

Select your country on this page:

https://www.playstation.com/country-selector/


Then scroll to the bottom of the page and click on Support (this is the UK Support page)


Search for "chat".


This is the link to the UK Live Chat.


Since the service is available from 10:30 to 19:00 Monday to Saturday, I will contact them tomorrow and hopefully find a solution.


What amazes me is the total lack of verification from these services. I could not access any sensitive information regarding these persons, but in the Uber case, I could find where this person has been in the last two weeks - not what I define as privacy.


The bottom line is: for the services you care about, always enable the 2-factor authentication and try and change your password as often as possible!

Saturday 24 September 2016

The Maltese Language #2

In the first post regarding the Maltese language, I introduced the alphabet.
Today, following my notes order, I am going to write about the article, but first let me add that in the Maltese alphabet the consonants are arranged in two groups:
Sun Consonants:  Ċ, D, N, R, S, T, X, Z, Ż
Moon Consonants: B, F, Ġ, Ħ, J, K, L, M, P, Q, V, W

This grouping will make easier to remember the rules for a correct use of the articles.

The Maltese language actually has only one article: il-
Note that the article requires to be separated from the following word with a "-" (dash).

Even though it is written as one of the Italian articles, its usage is in fact very similar to the English the: it remains the same regardless the number and the genre of the noun it precedes.

However, unlike the English article, the Maltese one changes slightly depending on the first letter of the following word.

If the following word starts with a        The article is
Vowel A, E, I, O, U, IE                    L-
GĦ, H                                      L-
Sun consonants                             I<consonant>-
Moon consonants                            IL-

Basically, when the word that follows starts with a sun consonants the L changes into that consonant. If the word that follows starts with a vowel, the I is dropped. In all the other cases the article is always IL-.

Since għ and h do not have a sound on themselves, the rule is the same of the vowels one.

Some examples:

L-Ilma      The water
L-Ieħor     The other one
L-Ħobż      The breadIĊ-Ċirasa   The cherry
ID-Dar      The house
IX-Xita     The rain
IL-Mara     The woman

The last example "il-mara" gives me the opportunity to introduce one characteristic of the Maltese language: adding the article to a word, can change the meaning of it.
In this case, "il-mara" can be used with the meaning "my wife".
To distinguish these cases in writing, the general rule is to change to capital the first letter of the word following the article.
In speaking, the intended meaning can be understood from the context.

Some examples:

Il-mara     The woman
Il-Mara     My wife 
Il-raġel    The man
Il-Raġel    My husband
L-erbgħa    The four
L-Erbgħa    Wednesday

As far as I know, there are no exceptions to the rules for determining the correct article, but I cannot be completely sure, being my knowledge limited.
Native Maltese speakers, am I correct?

Wednesday 3 August 2016

The Maltese language

Today I have received a letter from the MCAST institute with the score of the final assessment exam.
During the past four months I have attended the Maltese for Foreigners Level 1 course that was focused on the very basic of the grammar and the understanding of short text and speaking.

In general, learning a new language is a difficult task that requires a good effort especially at the beginning.
Considering that I am trying to improve my English at the same moment, learning Maltese is even more difficult for me considering the small amount of time I can dedicate to it.
Many teachers suggest the best way to learn a language is immerse yourself into it: I am listening radio (in Malta there are a few of very good stations), watching TV (even though, in general, I am not used to) and put some effort in trying to translate what native speakers say.

While waiting for the starting date of the next course of Maltese language (yes, I have passed the exam with a quite good score ), I have decided to revisit what I have learned writing a series of post in this blog.

The alphabet


Maltese alphabet is composed of 30 letters:

A B Ċ D E F Ġ G GĦ H Ħ I IE J K L M N O P Q R S T U V W X Ż Z
a b ċ d e f ġ g għ h ħ i ie j k l m n o p q r s t u v w x ż z

Maltese language is very phonetic and, with some very minor exceptions, letters are pronounced always in the same manner.

The author of this video spells the alphabet:



I have to say that for an Italian native the most difficult letters are "q", a guttural sound, and "ħ" the "sounding h" somewhat similar to the English one that we find so difficult to pronounce correctly.
On the other hand, even though not very difficult to pronounce, I find very difficult to distinguish ż from z when native people speak.
Għ is a particular case: it does not have sound per-se, but prolongs the vowel that precedes it. This is what the official rule says.
Unfortunately, native speakers pronounce it in several fashion because of dialects.

Example:


tiegħi (= mine/my) is pronounced "tiAi", "tiEi" or "tii-i" depending of the village of origin of the speaker.

There are a few other exceptions, but in general reading Maltese language consists in connecting the sounds of the alphabet letters.

 

Example (from Ager, Simon. "Omniglot - writing systems and languages of the world" www.omniglot.com):

Maltese
Il-bnedmin kollha jitwieldu ħielsa u ugwali fid-dinjità u d-drittijiet. Huma mogħnija bir-raġuni u bil-kuxjenza u għandhom igibu ruħhom ma' xulxin bi spirtu ta' aħwa. 

English
All human beings are born free and equal in dignity and rights. They are endowed with reason and conscience and should act towards one another in a spirit of brotherhood.
(Article 1 of the Universal Declaration of Human Rights)






Saturday 23 April 2016

How to seamlessly move your Downloads folder to another drive

Recently Windows notified me that my primary hard drive was almost full.
My laptop has two hard drives:
  • C: 250 GB Samsung SSD and
  • D: 750 GB mechanical Toshiba.
Since most of the space in C: was occupied by downloads, I decided to move the %USERPROFILE%\Downloads folder to D:

Instead of just moving all the contents to another folder in D:, I substituted the actual folder with a symbolic link. This means that all the future downloads will be stored directly in D:.

> D:
> mkdir Downloads
> robocopy %userprofile%\Downloads Downloads /MIR /MT
> C:
> cd %userprofile%
> rmdir /S Downloads
> mklink /J Downloads D:\Downloads

That's it! mklink is the command to create links using NTFS features.
The /J option asks to create a NTFS junction that is, in fact, a symbolic link to a folder. The advantage of a junction point over a regular symbolic link is that it can "trick" application to believe it a regular folder.
NTFS does not support hard links to folders


Sunday 17 April 2016

Come registrare il proprio veicolo a Malta

Il sito web di riferimento per tutti gli aspetti burocratici è ovviamente quello dell'ente istituzionale dei trasporti maltesi http://www.transport.gov.mt.
Nonostante ci sia una pagina (questa) in cui è spiegato l'iter da seguire, sento la necessità di puntualizzare alcuni dei passaggi.
Do per scontato che chi legge è cittadino italiano in possesso di una licenza di guida in corso di validità. In caso contrario l'iter è certamente diverso.
Da quando sbarcate con il vostro mezzo a Malta, potrete circolare per legge per un periodo determinato.
Mi raccomando, conservate il biglietto e la carta di imbarco (quella con la banda gialla) della Virtuferries!
Se è la prima volta che arrivate a Malta e quindi non siete ancora residenti maltesi, sappiate che il vostro veicolo potrà circolare senza problemi per un massimo di 7 mesi nell'arco di 12.
Quindi se state visitando Malta per turismo, nessun problema.
Se la vostra visita è invece dovuta a trasferimento perché avete trovato lavoro le cose sono diverse.
Infatti, per vivere a Malta dovrete richiedere la ID card - farne a meno è praticamente impossibile se si vuole accedere ai servizi bancari e ad alcuni servizi del governo. A questo punto però dovrete regolarizzare il vostro mezzo entro 30 giorni dall'ottenimento della ID card.
Per regolarizzare intendo cambiare targhe e certificato di proprietà con quelli maltesi.

Come si fa

Bisogna innanzitutto recarsi a Floriana (qui) per fare visionare il mezzo.
Qui gli addetti prepareranno un modulo che contiene fra le altre cose, il numero di telaio, il numero di serie del motore e la stima del valore del mezzo.
Il numero di serie NON è quello riportato nel libretto italiano: quello è il modello del motore.
Purtroppo per me, nel caso della mia automobile - una Peugeot 207 - il numero di serie si trova in una targa metallica dietro il motore per cui l'addetto non ha potuto leggerlo.
Rassegnato all'idea che fosse necessario smontare l'auto, mi sono recato in un centro Peugeot per chiedere un preventivo. Per mia fortuna, la Peugeot mantiene alla sede centrale un registro di tutte le auto prodotte: hanno pertanto potuto darmi il numero di serie del motore entro qualche giorno.

Ottenuto il modulo di ispezione dovrete andare a sottoscrivere una assicurazione maltese per la quale vi richiederanno libretto italiano, atto di proprietà italiano e gli ultimi attestati di rischio.

Con l'assicurazione in mano, potete finalmente recarvi agli uffici per la registrazione.
Dovrete prima compilare i moduli VEH01 e VEH02: in caso di dubbi potrete sempre terminare la compilazione all'ufficio stesso.
Vi consiglio di recarvi agli uffici con il mezzo che state per registare perché dovrete portare anche le targhe di esso. In alternativa, potrete lasciare il veicolo in un garage.

Sarete tenuti a pagare la registrazione con incluso l'equivalente del bollo, il costo delle targhe e le tasse d'ufficio. I costi sono indicati nel sito di Transport Malta.

Ricapitolando, ecco l'elenco dei documenti necessari per la registrazione:
  • Documento di ispezione del veicolo
    Si ottiene qui.
    Necessario libretto italiano 
  • Assicurazione maltese
    Necessari libretto e certificato di proprietà italiani, documento di ispezione, ultimi attestati di rischio. Assicurazioni diverse potrebbero richiedere documenti diversi. 
  • Biglietto e carta di imbarco Virtuferries originali
    Ricordate di conservarli! Nel caso li avesse gettati via o smarriti potrete sempre richiederne una copia alle biglietterie Virtuferries qui
  • ID card maltese
  • Moduli VEH01 e VEH02
  • Targhe del veicolo
Se tutto è andato bene, non vi resta che comunicare al PRA italiano l'avvenuta registrazione a Malta avviando la procedura di radiazione per esportazione per la quale dovrete inviare in Italia le vecchie targhe ed il certificato di proprietà. Non è obbligatorio certo, ma se volete evitare di continuare a pagare il bollo, vi conviene fare voi stessi la richiesta.

Ottenere lo sconto sulla tassa di registrazione

La tassa di registrazione è pari all'importo riportato nel documento di ispezione. Nel caso di veicoli recenti, questo potrebbe essere molto vicino al valore dello stesso, rendendo la registrazione estremamente antieconomica.
Se però siete intestatari del veicolo da almeno due anni e siete residenti in Italia da almeno due anni, potrete allora richiedere lo sconto della tassa per uso personale del veicolo.
Come indicato in questa pagina, dovrete compilare il modulo VEH07 e produrre tutta la documentazione in esso indicata comprovante quanto dichiarato (certificato di proprietà del veicolo, bollette ENEL, buste paga emesse in Italia, ecc.).
Presentando questa richiesta, riceverete un foglio che posticiperà il termine per la registrazione a dopo l'esito della richiesta che potrebbe richiedere qualche settimana (6 nel mio caso).

Conclusioni

L'iter di per se non è complicato.
Quello che ho trovato non chiaro è l'ordine con cui fare le cose ed il fatto che non tutti i documenti necessari per ogni passaggio sono indicati.
Spero che questo post possa servirvi ad evitare un po' di visite e telefonate agli uffici alla ricerca di informazioni.
Un ultimo consiglio: ottenuta la ID card, muovetevi immediatamente per la registrazione. Ottenere il documento di ispezione e l'assicurazione potrebbe richiedere qualche giorno ed è meglio non rischiare di pagare la multa per mancata registrazione entro i termini di legge.

Sunday 20 March 2016

Configure Windows Error Reporting

In Windows XP Microsoft introduced several changes in the exception management system.
The old Dr. Watson was archived in favour of the brand-new Windows Error Reporting system.
What was originally only a local debugger evolved in a more complex end-user reporting system.
The WER system evolved in the subsequent Windows version - significatively in Windows Vista, but from a developer point of view, even in Windows 10, it remained essentially the same as it was in Windows XP.

Main purpose of WER is to catch all the unhandled exceptions and create a report and, if enabled, a memory dump of the faulty process.

Part of WER is the debug dialog that sometimes appear on the desktop whenever a faulty application crashes.






WER also creates two new entries in the Application Event Log:





In the details of the events you can find the full path of the error report and, if enabled, the full path of the memory dump.

Enable Memory Dumps

The first step to identify the root cause of an unhandled exception is to analyse a memory dump. A memory dump is a file that contains a snapshot of the process memory at the time the exception was thrown.
The default Windows configuration is to create mini-memory dumps only for system faults (BSOD) and not for user-mode applications.
To enable user-mode memory dumps for the entire system, change the following System Registry values. You can find an exaustive documentation in this page on MSDN.

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps

Value Name      - Data Type     - Default Value

DumpFolder      - REG_EXPAND_SZ - %LOCALAPPDATA%\CrashDumps
DumpCount       - REG_DWORD     - 10
DumpType        - REG_DWORD     - 1
CustomDumpFlags - REG_DWORD

DumpType can be set to the following values:
  • 0: Custom dump
  • 1: Mini dump
  • 2: Full dump
Custom dump allows you to choose what section of the dump generate. You can configure the sections using the CustomDumpFlags value.
I would not recommend in the first to generate a full dump because it could become very large depending on how much RAM is available on your system.

You can also activate the dump only for an application.
Add a new key under HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\Windows Error Reporting\LocalDumps (for example, HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\Windows Error Reporting\LocalDumps\MyApplication.exe).
Then add the above mentioned dump settings under the MyApplication.exe key.

The consent dialog

In general, whenever your application throws an unhandled exception a dialog will be shown to the user.
There is an exception (no pun intended :) ) to this rule: if the exception is generated when your application does not have a visible window, the crash will be only logged in the Application Log and no dialog will be displayed to the user.This behaviour is to avoid confusion in the case of a crash in a background application not commonly known to the average user.

Unfortunately, this means that if your application has no window, hardly you will receive a call from your user in case of a crash.

This was exactly the case of an application I was worked on. This application, an MFC application normally displaying a dialog, had a fault in the shutdown process after the main window was destroyed.
The issue was discovered only because in one system, the fault happened before the destroy of the main window making WER display the consent dialog.
We lately discover the Application Log was full of crash events from this application.

To actually debug the issue, I needed first to force WER to display the consent dialog in the exact moment of the crash so that I could attach the debugger.

Force WER to display the consent dialog

Indeed, there is a not-so-well-documented way to force WER to display the consent dialog for a specific application.
Create a new DebugApplications key under
HKEY_CURRENT_USER\Software\Microsoft\Windows\Windows Error Reporting
Under this new key, create a REG_DWORD value with the name of your application including the extension.
Set then the new value to 1.


 

Conclusions

Whenever you are testing an application, I would recommend to keep looking at the Application Log in the case of a silent crash of the application.
In that case, to actively debug the issue, force WER to show always the consent dialog so that you can attach your debugger at the right moment.





Sunday 14 February 2016

The Pimpl idiom

Having a long-time C# background, I have spent some time understanding this C++ idiom.

You can implement this idiom for several reasons (I will mention them later on), but the one every article I have read mentions is to speed up compile time.

To fully understand this statement, you need to know how the C++ compiler works.

Every time you declare a variable in your program, the compiler will search the class declaration and definition because every type needs to be fully defined.

Before starting, please note that my IDE is Visual Studio 2015, which provides an almost-C++11/14/17 compliant compiler.

Let's start from a small example:
#include <iostream>
#include "MyTimer.h"

int main (int argc, char *argv[])
{
    MyTimer timer;
    std::cout << timer.GetMillisecsFromStart();

    return 0;
}


MyTimer implements a scoped timer functionality: it will start its internal counter upon construction and stop it upon destruction.

It also allows a caller to know the number of milliseconds that have passed from the timer's start.

When the compiler reads the first line of the function body, it will search the definition of the MyTimer type in the known compilation units.

Every part of the type, even the private one, needs to be defined because the compiler needs to know the exact size of the objects.
It will do the same every time a cpp file uses the MyTimer type (and include the MyTimer.h header.

In very large projects, this will increase compilation times.
Let's see now how the Pimpl idiom can speed up compile times.
Pimpl stands for pointer to implementation; this means moving your class's implementation to another class/struct and maintaining only a pointer to it.

The following code shows an example implementation of MyTimer:
MyTimer.h
#include <chrono> 

using namespace std::chrono;
class MyTimer
{
public:
    MyTimer();
    uint64_t GetMilliSecsFromStart();

private:
    time_point<steady_clock> Now();
    time_point<steady_clock> m_start;
}

MyTimer.cpp
#include "MyTimer.h"

MyTimer::MyTimer()
    : m_start(steady_clock::now())
{
}

uint64_t MyTimer::GetMilliSecsFromStart()
{
    return duration_cast<milliseconds>(Now() - m_start).count();
}

time_point<steady_clock> MyTimer::Now()
{
    return steady_clock::now();
}


Implementation

Let's try now to implement the Pimpl idiom:

1) Move all the private members to another class/struct

MyTimer.cpp
#include "MyTimer.h"

struct MyTimerImpl
{
    time_point<steady_clock> Now()
    {
        return steady_clock::now();
    }

    time_point<steady_clock> m_start;  
}

...


2) Declare a private smart pointer to the new implementation class/struct:

MyTimer.h
#include <memory> 

class MyTimer
{
public:
    MyTimer();
    uint64_t GetMilliSecsFromStart();

private:
    std::shared_ptr<MyTimerImpl> m_impl; // this should be a more appropriate
                                         // unique_ptr. Ignore it for the moment.
}


3) Construct the object containing the implementation:

MyTimer.cpp
...

Timer::Timer()
    : m_impl(std::make_shared<MyTimerImpl>())
{
}

...

4) Change the public methods in order to use the internal implementation:

MyTimer.cpp
...

uint64_t Timer::GetMilliSecsFromStart()
{
    return duration_cast<milliseconds>(m_impl->Now() - m_impl->m_start).count();
}

...



Here the resulting files after the implementation:

MyTimer.h
#include <memory>

class MyTimer
{
public:
    MyTimer();
    uint64_t GetMilliSecsFromStart();

private:
    struct MyTimerImpl;                  // Forward declaration
    std::shared_ptr<MyTimerImpl> m_impl; // This should be a more appropriate
                                         // unique_ptr. Ignore it for the moment.
};

MyTimer.cpp
#include "MyTimer.h"
#include <chrono>

using namespace std::chrono;
struct MyTimer::MyTimerImpl
{
    MyTimerImpl()
        : m_start(steady_clock::now())
    {
    }

    time_point<steady_clock> Now()
    {
        return steady_clock::now();
    }

    time_point<steady_clock> m_start;
};

MyTimer::MyTimer()
    : m_impl(std::make_shared<MyTimerImpl>())
{
}

uint64_t MyTimer::GetMilliSecsFromStart()
{
    return duration_cast<milliseconds>(m_impl->Now() - m_impl->m_start).count();
}


The compiler does not complain about this code because it has enough information on all the types. A (smart) pointer to an incomplete type is still valid because the size of a pointer is known.
Note I have used a std::shared_ptr on purpose to show you later in this article how using a more appropriate std::unique_ptr forces you to introduce a (minor) change in the code.
Regarding the new implementation, there are a few interesting points:

  • The header does not contain any reference to std::chrono;
  • The compiler is not forced to resolve the implementation dependencies every time a client code references the MyTimer class.
  • All the details of the timer been used are inside the MyTimerImpl struct; this allows us to change the implementation details easily; for example, replacing steady_clock with std::chrono::high_resolution_clock. More generally, platform-independent APIs can benefit from the PImpl idiom to hide the platform-dependent implementation details.
  • This fact also implies that the client code does not need to be recompiled upon MyTimerImpl change.
Now, let me elaborate on the type of smart pointer I used.

The "pointer to implementation" is a good use case for a unique_ptr; in fact, the ownership of this pointer belongs only to a MyTimer object, and the lifetime of the pointed object should be the same as a MyTimer object.

There is no harm in using a shared_ptr, but semantically unique_ptr is the correct type.

Let's change the code above to use a unique_ptr instead of a shared_ptr:

MyTimer.h
...

private:
    struct MyTimerImpl;                  // forward declaration
    std::unique_ptr<MyTimerImpl> m_impl; // Much better :)
};



MyTimer.cpp
...

MyTimer::MyTimer()
    : m_impl(std::make_unique<MyTimerImpl>())
{
}

...


Easy, right?

Unfortunately, the compiler will start complaining that MyTimerImpl is an incomplete type.
What happened?

The problem here is the default destructor of MyTimer the compiler is so kindly implicitly providing does not have enough information on MyTimerImpl: a side-effect of changing to unique_ptr, a non-copyable type (i.e. copy constructor and copy assignment operator are deleted).
For a profound explanation of this behaviour, please refer to Item 22 of the excellent Effective Modern C++ by Scott Meyers.

We can solve the issue by moving the implementation of the destructor to after the complete definition of MyTimerImpl:

MyTimer.h
...

public:
    MyTimer();
    ~MyTimer();

...


MyTimer.cpp
...

MyTimer::MyTimer()
    : m_impl(std::make_unique<MyTimerImpl>())
{
}

MyTimer::~MyTimer() = default;

...


The above tells the compiler to create the default destructor implementation at that precise point of the cpp file. Since it is after the definition of MyTimerImpl, the compiler has all the necessary information to create the body of the default destructor.



Conclusions

The PImpl idiom is another tool in the arsenal of a good C++ developer.
These are the main reasons to implement it:
  • Improve compilation time;
  • Hide class implementation;
  • Write code for different platforms;

By writing this article, I have improved my knowledge of the compiler behaviour, especially regarding incomplete types and the special default members.