[SetWindowLong](http://msdn.microsoft.com/en-us/library/windows/desktop/ms633591(v=vs.85).aspx) function is well known among those who want to change various properties of already created windows. However, there is a slight issue with it on 64-bit Windows - it does not work properly. Someone originally defined this function to return LONG. Unfortunately LONG is actually defined as a 32-bit integer on both 32 and 64-bit Windows. Since SetWindowLong is also intended for setting some pointer sized properties (e.g. GWL_WNDPROC) this will not do.
Fortunately Microsoft also saw the error and created new function SetWindowLongPtr which corrects declaration so it is valid for both 32 and 64-bit world. Except they didn’t.
While comment clearly says “This function has been superseded by the SetWindowLongPtr function. To write code that is compatible with both 32-bit and 64-bit versions of Windows, use the SetWindowLongPtr function.”, this is not really the full truth. If you check its declaration in WinUser.h you will see the ugly truth - on 32-bit system, SetWindowLongPtr is a simple #define toward good old SetWindowLong. This means that statement is valid for someone working in C/C++. For all other languages, this statement is misleading at best.
Solution for C# is simple, just check whether code is running in 32-bit mode and call SetWindowLong yourself. In all other cases just call SetWindowLongPtr. Code Analysis will complain a bit about CA1901 (P/Invoke declarations should be portable) and CA1400 (P/Invoke entry points should exist) but we can safely ignore these warnings if we make sure to call correct function ourselves.
voidDream(string theme,int rating){if(theme ==null){thrownewArgumentNullException(theme,"Theme must not be null.");}if(rating <0){thrownewArgumentOutOfRangeException(theme,"Theme must not be null.");}if(!OtherCheck(theme, rating)){thrownewArgumentException(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:
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.
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:
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:
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:
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.
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:
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:
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.
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.
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:
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. :)
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. :(
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.
Yep, there is an error in third “throwing”. For some unknown reason ArgumentException needs parameters in a different order. Correct statement would be:
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.