Microsoft.Office.Word.Interop.dll or don’t look here if you are lucky and have more interesting things to do


, ,

I spent a day with Microsoft.Office.Word.Interop.dll and… surprisingly it hurt less than I expected. API is strange but does the job and it somehow improved over the years. I needed to support Word templates with following functionality:

  • repeatedly filling the same field e.g., CompanyName could occur multiple times (unfortunately fields/bookmarks in Word’s template must have a unique names)
  • adding rows to the existing table
  • checkboxes (easy)
  • export to PDF (again easy – Word 2007+ supports it OOTB)

Not exactly rocket science but could be a time saver:

Testing and Refactoring Legacy Code


, , ,

Today at work I did a shameless remake of “Testing and Refactoring Legacy Code” kata by Sandro Mancuso. I’ve seen it recently at GeeCON and immediately wanted to steal a little bit from his fame share this experience with my coworkers. IMHO author did a very good job preparing example code which gives great opportunity for presenting variety of testing and refactoring techniques. Most importantly it’s presented in a manner interesting for both complete beginners and intermediate practitioners.

Original presentation took only 1h. I used over 3h split in 2 parts (interrupted by moving the team from one floor to another :)). Why so long? We are mostly .NET shop, so I ported it from Java to C# and used equivalent .NET tools/libraries. But no, no, it’s not a reason :). There was a lot of discussion – which is GREAT – it means I didn’t bore them too much! Also, I expanded subject matter by talking extensively on Inversion of Control pattern – completely unrelated to this:


It was also a good occasion for lobbying Resharper and NCrunch :).

Sources and notes for the presentation are on my GitHub account:

Here are some photos from the event, taken by Michał Wiktor Żmijewski:





EDIT 2013/06/07: Sandro pointed me that there is already C# version (and C++, PHP and Python too) of this kata:

But beware – there is no solution 😉

Chutzpah to run JavaScript tests


, , , ,

The time has come to retire NQUnit. NQUnit runs QUnit tests inside .NET by using WatiN. That means it can be used with any test runner supporting NUnit (e.g. TestDriven.NET or – since VS2012 – built-in + adapter). If you use CI server to run NUnit you got JavaScript tests nicely integrated for free (well, almost).

Unfortunately, there are some flaws:

  • tests are run in the full browser – which is slow
  • the only available browser option is Internet Explorer (on our CI server it can’t be upgraded beyond v8)
  • the are some privileges problems described in one of my previous posts
  • it requires some boilerplate C# code, which – of course – need to be compiled
  • tests can’t be run selectively
  • doesn’t play nice with continuous testing tools like NCrunch
  • supports only QUnit and only tests wrapped with HTML (forget about bare JavaScript tests or other frameworks e.g. Jasmine or Mocha)

NuGet Gallery showed me several candidates of whom I’ve chosen Chutzpah and so far I’m not disappointed. Chutzpah supports both the QUnit and Jasmine. Uses the PhantomJS headless browser to run tests. Not only JavaScript but also TypeScript and CoffeeScript are supported.

Chutzpah consists of 3 components:


  1. How to execute HTML wrapped QUnit tests:

    > chutzpah.console.exe /testMode Html /file AwesomeWidgetTest.html

  2. How to run all tests in a folder:

    > chutzpah.console.exe /testMode Html /path .\Facts\JS\

Parameter testMode is optional. Other values are: All (default), Html, AllExceptHTML, TypeScript, CoffeeScript, JavaScript. For more info see docs.

CI server support

Chutzpah support TeamCity OOTB. For other servers there is /junit switch that output results to JUnit-style XML file. I’ve used it for our CruiseControl.NET server. My MSBuild target looks as follows:

<Target Name="RunJavaScriptTests">
  <CreateItem Include="**\QUnit\*Test.html;**\Jasmine\*Test.js">
    <Output ItemName="JsTests" TaskParameter="Include" />
  <Exec Command="&quot;$(ChutzpahPath)&quot; /file &quot;%(JsTests.FullPath)&quot; /junit &quot;$(NUnitLogsDir)\%(JsTests.FileName)-test-results.xml&quot;" />

PS Today’s Chutzpah 2.4 release brings code coverage (via BlanketJS) and contains my tiny patch for unicode support :).

XSLT 1.0 to split CamelCase into words



What is the best practice for unit-test names? CamelCase or underscore or mixed or…? Good question. But you can side step it somehow. Here is the code I use for transforming unit-test names as displayed in CI server reports e.g. OrdersWithNoProductsShouldFail -> orders with no products should fail:

<xsl:template name="SplitCamelCase">
  <xsl:param name="text" />
  <xsl:param name="digitsMode" select="0" />
  <xsl:variable name="upper">ABCDEFGHIJKLMNOPQRSTUVWXYZ</xsl:variable>
  <xsl:variable name="lower">abcdefghijklmnopqrstuvwxyz</xsl:variable>
  <xsl:variable name="digits">0123456789</xsl:variable>

  <xsl:if test="$text != ''">
    <xsl:variable name="letter" select="substring($text, 1, 1)" />
      <xsl:when test="contains($upper, $letter)">
        <xsl:text> </xsl:text>
        <xsl:value-of select="translate($letter, $upper, $lower)" />
      <xsl:when test="contains($digits, $letter)">
          <xsl:when test="$digitsMode != 1">
            <xsl:text> </xsl:text>
        <xsl:value-of select="$letter" />
        <xsl:value-of select="$letter"/>
    <xsl:call-template name="SplitCamelCase">
      <xsl:with-param name="text" select="substring-after($text, $letter)" />
      <xsl:with-param name="digitsMode" select="contains($digits, $letter)" />

Tips for running VisualStudio 2010 + Resharper 7 on 32-bit Windows


, ,


On 32-bit operating systems Visual Studio can easily run out of memory (especially with memory hungry plugins like R# or NCrunch). But there are ways to reduce this problem.

Why oh why?

All desktop versions of Windows suffer from 3 GB barrier (see more here). It prevents the operating systems from using more than about 3 GB of RAM. But 3 GB is a lot and should be enough for VS et consortes, right? It appears not. I have decent machine with SSD, but running VS+R# with non trivial solutions _is_ constant pain. VS crashes throwing OutOfMemory exceptions or just stops responding for a few seconds (very annoying) all the time. 

If – for whatever reason – you cannot upgrade to 64-bit Windows try following tips:

Make Visual Studio large address aware

Well, 3 GB limit is not enough because it’s not reached. YES, there is another limit of 2 GB address space, but luckily it can be easily lifted:

editbin /LARGEADDRESSAWARE devenv.exe

Use JetBrains patch for Visual Studio to lessen address space fragmentation

Another problem is address space fragmentation. Default Visual Studio memory allocation is very… generous. But you can override its behavior with this patch:

Results after 1 month

No more crashes or mysterious slowdowns! Now I can fully appreciate “alt-enter driven development” with R#. Hurray!


Refactoring is like eating a proper diet



From Refactoring: Improving the Design of Existing Code:

In many ways, refactoring is like exercise and eating a proper diet. Many of us know that we ought to exercise more and eat a more balanced diet. Some of us live in cultures that highly encourage these habits. Some of us can get by for a while without practicing these good habits, even without visible effects. We can always make excuses, but we are only fooling ourselves if we continue to ignore good behavior.

Blanket.js, QUnit and IE8 (Please Die Now)


, , ,

QUnit tests with code coverage

Besides the funny name Blanket.js delivers what it promises: seamless code coverage. Adding it to an existing QUnit test suit is very easy and I’m not going to repeat after their website. But I had two special requirements which complicates matters:

  • My test suits must work on IE8 (that sucks, I know)
  • and run in browser both locally (using the file:// protocol) and remotely.

During development I use Chrome and IE9 (tests are run against IE8 automatically on build server) so the first point boils down to disabling Blanket.js completely for IE8:

The second one is tricky. There are some options to run Blanket.js locally in browser but they are… not so seamless or just insecure (disabling CORS restrictions altogether). Again, the simplest solution is to disable code coverage in that situation. Blanket.js integrates with new versions of QUnit and adds Enable coverage checkbox which is off by default. But I have to use an older version (v1.4.0 – forced by IE8 !#@!!) and then code coverage is always enabled. This little gist solves that problem:

Not related to Blanket.js but I encountered one more gotcha with IE: security zones. Build server refused to run my tests until I forced Local Intranet Zone by adding this line to beginning of each HTML files:

This is an obscure IE feature called Mark of the Web (MOTW).

To sum up: all of this workarounds are caused by IE8. Internet Explorer, please die now!

For the record: How to run NuGet.exe on OS X Mountain Lion


, ,

I’ve just finished reading C# Smorgasbord (will write review another time) and I am ashamed to admit I didn’t play with IL generation before. So I started with simple examples from the book (get the source from Bitbucket) and was curious if they work on Mono. Actually not all of them… But besides that the whole experience with Mono on Mac was very smooth. Here are steps to install Mono, MonoDevelop and NuGet – all you need to run typical Visual Studio solution:

How to restore NuGet packages for solution:
# mono --runtime=v4.0.30319 NuGet.exe install ./packages.config -OutputDirectory ./packages

Screenshot of MonoDevelop running unit tests:


Go get free SSL Cert from and make Google happy


Recently, I got hit by change in Google policy regarding self-signed certificates (see their FAQ). For many years I’ve used self-signed SSL certificates for my company’s server (f**k giving money to the CA mafia ;)). As some of us prefer to use Gmail over crappy desktop clients, they used Gmail Mail Fetcher feature… until it stopped working.

But there is a great site with free Class 1 SSL certificates (see comparison). It’s dead easy to create one. They even check your configuration automatically afterwards. Not being an expert I screwed it up a little and got an email with warning: “It seems, that the installation of your server certificate […] is not complete! You should add the intermediate CA certificate to your installation”. They pointed me to their FAQ where I’ve found instructions how to configure Apache server. Then it was easy to do the same for mail server.

Fun with Castle.DynamicProxy – Part II


, ,

It’s time for another adventure with Castle.DynamicProxy. One of the few things I really like in C++ is RAII – for example you can write code like this:

class DatabaseContext
    virtual ~DatabaseContext()

    void ExecuteNonQuery(string query)
         // and execute query...

    // ...

// somewhere else
void DoSomething()
    DatabaseContext db;
    db.ExecuteNonQuery("DELETE * FROM tb_users");

ExecuteNonQuery opens connection to the database and DatabaseContext destructor takes care of closing it regardless if an exception occurred or not. Great! In C# you need more verbose using/IDisposable or try/finally and… you have a chance to forget about them.

But Castle.DynamicProxy comes to the rescue:

Initially this proxy was much simpler but I wanted to support also iterators. Methods returning IEnumerable are tricky. The compiler rewrites them to the state machine i.e. code:

IEnumerable<int> GetEnumerable()
    for (int i = 0; i < 10; i++)
        yield return i;

List<int> GetList()
    var iterator = GetEnumerable(); // for loop not reached yet!
    return iterator.ToList(); // iterator executed

Here yield return is only a promise: it will be executed later when the .ToList() is called. As a result proxying those methods is not enough in my situation. What I really need to emulate RAII is to catch the moment after execution of the iterator. But how to do that? Well, the compiler can handle using statements inside iterators:

IEnumerable<int> GetEnumerable()
    using (... something IDisposable ...)
        for (int i = 0; i < 10; i++)
            yield return i;

List<int> GetList()
    var iterator = GetEnumerable();
    return iterator.ToList(); // Dispose() called

That’s because it returns control to the iterator after leaving foreach loop (ToList method is actually a foreach loop). So the easiest way to do the same is to wrap GetEnumerable with another iterator i.e. effectively proxying resulting iterator object. That’s what I did.