CAUBLESTONE INK

.net development and other geeky stuff

Effective use of Nullable<T>

Posted on May 22nd, 2009


In this post I will give a quick usage scenario for using Nullable<T> as well as the nice shortcut of the null coalescing operator ??.

I know when I first ran into some code with this ?? thing in it I was like what the heck is that. Well it is something that every developer should know about. So what does it do? If you are working with objects or value types that can be null you can use this to guarantee that you have a value.

Simple example of how this works:

string test = null;
Console.WriteLine(test ?? "We had a null value");

What this will do is print “We had a null value” to the console. Now in .Net 2.0 they introduced Nullable<T> objects as well. The null coalescing operator can be used with these quite effectively as well.

Let’s look at a Date object and how we used to have to use it:

DateTime today = new DateTime();
if (today.Year == 1900)
{
   today = DateTime.Now;
}

In the old days we would have old date times out there instead of a nice null value. So with .net 2.0 we can now do something like this.

DateTime? today = null;
if (!today.HasValue)
{
   today = DateTime.Now;
}

Now that still looks like a lot of code. This is where the null coalescing operator comes into play. Take a look:

DateTime? today = null;
today = today ?? DateTime.Now;

What this does is allows us to say, hey, if the today variable is null set it to DateTime.Now. It is clean and concise.

Now you may be also asking what the ? is after the DateTime variable. Well this is shorthand for the Nullable<T> object. You could also define the same code like this and it would mean the exact same thing. I just find the ? easier to read.

Nullable<DateTime> today = null;
today = today ?? DateTime.Now;

As you can see not only are nullable objects handy but the null coalescing operator is even handier. So now you might ask can I use it on my own objects. The answer is YES you can use the ?? operator on anything that can be null. This gives this operator true versatility and should be in every developers playbook.

kick it on DotNetKicks.com

Using Predicate<T>

Posted on May 14th, 2009


Unless you have been living under a rock or unable to use a newer version of .net since 1.1 you have probably run across the Predicate<T> object while using the List<T>. I know lots of people that use these Lists and there are other objects in the framework that use Predicate<t> as well. Another common one would be the Array object. The basic usage of the Predicate<T> object is to provide a delegate with a method that takes as a parameter the same data type of the object in your list. Then the List, Array, or some other object will essentially enumerate over your collection and test each object with this method. Thus the reason it returns a boolean.

What I’m going to show you here is a simple find process that will allow you to create a reusable delegate for use in the Predicate<T> processes using reflection.

First let’s get our pieces in place. Lets first see how to do it inline which is what most people use by default.

First lets define our person class we will use.

class Person
{
   private string _firstName;
   private string _lastName;
   private int _age;

   public Person(string firstName, string lastName, int age)
   {
      this._firstName = firstName;
      this._lastName = lastName;
      this._age = age;
   }

   public string FirstName
   {
      get { return this._firstName; }
      set { this._firstName = value; }
   }

   public string LastName
   {
      get { return this._lastName; }
      set { this._lastName = value; }
   }

   public int Age
   {
       get { return this._age; }
       set { this._age = value; }
   }
}

Next in our main app lets add some data.

List<Person> people = new List<Person>();

people.Add(new Person("John", "Smith", 35));
people.Add(new Person("Caitlin", "Smith", 13));
people.Add(new Person("Steve", "Long", 23));
people.Add(new Person("Justin", "Short", 45));
people.Add(new Person("Karigan", "Patterson", 16));

Now that we have data in our object we want to search. First I will show you the delegate method in-lined.

// Find one result
Person p = people.Find(delegate(Person p1) { if (p1.LastName == "Long") return true; else return false; });
Console.WriteLine("{0}, {1} - {2}", p.LastName, p.FirstName, p.Age);

As you can see we have created a delegate using the delegate keyword and we are passing in a object of the same datatype as our list as a parameter. Since we are doing a simple find operation we are looking for just 1 person with a last name of Long.

This statement is a little long but not too bad in the grand scheme of things. However what if you were writing an application where you had to do a lot of finds based on just 1 property. That in itself would be come very tedious and you would end up with a lot of repetitive code.

So now lets build a class that we can use to help us with this.

public class SimpleFind<T>
{
  private string _property;
  private object _valueToFind;
  private PropertyInfo _p;

  public SimpleFind(string property, object value)
  {
    this._property = property;
    this._valueToFind = value;
    this._p = typeof(T).GetProperty(this._property);
    Protect.Against<nullReferenceException>(p == null, string.Format("Property {0} not found on type {1}", this._property, typeof(T).FullName));
  }

  public bool Find(T t)
  {
    try
    {
      if (this._p.GetValue(t, null).Equals(this._valueToFind))
      {
        return true;
      }
      else
      {
        return false;
      }
    }
    catch
    {
      return false;
    }
  }
}

So let’s go over the class itself. First, you should notice that the class uses Generics in the class definition. The type you specify needs to match the type you use in your list. Next is the constructor. Since the delegate needs to take the type of object that matches your data type we need to pass in the information we need in the constructor. In this case since we are trying to find data based on a property value we specify the Property Name that we are going to search against and the Value we want to search for. Now the find method does all the real work though. In the find method you see we are getting the property via reflection and making sure that we actually have that property before we use it. The Protect object was discussed here. Other than that you will notice that the code pretty much matches what we did earlier.

Now to see the difference:

// Find one result
Person p = people.Find(new SimpleFind<Person>("LastName", "Long").Find);
Console.WriteLine("{0}, {1} - {2}", p.LastName, p.FirstName, p.Age);

As you can see it’s a bit shorter and highly reusable. So what if you wanted to find more than one record. The same class can be used again.

// Find one result
List<Person> p2 = people.FindAll(new SimpleFind<Person>("LastName", "Smith").Find);
Console.WriteLine(p2.Count.ToString());

Well that’s it. It’s a pretty straight forward process. However I find it very useful and easy to use and the nice thing about it is that since it’s an object you could re-use it with just a little bit of tweaking.

Enjoy.

*** UPDATE ***
After doing some more testing with this class I found that I needed to move the Property Info object up into the constructor to improve performance and reduce overhead. As well I moved the protect statement to the constructor as well as any error was causing the system to just return false and keep trying to process the find. It should stop. Last but not least the If condition in the find method was changed to just use the .Equals method.

kick it on DotNetKicks.com

Exception Handling Basics

Posted on April 14th, 2009


Download the code Here.

It’s amazing to see how exception handling is not used properly after all these years that the .net framework has been out. Some of it can be attributed to the Internet since anybody can post information anywhere, it get’s propagated through google and then upcoming developers find it and think that is how things are done. Of course for those that understand exception handling it’s always obvious when you see a rookie mistake. I don’t think we should always blame the rookie since still to this day people post things with bad exception handling just making the problem worse.

The goal of this is to show you a very very simple sample to show how you should code your exception handling so that if you ever have to debug a problem you can get right to it instead of having to find it.

I’m going to give you three examples of exception handling. Two of them work correctly. The first one I will show is what you tend to find a lot. This is the one that is wrong. I cannot say that rookies are the only ones that do this either. There are plenty of people that are very strong that still make this simple mistake. However it can mean a world of difference when done right and you run into a production problem.

The wrong way:

public void ExceptionHandlingA()
{
    try
    {
	throw new ArgumentNullException("ExceptionA", "Test Exception Call from DoStuff.ExceptionHandlingA");
    }
    catch (Exception ex)
    {
	throw ex;
    }
}

Now you may ask or even tell yourself that there is nothing wrong with this statement. The problem is both subtle and devious. It all hinges on your Catch block. Just looking at this statement you think it bubbles the exception up. While it does bubble it up what is wrong with this is that it bubbles it up as a new exception object. While if you only have a single layer of code this would never be obvious. However if you are calling this method from other classes that then are called by other classes is where you start to run into your problem.

Next I’ll show you two proper methods that do exception handling and then walk you through creating the code you need to show the very subtle difference in the result. Namely the stacktrace.

Good Exceptions:

public void ExceptionHandlingB()
{
    try
    {
	throw new ArgumentNullException("ExceptionB", "Test Exception Call from DoStuff.ExceptionHandlingB");
    }
    catch (Exception ex)
    {
	throw;
    }
}

public void ExceptionHandlingC()
{
    try
    {
	throw new ArgumentNullException("ExceptionC", "Test Exception Call from DoStuff.ExceptionHandlingC");
    }
    catch
    {
	throw;
    }
}

Now if you look at this code you will see that the only thing that is different is that in the Catch block we only use the keyword throw. This is very important and something you should understand. Basically when you call just the word throw it does a re-throw in the IL for .net whereas the other throw ex command creates a new exception.

In case you don’t believe what I’ve just said here is the IL from the Bad exception handler:

.method public hidebysig instance void  ExceptionHandlingA() cil managed
{
  // Code size       22 (0x16)
  .maxstack  3
  .locals init ([0] class [mscorlib]System.Exception ex)
  IL_0000:  nop
  .try
  {
    IL_0001:  nop
    IL_0002:  ldstr      "ExceptionA"
    IL_0007:  ldstr      "Test Exception Call from DoStuff.ExceptionHandlingA"
    IL_000c:  newobj     instance void [mscorlib]System.ArgumentNullException::.ctor(string,
                                                                                     string)
    IL_0011:  throw
  }  // end .try
  catch [mscorlib]System.Exception
  {
    IL_0012:  stloc.0
    IL_0013:  nop
    IL_0014:  ldloc.0
    IL_0015:  throw
  }  // end handler
} // end of method DoStuff::ExceptionHandlingA

and the code from the good exception handler:

.method public hidebysig instance void  ExceptionHandlingC() cil managed
{
  // Code size       22 (0x16)
  .maxstack  3
  IL_0000:  nop
  .try
  {
    IL_0001:  nop
    IL_0002:  ldstr      "ExceptionC"
    IL_0007:  ldstr      "Test Exception Call from DoStuff.ExceptionHandlingC"
    IL_000c:  newobj     instance void [mscorlib]System.ArgumentNullException::.ctor(string,
                                                                                     string)
    IL_0011:  throw
  }  // end .try
  catch [mscorlib]System.Object
  {
    IL_0012:  pop
    IL_0013:  nop
    IL_0014:  rethrow
  }  // end handler
} // end of method DoStuff::ExceptionHandlingC

If you notice towards the end of the IL that on the good one it uses the command rethrow where the bad handler does not. This is very important as the rethrow command allows your exception objects to retain the full stacktrace. Since stacktraces are very important in helping you find where your problem is the better it is the faster you can find your problem and fix it.

Now to show you what we have done so you can see for your own eyes. Create a new VS Console project or just put this stuff in notepad and compile using the SDK. Whatever your preference. I’ve included a VS2008 version of the project for download if you just want to download and run it.

Take the first three methods from a above and put them in a class called DoStuff like so:

using System;
using System.Collections.Generic;
using System.Text;

namespace EffectiveErrorHandling
{
    class DoStuff
    {
        public void ExceptionHandlingA()
        {
            try
            {
                throw new ArgumentNullException("ExceptionA", "Test Exception Call from DoStuff.ExceptionHandlingA");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void ExceptionHandlingB()
        {
            try
            {
                throw new ArgumentNullException("ExceptionB", "Test Exception Call from DoStuff.ExceptionHandlingB");
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        public void ExceptionHandlingC()
        {
            try
            {
                throw new ArgumentNullException("ExceptionC", "Test Exception Call from DoStuff.ExceptionHandlingC");
            }
            catch
            {
                throw;
            }
        }

    }
}

Next we are going to create a second layer that calls this class using the same exception handling constructs for each method type so we create a layer that can absorb our exceptions to show the loss of the stacktrace.


using System;
using System.Collections.Generic;
using System.Text;

namespace EffectiveErrorHandling
{
    class CallStuff
    {
        public void CallExceptionA()
        {
            try
            {
                DoStuff d = new DoStuff();
                d.ExceptionHandlingA();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void CallExceptionB()
        {
            try
            {
                DoStuff d = new DoStuff();
                d.ExceptionHandlingB();
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        public void CallExceptionC()
        {
            try
            {
                DoStuff d = new DoStuff();
                d.ExceptionHandlingC();
            }
            catch
            {
                throw;
            }
        }

    }
}

Next put the following code in your Program.cs file:

using System;
using System.Collections.Generic;
using System.Text;

namespace EffectiveErrorHandling
{
    class Program
    {
        static void Main(string[] args)
        {
            CallStuff c = new CallStuff();

            Console.WriteLine("Calling Exception Type A");
            try
            {
                c.CallExceptionA();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace);
            }
            Console.WriteLine("");
            Console.WriteLine("");
            Console.WriteLine("Calling Exception Type B");
            try
            {
                c.CallExceptionB();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace);
            }
            Console.WriteLine("");
            Console.WriteLine("");
            Console.WriteLine("Calling Exception Type C");
            try
            {
                c.CallExceptionC();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace);
            }
        }
    }
}

As you can see here we are handling the exception that is raised in each case and outputing it to the console.

Download the code Here.

Now if you are trusting this is the output from the program when you run it. As you can see the first exception has one less level of detail due to the fact that it does not rethrow the exception but instead it creates a new copy of the exception for bubbling up. So as you are progressing through your development career please take this to heart. You’ll thank me for it when you run up against some bug which you could have found and fixed if you had the right exception handling in place.

Output from the console:


Calling Exception Type A
Test Exception Call from DoStuff.ExceptionHandlingA
Parameter name: ExceptionA
at EffectiveErrorHandling.CallStuff.CallExceptionA() in G:\a951072\My Documen
ts\Visual Studio 2008\Projects\EffectiveErrorHandling\EffectiveErrorHandling\Cal
lStuff.cs:line 18
at EffectiveErrorHandling.Program.Main(String[] args) in G:\a951072\My Docume
nts\Visual Studio 2008\Projects\EffectiveErrorHandling\EffectiveErrorHandling\Pr
ogram.cs:line 16

Calling Exception Type B
Test Exception Call from DoStuff.ExceptionHandlingB
Parameter name: ExceptionB
at EffectiveErrorHandling.DoStuff.ExceptionHandlingB() in G:\a951072\My Docum
ents\Visual Studio 2008\Projects\EffectiveErrorHandling\EffectiveErrorHandling\D
oStuff.cs:line 29
at EffectiveErrorHandling.CallStuff.CallExceptionB() in G:\a951072\My Documen
ts\Visual Studio 2008\Projects\EffectiveErrorHandling\EffectiveErrorHandling\Cal
lStuff.cs:line 31
at EffectiveErrorHandling.Program.Main(String[] args) in G:\a951072\My Docume
nts\Visual Studio 2008\Projects\EffectiveErrorHandling\EffectiveErrorHandling\Pr
ogram.cs:line 27

Calling Exception Type C
Test Exception Call from DoStuff.ExceptionHandlingC
Parameter name: ExceptionC
at EffectiveErrorHandling.DoStuff.ExceptionHandlingC() in G:\a951072\My Docum
ents\Visual Studio 2008\Projects\EffectiveErrorHandling\EffectiveErrorHandling\D
oStuff.cs:line 42
at EffectiveErrorHandling.CallStuff.CallExceptionC() in G:\a951072\My Documen
ts\Visual Studio 2008\Projects\EffectiveErrorHandling\EffectiveErrorHandling\Cal
lStuff.cs:line 45
at EffectiveErrorHandling.Program.Main(String[] args) in G:\a951072\My Docume
nts\Visual Studio 2008\Projects\EffectiveErrorHandling\EffectiveErrorHandling\Pr
ogram.cs:line 38

kick it on DotNetKicks.com

Exception woes and the dreaded clr20r3 error

Posted on February 13th, 2009


Well, we got bit by this obscure bug as well. As most of you, if you have encountered this, have found out there is not really a lot of information out there on the web to really explain what the heck is going on. All we know is that it kills our app and we get no real information out of it.

So hopefully my information will provide some extra light on the subject. Since each case is different however from my research they are also very similar in there respective problems.

My scenario

Windows Service running on Windows 2003 server
Multi-threaded app (roughly 70 threads)
Lots of real-time messaging using Tibco EMS
nHibernate database layer
.Net 2.0 framework

The problem

Without reason or warning the windows service would crash, without any notifications going out, and our users would be dead in the water.

What we tried:

  • First, we tried adding the AppDomain.UnhandledException logic. Bam – NO good.
  • Next, we tried to add the .Net legacy exception handling tag to our app config file. Bam – NO good. Not only that but we could not even start our service properly.
  • Next, we called MS. Opened a case and got some tools to try and capture some mem dumps if we could replicate the server failure in our dev environment. This might have worked but we fixed the problem before we could find out.
  • Lastly, we were reviewing lots of our code to try and find any leaks, wholes, etc that could maybe cause a critical thread to fail and bring it down. Honestly we got lucky. Just so happens we found an area that did not look right, fixed the code, and Bam – No more exceptions.

What actually caused the problem

In as few lines as possible here is what caused the problem, this method is a shortened and modified version just showcasing the issue and also this is the method that was given to the thread process to run once the thread was started.

What we had in our code

public void RunMe()
{
    try
    {
       List data = new List();

       data.Add(new SomeObject());
       data.Add(new SomeObject());
       data.Add(new SomeObject());

       foreach(SomeObject o in data)
       {
           DoSomethingToObject(o);
           data.Remove(o)
       }
    }
    catch (ThreadAbortException ex)
    {
        Log(ex);
    }
}

So basically we had a bit of logic that had data in a List collection. We were enumerating over it and once it was processed removing it from the collection. We also had a Try..Catch block to try and catch a threadabort if one occured.

Why it blew up

Well looking at the code you’d think um that should not blow up. However if you stop and think about it for a second you will see what happened. If you guessed throwing an InvalidOperation exception… Here’s your cupie doll. :) You guessed it we were throwing an exception because we were removing from the collection while we were enumerating it. Does not matter if you have a lock or anything else this is just a no-no. Now if we had used a for loop instead of a foreach and iterated in reverse that would have been fine. However the rules around IEnumberable don’t like what we were doing.

So we threw the InvalidOperation exception and since we were in a thread and our Try..Catch handler was not catching generic exceptions it ends up being an unhandled thread exception which then bubbles up and bubbles up and bubbles up… you get the point. Even though we had Try..Catch handlers at the service layers it does not matter as this type of unhandled exception will just shut you down. It won’t even fire the Unhandled AppDomain exception.

How we fixed it

Well obviously we had to fix the foreach loop. However the biggest thing that we did to fix the problem was to actually catch the exceptions and handle them. Once we handled the exception it would still cause our thread to shut down (until we fixed the underlying issue) but our server stayed up and no more clr20r3 errors.

From everything I have found the crux of the clr20r3 is exception handling. Make sure in your threads you have a generic exception handler and log the exception to a log file, event log, database, or wherever else you need to so you can actually get the answer you need and go fix the underlying problem.

The final solution

In case you wanted to see the code that fixed the problem here it is:

public void RunMe()
{
  try
  {
       List data = new List();

       data.Add(new SomeObject());
       data.Add(new SomeObject());
       data.Add(new SomeObject());

       for (int i=data.Count-1;i!=0;i--)
       {
           DoSomethingToObject(data[i]);
           data.Remove(o)
       }
  }
  catch (Exception ex)
  {
     LogToEventLog(ex);
  }
}
kick it on DotNetKicks.com

nAnt: The master build file

Posted on February 13th, 2009


If you have been following along with the other nAnt articles, this is the final step of setting up your base project. From here you will be able to add additional projects, processes, etc. Then if you have a CI server (cruise control.net, Team City, or some other solution) you are ready to go.

Ok so without further ado here is the master build file for our sample project.

<?xml version="1.0" encoding='iso-8859-1' ?>
<project

	default="build"
	xmlns="http://nant.sf.net/release/0.85/nant.xsd"
>

	<property name="root.dir" value="${directory::get-current-directory()}" />
	<include buildfile="${root.dir}\common.xml" />

	<fileset id="buildfiles.all">
	  <include name="${root.dir}/NantSupportLibrary/default.build"/>
	  <include name="${root.dir}/NantBuildSample/default.build"/>
	</fileset>

  <target name="build" depends="cleanup common.init display-current-build-info">
    <echo message="${directory::get-current-directory()}"/>
    <echo message="${root.dir}"/>
    <echo message="${root.dir}/common.xml"/>
  	<nant>
    	<buildfiles refid="buildfiles.all" />
	</nant>
  </target>
</project>

As you can see there is not really a whole lot different in this file than a standard build file. However we will start at the top.

The very first thing we do is set our “root.dir” property. Now I did this one a little differently to show you another way to do things if you wanted to. You can also just replace this line with the following in the sample project code and it will work just fine:


Either one will work in this case. Since this file is in the root of our source tree it’s just set to the current working directory.

Next as with the other files we include our common.xml file.

The next thing is a little new. Since this considered to be a master build file what we are going to do is setup a fileset that will tell the build file where all the project level build files are.

Important: The order in which you include the files is important. They will be executed from top to bottom so make sure you have any dependencies figured out and built in the proper order.

Last but not least we have our build target. This is the sucker that starts all the work. As you can see we have several dependencies. The first is a “cleanup” step. This will cleanup our output folder so we can make sure we always have a nice clean build. Next it runs the “common.init” again to make sure our output folders are in place and that we have our project.sources defined (needed to compile the code). Lastly we call the “display-current-build-info” target. This will display some of the settings we have, framework version, etc. you can add to this output in the common.xml file if you feel the need.

Once all those are run we get into the core of the task. Here we are going to essentially have nant spawn instances of itself to run all the build files we defined up above. It will basically loop through that list and run each build file sequentially.

Well that’s about it. Your ready to run the thing. If you downloaded the zip file you can just run nant in the root source folder and it should spit everything out for you.

After it’s done running you should have your output in the output folder.

I hope you enjoyed these posts and it helps you if you plan on using nAnt as a build tool. In the future I will add more articles that build off of these. Things like adding unit testing, calling external objects, using extensions like nAntContrib, etc.

If there is anything you’d like to see drop a line and let me know.

Download the zip sample project.

kick it on DotNetKicks.com
Page 1 of 41234