Adding tracing to your code

One thing you might want in your code is to add tracing to it so that your application log file will contain entries for all function entries and exits. This is tremendously useful when debugging a running application especially when you cannot connect a debugger to it for any reason. It is also very helpful when your application behaved unexpectedly once and you can’t get to repro it while you have a debugger attached. In those cases your log file is your best friend. Assuming that your log file has all the information that you need to debug the issue. Tracing all the function calls is a big help.

You don’t want to do this:

bool SaveUserInfo(User* pUser)
{
    log.Trace("Entering function SaveUserInfo");

    Database.Connect(connectionString);
    Database.Update(GetUserUpdateSql(pUser));
    Database.Disconnect();

    log.Trace("Exiting function SaveUserInfo");

    return true;
}

It should be obvious that this approach is both tedious and error prone, especially with future changes. For example if we add a parameter validation such as the one given below:

bool SaveUserInfo(User* pUser)
{
    log.Trace("Entering function SaveUserInfo");

    if (nullptr == pUser)
    {
        return false;
    }

    Database.Connect(connectionString);
    Database.Update(GetUserUpdateSql(pUser));
    Database.Disconnect();

    log.Trace("Exiting function SaveUserInfo");

    return true;
}

Ofcourse we can fix this in multiple ways. We could add a trace just before returning from the validation failure block. Or we could add a goto towards the end of the program where we trace the function exit. Or we could just restructure the program as below:

bool SaveUserInfo(User* pUser)
{
    log.Trace("Entering function SaveUserInfo");

    bool retValue = false;

    if (nullptr != pUser)
    {
        Database.Connect(connectionString);
        Database.Update(GetUserUpdateSql(pUser));
        Database.Disconnect();

        retValue = true;

    }

    log.Trace("Exiting function SaveUserInfo");
    return retValue;
}

But you get the point, this is not a good solution.

So what is the solution. I had talked about RAII in a previous post. We could employ the same concept here. We can have an object created on the function stack frame. The constructor will trace the function entry and destructor (which is guaranteed to be invoked on function exit) can trace the function exit. The only thing the developer need to know is that a function trace object should be created on the stack and it should be the first line of the function. Here is some sample code.

class FunctionTrace
{
    CString _functionName;

public:
    FunctionTrace(CString functionName)
    {
        _functionName = functionName;
        log.TraceEnter(_functionName);
    }

    ~FunctionTrace()
    {
        log.TraceExit(_functionName);
    }
};

Using the FunctionTrace class is trivial.

bool SaveUserInfo(User* pUser)
{
    FunctionTrace ft("SaveUserInfo");

    if (nullptr == pUser)
    {
        return false;
    }

    Database.Connect(connectionString);
    Database.Update(GetUserUpdateSql(pUser));
    Database.Disconnect();

    return true;
}

As you can see, exiting from the function in the middle is not a problem anymore. The code is much more compact and clean.

One thing I would like to avoid is having to specify the name of the function myself. It is a problem because it is more typing and also because there is a chance that I would rename the function some time in the future and forget to update the string parameter to the FunctionTrace constructor. It is just too easy to miss that. The compiler will not be able to help me catch that oversight.

But the preprocessor can help. Lucky for us, Visual C++ defines a macro __FUNCTIONW__ that we can use to get the function name. One could easily write a macro that encapsulates this knowledge and makes sure that a FunctionTrace instance is created on the stack and passes the __FUNCTIONW__ to the constructor of FunctionTrace. We could even modify the trace to include the file name and line number using the __FILE__ and __LINE__ macros. Now the client code becomes much more simple.

bool SaveUserInfo(User* pUser)
{
    // macro that creates FunctionTrace instance
 // on stack and passes in the name of the function. 
    FUNCTION_TRACE(); 

    if (nullptr == pUser)
    {
        return false;
    }

    Database.Connect(connectionString);
    Database.Update(GetUserUpdateSql(pUser));
    Database.Disconnect();

    return true;
}

The FUNCTION_TRACE could be implemented like this:

#define FUNCTION_TRACE() FunctionTrace fn(__FUNCTIONW__)

If we modify FunctionTrace class to trace the line number and file name, we could pass those information from FUNCTION_TRACE as follows:

#define FUNCTION_TRACE() FunctionTrace fn(__FUNCTIONW__, __LINE__, __FILEW__)

This assumes that FunctionTrace constructor now takes two strings and an integer.

class FunctionTrace
{
public:
    FunctionTrace(
        LPWSTR functionName,
        int lineNumber,
        LPWSTR fileName);

    ~FunctionTrace();
};

Have fun tracing.

RAII – Resource Acquisition Is Initialization

Resource Acquisition Is Initialization (RAII) is a programming idiom used in C++ for resource management. To understand it clearly let us look at a common programming problem.

Consider a method that needs to be synchronized across multiple threads. If you were programming against Win32 and if you were using Critical Sections as your synchronization primitive, you would call EnterCriticalSection at the beginning of the method and call LeaveCriticalSection at the end.

void DoStuff()
{
EnterCriticalSection(_pcs);

/* Code that should accessed only by one thread at a time. */

LeaveCriticalSection(_pcs);
}

There are two major drawbacks to this approach.

The first is that the programmer might forget to call LeaveCriticalSection at the end of the code. The chances of this happening increases when there are multiple exit points in the function. Even if you take care to exit at a single point and do the resource cleanup it is possible that somebody maintaining your code several years later might add an exit point in the middle of the function thereby missing cleanup. While code reviews will help alleviate this problem to some extend I have personally seen this happening in code that was reviewed by multiple people, unit tested and checked in.

The second problem with manually allocating and cleaning up resources is exceptions. Unless you handle the exception and do cleanup in the exception handler, you will leak your resource. In C++ exceptions are not idiomatic and you rarely see exception handlers. Even though your code itself might not throw exceptions the code that you call into might throw exceptions (for example a third party library). Most implementations nowadays When an exception is thrown after you acquired a resource but before your cleanup code is executed, your resource is now leaked. If we consider the example I mentioned above, your code has now acquired a thread synchronization primitive but never released it. There is a chance you will have a thread waiting forever. That may mean an unresponsive UI and an unhappy customer.

RAII solves this problem. RAII depends on three C++ features – constructors, destructors and the ability to create objects on the stack. The constructor of a class is invoked when an instance of the class is created. The destructor of a class is invoked when the instance is deleted. Objects created on the stack are automatically deleted when it goes out of scope.

This is how we use RAII to solve our problem:

  • We need a class whose purpose is to manage the resource. In the example above, the resource is the critical section. Let us create a class named Lock to manage the critical section.
  • An instance of the resource manager should be created on the stack.
  • The resource is initialized in the constructor of the resource manager. So, in our example, we call EnterCriticalSection() in the constructor of the Lock class.
  • We add the code that use the resource. In our case, we add the code that needs to be synchronized between multiple threads.
  • The resource is cleaned up in the destructor. Since the object is on the stack, the object is deleted when the function exits and the stack unwinds. In our example, we call LeaveCriticalSection() in the destructor of the Lock class.
// Manages a critical section. class Lock
{
public:
    Lock(PCRITICAL_SECTION pcs) : _pcs(pcs)
    {
        // Initialize resource in the constructor. EnterCriticalSection(_pcs);
    }

    ~Lock()
    {
        // Release resource in the destructor. LeaveCriticalSection(_pcs);
    }

private:
    PCRITICAL_SECTION _pcs;
};

Now the DoStuff() method can be re-written as follows:

void DoStuff()
{
    Lock lock(_pcs); /* Create the resource manager on the stack */

    /* Code that should accessed only by one thread at a time. */
 /* Critical section automatically released when function returns. */ 
}

Of course this can be wasteful only if a small part of the code needs to be synchronized. The way it is implemented above, the whole function is synchronized. We can get around this limitation by creating a new scope and using the lock only inside that scope.

void DoStuff()
{
    /* Code that need not be synchronized. */ 
   { // Start new scope. 
        Lock lock(_pcs);

        /* Code that should accessed only by one thread at a time. */ 

   } // End of the scope. lock is destroyed and crtical section is released. 

 /* More code that need not be synchronized. */ 
}

That is it folks. Guaranteed cleanup using RAII.

What I miss about C#

It has been a month or so since I started programming in C++. To be frank it is not the monster that I thought it would be and it wasn’t that hard to move to C++ from C#. Granted I haven’t faced any of the notorious and nasty bugs that is difficult to debug in native code but I still think C++ isn’t as hard as I thought it would be (touch wood).

That being said I do miss a few things that I was used to in C# and .NET. Here are the top 3:

  1. Refactoring tools
  2. Garbage collection
  3. A good mocking framework for unit testing

Coming Home

C++ was my first programming language. We were “taught” C++ in our first semester for our Engineering curriculum. Needless to say it was a nightmare. C++ is too big and too hard as a first programming language. At least it was for me. I didn’t own a computer at that time and I hadn’t really programmed before. So I really struggled in that class. For once I was happy that I didn’t get a seat for Computer Science for my undergraduate studies. The teacher was clueless and the students even more. There were a few students who had studied C++ or some other programming language before and they managed to help us with the assignments and stuff. I barely made the pass mark in the final exam. With all that struggle C++ left some lasting scars.

My professional life as a programmer (Programmer sounds a little lowly, maybe I should say Software Engineer) I started with Visual Basic and then moved to C#. Nine years passed and I was still scared of having to program in C++. But some time back I decided that I should conquer my fear of C++. I moved teams and joined a team that uses C++, COM, ATL and other stuff that scares the shit out of the ordinary programmers. I think I have got my feet wet now and you know what, I believe I can do it. I will share my learning experiences here. And you lucky fellow wayfarer, you will get to read it all – imagine all that reading pleasure – for free. When you read about adjustor thunks and single threaded apartments you might even get a small orgasm. Well, unless I find C++ too hard for me to handle and join another team that use Visual Basic.

Creating a Windows Service in Visual Studio

In earlier versions of Visual Studio there was a template to create Windows Service in C++ by going to File menu -> New and clicking on Project. In the New Project dialog, if we click the Visual C++ Projects node in the Project Types pane, there was a Window Service template. This is not available in Visual Studio 2010. The C++/CLI template for creating Windows Services was also removed. Only the C# template is available if you want to use managed code to develop Windows Services. If you need to create a Windows Service in unmanaged C++, your option is to use ATL.

In the new Project dialog, under Visual C++, click on ATL and select ATL Project in the center pane. Enter the name of the project and click Ok button.

 

This displays the ATL Project Wizard. Click on the Next button.

 

In the Application Settings, select Service (EXE) as the Application type and click Finish. Now Visual Studio will generate the required code files to get you started on developing a Windows Service.

 

However, there is one gotcha.

When you build the solution that you just created you will (most probably) get an error:

Error    1    error MSB3073: The command “”<path to Atl.Service.exe>” /RegServer :VCEnd” exited with code -2147024891.    C:\Program Files\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets    113    6    Atl.Service

Not a very useful error message. And I was a little confused because I was building the template created by Visual Studio, I didn’t make any modifications to it. Was Visual Studio shipping templates that won’t compile ? It turns out that the problem was that Visual Studio was not running as an administrator. Once you close Visual Studio and restart it to run as an Administrator, you will not the see this problem anymore. The project will build fine.

Happy coding.