Checking all values of an enumeration in C#

I have a utility function that takes in a status enumeration and returns a string description associated with the given status code.

It looks something like this:

internal static string MailProcessCodeToString(MailProcessCodes eCode)
{
switch (eCode)
{
case MailProcessCodes.mpcGoodData:
    return “No errors detected in the order mail”;case MailProcessCodes.mpcNoHeader:
    return “Could not find header in order mail”;

//etc….
I wanted to create a unit test that ensure there was an error message for every possible value of the eCode. Rather than write a separate unit test for each value (there are over 30–don’t ask).It’s fairly easy to do in .Net (using NUnit):

[Test]
public void MailProcessCodeToString_AllSuccess()
{
   
int[] vals = (int[])Enum.GetValues(typeof(MailProcessCodes));
   
foreach (int val in vals)
    {
       
string errorString = Utils.MailProcessCodeToString((MailProcessCodes)val);       

        string msg = string.Format(“{0} has no error string defined”,
                      
Enum.GetName(typeof(MailProcessCodes), val));        Assert.IsTrue(errorString.Length > 0, msg);
    }
}

Enum.GetValues() returns an array of all defined values for an enum, and Enum.GetName() translates a value into the name of the constant.

Now I have a unit  test which will tell me which error code does not have a corresponding string.

Goodbye newsletters, hello RSS

I used to subscribe to tons of CNet, TechRepulic, PCMagazine, and Builder.com newsletters, but as of today–no longer. I’ve been unsubscribing from them as I get them. Unfortunately for them, I didn’t really use their content so I’m not bothering to subscribe to their RSS feeds. Maybe in the future…

I am relying more on RSS, however, to keep me informed on the world (technical and otherwise). I’ve got about 80 feeds.

When considering the spam situation alone, RSS makes a lot of sense. Will RSS ever overtake e-mail as a personal communications medium? I’m not sure. The way it’s setup right now is a little awkward–I would have to create a private feed for each recipient, we need better tools for publishing to multiple feeds, targeting individuals.

Alexandria, Virginia has RSS Feeds available

My city of Alexandria, VA has a couple of RSS feeds available. They’re not much quite yet (DASH bus service notifications and city press releases), but there is the promise of more.

 What I’d like to see next? Daily crime reports and history and recreation news.

Alexandria also has a very impressive collection of online GIS applications that give you multiple views of the city.

It’s nice to see towns becoming more technologically adept, especially with their communications options. I already get some city news via e-mail, but I would prefer RSS.

Factory Design Pattern to the Rescue: Practical Example

Design patterns really are quite useful. I have a situation in the code I’m working on where I was obviously repeating a lot of the same patterns and code (functions that were 90% the same–the only thing different was the specific class being instantianted): perfect candidate for factory techniques.

Let’s say we have the following set of classes representing a data access layer meant to abstract some database information from the client code. We have a BaseDBObject class that defines all of the common. We derive from that for each table we want to access.

class BaseDBObject
{
    protected BaseDBObject(Database database) {...}
    public void SetProperty(string name, object value) {...}
    //...more common functionality

};

Derived from this base are lots of classes that implement table-specific database objects. To control object creation, constructors are declared protected and static member functions are used. To wit:

class MyTableObject : BaseDBObject
{
    protected MyTableObject(Database database) : base(database) { }
    public static void Create(Database database, int param1, string param2)
    {
        string query = "INSERTO INTO MyTable (param1, param2) VALUES (@PARAM1, @PARAM2)";
        SqlCommand cmd = new SqlCommand(query, database.GetConnection());
        //paramterize query
        try {
            //exeute query
            //error check
            MyTableObject mto = new MyTableObject();
            //set object properties to match what's inserted
            return mto;
        }
        catch (SqlException ex)
        {
            //handle exception
        }
        finally
        {
            //close connection
        }
    }
    //...
    public static IList<MyTableObject> LookupById(Database database, int id)
    {
        string query = "SELECT * FROM MyTable WHERE ID = @ID";
        SqlCommand cmd = new SqlCommand(query, database.GetConnection());
        //parameterize query
        try
        {
            //execute query
            SqlDataReader reader = cmd.ExecuteReader(...);
            List<MyTableObject> list = new List<MyTableObject>();
            while (reader.Read())
            {
                MyTableObject mto = new MyTableObject();
                //set properties in mto
                list.Add(mto);
               
            }
            return mto;
        }
        catch (SqlException ex)
        {
            //handle exceptions
        }
        finally
        {
            //close connections
        }
    }
};

There are two functions here that must be created for every single table object derivation. That can be a LOT of code, and most of it is doing the same thing. There are a number of simple ways to handle some of the repetition:

  1. There will be multiple LookupByXXXXX functions. They can all specify the query they will use and pass it to a common function that executes and returns a list the class’s objects.
  2. Paramterizing queries can be accomplished by a function that takes a query string, a list of parameters (say, in a struct that describes each parameter), and produces a paramterized SqlCommand, ready for execution.
  3. Other helper functions that do the actual execution and checking of errors.

In the end, however, you are still left with two things that can’t be relegated to helper functions: MyTableObject mto = new MyTableObject(); and List<MyTableObject> list = new List<MyTableObject>(); One possible solution is to use reflection to dynamically generate the required objects. From a performance and understandability perspective, I don’t think this is a first choice.

Which leaves a factory method. My first attempt involved using templates to simplify this (you will see why shortly). Something like this:

class DatabaseObjectFactory<T> where T : BaseDBObject, new()
{
    public T Create(Database database) { return new T(database); } 
    public IList<T> CreateList() { return new List<T>(); }
};

This way, I could simply define a function in the base class BaseDBObject, which I could call like this:

Lookup(database, query, arguments, new DatabaseObjectFactory<MyTableObject>());

and that would automagically return a list of the correct objects. The problem with this approach, however, lies in the Create function. .Net can’t pass arguments to a constructor of T. It can only return new T() with no parameters. Nor can you access properties of BaseDBObject through T after creation. Back to the drawing board…

Now I had to face the problem of creating a duplicate inheritance hierarchy of object factories. This is what I had hoped to avoid by using generics. I designed an interface like this:

interface IDatabaseObjectFactory
{
    BaseDBObject Create(Database database);
    IList<BaseDBObject> CreateList();
};

And in each table object derivation I declare a private class and static member like this:

private class MyTableObject : IDatabaseObjectFactory
{
    public BaseDBObject Create(Database database) { return new MyTableObject(database); }
    public IList<BaseDBObject> CreateList() { return new List<MyTableObject>(); }
};
private static IDatabaseObjectFactory s_factory = new MyTableObjectFactory();

Now, I can have a Lookup function in BaseDBObject that accepts an IDatabaseObjectFactory parameter. At the expense of creating a small, simple factory class for each table object that needs it, I can remove roughly 50 lines of code from each of those classes. Smaller code = fewer bugs and easier maintenance.

The base lookup function would look something like this:

protected Lookup(Database database, string query, ICollection<QueryArgument>, IDatabaseObjectFactory factory)
{
    //paramterize query
    //execute query
    //ignoring error-handling for sake of brevity
    SqlDataReader reader = cmd.ExecuteReader(...);
    IList<BaseDBObject> list = factory.CreateList();
    while (reader.Read())
    {
        BaseDBObject obj = factory.Create(database);
        obj.Fill(reader);    //another common function that
                             // automatically fills in all properties
                             //of object from SqlDataReader
        list.Add(obj);
    }
    return list;
}

But what about theMyTableObject.Create()? It’s possible to do something like this, but in a different way. In order to handle inserting rows in a table that uses identity fields (that you don’t know until after creation), I created a utility function that inserted the data using database, query string, and QueryArgument objects. Then, instead of creating the object directly, I do a Lookup based on values that I know are unique to the row I just inserted. This ensures I get the most complete object (at the expense of an extra database trip).

Math Magic

I just started reading Scott Flansburg’s Math Magic book. It’s all about more efficient and intelligent ways of doing math. It’s an idea I’ve long wanted to try–to increase my speed and ability to crunch numbers in my head. The hard part is practice–how do you make yourself good at this without a lot of practice? And how fun is it to practice adding numbers in your head? It’s easy to think of some periodic situations: shopping and budget balancing, for example, but after that I’m not sure.

I think I’ll write a small PocketPC app that can give me random problems to solve in my head, as well as time me and note improvements. Cool…any excuse to write a program!

Raising Taxes versus Lowering Spending

Every few months, our Senators and Congress-men and women debate taxes and whether or not to raise, lower, keep them steady, or blame others for doing so.

The main thing that I notice during this ridiculous political fights is that nobody ever talks about the most basic financial wisdom: Spend Less Than You Earn. Why doesn’t this apply to governments as well as individuals? Most people in Congress are very wealthy and presumably understand basic financial principles of wealth-building quite well. So why can’t they all exercise restraint and simply spend less? Raising taxes to cover budget shortfalls makes me very nervous because there is no amount of money that cannot be overspent! Raising taxes is not a real solution, just as earning more money isn’t a solution to your bad spending habits.

Qumana

I think, however, that I like Qumana better. The WYSIWYG is nice. Seems easier to use. I don’t need a lot of advanced features. It works simply and well. I’m not sure what I think of the drop-pad, however. It doesn’t really support how I typically write posts, but perhaps I can make some use of it. For now, I’ll probably just turn it off.

Overall, I think I’ll stick with this for at least a while.

w.bloggar

I’m out various offline blog editors. Currently I’m using w.bloggar. I’m not sure what I think of it. WYSIWYG is really a nice thing to have in an editor, but the ability to see the HTML is useful too. Probably the best editor I’ve used is Dreamweaver’s split-pane HTML/WYSIWYG interface, which allows you to view and edit either one simultaneously.

Also, their forums are filled with so much spam to be nearly unusable.

I’ll give it a try for a while and see how I like it. I really need to be blogging more…

Windows Media Player 11 continued…

Some things I really like about the new media player:

  • It is a LOT faster. I have at least 15,000 songs I’ve ripped from my large CD collection. WMP 10 took far too long enumerating albums and songs.
  • The instant search may become my primary way of finding specific music to listen to.
  • I like the tile view — it makes the experience of picking music to play sort of like browsing a physical array of CDs. I have so much music that I often don’t know what I want to listen to–browsing is essential.
  • Very intuitive–I figured out how to navigate among the new views very easily.
  • The shuffle/repeat options is much more prominent on the play-control bar. I switch shuffle on and off constantly.