c#

Two simple tips for working with LINQ and IEnumerable<T>

Let’s create a simple class that returns the numbers from 1 to 100.

Read more...

Getting the Windows Product ID using WMI

I needed to get the Windows Product ID from managed code recently and decided that using WMI would be the most reliable and stable way to get the job done. Do not follow any examples that show you how to get this information from the registry. You simply cannot rely on those registry keys being present in the many different versions of Windows. There is also no guarantee that if they are present, that this will continue to be the case into the future. Using an official and supported API means that maintaining compatibility is Microsoft’s problem and not yours.

Read more...

CodeDomProvider and Compiler Warning Levels

When generating code using the CodeDomProvider you may noticed that by default you do not get the same warning messages in the CompilerResults that you receive when compiling in Visual Studio. For example, lets take the simple code below that has a static method with two unused variables.

Read more...

Attaching the Debugger only in Debug

I noticed an article on the Infinite Codex blog that demonstrates how to debug CLR Stored Procedures. The example uses a #if preprocessor directive to compile the debugging code only if the DEBUG symbol is defined. Personally, I find using the #if directive makes your code look rather ugly, and accidentally including code inside the directive that you did not intend to becomes a real possibility. My preferred solution is to use the ConditionalAttribute to refactor such code out into a separate method.

Read more...

Compute any hash for any object in C#

The .NET Framework already has many classes for cryptography in the System.Security.Cryptography namespace, so there is no need to worry about the hashing algorithms myself. The cryptography classes supplied by the .NET Framework expect to be given a byte array from which the hash can be computed. So, if I can create a hash from an array of bytes, and can convert any object into an array of bytes, then I will be able to calculate the hash for any object. Also, if I can select the CSP (Cryptographic Service Provider) to use for computing the hash, I can then “Compute any hash for any object”. Well, any hash algorithm supported by the .NET Framework at least.

Read more...