Lazy<T>

Quite often in singleton classes you might find yourself doing the standard plumbing code like this:

private static MyClass _current = new MyClass();

public static MyClass Current {
    get { return _current; }
}

or a bit simpler with C# 7:

public static MyClass Current = new MyClass();

If class is a bit heavier (e.g. using lots of memory) you might do it lazily with a lock:

private static MyClass _current;

public static MyClass Current {
    get {
        lock(SyncRoot) {
            if (_current == null) { _current = new MyClass(); }
            return _current;
        }
    }
}

What almost never gets any love is Lazy construct known from .NET Framework 4:

private static Lazy<MyClass> _current = new Lazy<MyClass>();

public static MyClass Current {
    get { return _current.Value; }
}

This will initialize class on the first access, it is tread safe by default, and you can even use custom initializer if needed, e.g.:

private static Lazy<MyClass> _current = new Lazy<MyClass>(() =&gt; new MyClass(42));

public static MyClass Current {
    get { return _current.Value; }
}

Exactly what doctor prescribed. :)

PS: And stop using double-check locking.

Average Number of Lighted Segments on 7-Segment Display

For a project I am doing with kids we decided to use 3-digit 7-segment display. As we intended to video the project (eventually), it was easy to make decision that we’re gonna drive every digit fully - no multiplexing. Not only that simplifies programming logic but it also makes display rock steady during video - no flickering here.

However, with so many pins to drive, I got a bit scared about maximum power consumption MCU would need to deal with. Assuming we go with 10 mA per LED, what is actually the maximum current we’ll need?

The easy answer is 7x10 = 70 mA per digit, bringing it to 210 mA total. Assuming all digits are fully on (we haven’t used decimal point - otherwise it would be 8) we would indeed need that much current. However, realistically, are we always going to have number 8 on display?

For this purpose, we’ve gone and created a table - how many segments we actually use for each digit:

DigitSegmentsCurrent
0660 mA
1220 mA
2550 mA
3550 mA
4440 mA
5550 mA
6660 mA
7330 mA
8770 mA
9660 mA
Median550 mA

As you can see, the most common result ended up 5 segments being lighted. This tells we actually can usually count on 150 mA of precious current needed.

But wait, since our project will count from 0 to 255, we actually won’t have all our digits on all of the time. We need to calculate how many segments we actually have lighted for numbers that we need. An eternity in Excel later we’ve found that median current needed (assuming random distribution) was 120 mA. Maximum was 180 mA (darn 208!) and minimum was 20 mA.

While 180 mA is not trivial, it is definitely less than 210 mA we originally had to count.

My Most Favorite C# 7 Features

Illustration

With Visual Studio 2017 out and C# 7 in the wild we got a couple of new features. After using them for a while, here are my favorites.

Out Variables The change here is subtle and many would call it inconsequential but I love. Out variables can finally be declared inline instead of pre-declaring them above parsing statement. This small change makes code flow much smoother and, in my opinion, makes all the difference. For example, note the difference between these two code fragments:

int count;
if (int.TryParse(text, out count) && (count &gt; 1)) {
    //do something with count
}
if (int.TryParse(text, out **var** count) && (count &gt; 1)) {
    //do something with count
}

For rare cases when you don’t care about result you can also use underscore (_) character:

if (int.TryParse(text, out **var _**)) {
    //do something
}

Throw Expressions If you are creating classes for public consumption, quite often a big part of your code is boilerplate argument verification and throwing of exceptions. You can now merge usage of that argument with null coalescing or ternary operators. Again, nothing huge but makes code a bit more to the point:

if (text == null) { throw new ArgumentNullException(nameof(text), "Text cannot be null."); }
this.Text = text;

if (number &gt;= 2) { thrown new ArgumentOutOfRange(nameof(number), "Number must be 2 or more."); }
this.Number = number;
this.Text = text ?? **throw new ArgumentNullException(nameof(text), "Value cannot be null.")**;
this.Number = (number &gt;= 2) ? number : **throw new ArgumentOutOfRange(nameof(number), "Number must be 2 or more.")**;

Is Expressions Another change that seems small but it really improves code is just another style of as operator and it will probably cause its demise. It is a syntax candy allowing for inline variable declaration and a bit more readable code:

var comboBox = sender as ComboBox;
if (comboBox != null) {
    //do something with comboBox
}
if (sender is **ComboBox comboBox**) {
    /do something with comboBox
}

Local Functions And lastly, there are local functions. Again, these are nothing you couldn’t do before. I don’t think they are going to be used often most of the time. However, when you parse stuff or deal with state machines, they do come in handy as they do capture local variables.

Wish list

The only thing I still desire in C# as compared to other languages are enum methods. It is not a big thing but it would remove a whole set of helper methods and similar plumbing.

Bimil 2.00

Illustration

For this version probably the most notable change is copy/paste support. I know, how the heck can application in 2017 not support copy/paste in the first place. I can definitely think of an excuse or two but reality is that it was an inexcusable omission. Similar in the “revolutionary concepts”, finally a right-click menu is available so you don’t need to open an entry just to copy a password.

A lot of work has been done around textual passwords. As compared to the previous version, word count has gone down (27261 before vs 17701 now) but words that remained should be a bit easier to remember. Considering the default recommendation of 5 words per password is still giving you about 1 millennium in the worst case, I would say it is worth it. And don’t forget that estimate is conservative as heck: it assumes everybody knows all words you’ve used and that attacker can do 100 trillion guesses per second.

I also took liberty in removing the words found in the most common leaked passwords as well as showing the warning to user if he uses one. You can remove that warning in the Options at your own peril. :)

Filtering of entries has been improved, especially for the PasswordSafe imported categories. Additionally one can simply write * to show all elements and that should help the searches as well. Likewise Auto-type form got a bit of cleanup. Basic auto-type didn’t change but fields got Tab and Enter suffix each. It makes filling out information on forms much easier without having to predefine exact format.

A separate form for password history and other details has been added. While it doesn’t show anything that you couldn’t see in the old historical password combo box, different presentation does wonders for clarity.

Two noticeable changes happened on the setup side. The first one is change to .NET Framework 4 as .NET 2.0 simply became way too restrictive. I still didn’t want to leave Windows XP users stranded so this was as far as I was willing to go. You will also notice that most of settings are not stored in registry any more but in textual file. This should make those using Bimil without installing it much happier. :)

A few additional minor changes and bug-fixes were made but I will leave it for you to discover. As always, you can download new version from Bimil pages or upgrade from within application.

Internal Domain Name

Illustration

For the longest time anything was a good internal domain name. Yes, obviously you avoided .com, .net, .org, and other usual suspects but anything else was quite OK. While some people did go distance on this, most of networks sort-of settled on .local or .lan. And all was nice and dandy.

However, lately two things have happened lately to mess with fairy tale. First was of course that ICANN smarties decided to create a zillion new top-level domains. And then there was Apple and their kidnapping of .local suffix for the purpose of mDNS.

Just like that people found Apple devices no longer playing nicely on .local domain and all other domains got big on-sale sign with a potential for collision down the road. There was an RFC with a few reserved domain names but neither one of those actually fits the local LAN setup. And yes, there were some attempts at properly reserving the few most common domains (e.g., .lan, .home, .corp, …) but that RFC never went anywhere.

And ICANN did try to sell all three most common local names already but found itself in a bit of a bind due to a high usage of these domains in households and companies alike. Just imagine a mess some company’s network could be in if .corp gets delegated and someone buys login.corp domain. While ICANN has slowed process a bit for the most conflicting domains due to the security report, spammers are pushing to get those domains on market.

As a general rule, the only sure way not to have your domain clash with newly introduced spam domains is actually to buy your own domain. Even if you don’t want to ever have a website, you need to get a domain. I find this solution annoyance and a mini money grab at best. However, this seems to be the only sure way spammers won’t get to resolve your DNS requests. That is until you forget to renew the domain.

I personally have settled on .home for now for my own network. Based on the DNS query stats for the undelegated domains, it is among top 3 most abused domains and thus it is unlikely it will be sold for use as top domain without many feathers being ruffled. That should allow me enough time for the migration to some other domain.