I hate it when my laptop’s fan switches on – here’s how I solved it (Part 1)!

I’ve made it a point that I’d buy my laptop equipped with a Intel U-Based – this is to make sure that my laptop is as light, power efficient and quiet as possible. My HP Spectre X360 does all of this; well almost. It’s light (around 1.3kg), power efficient (8-10 hours of battery plus), but is not the quietest laptop on the planet.

When the laptop has a relatively moderate task to process, it ramps up the CPU to full (3.5 Ghz). That’s great, except for the fact that high clocks generate a lot of heat. When the threshold temperature is constantly exceeded (in my laptop’s case, around 50c), the fan needs to kick-in in order to manage thermals.

There’s nothing wrong with that; the laptop functions perfectly. What I’d like is to do all these tasks, whilst the laptop remains cool and will only require passive cooling. How can this be achieved? By lowering the maximum CPU Clock, of course!

What I ended up doing is setting up the maximum CPU usage to 45% (at around 1.6 Ghz), instead of 100%. This means that tasks run slightly slower, but meaning that the laptop runs way cooler. Even better, most of the time, the performance cost is not felt since the tasks do not actually max the CPU usage; thus a lower CPU clock is sufficient!

For now, I’ve solved it naively – setting up this value as a fixed value is not the most efficient. There are times that my laptop is running well below under the threshold temperature where the fan needs to kick-in. A more intelligent solution is to adjust the temperatures on the fly, so that the laptop maintains a target temperature, much like how NVIDA’s GPU Boost works.

This is very easy to set up – this can be accessed through the Windows Power Options. Here’s a step by step guide.

Power Options
1) Right click the battery icon – select Power Options

 

Change Plan Settings
2) Select your desired power plan and select Change plan settings

 

Change Advanced Power Settings
3) Select Change Advanced Power Settings

 

Max Processor State
4) Scroll down, open Processor power management, open Maximum processor state, and type your maximum value. (Eg 45%)

That’s it! Next time, we’ll see how we can do all this programmatically, through WinAPI.

Until the next one.

Security by Obscurity – in real life!

We were discussing security by obscurity in the office today – it’s always a topic that we end up having a laugh at. If you have no idea what I’m talking about, read about security by obscurity here.

That’s all fine and funny, until you witness it. Us Maltese just witnessed it, last weekend, with a twist. Instead of being in some poorly written software, this was in a shop. Basically, a local Jewellery shop was robbed by professionals and they removed / deleted all security footage in the process!

You might say that this is not IT related – but I’m afraid that it’s very relevant. This got me thinking – how did they get access to the security footage? Was it there, exposed, just waiting for some person to meddle and delete with the footage? It seemed that these people thought so. Although I don’t have much details on how this was done, I would assume that these shops don’t have another site where these footage are kept just in case accidents like these happen.

So, what do I propose? Simple – it’s a bit illogical to keep the security footage at the same site where it’s being recorded. Ideally, this footage would be (instantly) moved to some off-site storage, making use of the cloud. Is there any provider doing this? A quick Google Search says yes: I’ve found examples such as CamCloud. Of course, I have no idea what the company offers since I’m not affiliated with it.

Given that today’s world is moving to the cloud, I can’t help but wonder if incidents like these can be mitigated by using such cloud services.

Examining the Ensure Pattern

The ensure concept is a programming practice that involves calling a method called EnsureXxx() before proceeding with your method call which deals with two main usages: security and performance.

Security

Let’s start by discussing the security usage of the Ensure pattern. When you enter a piece of code that can be considered critical, one needs to make sure that the code can proceed safely. Thus, before executing any call that requires such safety, an Ensure method is called.

Typically, this method will check the state that the code is currently is running is valid (what defines valid is up to the program itself) and any properties are sanity checked. In case that the state or properties are invalid, the code will simply throw an exception and the execution is immediately stopped.

A typical signature of this method will not accept any parameter and return void, such as EnsureAccessToDatabase(). Such method will make sure that the application is in the correct state and any properties (such as the connection string) are properly set.

Performance

The second usage of the Ensure pattern is performance. Many times, creating new objects will create internal dependencies which may be expensive to create. Even worse, it might be the case that the code only makes use of a portion of such objects and ends up not using the expensive dependencies. In order to circumvent this, any performant code will delegate the creation of expensive objects until they are needed.

Let’s consider an example – let’s say we have an object that may require a database access if certain operations are executed. These certain operations would implement a call such as EnsureDatabaseConnection(), which would check if the database connection exists and opens it if it does not.

The second usage is a but obsolete nowadays though – given the introduction of the Lazy<T> class nowadays, it makes more sense to wrap your deferred instances in a Lazy<T> rather than in an Ensure method. The Lazy provides native multi-thread initialisation support which you will have to do manually in an ensure pattern.

In real world applications, I still use the security component of the pattern though; it’s a very clean way to do security and sanity checks in your code, without becoming bloated.

Until the next one!

Exception Filtering in C#

What do you do when you have a piece of code that can fail, and when it fails, you need to log to a database? You wrap your code in a try-catch block and chuck a Log call in the catch block. That’s all good! What if I tell you that there is a better way to do it?

try
{
    // Code that might fail
}
catch(Exception ex)
{
    // Handle
    // Log to database
}

What’s the problem with the typical approach?

When your code enters a catch block – the stack unwinds. This refers to the process when the stack goes backwards / upwards in order to arrive the stack frame where the original call is located. Wikipedia can explain this in a bit more detail. What this means is that we might lose information with regards to the original stack location and information. If a catch block is being entered just to log to the database and then the exception is being re-thrown, this means that we’re losing vital information to discover where the issue exists; this is especially true in release / live environments.

What’s the way forward?

C# 6 offers the Exception Filtering concept; here’s how to use it.

try
{
    //Code
}
catch (FancyException fe) when (fe.ErrorCode > 0)
{
    //Handle
}

The above catch block won’t be executed if the ErrorCode property of the exception is not greater than zero. Brilliant, we can now introduce logic without interfering with the catch mechanism and avoiding stack unwinding!

A more advanced example

Let’s now go and see a more advanced example. The application below accepts input from the Console – when the input length is zero, an exception with code 0 is raised, else an exception with code 1 is raised. Anytime an exception is raised, the application logs it. Though, the exception is only caught if only if the ErrorCode is greater than 0. The complete application is on GitHub.


class Program
{
    static void Main(string[] args)
    {
        while (true)
        {
            new FancyRepository().GetCatchErrorGreaterThanZero(Console.ReadLine());
        }
    }
}

public class FancyRepository
{
    public string GetCatchErrorGreaterThanZero(string value)
    {
        try
        {
            return GetInternal(value);
        }
        catch (FancyException fe) when (LogToDatabase(fe.ErrorCode) || fe.ErrorCode > 0)
        {
            throw;
        }
    }

    private string GetInternal(string value)
    {
        if (!value.Any())
           throw new FancyException(0);

        throw new FancyException(1);
    }

    private bool LogToDatabase(int errorCode)
    {
        Console.WriteLine($"Exception with code {errorCode} has been logged");
        return false;
    }
}

 

1st Scenario – Triggering the filter

In the first scenario, when the exception is thrown by the GetInternal method, the filter successfully executes and prevents the code from entering the catch statement. This can be illustrated by the fact that Visual Studio breaks in the throw new FancyException(0); line rather than in the throw; line. This means that the stack has not been unwound; this can be proven by the fact that we can still investigate the randomNumber value. The Call Stack is fully preserved – we can go through each frame and investigate the data in each call stack.

1

2nd Scenario – Triggering the catch

In the second scenario, when the exception is thrown by the GetInternal method, the filter does not handle it due to the ErrorCode is greater than 0. This means that the catch statement is executed and the error is re-thrown. In the debugger, we can see this due to the fact that Visual Studio break in the throw; line rather than the throw new FancyException(1); line. This means that we’ve lost a stack frame; it is impossible to investigate the randomNumber value, since the stack has been unwound to the GetCatchErrorGreaterThanZero call.

2catch

What’s happening under the hood?

As one can assume, the underlying code being generated must differ at an IL level, since the stack is not being unwound. And one would assume right – the when keyword is being translated into the filter instruction.

Let’s take two try-catch blocks, and see their equivalent IL.


try
{
    throw new Exception();
}
catch(Exception ex)
{

}

Generates

 .try
 {
     IL_0003: nop
     IL_0004: newobj instance void [mscorlib]System.Exception::.ctor()
     IL_0009: throw
 } // end .try
 catch [mscorlib]System.Exception
 {
     IL_000a: stloc.1
     IL_000b: nop
     IL_000c: nop
     IL_000d: leave.s IL_000f
 } // end handler

The next one is just like the previous, but it introduces a filter to check on some value on whether it’s equivalent to 1.


try
{
    throw new Exception();
}
catch(Exception ex) when(value == 1)
{

}

Generates

.try
 {
     IL_0010: nop
     IL_0011: newobj instance void [mscorlib]System.Exception::.ctor()
     IL_0016: throw
 } // end .try
 filter
 {
     IL_0017: isinst [mscorlib]System.Exception
     IL_001c: dup
     IL_001d: brtrue.s IL_0023
     IL_001f: pop
     IL_0020: ldc.i4.0
     IL_0021: br.s IL_002d
     IL_0023: stloc.2
     IL_0024: ldloc.0
     IL_0025: ldc.i4.1
     IL_0026: ceq
     IL_0028: stloc.3
     IL_0029: ldloc.3
     IL_002a: ldc.i4.0
     IL_002b: cgt.un
     IL_002d: endfilter
 } // end filter
 { // handler
     IL_002f: pop
     IL_0030: nop
     IL_0031: nop
     IL_0032: leave.s IL_0034
 } // end handler

Although the second example generates more IL (which is partly due the value checking), it does not enter the catch block! Interestingly enough the filter keyword, is not available in C# directly (only available through the use of the when keyword.

Credits

This blog post would have been impossible if readers of my blog did not provide me with the necessary feedback. I understand that the first version of this post was outright wrong. I’ve taken feedback received from my readers and changed it so now it delivers the intended message. I thank all the below people.

Rachel Farrell – Introduced me to the fact that the when keyword generates the filter IL rather than just being syntactic sugar.

Ben Camilleri – Pointed out that when catching the exception, the statement should be throw; instead of throw ex; to maintain the StackTrace property properly.

Cedric Mamo – Pointed out that the logic was flawed and provided the appropriate solution in order to successfully demonstrate it using Visual Studio.

Until the next one!

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, pinvoke.net 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_START_PENDING = 0x00000002,
SERVICE_STOP_PENDING = 0x00000003,
SERVICE_RUNNING = 0x00000004,
SERVICE_CONTINUE_PENDING = 0x00000005,
SERVICE_PAUSE_PENDING = 0x00000006,
SERVICE_PAUSED = 0x00000007,
}

[StructLayout(LayoutKind.Sequential)]
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: https://insight.jbs.cam.ac.uk/2016/could-cryptocurrency-help-the-bottom-billion)

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.

window
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.

roslyn1
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.

interactive
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!