Code never lies, Documentation sometimes does!

Lately, I was working on a Windows Service using C#. Having never done such using C#, I’d thought that I’d go through the documentation that Microsoft provides. I went through it in quite a breeze; my service was running in no time.

I then added some initialisation code, which means that service startup is not instant. No problem with that; in fact the documentation has a section dedicated for such. The user’s code can provide some status update on what state the initialisation is. Unfortunately, C# does not provide this functionality; you’ll have to call native API to do so (through the SetServiceStatus call).

As I was going through the C# documentation of the struct that it accepts, I noticed that it does not match up with the documentation for the native API. The C# says that it accept long (64-bit) parameters, whilst the native API says that it accepts DWORD (32-bit) parameters. This got me thinking; is the C# documentation wrong?

I’ve whipped up two applications: one in C++ and one in C#. I checked the size of, in bytes, of the SERVICE_STATUS that SetServiceStatus expects. The answer was 28 bytes, which makes sense given that it consists of 7 DWORDs (32-bit) – 7 * 4  = 28 bytes.

size_t sizeOfServiceStatus = sizeof(SERVICE_STATUS);
cout << "Size: " << sizeOfServiceStatus << endl;

The C# application consists of copying and pasting the example in Microsoft’s documentation. After checking out the ServiceStatus struct’s size, it showed 56! Again, this was not surprising, since it consists of 6 long (64-bit) plus the ServiceState enum (which defaults to int, 32-bit) plus an additional 32-bit of padding – (6 * 8) + 4 + 4 = 56 . Therefore, the resultant struct is 56 bytes instead of 28 bytes!

int size = Marshal.SizeOf(typeof(ServiceStatus));
Console.WriteLine("Size: " + size);

Unfortunately, this will still to appear to work in the code, but obviously the output of this function is undefined since the data that’s being fed in is totally out of alignment. To make matters worse, reports this as Microsoft do, which threw me off in the beginning as well.

Naturally, fixing this issue is trivial; it’s just a matter of converting all longs to uint (since DWORD is an unsigned integer). Therefore, the example should look like the following:

public enum ServiceState
SERVICE_STOPPED = 0x00000001,
SERVICE_RUNNING = 0x00000004,
SERVICE_PAUSED = 0x00000007,

public struct ServiceStatus
public uint dwServiceType;
public ServiceState dwCurrentState;
public uint dwControlsAccepted;
public uint dwWin32ExitCode;
public uint dwServiceSpecificExitCode;
public uint dwCheckPoint;
public uint dwWaitHint;


We need HTTPS – Today more than ever! – Avoiding the KRACK Wi-Fi Attack

Any decent tech guy knows that WPA2 has been officialy broken using an attack called KRACK. What does this mean? It means that any WPA2 network can be attacked with a Man in the Middle Attack, providing that the attacker is close (or has a device close) to you. Ouch!

This reminds me back in the day where FireSheep was still a thing. This allowed any user to Hijack any unsecured Wi-Fi and browse the user’s session. This now means that WPA2 is now as secure as Unsecured Wi-Fi since any data travelling on WPA2 can potentially be sniffed out.

Allright then, what does it mean for me, as a consumer? This means that at the moment, one cannot fully trust that no-one is listening on his WPA2 network. This also means that we need HTTPS now, more than ever! Why? Simple, because this means that if the user does indeed get a hold of your traffic, he still would not make any sense of it since it’s being encrypted! VPNs now also play a good role here; one can use a VPN to make sure that any traffic that he generates (even HTTP traffic) is indeed encrypted.

If you’re connected to a network and not using HTTPS (or the HTTP protocol in general), unfortunately, you’re out of luck. You can’t safely rely that no-one is listening on your data. This means that if you’re running some Wi-Fi enabled camera, make sure that it’s either running a secure (HTTPS based for example) protocol, or just turn it off.

Fortunately, this issue is not persistent – a software update can be handed out in order to address this issue. Software vendors have already been notified on how to address this issue, it’s just a matter of waiting for said vendors to issue a fix.

In short, don’t assume that you’re safe if you’re running WPA2; the only way to encrypt your traffic is by encrypting it (HTTPS / VPN). Read more in depth on this hack here.

On the usage of ‘out’ parameters

The other day, I was discussing with a colleague on whether or not the usage of out parameters is OK. If I’m honest, I immediately cringed as I am not really a fan of said keyword. But first, let’s briefly discuss what on how the ‘out’ parameter keyword works.

In C#, the ‘out’ keyword is used to allow a method to return multiple values of data. This means that the method can return data using the ‘return’ statement and modify values using the ‘out’ keyword. Why did I say modify instead of return when referring to the out statement? Simple, because what the ‘out’ does, is that it receives a pointer to said data structure and then dereferences and applies the value when a new value is assigned. This means that the ‘out’ keyword is introducing the concept of pointers.

OK, the previous paragraph may not make much sense if you do not have any experience with unmanaged languages and pointers. And that’s exactly the main problem with the ‘out’ parameter. It’s introducing pointers without the user’s awareness.

Let’s now talk about the pattern and architecture of said ‘out’ parameter. As we said earlier, the ‘out’ keyword is used in a method to allow it to return multiple values. An ‘out’ parameter gives a guarantee that the value will get initialised by the callee and the callee does not expect the value passed as the out parameter to be initialised.  Let’s see an example:

User GetUser(int id, out string errorMessage)
 // User is fetched from database
 // ErrorMessage is set if there was an error fetching the user

This may be used as such

string errorMessage;
User user = GetUser(1, out errorMessage);

By the way, C# 7 now allows the out variable to be declared inline, looking something like this:

User user = GetUser(1, out string errorMessage);

This can easily be refactored, so that the message can be returned encapsulated within the same object. It may look something like the below:

class UserWithError
 User user {get; set;}
 string ErrorMessage {get; set;}

UserWithError GetUser(int id)
 // User is fetched from database
 // ErrorMessage is set if there was an error fetching the user

Let’s quickly go through the problems with the ‘out’ keyword exposed. Firstly, it’s not easy to discard the return value. With a return value, we can easily call GetUser and ignore the return value. But with the out parameter, we do have to pass a string to capture the error message, even if one does not need the actual error message. Secondly, declaration is a bit more cumbersome since it needs to happen in more than one line (since we need to declare the out parameter). Although this was fixed in C# 7, there are a lot of code-bases which are not running C# 7. Lastly, this prevents from the method to run as “async”.

By the way, ‘out’ raises a Code Quality warning, as defined by Microsoft’s design patterns.

Last thing I want to mention is the use of the ‘out’ keyword in the Try pattern, which returns a bool as a return type, and sets a value using the ‘out’ keyword. This is the only globally accepted pattern which makes use of the ‘out’ keyword.

int amount;
if(Int32.TryParse(amountAsString, out amount))
//amountAsString was indeed an integer

Long story short, if you want a method to return multiple values, wrap them in a class; don’t use thee ‘out’ keyword.

On sites using Javascript based cryptocurrency mining

Lately, clicked a link from those “funny” programming related Facebook pages, read the article and did not close the tab. No harm done, right? Well, after 10-15 minutes I heard the CPU fan revving more than usual and I thought that it’s quite odd. I fired up Task Manager, and I found out that my Chrome tab is running on 100% CPU usage. Odd, what was going on?

I immediately remembered an article I read a days back that Pirate Bay have implemented a script to mine coins in the background.  I fired up Developer Tools, and unsurprisingly, I found out that the site was using CoinHive.

What’s my take on this? First and foremost, as a server, it’s Illegal to use your client’s CPU cycles without letting them know upfront what you’re doing. This is essentially turning your clients into botnets. Second of all, if you’re going to do such task, at least give the client some breathing space. These coin miners can seriously hammer the CPU; since they are multi threaded, they can easily cause a 100% CPU load!

Alright then, let’s now discuss a bit from an ethic point of view. Chances are that if you are running a legit / legal site (such as this blog), you don’t want to turn your precious visitors into mining machines. Thus probably the servers which end up using such services will be more shady sites, such as Torrent Sites, Streaming Sites, some (illegal) sharing sites and any other shady service. This means that these people do not care much on how they’ll monetize their service, be it (shady) advertisements or cryptocurrency mining.

Though this had me thinking, from a consumer point of view, should I prefer giving away CPU usage for a couple of minutes in exchange for their services? Or should I prefer being bombarded with really terrible advertisements (which if interacted, can download some really malicious software). I mean, I understand that CPU usage hogging is very annoying, but so is getting bombarded with adverts. If I were in a position where I had to choose to give some CPU usage for a couple of minutes versus those adverts, I’d choose the CPU usage choice any day. But then, of course, you can always use a good Ad-Blocker!

Some closing thoughts – is it possible that sites that rely purely on adverts have a choice to finally remove (or tone down) the use of adverts, in exchange of using the client’s machine CPU Cycles? From a legal standpoint? No. From a realistic point? Probably not, or at least. I really doubt. Maybe if they strike a balance between tasteful ads and low CPU consumption? Only the future will tell. Or maybe it’s just a fad, like 3D TVs (but that’s an argument for another day).

(Article image credit:

On blindly trusting Software Vendors (and discussing CCleaner’s hacking)

By now, any software enthusiast is aware that CCleaner and CCleaner Cloud (Piriform) has been a victim of hackers. These hackers have injected malicious code in the release versions of such software and ended up on (roughly) 2 million end user machines.

For those who are not familiar with CCleaner, it allows the user to remove unwanted files, browser caches, registry keys cleanup and such. This means that it basically has access to all your system files and data on your drives. It’s a free software (with premium subscription available) and it’s installed on millions of machine all over the world.

Given the fact that this software has permission to modify system files on your machine by default, one can only imagine what a compromised installation is able to do on your machine.

From a consumer point of view, there is no way that we could have known that the software was compromised. I mean, even if they provided hashes to verify that the downloaded software is indeed the version they intended to, this would have NOT prevented anything! Why? It’s because the breach has occurred internally! In the sense that someone went into their private code repository, changed some code in their CRT and went unnoticed. How this has been done; that’s a story for another day (Piriform has not how this happened).

Anyway, the guys from Piriform has publicly acknowledged this, without being a coward or trying to cover anything up. They have also taken any measures necessary to assure that the threat is now over and issued updates to such software. This does not change the fact they’ll be losing trust from their loyal customers.

This of course left me a bit skeptical, sometimes I download applications from third party vendors, without thinking twice (and trusting them by default). This has definitely been a wake-up call to all of us, in the sense that you can never fully trust third party vendors. Can a similar thing happen in the future? Maybe. Is it avoidable some how? Well no, (or at least, maybe!)

Let’s talk about something a bit different now: Windows Apps (Universal Windows Platform Apps)!

One might ask: how is this relevant! Oh, but they are very relevant. You see, the execution of these apps works a bit different than your traditional desktop applications. These applications run in a Sandbox i.e they do not have direct access to your system. You can read more about Sandbox applications here. My point is that these apps are far safer; in case these applications get compromised, their damage is significantly reduced due to the nature of how they execute.

These applications have disadvantages of course; given that they are sandboxed, there are simply actions that they cannot do. For example, I simply cannot imagine CCleaner living as a UWP, given the fact that one of it’s capabilities is making changes to the registry. That definitely requires a “full trust” application in order to do so!

Let’s just hope that Piriform (and similar software vendors) get their act up and avoid such fiascos in the future!

Run your C# code instantly in Visual Studio (2015 and up)

A lesser known trick introduced in Visual Studio 2015 (Update 1) is the fact that you can instantly run C# code without having to create a dummy project. The new Roslyn compiler has introduced C# Interactive Shell; a REPL engine. The REPL engine provides instant feedback to the user according to the input provided. This means that you do not need any main method or any other magic; just pluck in your C# code and get feedback immediately.

In order to fire up the C# Interactive Shell, go to View -> Other Windows -> C# Interactive.

Firing up the C# Interactive Shell

The C# Interactive shell equipped with many features that we are accustomed with when using Visual Studio such as Syntax Highlighting, Code Completion, Intellisense and such.

Sample code running in the C# Interactive shell

When you run the C# Interactive shell by default, it does not take into consideration the code that you’re currently editing; it’ll behave like a basic REPL engine; nothing more. Visual Studio provides functionality to run the shell in the context of the currently loaded project. To do that, right click the desired project and press “Initialize Interactive with Project”. Doing this will allow the C# Interactive shell to work directly with the loaded project.

Initialize Interative with Project

The C# interactive shell provides a lot of functionality such as making use of the async features seamlessly. One must note that obviously, code will still run synchronously. It also has several other features, which have been thoroughly documented on Roslyn’s Github page.

One must note that this is NOT a replacement for the immediate window. Whilst debugging a process, it seems that the only way to interact immediately with the process is through the immediate window; the Interactive shell does not work. To be honest, it makes sense since the C# interactive shell is intended to run C# code instantly without requiring a running solution, unlike the immediate window.

This feature is an ideal addition to any developer who need to run some experimental /dirty code quickly, without any headache whatsoever. I used to use tools such as LINQPad (it has other uses too through) or sites such as RexTester to try out something quickly. With this tool, such tools are not needed anymore!

Edit: Thanks for spotting the typo Christopher Demicoli!

The dirty secret behind those ‘log with Facebook to view your past life’ pages.

The other day I was randomly wasting time on Facebook whilst chilling out a bit. On the news feed I saw a post of a friend which goes like “How was your past life?” (Picture below to illustrate). These posts will typically require you to log in with your social media account and then you can choose to post your result to your favorite social platform.

Typical example in order to lure in unsuspecting people.

Nothing harmful; it’s just random fun right? Unfortunately, it’s not the case. So one might wonder: what’s so dangerous with these? Let’s go through the workflow of how these pages work.

1) You visit these kind of pages

Someway or another, you end up on these pages. This can be either visiting a link which some friend has already shared on their profile or maybe some shady advert. Typically, it will bombard you to log in with your social media account, just to make it easy for you to follow through.

Easy right? Login with Facebook for some magic!

2) You click the link and you are redirected to provide your personal information

Let’s face it, probably everyone has some social media account today. These “Login with Facebook” buttons makes it a breeze to log in to your favorite site, so why not click it here as well? Anyway, when clicking it, you’re faced with this screen.

Logging in with Facebook; pretty normal.

All right, this screen is familiar, thus this is 100% safe. Well, not so much. Let’s take a second to read what the website will obtain from my Facebook profile:

  • Public Profile (picture and public information)
  • Photos (it seems ALL your public photos; that’s not very cool!)
  • Email Address

Aha! There’s the catch! So this silly application which obviously does not require my email address is requiring it? Even worse, what’s that information icon hiding?

Would you like a sample of my blood as well?

There we go, so the complete list now looks like the following:

  • Name
  • Profile Picture
  • Age (range)
  • Gender
  • Language
  • Country
  • Other Public Info (This is not properly described)
  • Photos (it seems ALL your public photos; that’s not very cool!)
  • Email Address

I think I’ve made my point now; in order to access something trivial, this page is stealing and harvesting a LOT of innocent user data!

So what, they’ve got my email! Does it really matter? I mean, it’s just my email! Actually, it’s still dangerous unfortunately. These emails end up in some guy’s list and potentially cross-checked with some known email – password combination. But, that might be just me and my paranoid thoughts.

PS: You think someone can’t cross-check your email and password from hacked lists? Check out this site.


Do we really have a lack of developers in Malta?

Recently, I was talking to a friend of mine who works in the same industry; software development. We were talking about the fact that the more time passes, the more difficult it’s becoming to find some good developers on board to get some work done. The argument was that the company he’s working for had to decline some work due to the fact that they simply do not have enough developers in order to get around and deliver this work within a reasonable time frame.

During the same argument, I’ve also mentioned the fact that we, as developers, are always getting messages on platforms such as LinkedIn in order to attempt to poach us. I understand that these people need to recruit people in order to get their monthly wage; I’m not saying that they should not be doing their job. What I’m saying is that it seems that the amount of demand for developers is higher than the actual amount of developers that are ready to work here in Malta. What’s going on?

At my workplace, I’ve noticed that the typical recruitment that occurs during the summer (recruiting new graduates) did not as well as usual. There were some new faces, but then I discovered that they were actually students / interns, not full timers! It seems that even us, we’re finding it very difficult to get more developers on board with us. We can also talk about the high turnover that’s obviously present, but that’s an argument for another day.

We must then ask another question then: what happened to the new graduates? I have no idea on the amount of graduates per year in Malta, but I’m pretty sure it’s not THAT bad. So, are they being poached by bigger companies (iGaming) with huge salaries? Are they working on their own projects? Or maybe, the new graduates are sub-par to the industry standards and end up un-recruited?

Putting a face to the name

If you’re a developer on an island like me, chances are your end clients are foreigners, not local. This means that most of the communication is done either by e-mails or by some kind of voice calls. This is exactly my case; but after working with the clients for around three years, I finally got a chance to meet them in person, in London.

Although I’ve spent quite a lot of time talking to these people by both e-mails and weekly phone conversations, the experience of communicating with a person face to face is so much better than behind a screen. Face to face communications shows far more emotion and connection between people; it’s amazing.

I’ve only had two days with my clients; so time was definitely not on our side. Would more time meant better understanding of what they want from our side? Of course! But it does not matter that much; plus such conversations can now be continued by phone in the coming days. Of course, we went through lengthy discussions with regards to our vision for the foreseeable future. The sad part is that half of what we said will probably never be realised due to the usual problem: budgets.

What did this trip yield? Frankly; less than expected. Conversations got dragged and go on tangents, schedules were ignored and sometimes the clients just started having conversations with each other, leaving us just listening and waiting for them to conclude. But the fact that both my clients and I can now put a face to the name is worth the trip on its own.

In the end of the day, was the trip worth? Yes, hands down! Such meetings aid in boosting the confidence of both parties; which will (hopefully) result in better understanding between the two parties.

Plus, I got to spend some time touring through London, so that’s great as well!

You don’t need more than 1080p on a 13″ screen!

Recently, I’ve been on the market to buy a new 13″ Laptop. I ended up buying a HP Spectre x360: i7, 8GB RAM, 1080p touch screen and the usual gizmos. I’ll talk about the huge headache I went through (not counting the hours spent searching reviews) in order to actually determine what I’m going to buy.

I was quite sure on what I wanted – a lightweight 13″ laptop with an i7 and 8GB of RAM and stuff like that. In other words, a really portable machine which won’t slow me down on the go. There were several contenders in this department, the Dell XPS 13, Lenovo Yoga 910, Razer Blade Stealth, the aforementioned HP Spectre x360  and some others which were quickly eliminated from the list. The biggest question was always : 1080p or 4K screen?

People had mixed feelings about this, some said go for 1080p and some said 4K. Here are my thoughts on this subject. Oh, by the way – this argument is only for Windows Based laptops. This does not apply for non-Windows based machines.

Let’s start by the biggest problem that screen size carries. If the pixel count grows and the screen does not, this means that the actual pixel size gets smaller. So, this means that a 300 pixels on a 13″ 1080p might be 4cm long, but 300 pixels on a 13″ 4k might be just 1 cm long. Most (older) applications were designed to work with pixels, so they do not cater for big resolutions on small screens.

Fortunately, Microsoft have realised this problem and provide a feature to scale the size of the display accordingly. So, old applications will scale up to the appropriate size, but this comes at a cost. Most of the time, the bigger the scale, the blurrier the window will actually look; I’ve illustrated this below. One can “clearly” see that the D is quite blurred out.


This problem is acknowledged by Microsoft themselves and provide some workarounds for this. Fortunately, as time goes on, more and more applications are being designed with this problem in mind and scale quite nicely. Also, the new UWP applications (such as the new looking applications on Windows 10 – Settings, Calculator and such handle this problem natively; they will not suffer from these problems.

In my case, my 1080P 13″ display came configured out of the box to use 150% scaling. This means that applications that do not handle such scaling will be multiplied by 1.5 times in order to scale appropriately. So the problem with scaling and blurring already exist with a 1080P display, let alone a 4K display! Those apps which scale poorly will simply exhibit worse symptoms since the scaling needs to be bigger at a 4K resolution.

This problem also exists in games; Linus played Half Life on a 16K monitor; scaling was just laughable.

My end verdict? If you’re buying a Windows-Based machine, don’t opt for a 4K on a 13″ display. It will make the scaling problem just worse. Let’s just hope for a better future where all applications scale correctly! I hope I’ll save some time and headache for anyone who is in the market for a 13″ laptop.

I have not mentioned too much technical details on what actually is going on; I do not want to confuse potential non-technical readers. This post will be followed up by a technical blog post explaining what is actually going on and as a programmer, how to program against this problem. If interested though, the problem mostly lies in the domain of DPI and DIP.