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

Avoiding ArgumentException

Lets have an imaginary function:

void Dream(string theme, int rating) {
    if (theme == null) { throw new ArgumentNullException(theme, "Theme must not be null."); }
    if (rating < 0) { throw new ArgumentOutOfRangeException(theme, "Theme must not be null."); }
    if (!OtherCheck(theme, rating)) { throw new ArgumentException(theme, "Some other reason."); }
    ...
}

On first look it looks fine. As always, devil is in the details. Let’s see how constructors for these functions look like:

public ArgumentNullException      (string paramName, string message)
public ArgumentOutOfRangeException(string paramName, string message)
public ArgumentException          (string message, string paramName)

Notice small difference in last line? Yes, order of arguments is different. Once this code is written you will probably never notice it unless you have code analysis turned on (CA2208). Unit tests will still catch correct exception and 95% developers will probably just skip over it because it “looks right”.

Would this be a critical bug? Well, not really. All properly written exception handling code will still work. Worst thing that might happen is for user to see wrong exception text. Chances are that this will be one of bugs that sits for ages although it is trivial to fix.

It is pointless to discuss whether ArgumentException has a bug in parameter ordering. Even if it is a bug (and I personally think it is), it will never get fixed. Fixing it would mean that you automatically break code for someone else and I cannot imagine any sensible person approving of this. Best that you can do is to just forget this class exists. ArgumentOutOfRangeException fits most of use cases for it anyhow.

PS: Everybody would probably be happier if ArgumentException was an abstract class.

PPS: Don’t let me get started ranting about ArgumentNullException and why it was wrong to have three argument exceptions in framework.

Dealing With Namespaces in XmlWriter

XmlTextWriter comes in really handy when all you need is serial XML output. With simple commands you can create well formed and nicely indented document:

using (var xw = new XmlTextWriter(stream)) {
    xw.WriteStartDocument(true);
    xw.Formatting = Formatting.Indented;
	xw.WriteStartElement("abc:Group");
    xw.WriteAttributeString("xmlns:abc", "http://www.example.com/something/");
    xw.WriteStartElement("abc:Element");
    ...
}

However, XmlTextWriter has limited formatting capabilities. If you want LF instead of Windows-style CRLF you will need to use something else. For me that “something else” was XmlWellFormedWriter.

To get XmlWellFormedWriter you just ask XmlWriter to create one for you. Direct replacement code would look close to this:

var settings = new XmlWriterSettings() {
	Encoding = new UTF8Encoding(false),
	Indent = true,
	IndentChars = "    ",
	NewLineChars = "\n"
};
using (var xw = XmlWriter.Create(stream, settings)) {
    xw.WriteStartDocument(true);
	xw.WriteStartElement("abc:Group");
    xw.WriteAttributeString("xmlns:abc", "http://www.example.com/something/");
    xw.WriteStartElement("abc:Element");
    ...
}

And, lo and behold, this code causes ArgumentException (Invalid name character in 'abc:Group'. The ':' character, hexadecimal value 0x3A, cannot be included in a name.). With XmlWellFormedWriter there is no cheating and manually creating XML namespaces. You can still use them, but code will look a bit different:

using (var xw = XmlWriter.Create(stream, settings)) {
    xw.WriteStartDocument(true);
    xw.WriteStartElement("abc", "Group", "http://www.example.com/something/");
    xw.WriteStartElement("abc", "Element", null);
    ...
}

PS: Yes, there is no guarantee that XmlWriter.Create will give you XmlWellFormedWriter. However, it will surely give you something close enough for this code to work.

Taking Over Standard Output

As I was running Java process from .NET program, occassionaly I would notice that program would got stuck. Long story short, I traced my issue to following exception:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    ...
    at java.awt.AWTEventMulticaster.focusLost(AWTEventMulticaster.java:230)
    at java.awt.Component.processFocusEvent(Component.java:6397)
    ...
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:97)

This exception is not something that would crash application. If I ran Java program from command prompt, exception would be printed out and program would continue.

What ended up being problem was fact that I was reading standard output from my .NET application only upon application exit. If Java application started printing too much stuff before that point, it would fill up the buffer and wait for somebody to read that data. Since there was nobody reading that data, it would wait indifinetely.

There is really easy way around it. Trick is to consume data as soon as it arrives with help of BeginOutputReadLine and OutputDataReceived handler:

process.StartInfo.RedirectStandardOutput = true;
process.OutputDataReceived += process_DataReceived;

process.Start();
process.BeginOutputReadLine();

if (process.HasExited) {
    //do something with collected data
}
private static void process_DataReceived(object sender, DataReceivedEventArgs e) {
    //store data somewhere (e.g. global StringBuilder)
}

Console Mouse Input in C#

Few days ago I read a blog post about reading console input. It was quite straight-forward explanation and I wondered how difficult would it be to have this done in C#. Well, not really hard at all.

First step is to setup our console. We enable mouse input and we disable quick edit mode:

var handle = NativeMethods.GetStdHandle(NativeMethods.STD_INPUT_HANDLE);

int mode = 0;
if (!(NativeMethods.GetConsoleMode(handle, ref mode))) { throw new Win32Exception(); }

mode |= NativeMethods.ENABLE_MOUSE_INPUT;
mode &= ~NativeMethods.ENABLE_QUICK_EDIT_MODE;
mode |= NativeMethods.ENABLE_EXTENDED_FLAGS;

if (!(NativeMethods.SetConsoleMode(handle, mode))) { throw new Win32Exception(); }

All is left to do next is a simple loop that will check for new input:

while (true) {
    if (!(NativeMethods.ReadConsoleInput(handle, ref record, 1, ref recordLen))) { throw new Win32Exception(); }
    switch (record.EventType) {
        case NativeMethods.MOUSE_EVENT:
            //do something
            break;

        case NativeMethods.KEY_EVENT:
            if (record.KeyEvent.wVirtualKeyCode == (int)ConsoleKey.Escape) { return; }
            break;
    }
}

Check out example program.

PS: Expanding program to handle other key events should be relatively easy since all structures are already in place. Check console reference for more details.

PPS: I really hate C unions. :)

Immediate Window and Visual Studio Hosting Process

Illustration

When you are debugging in Visual Studio it might be really hard to tell whether you are using Visual Studio hosting process or not. Yes, there are subtle differences but nothing that would affect anybody developing full-trust desktop applications. Unless you are fan of Immediate window (Debug -> Windows -> Immediate).

I personally adore that little window. When you hit a break-point you can use it to view whatever expression your heart desires, all with variables as they are during runtime. If you notice error (or you deliberately want to have it) in one of your values you just write myVar = 42 and value is there. Complexity of what you can do has no limit.

You can use this window even if application is not running. Just write whatever expression you want (e.g. ? 4 + 2) and you will get your result. Unless you have compile error and Visual Studio hosting process is disabled.

Among a few documented usages there is mention of design-time expression evaluation. It simply states that, in absence of hosting process, any evaluation (even simple addition) will trigger starting executable. This is not really something to worry about because it is done seamlessly. Unless you happen to have compile-error.

If you love immediate window, don’t uncheck Visual Studio hosting process debug option. Otherwise you will lose Immediate’s window functionality when you need it the most.

Inline Sorting

Sort is something that is almost mandatory when dealing with user-facing data. Everybody is so used to have items sorted that unsorted list really sticks out.

Assuming that we have list named myList, sorting is really easy to implement. Just call myList.Sort(). This method will search for IComparable interface (somewhat simplified view) and use it to compare elements. But what if we want order other than one defined in IComparable? And what can be done if there is no way to implement such interface (e.g. no source code for class)?

You can count on our friend delegate and Sort overload. Assuming that we want to do sort according to property DisplayName, code is:

drivers.Sort(
    delegate(MyClass item1, MyClass item2) {
        return string.Compare(item1.DisplayName, item2.DisplayName);
    });

Yes, I know that code is old fashioned and that Linq is sooooo much better. However, this code will work on .NET Framework 2.0. And it doesn’t look that bad. :)

Visual Studio 2012 - Update 2

After long time in CTP, Visual Studio 2012 finally got its second update.

Quite a lot of changes touch agile workflows and this alone will make it worthwhile. Unlike update 1, there are actually quite a few changes related to development so this is definitely update to install.

Update is cumulative so you don’t need anything other than base Visual Studio 2012 installation. Go forth and download.

PS: My favorite new feature is grouping of unit tests by class name and possibility to add them in playlists.

PPS: Feature that I wish I had is new Code Map. Unfortunately it is not available on Visual Studio 2012 Professional and below. :(

Crypt-compatible Passwords in C#

For hashing passwords I usually use SHA-256 PBKDF2. No project I ever made needed anything better than this. There is only one problem with this hashing function - it is not really compatible with anything.

Kinda unofficial standard for password hashing is an Unix crypt function. You can recognize its passwords by following format: $id$salt$hash. It was originally used for hashing user password on *nix systems but with time it became common format for other usages also.

After scouring Internet to find C# implementation I decided to code it myself. It seems that C# porting stopped for everybody with MD-5 variant of crypt. While that lowest common format supported quite a few use cases, I wanted to use a bit newer SHA-512 based hashing. It should have been just an hour of coding. Eventually it took me almost eight to get it working.

Few things took me by surprise during development. I was surprised how many pointless steps were in SHA-256/512 hash creation. Best example would be base-64 implementation that not only uses incompatible character set but it also shuffles bytes around before encoding. These steps don’t add any security nor they serve to slow attacker.

Lack of proper specification for MD-5 hash was annoying more than anything else. For most of part I used just specification for SHA-256/512 combined with reference implementation in C. Yes, it wasn’t mission impossible, but lack of description for something that is part of every Unix/Linux system for more than decade is an annoyance at best.

Sample supporting MD-5 ($1$), Apache MD-5 ($apr1$), SHA-256 ($5$) and SHA-512 ($6$) password generation is available for download.

PS: If you are interested in test cases for it, you can check Medo.dll repository.

Naughty ArgumentException

Writing a function you probably write following checks as a reflex:

void DoSomething(string argument) {
    if (argument == null) {
        throw new ArgumentNullException("argument", "No nulls allowed!");
    }
    if (argument == string.Empty) {
        throw new ArgumentOutOfRangeException("argument", "No empty strings!");
    }
    if (Environment.Foo && (argument == "bar")) {
        throw new ArgumentException("argument", "Something else!");
    }
    ...
}

Yep, there is an error in third “throwing”. For some unknown reason ArgumentException needs parameters in a different order. Correct statement would be:

    ...
        throw new ArgumentException("Something else!", "argument");
    ...
}

What will happen if you mess it up?

Well, nothing much. Exception will still be thrown and your code should be fine. You will see wrong exception text but any stacktrace will probably lead you to correct spot in code.

But it looks ugly.

TextBox With a Cue

Illustration

On web it became very popular to have gray, watermarked, text that offers a cue for filling out a field. As you start writing, cue disappears.

For a while now, Windows have full support of this feature. However, Windows Forms in .NET framework are bit behind. Fortunately implementing this feature is not really hard. All we need is property (e.g. CueText) in a class inherited from TextBox.

Setting value is done by sending a EM_SETCUEBANNER message to TextBox:

NativeMethods.SendMessage(this.Handle,
                          EM_SETCUEBANNER,
                          new IntPtr(1),
                          new StringBuilder(value));

There is no need to check this function for success. If visual styles are turned on, it will not fail. And even if it fails, there is not a thing we can do to fix it. Ignoring result code is as good solution as any.

Retrieving value via EM_GETCUEBANNER is a bit more involved:

var text = new StringBuilder(256);
var res = NativeMethods.SendMessage(this.Handle,
                                    EM_GETCUEBANNER,
                                    text,
                                    new IntPtr(text.Capacity));
if (res.ToInt64() != 0) {
    return text.ToString();
} else {
    return null;
}

This time check for valid result is warranted. If result is good, string will be returned. Otherwise, null gets to mess things up.

These few lines (along with Interop definitions) are all that is needed for this useful functionality.

Sample project is available for download.