More Ohms Please

One of first things that you might learn as electronic hobbyist is that you should have 20 mA running through your indicator LEDs. For example, if you have 5 V power supply and your LED has voltage drop of 2V at 20 mA just give it 150 ohm resistor and you are golden.

And that is wrong. This recipe was valid 20 years ago but it is not something you should follow these days. If you have 20 mA coursing through LED, that is BRIGHT as hell. When you work in dark, every look at such device blinds you for minutes.

Don’t misunderstand me, I like to see some indication that device is alive but 1 mA or less should do the trick. These new LEDs are extremely efficient with their output and, while they still specify their current at 20 mA (or even higher), they will be bright enough at lower currents also.

PS: This rant is only about indicator LEDs; if your device needs to light-up the room, so be it.

Do I Have This Certificate?

For one build script I had to know whether certain certificate is present. It took me a while until I found Certutil. Assuming that you know a hash of desired key (and you should) command is simple:

CERTUTIL -silent -verifystore -user My e2d7b02c55d5fe76540bab384d85833376f94c13

In order to automate things you just need to extend it a bit to check exit code:

CERTUTIL -silent -verifystore -user My e2d7b02c55d5fe76540bab384d85833376f94c13
IF ERRORLEVEL 1 ECHO No certificate found.

All nice-and-dandy except that it does not work. For some reason Certutil always returns exit code 0 regardless of success. But not all is lost, command does set ERRORLEVEL environment variable (not the same thing as exit code):

CERTUTIL -silent -verifystore -user My e2d7b02c55d5fe76540bab384d85833376f94c13
IF NOT %ERRORLEVEL%==0 ECHO No certificate found.

Keys.RButton | Keys.ShiftKey | Keys.Alt

Let’s assume very simple code for purpose of key detection:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
    Debug.WriteLine(keyData);
}

Whichever key you press you will get short output in Output window. Totally boring.

But interesting thing happens when you press Alt key. Output is (sort of) as expected:

Menu, Alt

However, if you put breakpoint there and hover your mouse over keyData you will see that value is actually Keys.RButton | Keys.ShiftKey | Keys.Alt. Which one is it?

Answer is that it does not really matter. If we check values in Keys enumeration we will find following:

RButton  = 2
ShiftKey = 16
Menu     = 18
Alt      = 262144

We can see or as simple addition and thus Menu + Alt will give you 262162. Same result can also be obtained with RButton + ShiftKey + Alt.

CLR will get just integer with value of 0x40000 (262144 in decimal) from Windows. No matter what you do, it stays in integer domain. When you say Keys.Menu you are just saying 18 in human readable way. So for any text display code actually needs to guess what combination will give that result.

Code that handles string conversion goes from highest element and matches Alt and Menu. Code that handles tooltips matches values from lower end and thus it will find RButton, ShiftKey and Alt. Computer cannot say that one solution is better than other.

Regardless which combination you choose result will be the same.

Something Happened

Illustration

Going around Windows Store I managed to trigger an error “Something happened and your purchase can’t be completed.”

Maybe I am too much of an power user but this message bothers me.

Did problem happen on my computer or remote server? Is author of application at fault? Do I even have connection to server? Am I in wrong region? If I try again will it help? Should I try again now or at some later time? Is error already reported to someone or should I report it?

So many questions and just a short unhelpful message to answer them all…

Next Integer, Please

Generating sequential integers is not hard - simple counter++ is enough. Generating sequential positive integers is as trivial if you can use unsigned type. If you must stay in signed world, wrapping everything in condition will do the trick:

if (counter == Int32.MaxValue) {
    counter = 0;
} else {
    counter++;
}

Things get a bit more interesting if you need to do same in thread-safe manner. Obvious (and simplest) solution would be to put code in lock block:

lock (syncRoot) {
    if (counter == Int32.MaxValue) {
        counter = 0;
    } else {
        counter++;
    }
}

That will make code thread safe but it will also make it a lot slower. Every time you take a full blown lock, you will pay a hefty penalty. This example (on my computer) ran more than 30 times slower compared to first solution.

Only if there was an instruction specialized for integer incrementing…

Well, actually there is one - Interlocked.Increment. Unfortunate feature of this function is that (in case of 32-bit integers) once it goes up to 2147483647 it will return -1 as next value. Simple condition is all it takes to make code work:

Interlocked.Increment(ref counter);
if (counter == int.MinValue) { counter = 0; }

Except that this code does not work.

Any condition that touches our variable without being wrapped in some thread-safe construct will make a mess of things. In this case everything will work properly until variable reaches int.MaxValue (2147483647). Step after that we have a race condition between resetting variable to 0 and incrementing it further. If you have it running in two threads maybe it will even work. If code is running in more than that there is high chance you will see number 0 multiple times. Depending on your luck you might even see negative numbers counting up.

Fortunately code can be fixed:

var currCounter = Interlocked.Increment(ref counter);
if (currCounter < 0) { currCounter = currCounter + Int32.MaxValue + 1; }

We leave counter to increment as it wishes. Once it overflows we let it be - it will loop back eventually. However, there is nothing preventing us from modifying returned value because this value is ours alone and no other thread can touch it. We can simply increase all negative value by 2147483648 and we will get nice sequence of [... 2147483646 2147483647 0 1 ...]. Exactly what we wanted. And variable is held “locked” for only one instruction (Interlocked.Increment) so wait between threads is only as long as it needs to be to insure thread-safe operation.

This code is still more about ten times slower than simple non thread-safe example. But it is three times faster than our first go at locking whole operation. Whether this is even needed highly depends on your code. If you increment number only few times, there is nothing really wrong with locking even whole function. Don’t optimize code before you need to.

Timing routines are available for download. Be sure to measure on release code without debugging (Ctrl+F5). Measuring performance on debugging code is worthless because you might detect bottleneck where there isn’t any.