I’ve been tagged. . . and enumerated classes – level 200

After being tagged my numerous people, here's my 5.  My
long-time readers might know some of these if they've been reading closely over
the past few years, but here are 5 things about me that aren't widely known:

  • In college, I was a member of the Texas
    A&M country & western dance team:  www.aggiewranglers.com – I got to travel
    the country and world performing c&w dance.  I married a girl who was also
    on the team. (all partner dancing, people, no line dancing).  Think "girl being
    thrown in the air".
  • In 2003 I was
    called up for Army service to Iraq – was there 1 year and 3 days.  I'm 1.5 months
    from separation, so I'm hoping the nothing BIG happens between now and March
    3rd.
  • I was using Yahoo before it had
    e-mail service, and my account is one of those that is really jacked up because
    my id I originally registered had to be an e-mail address.
  • I started writing database web applications
    before the dawn of ASP 1.0 – Anybody remember .idc and .htx files? – My CGI work
    was configuring WODA for a few clients.
  • When I was a kid, I read every book on
    motorcycles/dirtbikes/ATVs in the public library, and I'd moved on to the adult
    section.  I was the only young kid who knew the difference between a two-stroke
    and four-stroke engine.  I now have a motorcycle, love to ride dirtbikes, and I'm
    lobbying my wife for a Harley.

Now, I'm going to tag Scott Bellware 5 times.

So
that this post is now void of technical content, here is a tip for using
enumerations in your applications:

Consider the following class: 

    1     public class WorkOrder

    2     {

    3         private Status
_status;

    4    
    private string _description;

    5 

    6         public Status
Status

    7    
    {

    8    
        get { return _status; }

    9             set { _status = value; }

   10         }

   11         public string
Description

   12         {

   13             get { return
_description; }

   14             set { _description = value; }

   15         }

   16     }

Notice that we are using a
Status class (enum):

    public enum Status

    {

        Pending,

        InProcess,

       
CompleteNApproved,

    }

My system manages work
orders.  Realize that this is an over-simplified example, but what happens when
you need to list our many WorkOrder(s) in a grid or for a printable report? 
Easy, right?  No.  You have this Status property that is very ugly when
displayed.  "InProcess", "CompleteNApproved".  Your users don't want to see
that.  In business speak, it needs to be displayed as "In-Process", and
"Complete & Approved".  How do we do this easily in code?  On possible way
is to create a Facade class that is used in reports.  This facade class could
translate the enum to our required Status titles.  This is undesirable because
we then have to wrap each WorkOrder instance in a new class just for display
purposes.  I would prefer that our WorkOrder could be displayed on its own, but
we have to do something about that enum.  Let's turn our enum into an enumerated
class:

First, I'll rename the enum like so:

    public enum StatusValue

    {

        Pending,

       
InProcess,

        CompleteNApproved,

    }

Then I'll make Status a
class with 3 static instances: 

    public class Status

    {

        private static Status
_pending = new Status(StatusValue.Pending, "Pending");

       
private static
Status _inProcess = new Status(StatusValue.InProcess, "In-Process");

       
private static
Status _complete = new Status(StatusValue.CompleteNApproved, "Complete & Approved");

 

        private StatusValue _statusValue;

        private string _displayTitle;

 

        private Status(StatusValue statusValue, string displayTitle)

   
    {

            _statusValue = statusValue;

            _displayTitle = displayTitle;

        }

 

        public StatusValue StatusValue

        {

            get { return
_statusValue; }

        }

 

        public string
DisplayTitle

        {

   
        get { return _displayTitle; }

   
    }

 

        public override
string ToString()

   
    {

            return _displayTitle;

   
    }

 

        public static Status Pending

       
{

            get {
return _pending; }

        }

 

        public static Status
InProcess

        {

       
    get { return _inProcess; }

   
    }

 

        public static Status Complete

       
{

            get {
return _complete; }

        }

    }

Notice that I've overridden the ToString() method
so that my _displayTitle field is returned.  Now, when I throw my WorkOrder
class (or List<T> of instances) into a grid or some other binding
container, I'll see the proper display title for my Status.  Now my users are
happy, and I can move a WorkOrder class around anywhere in my application.  For
persisting to the database, I use the StatusValue (which can be Int32, Int16, or
byte) in my database table.  It's easy to do that whether I'm using a
hand-crafted SQL statement or (my favorite) NHibernate for my ORM
solution.

Our lack of built-in enumerated classes is something I plan to
gripe about at the up-coming MVP Summit.  Our enum construct is very weak and is
no more than glorified primitives.  Consider what Java has as of version 5
(taken from http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html):

public enum Planet {
MERCURY (3.303e+23, 2.4397e6),
VENUS (4.869e+24, 6.0518e6),
EARTH (5.976e+24, 6.37814e6),
MARS (6.421e+23, 3.3972e6),
JUPITER (1.9e+27, 7.1492e7),
SATURN (5.688e+26, 6.0268e7),
URANUS (8.686e+25, 2.5559e7),
NEPTUNE (1.024e+26, 2.4746e7),
PLUTO (1.27e+22, 1.137e6);

private final double mass; // in kilograms
private final double radius; // in meters
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
public double mass() { return mass; }
public double radius() { return radius; }

// universal gravitational constant (m3 kg-1 s-2)
public static final double G = 6.67300E-11;

public double surfaceGravity() {
return G * mass / (radius * radius);
}
public double surfaceWeight(double otherMass) {
return otherMass * surfaceGravity();
}
}

Now we need to play catch-up again.  If in C# I was able to declare my
Status enum like this, I could give it a friendly display title and even some
methods right there in the enum definition.  I would have less code to maintain,
and I would get the build in enum behavior for free.

Driving a “no bugs” team culture – level 200

I've been reviewing Jim Shore and chromatic's upcoming Agile book, and I especially like the "No Bugs" section here: http://jimshore.textdriven.com/Agile-Book/no_bugs.html

Large, dusty bug databases abound.  Some teams have a process where this is unavoidable.  Some teams use a bug database as a roadmap *shudder*. 

Personally, I believer that a "low priority bug" doesn't exist.  If it's a bug, why would you ever think of not fixing it?  If a product manager decides that the current behavior of the system is acceptable for the time being, then why would you call it a bug?  You may find the behavior of the system undesirable, but ultimately, it's the product owner's call what is desirable or not.  Maybe he agrees it's undesirable, but there are other things more undesirable (like the complete absence of several large stories). 

In my experience, poor management leads to a code-and-fix culture – working off a bug list.  It's "easy" if there is just a running list of bugs.  The team stays busy, and you can track work (kind of).  What is hard is to lay out a prioritized road map and manage the growth of the product.  Managing the product is actual work. 

Many things can contribute to a low bug count:  proper roadmap planning, good developers, automated tests, good software design, etc.  I think the average life of a bug is also very important for the team culture.

To drive a culture of "no bugs", bugs cannot be allowed to live long.  If a bug is announced, and nothing happens, the team accepts that the bug is there, and they will fix it "when they get to it".  If someone stops and immediately addresses the bug, then the team knows that bugs are not acceptable.  From a management perspective, I give bugs top priority.  If there is a bug on our wall (red index card), it has top priority – no questions.  The bug is not allowed to live.  This is key for driving a "no bugs" team culture.
 

Searching in .Net (don’t search manually, let .Net do it for you) – level 100

With .Net 2.0, we have some basic search
functionality baked in to the .Net Framework.  With Linq coming out in .Net 3.5,
we will have full querying support on IEnumerable types, but we have quite a bit
of power with .Net 2.0.  In this short article, I'll outline how to search
objects in memory with .Net 2.0 or higher.

Consider the following class, Person:

public class Person : IComparable

{

    private string _firstName;

    private string
_lastName;

 

    public Person(string firstName,
string
lastName)

   
{

        _firstName
= firstName;

       
_lastName = lastName;

    }

 

    public string FirstName

    {

        get { return _firstName;
}

    }

 

    public string
LastName

    {

        get { return _lastName;
}

    }

 

    public string
FullName

    {

        get { return string.Format("{0} {1}",
FirstName, LastName); }

    }

 

    public int CompareTo(object obj)

    {

        Person person = (Person)obj;

        int compareResult =
LastName.CompareTo(person.LastName);

        if(compareResult == 0)

        {

               
compareResult = FirstName.CompareTo(person.FirstName);

        }

 

        return compareResult;

    }

 

    public override string
ToString()

   
{

        return
FullName;

   
}

}

Consider
this a basic domain object within the application.  We have the need to work
with many instances of this class in memory.  Assume that there is no need for a
relational database for this application.  We pull Person instances in memory
and work with them.  Often, we'll need to pare down the set to only include
instances that match some criteria.  We could loop through each one and create a
new list with matches, but with .Net 2.0 and "Comparison"(s), we have a more
elegant way.  Here is an example.

        public void ShouldQueryArray()

   
    {

            Person[] people = new Person[]{new Person("Homer", "Simpson"), new
Person("Jeffrey", "Palermo")};

           
Person[] matches = Array.FindAll<Person>(people, delegate(Person
obj)

                                               
                {

                                   
                                return
(obj.FirstName.Contains("ome"));

                                                           
    });

 

            foreach(Person
person in matches)

            {

               
Console.WriteLine(person);

            }

        }


In this example, we can just specify the
condition that causes an instance to match, and we'll get back a new array with
only the matches.  In this case, we get the following output:

Homer Simpson

I work with
arrays a lot.  In fact, it is my favorite IEnumerable data structure because of
it's power, but it isn't the only structure that supports comparisons (and there
are other methods similar to FindAll, but FindAll is the most common).  

public void ShouldQueryIList()

{

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

   
list.Add(new Person("Homer",
"Simpson"));

   
list.Add(new Person("Jeffrey",
"Palermo"));

 

    List<Person>
matches = list.FindAll(delegate(Person obj)

               
                            {

                       
                        return
(obj.FirstName.Contains("ome"));

                                            });

 

    foreach (Person
person in matches)

    {

        Console.WriteLine(person);

    }

}


Here, we are using the
List<T> class for our search.  The following example is more complex. 
This illustrates that the matching criteria can be as complicated as you need it
to be.

public void ShouldQueryArrayWithComplexComparison()

{

    Person[] people = new Person[] { new Person("Homer", "Simpson"), new
Person("Jeffrey", "Palermo") };

    Person[] matches = Array.FindAll<Person>(people, delegate(Person
obj)

                                               
        {

                                           
                return
(obj.FirstName.StartsWith("j", StringComparison.InvariantCultureIgnoreCase)

                                                           
       && obj.LastName.EndsWith("mo"));

               
                                        });

 

    foreach (Person person in
matches)

    {

        Console.WriteLine(person);

    }

}


By the way, if you aren't
familiar with the "delegate" keyword, this is an anonymous method.  I could
refactor it into a private method, but I'm using it inline instead.  In short,
FindAll just requires a delegate.  However you wish to provide it is fine.

Making images in .resx files available to other projects (they default to internal) – level 200

I find it very frustrating that there is no obvious way to have the .resx
generator mark members as public instead of internal.  In my team's solution, we
have a need for these to be public.  Here's how I solved it:

Add a nant target that can do a
find/replace in a file (I don't know of a shell command that will do that)

<?xml version="1.0" encoding="utf-8"?>

<!–EXTERNAL_PROPERTIES:
filename;stringToReplace;newString
–>

<project name="BuildTasks" xmlns="http://nant.sf.net/release/0.85-rc4/nant.xsd">

  <target name="FindReplace">

    <move file="${filename}" tofile="${filename}.bak">

      <filterchain>

        <replacestring from="${stringToReplace}" to="${newString}" />

      </filterchain>

    </move>

 

    <move file="${filename}.bak" tofile="${filename}"/>

  </target>

</project>

Add a pre-build step to the project
to run this target and feed in the correct file:

pushd .
cd "$(ProjectDir)...."
binnantnant.exe -buildfile:buildtasks.build FindReplace -D:filename="$(ProjectDir)PropertiesIcons.Designer.cs" -D:stringToReplace=internal -D:newString=public
binnantnant.exe -buildfile:buildtasks.build FindReplace -D:filename="$(ProjectDir)PropertiesToolbarIcons.Designer.cs" -D:stringToReplace=internal -D:newString=public
popd

Compile as you normally would and
note the output:

------ Build started: Project: MyProject, Configuration: Debug Any CPU ------
pushd .
cd "C:svnMyProject-trunksrcMyProject...."
binnantnant.exe -buildfile:buildtasks.build FindReplace -D:filename="C:svnMyProject-trunksrcMyProject\PropertiesIcons.Designer.cs" -D:stringToReplace=internal -D:newString=public
binnantnant.exe -buildfile:buildtasks.build FindReplace -D:filename="C:svnMyProject-trunksrcMyProject\PropertiesToolbarIcons.Designer.cs" -D:stringToReplace=internal -D:newString=public
popd
NAnt 0.85 (Build 0.85.2344.0; rc4; 6/2/2006)
Copyright (C) 2001-2006 Gerry Shaw
http://nant.sourceforge.net

Buildfile: file:///C:/svn/MyProject-trunk/buildtasks.build
Target framework: Microsoft .NET Framework 2.0
Target(s) specified: FindReplace


FindReplace:

[move] 1 files moved.
[move] 1 files moved.

BUILD SUCCEEDED

Total time: 0 seconds.

NAnt 0.85 (Build 0.85.2344.0; rc4; 6/2/2006)
Copyright (C) 2001-2006 Gerry Shaw
http://nant.sourceforge.net

Buildfile: file:///C:/svn/MyProject-trunk/buildtasks.build
Target framework: Microsoft .NET Framework 2.0
Target(s) specified: FindReplace


FindReplace:

[move] 1 files moved.
[move] 1 files moved.

BUILD SUCCEEDED

Total time: 0 seconds.

Compile complete -- 0 errors, 0 warnings
MyProject -> C:svnMyProject-trunksrcMyProjectbinDebugMyProject.dll
========== Build: 1 succeeded or up-to-date, 0 failed, 0 skipped ==========

XmlSerializer will use the Equals() method to find circular references

This post saved me quite a bit of time:

http://sqljunkies.com/WebLog/kmarple/archive/2005/01/11/6180.aspx

 We were having a problem with serializing a domain object.  It was reporting a circular reference problem.  We found out that because we had overriden the Equals method to compare our ids, the XmlSerializer thought all the objects were the same if the id had not been assigned yet.  Assigning an id up front solved this serialization issue.
 

Firefox 2 installed – love the spellchecking! – level 100

There's a lot of talk about IE7 vs. FF2.  It's all pretty boring for me. 
Browsers are boring.  They are glorified terminals.  Dave Thomas (of Pragmatic
Programmers fame) puts it in an interesting way: (paraphrasing) -We have the same
client-server terminal we had years ago, but now the terminal can show porn.- 
That drew quite a few laughs at the NoFluffJustStuff conference in Austin this
past summer.

In short, displaying web pages isn't all
that exciting.  What all the browsers have turned to for added value is
add-ins.  Add-ins for ad-blocking, popup blocking, anti-phishing, etc.  While
some browsers develop all add-ins in-house, I believe the main factor behind
Firefox's success is the large number of add-ins available for free that have
been contributed by the developer community.  The other browsers don't have
this.  If it weren't for all the FF add-ins, FF wouldn't have much of a leg to
stand on.

Back to my main reason for this post:  I
have installed Firefox 2, and I love the spell checking.  Anywhere I write text
in a web-page, I get in-line spell checking.  Write emails with Gmail, Forum
posts, anything – instant spell-checking.  Brilliant!

Sorting in .Net (don’t sort manually, let .Net do it for you) – level 100

I've labeled this as a level 100 topic because I feel that every .Net developer
should know the basics of sorting.  With the base class library that we have to
work with, we don't have to worry about sorting algorithms or speeding up our
sorts.  Folks smarter than I have implemented the fast sorting that we have in
.Net.

Here, I'll cover the basics of how
to sort your own domain object as well as how to sort any other object (even
ones you didn't create).

Let's consider
the following domain object, Person:

   11 public class Person

   12 {

   13     private string _firstName;

   14     private string
_lastName;

   15 

   16     public Person(string firstName,
string
lastName)

   17    
{

   18        
_firstName = firstName;

   19         _lastName =
lastName;

   20    
}

   21 

   22     public string
FirstName

   23    
{

   24        
get { return _firstName;
}

   25    
}

   26 

   27     public string
LastName

   28    
{

   29        
get { return _lastName;
}

   30    
}

   31 }

In our application, we may want to display
FirstName LastName or LastName, FirstName.  Also, we may want ascending or
descending sorts.  If you are using a database, you may be tempted to let the
database order the records for you, and that's fine if you never need to change
the sort inside the application.  In object-oriented systems, however, a lot of
code never talks to the database, so we need to be able to sort.  Now, suppose I
wanted the following code to work:

 

[Test]

public void ShouldSortPersonsAscending()

{

    Person[] persons =
new Person[]{new Person("Homer", "Simpson"), new Person("Bart", "Simpson"), new Person("Jerry", "Seinfeld")};

    Array.Sort(persons);

    foreach(Person person in persons)

    {

        Console.WriteLine(person.FullName);

    }

}


This code won't work right now because
Array.Sort( ) counts on the elements in the array implementing the IComparable
interface.  This is a key interface in .net for sorting.  By adding an
implementation of that method to my Person class, I get sorting for free.  What
I am going for here is a sort by last name and then first name:

public class Person : IComparable

{

    private string _firstName;

    private string
_lastName;

 

    public Person(string firstName,
string
lastName)

   
{

        _firstName
= firstName;

       
_lastName = lastName;

    }

 

    public string FirstName

    {

        get { return _firstName;
}

    }

 

    public string
LastName

    {

        get { return _lastName;
}

    }

 

    public string
FullName

    {

        get { return string.Format("{0} {1}",
FirstName, LastName); }

    }

 

    public int CompareTo(object obj)

    {

        Person person = (Person)obj;

        int compareResult =
LastName.CompareTo(person.LastName);

        if(compareResult == 0)

        {

            compareResult
= FirstName.CompareTo(person.FirstName);

        }

 

        return compareResult;

    }


Notice how
I just had to implement a single method comparing first on last name and then on
first name.  Here is my output:

------ Test started: Assembly: BlogScratchPad.dll ------

Jerry Seinfeld
Bart Simpson
Homer Simpson

1 passed, 0 failed, 0 skipped, took 0.41 seconds.

That's the bread and butter sorting case,
and that gives my Person object a default sort order.  Anyone working with
Person(s) can now sort by last name, first name in ascending order.  But what if
I wanted to sort in descending order?  There is another key interface in .Net
called IComparer.  This interface enables you to create a class that defines the
sort order for any class.  Consider the following tests.  I would like my
Person(s) to be listed in descending alphabetical order (reverse of above). 
Here, I choose to implement the generic form to avoid some casting:
IComparer<T>.

[Test]

public void
ShouldSortPersonsDescending()

{

    Person[] persons = new Person[] { new Person("Homer", "Simpson"), new Person("Bart", "Simpson"), new Person("Jerry", "Seinfeld")
};

    Array.Sort(persons,
new ByLastNameFirstNameDescendingComparer());

    foreach (Person person in persons)

    {

        Console.WriteLine(person.FullName);

    }

}


Notice how this test looks very similar to
the previous one; however, I've added my new comparer class to instruct
Array.Sort( ) how to sort the array.

public class ByLastNameFirstNameDescendingComparer :
IComparer<Person>

{

    public int Compare(Person x, Person y)

    {

        int compareResult =
y.LastName.CompareTo(x.LastName);

        if (compareResult == 0)

        {

            compareResult
= y.FirstName.CompareTo(x.FirstName);

        }

 

        return compareResult;

    }

}


Notice how I just compared y to x instead of
x to y.  This gets me the descending order that I want.  Here is the result of
running the test:

------ Test started: Assembly: BlogScratchPad.dll ------

Homer Simpson
Bart Simpson
Jerry Seinfeld

1 passed, 0 failed, 0 skipped, took 0.41 seconds.

Notice how it is exactly the
reverse of the previous result – just what I wanted. 

Array.Sort(Array, IComparer) works to sort an array of any object under the
sun.  My team's Visual Studio solution has accumulated  a healthy number of
IComparer classes.  This allows our application to sort objects however needed,
whenever needed. 

NHibernate: ICriteria may cause update – know about AutoFlush mode – level 300

This topic is for those already using NHibernate.  By looking at the forum, that is a whole load of people!

As always, my blog posts stem from experience, and this is no different.  It's been a year since I first tried out NHibernate, and since then I've used it on 4 large, unrelated applications.  This latest application of NHibernate is by far the most exciting, however, because we are able to take advantage of the full power of the library.  The others have always been tempered with the few things that couldn't be changed that hampered seamless data access.  My team no longer has to slow down to think about what SQL to write.  We stay in C#, and we're going faster and faster.  For the performance-minded, the NHibernate SQL is pretty darned fast (because there is nothing special about it – just CRUD).  We run about 120 database tests in 2.5 seconds – not bad.

Last week, I learned another thing new about NHibernate – AutoFlush mode.  This is important because NHibernate only keeps 1 instance of your domain object per ISession instance, so if you ask for the same object multiple times from the same ISession instance, you'll get the same domain object instance.  Imagine this scenario: 

  • You pull some objects into memory.
  • The user modifies one object.
  • You query for a list using ICriteria (the object the user modified is a match for this list)

What should the system do?  Should the fresh query refresh all the objects and throw away the user's changes?  NHibernate's default behavior is "no".  It is configured to "autoflush" by default.  When it detects that some changes might inadvertently be thrown away by a fresh query, it will auto update the modified object to the database.  If you open up SQL Profiler, look for UPDATE commands amidst SELECTs.  If you choose to set the autoflush mode to "NEVER", then you'll get a big fat exception, and you can write some code to handle the times when you need to do a fresh query after a persistent object has been modified.

Podcasts I listen to – level 100

I was listening to Internet radio before the term "podcast" was coined.  With the term, we have an explosion of Internet radio and listenership.  I've been asked several times what podcasts I follow.  I'll admit, there is limited time for listening, so over time, I have dropped some shows and picked up some others.  Here is my current list:

GAIM & MSN crash bug fixed – level 100

I use GAIM for all my instant messaging.  I used to use Trillian, but I switched.  I use MSN, Yahoo, AOL, and GoogleTalk (Jabber).  I dropped ICQ some time ago because no one I knew still used it.

Recently, some MSN server changes caused GAIM to crash when logging in.  The GAIM team has fixed this bug and has released a beta with the bug-fix.  I've installed it with no problems, and I'm on universal IM once again.