Programming in C#, Java, and god knows what not

Old Fella Is Here to Stay

Illustration

Visual Basic 6.0 seems to be indestructible.

Windows 8 officially offers support for Visual Basic 6 run-time and limited support for it’s IDE (yes, believe it or not, it still works).

For those counting, that means end-of-life earliest at year 2022. Since it was created in year 1998 that gives an impressive 24 years of support. Name me one language that had longer support for single version. Yes, Marc, I know of Visual C++. Name me some other. :)

First program I ever sold (and quite a few afterward) was written in this beautiful language. It was not powerful. It was not fast. It was not even sensible at times. But it got job done and that is what counts.

While I am happy with my current choice of C# I cannot but smile at simpler times and language that marked them. May it live forever (or until Windows 9, whichever comes first).

Visual Studio 2012 RC

Illustration

First thing that you will notice when starting Visual Studio 2012 RC is that things got slower. It is not as bad as Eclipse but it is definitely not as speedy as Visual Studio 2010. Second thing you will notice is SCREAMING CAPITAL LETTERS in menu. This change was done in desire to Metro style everything and increase visibility. I can confirm success since it sticks out like a sore thumb.

Fortunately, once you get into editor, everything gets better. There are no major changes for users for old Visual Studio but evolution steps are visible. Find/Replace got major overhaul. Coloring is improved a bit. Pinning files is nice touch. That sums most of it. It was best editor and it remained as such.

Solution window now shows preview when you go through your files so just browsing around saves you a click or two. Beneath each item there is small class explorer. While this might works for small project, I have doubts that it will be usable on anything larger. But I give it a green light since it stays out of your way.

Beautiful change is that every new project automaticaly gets compiled for Any CPU. This is more than welcome change especialy considering utter stupidity from Visual Studio 2010. I just hope that Microsoft keeps it this way. Whoever is incapable of 64-bit programming these days should probably stick to COBOL.

Speaking of utter stupidities, there were rumors that Express editions will not support proper application development but only Metro subset. While I am not against Metro as such, I consider decision to remove Windows application development as good as Windows Phone is. Or, in other words, it might seem logical in head of some manager but in real life there is no chance of this working.

I see Visual Studio Express as a gateway drug toward other, more powerful, editions. Crippling it will just lead to folks staying on perfectly good Visual Studio 2010. Not everybody will have Windows 8 nor care about them. Since I schedule posts few days/weeks in advance, original post had continued rant here. However, there are still some smart guys in Microsoft so desktop application development is still with us in Express.

If I read things correctly it gets even better. It seems that unit testing and source control is now part of Express edition. That were the only two things missing! Now I am all wired up for Express to come. Judging from experience I should probably tone it down unless Microsoft management decides to take some/all stuff away.

All things considered, I am happy with this edition. It is stable, it has no major issues and it is completely compatible with Visual Studio 2010. For most time it feels like Visual Studio 2010 SP2. Try it out.

Mutex for InnoSetup

Illustration

If you are using InnoSetup for your installation needs you might be familiar with AppMutex parameter. You just give it SomeUniqueValue and make sure that Mutex with same value is created within your application. That way setup will warn you if your application is already running. Useful function indeed.

Simplest way to implement this would be:

static class App {
    private static Mutex SetupMutex;

    [STAThread]
    static void Main() {
        using (var setupMutex = new Mutex(false, @"Global\SomeUniqueValue")) {
            ...
            Application.Run(myForm);
        }
    }
}

And this code will work if you deal with single user. In multi-user environment this will throw UnauthorizedAccessException. Why? Because Mutex is created within current user security context by default. To have behavior where any instance, no matter which user, will keep our Mutex alive, we need to adjust security a little.

Since making null security descriptor in .NET is real pain, we can do next best thing - give everybody an access. With slightly more code we can cover multi-user scenario.

static class App {
    static void Main() {
        bool createdNew;
        var mutexSec = new MutexSecurity();
        mutexSec.AddAccessRule(new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                                                   MutexRights.FullControl,
                                                   AccessControlType.Allow));
        using (var setupMutex = new Mutex(false, @"Global\SomeUniqueValue", out createdNew, mutexSec)) {
            ...
            Application.Run(myForm);
        }
    }
}

P.S. No, giving full access to mutex that is used purely for this purpose is not a security hole…

DebuggerDisplay Can Do More

Illustration

Quite often I see code that overrides ToString() just for the sake of a tooltip when debugging. Don’t misunderstand me, I like a good tooltip but, if that is single reason for override, there is other way to do it.

.NET has [DebuggerDisplay](http://msdn.microsoft.com/en-us/library/x810d419.aspx) attribute. Simple class could implement it like this:

[DebuggerDisplay("Text={Text} Value={Value}")]
internal class XXX {
    public string Text { get; private set; }
    public float Value { get; private set; }
}

And that will result in debugging tooltip Text="MyExample" Value=3.34. Not too shabby. But what if we want our display without quotes and with different rounding rules?

There comes in expression parsing part of that attribute. Anything withing curly braces ({}) will be evaluated. So let’s change our example to:

[DebuggerDisplay(@"{Text + "" at "" + Value.ToString(""0.0"")}")]
internal class XXX {
    public string Text { get; private set; }
    public float Value { get; private set; }
}

This expression will result in tooltip that shows MyExample at 3.3. And I see that as an improvement.

Nice thing never comes without consequences. In this case advanced formatting is dependent on language used. If you stick to single language you will not see anything wrong. However, if you mix and match (e.g. C# and VB) you might end up in situation where DebuggerDisplay expression is evaluated by language currently being debugged regardless of language which it was written in.

I usually ignore that risk for sake of convenience.

P.S. And anyhow worst thing that could happen is not seeing your tooltip in very rare situations. Your actual program will not be affected in any manner.

Programming Windows

Illustration

One book that brought me into Windows programming was Programming Windows by Charles Petzold. While examples were C-based actual theory was mostly language-agnostic. APIs tend to work the same whether you do it in C or VB.

If you had any interest in Windows API, I do not think that there was a better source at the time. Unfortunately this great book died after 5th edition (Windows XP based).

Well, book is back from retirement and this time it deals with Windows 8. It will be published in November at price of $50. However if you buy it before May 31st 2012, you can grab it for a $10. I would call that a good deal.

I already ordered my copy.

P.S. I must warn you that this book is very distant relative to original series at the best. Instead of low-level programming you will get XAML and panes. However, Petzold is known for good books and that alone should justify $10.

P.S. If you are interested in real C++ programming book, do check Professional C++.

CA2000 and Using Statement

I started with code like this (give-or-take few white-spaces):

using (var aes = new RijndaelManaged() { BlockSize = 128, KeySize = 256, Key = key, IV = iv, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 }) {
    this.Transform = aes.CreateEncryptor();
    this.Stream = new CryptoStream(stream, this.Transform, CryptoStreamMode.Write);
}

Running code analysis on this returned [CA2000](http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&k=k(%22DISPOSE+OBJECTS+BEFORE+LOSING+SCOPE%22)) (Microsoft.Reliability) error. It simply stated “In method ‘Aes256CbcStream.Aes256CbcStream(Stream, CryptoStreamMode, byte[])’, object ‘<>g__initLocal0’ is not disposed along all exception paths. Call System.IDisposable.Dispose on object ‘<>g__initLocal0’ before all references to it are out of scope.”

Problem here is that all object references ARE being released by using statement. Or so I thought.

If you are using Object Initializer, compiler will generate code to support it. And that compiler-generated code is culprit for that message. And yes, there is a reason for why it behaves like this.

Personally I often ignore this warning. Strictly speaking this is not a real solution and definitely not a best practice. However it is quite often acceptable. If you are generating just few of these objects and there is no failure expected (famous last words), little bit more work for garbage collector is acceptable scenario.

Real solution for now would be not to use Object Initializer syntax when dealing with using statement. In our example that would mean:

using (var aes = new RijndaelManaged()) {
    aes.BlockSize = 128;
    aes.KeySize = 256;
    aes.Key = key;
    aes.IV = iv;
    aes.Mode = CipherMode.CBC;
    aes.Padding = PaddingMode.PKCS7;
    this.Transform = aes.CreateEncryptor();
    this.Stream = new CryptoStream(stream, this.Transform, CryptoStreamMode.Write);
}

Case for TryGetValue

When I am reviewing code, I always check how program retrieved items from dictionary. Most often I find following pattern:

if (dict.ContainsKey(key)) {
    object obj = dict[key];
    //do something with obj
}

Whenever I see it, I wonder why somebody would use it over TryGetValue:

object obj;
if (dict.TryGetValue(i, out obj)) {
    //do something with obj
}

If you deal with dictionary of objects, later code is something around 25% (depends on size of dictionary and bunch of other stuff) faster. If you deal with dictionary of structures, difference is much smaller (7-8%) since in later case you need to deal with memory allocations (remember that there is no null for structures).

Most of the time, dictionaries are used in time critical code so changing code to later is almost a no-brainer.

I only ever came to see one single scenario where key check separated from retrieval is desired. On case your dictionary has structures in it and you expect lot of look-up failures you will be better off using first example. Second code will use much more memory and need to create structure before each key check will offset any time savings you might get when item is found.

Get a Float From RandomNumberGenerator

Standard Random class works perfectly fine most of time. However, on bigger sample, you will see some non-random tendencies. Much better random source is RandomNumberGenerator.

Unfortunately RandomNumberGenerator does not actually return random numbers. It returns random bytes. It is our duty to change those random bytes to single double value ranging from 0 to 1 (as from NextDouble function).

Idea is to get 4 random bytes and to convert them to unsigned integer (negative numbers are so passé). If that number was to be in 0 to 1 range it would be enough to divide it by UInt32.MaxValue. Since we need result to be less than 1, we have slightly larger divisor:

private RandomNumberGenerator Rnd;

private double GetRandom() {
    if (this.Rnd == null) { this.Rnd = RandomNumberGenerator.Create(); }
    var bytes = new byte[4];
    this.Rnd.GetBytes(bytes);
    var number = BitConverter.ToUInt32(bytes, 0);
    return number / (UInt32.MaxValue + 1.0);
}

Not Too Unique

My personal favorite when it comes to databases is Microsoft SQL Server. However, reality dictates that I sometime have to use different database. Actually quite often I need to have one application supporting different database servers. I might need application to work on SQL Server, PostgreSQL and (god forbid) Oracle.

With time I got used to prefer standardized parts of SQL. It makes life a lot simpler and SQL Server is usually ok with that plan. Except when it comes to NULLs where things can get little bit quirky. Setting ANSI_NULLS to true does sort most of issues but one.

If you have unique index on nullable column, SQL compliant behavior is to force uniqueness on all values except null ones. That means that having "a", "b", null, null is valid scenario. In SQL Server that second null will not be allowed under premise that such value already exists and thus violates unique index. That “feature” is part of SQL Server since it’s very first days and it is very unlikely that it will be changed in the future. Compatibility is a bitch sometime.

Fortunately there is a workaround since SQL Server 2008 in form of filtered indexes. That enables unique index on only some values. In our scenario we just need to ignore nulls and standard behavior here we come:

CREATE UNIQUE INDEX UX_MyIndex ON MyTable(MyColumn) WHERE MyColumn IS NOT NULL;

PBKDF2 With SHA-256 (And Others)

.NET has built-in class handling all your PBKDF2 needs. It is called Rfc2898DeriveBytes and it works as long as you stick to SHA-1 HMAC. If your needs move in direction of SHA-256, you are out of luck.

Therefore I created Pbkdf2 class that takes any HMAC algorithm (e.g. SHA-1, SHA-256 or SHA-512) as input and allows you to derive key based on it.

using (var hmac = new HMACSHA256()) {
    var df = new Pbkdf2(hmac, password, salt, iterations);
    Console.WriteLine(BitConverter.ToString(df.GetBytes(32)));
}

Full code is available for download.