Category Archives: Code

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.

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).

Getting the real view under a CPreviewView (MFC)

I had an interesting problem at work the other day. In this MFC application, there are a number of views that can be printed and we support the Print Preview function.

However, in one of these views we rely on getting the view from the frame window in order to handle command updates. This is accomplished with code like this:

 pWnd = reinterpret_cast< CBaseView*>(GetActiveView());

However, when you’re in print preview mode, GetActiveView() returns a CPreviewView, not the underlying view (CBaseView). If you look in the source of CPreviewView, you’ll notice that it has a protected member m_pOrigView, which is indeed the one I want. However, there is no way of accessing that value. (I briefly toyed with the idea of directly accessing the memory via its offset from the beginning of the object, but as this software has to run in unpredictable environments, and it’s a horrible idea anyway, I let that go…)

 If you try this:

pWnd=(CBaseView*)pWnd->GetDescendantWindow(MAP_WINDOW);

Where MAP_WINDOW is the ID of the real view that I want, it won’t work (it may work in the general case, but it doesn’t work in my case).

I had two options, just return NULL and tell the higher-level functions to not do those certain command updates when the returned view is NULL. This should be done anyway, so I implemented those checks.

However, it still bugged me that I couldn’t get access to the real view. At last I hit on the idea of going through the document (this uses the Doc/View framework).

 I used this code and it did exactly what I needed:

CDocument* pDoc = GetActiveDocument();
if (pDoc!=NULL) {
    
POSITION pos = pDoc->GetFirstViewPosition();
    
CView* pView = NULL;
    
do {
            
pView = pDoc->GetNextView(pos);
            
if (pView != NULL && pView->IsKindOf(RUNTIME_CLASS(CBaseView)))
                        
return (CBaseView*)pView;     } while (pos!=NULL);
}

 

What’s Wrong with this code? – 2 – Answer

In the last post, I showed some code that had a very simple problem.

The problem is that when you call HIWORD, it converts the 16 bits into an unsigned short, which then gets passed as an int padded with zeros–not sign extended (it’s not signed). It will NEVER be less than zero. The solution is to cast it to a signed short before calling the function or change the function parameters to be signed short instead of int.

 

The First Thing in an XML file needs to be…

I just discovered a fun tidbit of information. I was using NUnit to test a number of assemblies in a single project, and many functions need an app.config file. The instructions on how to do this can be found in various places, but I was having a problem that nobody else seemed to have.

My config file looked like this:

<!– config values for nunit –>
<?xml version=”1.0″ encoding=”utf-8″ ?>
<configuration>
    <appSettings>
       <add key=”…” value=”……” />
    </appSettings>
</configuration>
    
    
   

Every time NUnit started up that project, it would fail with an assembly load error:

System.IO.FileNotFoundException : File or assembly name nunit.core, or one of its dependencies, was not found.

For further information, use the Exception Details menu item.

My first thought to that was “Huh?!” It was a highly annoying problem, because I thought I was following the instructions exactly and it should have worked!

Do you see the problem? It’s this line:

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

It needs to be the first line in the file (or taken out completely). Voila, everything works.

Pausing a Thread Safely

In .Net you have the option of Thread.Suspend() and Thread.Abort(), but under normal circumstances these are horrible options to use because they’re likely to create locking problems (i.e., the thread has a locks on resource that other threads need).

A far better way is to signal to the thread that it should pause and wait for a signal to continue.  Sometimes it can be as simple as setting a boolean value where both threads can see it. Or you could wrap the boolean value in a property and protect it with a lock, but this is probably overkill for most applications.

To pause a thread safely requires you to use a blocking signal mechanism and .Net has ManualResetEvent for just this purpose.

You could then have some C# code like this:

ManualResetEvent pauseEvent = new ManualResetEvent();

//Thread A (Controlling thread)
void OnPause()
{
 pauseEvent.Reset();
}

void OnStart()
{
pauseEvent.Set();
}

//Thread B (the one to pause)
void ThreadFunction()
{
while(doWork == true)
 {
 //do work
 …
 …

 //wait until event is set
 pauseEvent.WaitOne();
 }
}

This way, you can safely pause work and continue it at a later time, safely avoiding the possibility of deadlocks*.

* Actually, it’s still possible to create a resource locking problem–make sure you release any shared resource locks before pausing.

Free Code Here!

I just received this hilarious message: 

Thanks, you *****, for not responding to my Prim’s e-mail, and may you be cursed with the worst of success in Computer Science.

Sincerely,

Michael

Every once in a while I get requests from people asking me for completed code. The purpose of my articles (and this blog) is to aid understanding, not provide wholesale code. My job keeps me plenty busy, I receive a LOT of e-mails every day, and I probably don’t have the fully-functional, runnable code that people are looking for anyway, when they can probably find it on the Internet.

That said, I have received numerous comments, specific questions, disagreements, kudos, and suggestions that I have warmly responded to.

What’s wrong with this code? – 1

What is wrong with the following code? 

struct Foo {
    public int id;
    public string value;
    public static readonly Foo Empty = new Foo(“”);

    public Foo(string val)
    {
         this.value = val;
         this.id = -1;
     }

};

and elsewhere…

Foo m = new Foo(“Something”); 

if (object.ReferenceEquals(m, Foo.Empty))
{
    …//do something
} else
{

}

Â