Friday, August 14, 2009

Debugging the C++ Preprocessor

I don't want to start a discussion about the good and the bad of the good old c preprocessor macros. Today a macro helped me keeping the DRY principle. I found myself repeatingly writing the following three lines:
int GetValue() const {return this->value_;}
void SetValue(const int& value) {this->value_ = value;}
__declspec(property(get = GetValue, put = SetValue)) int Value;
So why not make a makro:
#define DECLARE_PROPERTY(Type,Name,Member) \
Type Get##Name() const {return Member;} \
void Set##Name(const Type##& value) {Member = value;} \
__declspec(property(get = Get##Name, put = Set##Name)) Type Name;
The definiton would look like this:
DECLARE_PROPERTY(int, Value, this->value_)
Because I'm not writing macros too often (and this should be the case in future, too) I needed to review the preprocessor output. Here are the steps: Enable the following options for the cpp file you want to debug and compile the unit or module:
The result will be a a file with the extension .i in the source directory which contains the preprocessor expanded file. This file can be very large so it is a good idea to put a unique comment marker before (and/or after) the definition to find the result easier.
ps.: One advantage of C++/CLI is that you still have the power of the c preprocessor which I'm sometimes (not too often) missing in C#. Okay, you can kick on T4 templates but that's a different story and it's questionable if this doesn't violate the KISS principle.

Thursday, August 13, 2009

Running Notepad++ under Wine

Notepad++ is a great Editor which unfortunately is just compiled for windows.
But it runs nicely under Wine:

So far I was a big fan of Live Writer. Now, searching for an alternative on Linux (Drivel didn't do the job), I discovered that I can write my posts with Google Docs.
This is the first post I've written and published with Google Docs.

SyntaxHighlighter does the better job

I was using Code Snippet plugin for Windows Live Writer with poor resutls. Thanks to this instructions now I'm using SyntaxHighlighter with much better results and I reworked the C++/CLI unit testing post to make use of SyntaxHighlighter.

How MbUnit helps not violating DRY

When I was on a .NET user group meeting in Karlsruhe about TDD the speaker (speaking nicest bavarian dialect) created a unit test and did the unbelievable: He marked the 15 lines of code that made up the first test pressed <CTRL>+<C>, moved some lines below and pressed <CTRL>+<V> and changed some values of the test.

The audience was uhhing! Several of the listeners were wearing the CCD arm ring and could not tolerate a violation of the DRY principle.

Indeed Unit Test code must be written and maintained with the same care as production code.

MbUnit supports a very neat feature that helps keeping the DRY principle: [RowTest]

Instead of writing many TestEquals derivates you simply call the function multiple times with the Row attribute...

[Row("03000000010000000000110101000063","","03000000010000001100110101000023","", false)]
[Row("03000000010000000000110101000063","","03000000010000000000110101000063","", true)]
[Row("03000000010000000000110101000063","name","03000000010000000000110101000063","", false)]
[Row("03000000010000000000110101000063","","03000000010000000000110101000063","name", false)]
[Row("03000000010000000000110101000063","name","03000000010000000000110101000063","name", true)]
[Row("03000000010000000000110101000063","name","03000000010000001100110101000023","name", false)]
void BarcodePatternTest::TestEquals(String^ barcode1, String^ realName1, String^ barcode2,  String^ realName2, bool isEqual)
 CBarcodePattern patternA((LPCTSTR)CString(barcode1),(LPCTSTR)CString(realName1));
 CBarcodePattern patternB((LPCTSTR)CString(barcode2),(LPCTSTR)CString(realName2));

 Assert::AreEqual(isEqual, CBarcodePattern::Equals(patternA,patternB));
 Assert::AreEqual(isEqual, (patternA == patternB));
 Assert::AreEqual(isEqual, (patternA.Equals(&patternB)));

Tuesday, August 11, 2009

Refactorings in Agile Development

In Agile Software Development Refactoring starts with the first lines of code you write. Jeremy Miller discusses in this excellent article published in the MSDN magazine why this makes sense and can help you deliver products that meet your customer expectations in time.

As most practices in software development Refactoring is not an art but a science.

I recommend Refactoring to patterns by Joshua Kerievsky as a book resource.

The web page maintained by well known Martin Fowler contains a brief catalog I regularly use to lookup patterns when doing refactoring work.

Friday, August 7, 2009

Code Snippet plugin for Windows Live Writer

Writing my last blog post I used “Code Snippet plugin for Windows Live Writer” to embed source code.
I had some difficulty with the formatting once posted.
This post suggested to switch off a special BlogSpot setting to convert line feeds. It didn't really work, but when I remove all linefeeds from the html I get it right:
   1: #pragma once
   3: namespace MyDiagnosticsNet {
   5:   using namespace System;
   6:   using namespace System::Diagnostics;
   8:   public ref class MyTraceListener : public TraceListener
   9:   {
  10:   public:
  11:     MyTraceListener();
  12:     virtual void Write(String^ message) override;
  13:     virtual void WriteLine(String^ message) override;
  14:     virtual void TraceEvent(TraceEventCache^ eventCache, String^ source, TraceEventType eventType, int id);
  15:     virtual void TraceEvent(TraceEventCache^ eventCache, String^ source, TraceEventType eventType, int id, String^ message);
  16: )
  17: )  private:
  18:     void CheckedTrace(String^ message);
  19:     static String^ PrependTimeStamp(String^ message);
  20:     MyBaseDescr* GetBaseDescr();
  21:     MyBaseDescr* myBaseDescr_;
  22:   };
  23: }
I think I have to do some more experiments...

Thursday, August 6, 2009

My Approach for Unit testing c++ with Visual Studio 2005

Visual Studio 2008 offers the ability to write unit tests in managed c++ code. In my current project work I have to use Visual Studio 2005 because of external constraints.

In the following article I will describe how…

  • to setup and write unit tests in c++/cli for MbUnti
  • to write the production code in unmanaged c++ with MFC
  • to setup a test project for debugging


You need to have Visual Studio 2005 and MbUnit installed.

Create a new Unit Test Project

1.) Create a new CLR Class Library.


2.) Add a reference to the MbUnit framework you want to use.


3.) Add the namespace MbUnit::Framework.

using namespace MbUnit::Framework;

4.) Add the [TestFixture] attribute to the public ref class you want to use as test container.

public ref class HelloUnitTest    
5.) Add a new public method to the test class and mark it with the[Test] attribute.
  void TestHello()

6.) Now the code should look like this:

// MyCppTest.h

#pragma once

namespace MyCppTest {

  using namespace System;    
  using namespace MbUnit::Framework;

  public ref class HelloUnitTest    
    void TestHello()    

7.) Build the project and give it a first run in the MbUnit Gui Runner.

Therefore click on Assemblies->Add Assemblies.. and select the test dll.


You can expand the tree and you will see your test fixture and your test method.


Now we have the first working version of the unit test. It passes and we’re done! Done? Not quite. Now we need to test the code we are writing to get paid for. Following the rules of TDD we need to test first.

So let’s look into the requirements: The module should return a string that contains “Hello†on request. (Ok, maybe this is not a for a real word product, but you never know…)

8.) Implementing the testing code

I know that the module is used in a MFC environment. So I first need to enable support for that. Switch on 'Use MFC in a Shared DLLâ€


Include afxwin.h in StdAfx.h

#include "afxwin.h"
Now write the the test code:
  void TestHello()    
    HelloWorldProvider provider;
    CString response = provider.request();
    Assert::Contains("Hello", response);

first test failure is that we cannot compile, so we need to create the production library.
Implementing the production code

The production library shall be unmanaged. So we go to the solution, click ‘Add new project’ and create a new MFC DLL.


Use the standard settings and finish the wizard (If you look into the generated StdAfx.h file we’ll see the what additionally might be added to the StdAfx.h file for the unit test).

Add a new class HelloWorldProvider:



Implement the request function:

class HelloWorldProvider    
  CString request() const
  return L"hello world!";
Compile the production code and compile the test code. The test code does not compile I changed it to:
// MyCppTest.h
#pragma once

#include "..\HelloWorldProvider\HelloWorldProviderImpl.h"

namespace MyCppTest {
  using namespace System;
  using namespace MbUnit::Framework; 

  public ref class HelloUnitTest    
      void TestHello()    
        HelloWorldProvider provider;    
        CString response = provider.request();
        Assert::Contains("Hello", gcnew String(response));    

Compile again and I get a linker error:

1>------ Build started: Project: MyCppTest, Configuration: Debug Win32 ------ 1>Compiling... 1>MyCppTest.cpp 1>Linking... 1>MyCppTest.obj : error LNK2028: unresolved token (0A000010) "public: __thiscall HelloWorldProvider::~HelloWorldProvider(void)" (??1HelloWorldProvider@@$$FQAE@XZ) referenced in function "public: void __clrcall MyCppTest::HelloUnitTest::TestHello(void)" (?TestHello@HelloUnitTest@MyCppTest@@$$FQ$AAMXXZ) 1>MyCppTest.obj : error LNK2028: unresolved token (0A000011) "public: __thiscall HelloWorldProvider::HelloWorldProvider(void)" (??0HelloWorldProvider@@$$FQAE@XZ) referenced in function "public: void __clrcall MyCppTest::HelloUnitTest::TestHello(void)" (?TestHello@HelloUnitTest@MyCppTest@@$$FQ$AAMXXZ) 1>MyCppTest.obj : error LNK2019: unresolved external symbol "public: __thiscall HelloWorldProvider::~HelloWorldProvider(void)" (??1HelloWorldProvider@@$$FQAE@XZ) referenced in function "public: void __clrcall MyCppTest::HelloUnitTest::TestHello(void)" (?TestHello@HelloUnitTest@MyCppTest@@$$FQ$AAMXXZ) 1>MyCppTest.obj : error LNK2019: unresolved external symbol "public: __thiscall HelloWorldProvider::HelloWorldProvider(void)" (??0HelloWorldProvider@@$$FQAE@XZ) referenced in function "public: void __clrcall MyCppTest::HelloUnitTest::TestHello(void)" (?TestHello@HelloUnitTest@MyCppTest@@$$FQ$AAMXXZ) 1>c:\temp\MyCppTest\Debug\MyCppTest.dll : fatal error LNK1120: 4 unresolved externals 1>Build log was saved at "file://c:\temp\MyCppTest\MyCppTest\Debug\BuildLog.htm" 1>MyCppTest - 5 error(s), 0 warning(s) ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Now we have the following choices: 1.) If the class is exposed in the dll interface, we can statically link to the production code which is the most accurate solution because you are testing the binary code that get’s shipped. 2.) If the class is not part of the dll interface, we can create a link library with that class and link it to both: the production module and the test module 3.) If the class is not part of the dll interface, we can add the cpp file to the test project that a object file get’s created for it and mark it as unmanaged .

I will now follow the 3rd approach…

Use ‘Add existing …’ to add the HelloWorldProviderImpl.cpp to the project, compile, run the test and …


It fails! It complains that the returned string does not contain “Helloâ€. The inspected string is “hello world†which does not comply to our requirements. So let’s correct that and run again: It fails again! A closer look at the MbUnit message reveals the problem:

String “Hello†does not contain “hello worldâ€

The assert must be vice versa. Obviously this is a code comment bug in MbUnit:


So let’s correct the order:
Assert::Contains(gcnew String(response),"Hello";
…and the test is GREEN:


Setting up for debugging

To debug into the test code simply set up the GUI runner as startup project with the following options:


Now you can start the runner by pressing F5…

Finally some useful links

Executing MbUnit GUI and Console from Visual Studio

Unit Testing with MBUnit (An Introduction) typeof Goes to T::typeid for use of [ExpectedException = ArgumentException::typeid] attribute

ps.: sorry for the poor code formatting. I was using first time Code Snippet plugin for Windows Live Writer.

Wednesday, June 24, 2009

Next books to read: Working Effectively with Legacy Code

One of the next books I will be reading is image Working Effectively with Legacy Code by Michael C. Feathers. First I've seen it on the desk of my colleague and friend Thomas. Then I read about it in great book Clean Code.  Recently I listened to a podcast on Hanselminutes. Now I decided as soon I finished the current book stack I will turn into this one.

LINQ to XSD for typed XML programming

image I have been looking at LINQ to XSD since alpha 0.2 came out. Before that I was using Liquid Technologies for xml data binding with great success. When LINQ was released LINQ to XSD looked very interesting because of the tight integration into VS and well the LINQ support. I was not brave enough to put it into production code though this version worked fairly well.

Now the project is hosted on CodePlex and comes to live again.

Monday, June 22, 2009

Tools I need to do my job: Sandcastle

image As a Clean Code Developer I'm using StyleCop to make my code look like other professional developers code (which I hope is a good thing). StyleCop pushes you to comment your code (at least the option to check for public API documentation makes a lot of sense - for the privates you might argue). For getting the full benefit of source code documentation I'm using Sandcastle to build my reference files. Sandcastle Help File Builder is a neat UI tool that eases the use of Sandcastle.

Rating: Very useful!

Web Resources: Production Debugging for .NET Framework Applications

A good introduction to .NET debugging in production environments is publicly available on msdn here:

Production Debugging for .NET Framework Applications

Books on my desk: Debugging Microsoft .NET 2.0 Applications

image A great resource not only for debugging .NET but also about preventing the need for debugging in the first place. Writing posts for my windbg blog I regularly used this resource.

Rating: Very good!

Books on my desk: Beyond the C++ Standard Library - An Introduction to Boost

Today C++ is still a major player in the software industry and you are well advices to have at leastimage some basic understanding of it. Boost comprises a big resource of utilities to better get along with this long time evolved language. This book gives a quick introduction to some of the libraries boost provides. It's not a reference but a good starting point.

You can pick a chm version of this book here...

Rating: Useful!

Wednesday, June 17, 2009

Interesting picks: Enterprise Integration Patterns

image Listening to the SoftwareArchitekTOUR podcast I always need to lookup the mentioned patterns because understanding pattern of spoken words is not one of the easiest things (understanding patterns in general is not something I do with my brain stem). Googling for the pattern names I found the Enterprise Integration Patterns site mantained by Gregor Hohpe.

Rating: Great!

Tuesday, June 16, 2009

Components I use: NConsoler

Need an equivalent to boost program_options in c#?
Here you go; NConsoler provides an AOP approach on command line parsing.

Code looks like this:

using System;
using NConsoler;

public class Program {
    public static void Main(params string[] args) {
        Consolery.Run(typeof(Program), args);

    public static void Method(
        [Required] string name,
        [Optional(true)] bool flag) {
        Console.WriteLine("name: {0}, flag: {1}", name, flag);

Rating: Great!

Thursday, June 11, 2009

Books on my desk: Framework Design Guidelines

imageThis book is not the kind of book you start reading and you just cannot stop. It is a reference book I regularly take at hand when I'm I'm in doubt on how to do something like what kind of exception should I catch or throw. Additionally it is a good idea to watch Krzysztof Cwalinas and Brad Adams blogs because they publish updates to new and changed rules there.

Rating: Must be available!

Wednesday, June 10, 2009

Books on my desk: .NET 2.0 Interoperability Recipes by Bruce Bukovics

One book I more often touch than I would like to is ".NET 2.0 Interoperability Recipes by Bruce Bukovics". Every time imagewhen I need to interface old code with new code (or vice versa) I find myself grabbing this book. The book does what the cover promises: it provides short recipes on how to tackle common Interop scenarios.

Rating: Very useful

Tuesday, June 9, 2009

Tools I need to do my job: Clonezilla

imageFor testing software a good approach is to use virtualization with tools like VMWare. Sometimes you find yourself in the situation to test on real hardware especially when you rely on concrete non virtual hardware. In those cases Clonezilla helps to get a clean system snapshot which can be restored at any time.

ReSharper Short Cuts

In my "Tools I need to do my job..." series I already mentioned ReSharper here.
To gain the full productivity power of this tool it's good to know the keyboard shortcuts. I have a printout of this pdf always on my desk:


Monday, June 8, 2009

Tools I need to do my job: ... Commander

I've always been a big fan of two file window managers since the my early computer days. Starting with Midnight Commander on unix systems I switched to (windows) Total Commander and and used this one for many years. Even on my Ubuntu I'm using at home I'm using more ore less only this type of file manager (Krusader). Now writing this post I thought of looking for an alternative to this and found two things:

1.) A site that lists alternatives to something:

2.) A free alternative to Total Commander: FreeCommander (found via here...)


At first look I was missing nothing. Maybe I will update this post once I found something that would make me change back to Total Commander.

Friday, May 29, 2009

Tools I need to do my job: Link Shell Extension

Heard of Hardlinks , Junctions , Volume Mountpoints? Powerful as they are, here's a helper to create and mange those: Link Shell Extension

Rating: Very useful!

Tools I need to do my job: PureText

PureText from Steve Miller is a little helper I use almost every day. It does simply one thing: If you have formatted text in the clipboard it will remove the formatting to pure text.

Rating: Hard to live without!

Tools I need to do my job: Console2

Console2 Console2 is a little nice helper that can host multiple command shells as tabs getting rid of many shell windows in the task bar.

Rating: Useful!

Thursday, May 28, 2009

Tools I need to do my job: Debugging Tools for Windows

windbg It is no secret that I'm a big fan of WinDbg. I try to use the Visual Studio Debugger if possible but when it comes to hard core debugging, there is no way around this tool.

Rating: Cannot do without!

Tools I need to do my job: AQTime

Profiling is important when it comes to the CCD rule "Don't optimize" which means you should not optimize code without proving that it really represents a bottle neck.AQTime I do not have very dedicated opinion on Profilers, but I can say so much that I personally found the profiler that comes with Visual Studio 2008 not very convincing. The best one I personally worked with is AQTime.

Rating: Strongly recommended.

Tools I need to do my job: XML Spy

xmlspy When you are a power user of xml family techniques I really recommend using XML Spy from Altova. I've been trying lots of xml editing tools but none of them convinced me that much.

Rating: (Very) hard to do without!

Tools I need to do my job: UltraEdit

ultraedit Does your Visual Studio starts quickly by clicking onto a source code file? Mine does not! So there is the need for an independent light footprint text editor that does a bit more that notepad. I tried some editors but none of them convinced me from moving away from from UltraEdit.

Rating: Hard to do without!

Tuesday, May 19, 2009

Tools I need to do my job: ManicTime

A new tool I just recently added to my toolbox is ManicTime. image I was searching for something like a stop watch application where I could measure the time I'm spending for a specific task in order to get a better planning basis for SCRUM sprint planning. What I found with this tool is a time tagging application. It automatically detects idle times and lists on a time line which applications you are using. So you can easily rebuild time for tasks retrospectively because most of the time you will forget to switch stop watches in the common time keeping approach.

Rating: Really helpful for time keeping

Tools I need to do my job: VMWare

No need to stress the importance of Virtualization. There are several solutions outsite. I feel VMWare is most professional and I use the workstation in software development for system integration testing and various other tasks. (At home I'm running XP on VirtualBox in a Ubuntu Linux host and it does the job also pretty well.)

Monday, May 18, 2009

Tools I need to do my job: Visual Studio and Friends

Actually I don't know many other IDEs besides Visual Studio (have worked with Borland, VB6, Eclipse and MonoDevelop - a bit ). Visual Studio (2008) gives me together with some Add-ons a tooling that enables me providing solutions for my customers. Here's the list of Extensions I'm currently using:

ReSharper - Very, very hard to do without!
StyleCop for ReSharper - Cannot do without if you are a Clean Code Developer!
PowerToys for the Class Designer - Very nice!
GhostDoc - Hard to do without!

Tool I need to do my job: Live Writer

LiveWriter This is the first post in a series where I will discuss tools I regularly use to do my job. The first one to mention is:

Live Writer which I'm just now using to write this post. Nothing really needed for software development but to maintain my brain extension (this blog).

Rating: Can hardly do without.

Starting a new Blog

This is the first post in a new Blog series about software development. So I should carefully consider what to write and what not. Honestly I'm not a poet and I will never be. I'm a a software developer with passion and with a hard link to technology. So what to start with? When I started my first Blog in voneinem-windbg in 2005 the first post was something like "Hello World...". Unfortunately I deleted this one because I considered it as silly and not serious. The main intention that time was to keep my lernings about windbg for me and as I stated 'possibly for others'. As I can register ~1000 reads/month others can now also benefit from my lernings. Over the time I found myself in the situation that I wanted blog about other things besides debugging so I'm now comming up with this blog. This time I will start again with the famous: Hello world!