Friday, March 5, 2010

Right way to print details of .NET exception

The right answer is also the simplest way to achieve this – just use e.ToString(). This prints everything including the exception type, message, stack trace, walk the inner exceptions until the last one etc.

May sound too simple to warrant a blog – but I have seen numerous times people writing several lines of code and invariably missing some crucial piece of information.

Bad Ex#1:

catch(Exception ex)
{
    Log(string.Format("Encountered exception: {0}", ex.Message));
    Log(ex.StackTrace);
    return false;
}

This lacks exception type, inner exception details etc.

Bad Ex#2:

catch (Exception ex)
{
    Console.Error.WriteLine("Unknown/Unhandled exception got while running the process");
    Console.Error.WriteLine("Message: " + ex.Message);
    Console.Error.WriteLine("Stack  : ");
    Console.Error.WriteLine(ex.StackTrace);

    if (ex.InnerException != null)
    {
        Console.Error.WriteLine("Inner Exception: " + ex.InnerException.Message);
        Console.Error.WriteLine("Stack  : ");
        Console.Error.WriteLine(ex.InnerException.StackTrace);
    }

    exitcode = -1;
}

This is missing exception type, walking of inner exceptions beyond the first one etc.

So the lesson is quite simple – always use e.ToString() to print the complete information about an exception!

Tuesday, February 9, 2010

Nasal rinse as a natural way to fight common cold

Whenever I get cold, I’m very averse to taking medicine as technically there is no medicine for cold and taking some will unnecessarily reduce my body’s ability to fight virus. At the same time I always wondered if there is something I could do that’s completely natural and gives me relief at that hard time.

Recently I discovered this NeilMed Sinus rinse that apparently is followed since ages in India. This time I used this towards the end of my ‘cold’ episode and loved it!

Next time I’ll try earlier – usually I know about my cold before a day or 2 of its arrival…

Friday, January 22, 2010

Get subject common name from an X509Certificate2 object

Both Subject and SubjectName properties of X509Certificate2 have the full distinguished name (ex: “CN = Rags, OU = UserAccounts, DC = corp, O = microsoft”). But what if we only want the common name part of it (in this case “Rags”). This was unintuitive to find, but I finally figured out. You use

cert.GetNameInfo(X509NameType.SimpleName, false)

This prevents parsing the string etc and is certainly better!