Also available at

Also available at my website http://tosh.me/ and on Twitter @toshafanasiev

Tuesday, 10 June 2014

Loading "Vanilla" JavaScript files in Node

I'm writing more and more JavaScript these days and it's nice to have some sort of test infrastructure in place for all but the most trivial codebase.

If you're using a framework like AngularJS where modularity and dependency injection are first-class citizens then you're all set up. If, for whatever reason, you can't package things up in nice modules then testing can be tricky, particularly when there are dependencies involved.

I came up against this recently and my solution was to use Node.js and the excellent jasmine-node package
installing jasmine-node




I wrote a very simple Node module called include


Which lets me test simple JS files with no dependencies ...

maths.js
spec/maths.spec.js
... and more interestingly, those that rely on global objects such as window and document

ui.js
spec/ui.spec.js
So with a directory structure like this

directory structure

Tests can go from this ...
failing tests
... to this

Most of the code I write is more involved than this though :)

Tuesday, 4 February 2014

Managing CLR Assemblies in SQL Server

I've just employed a SQL Server CLR stored procedure in a project I'm working on (I was initially worried about performance, but having looked into it I've found that it can be quite good, provided you're mindful of marshalling boundaries etc.).

Having added a dedicated DLL project for SQL Server CLR artefacts (using .NET 2.0 as we target SQL Server 2005 in some instances) I extended our upgrade tool to generate and issue a CREATE/ALTER ASSEMBLY statement using a binary literal of this DLL. It was here I ran into one of Microsoft's weirder design decisions.

Running the following statement

ALTER ASSEMBLY SearchTools FROM 0xDEADBEEF...C001EE15

yields the following error if the new version of the assembly provided is identical to the existing one.

ALTER ASSEMBLY failed because the source assembly is, according to MVID, identical to an assembly that is already registered under the name "SearchTools".

This is a bit of a pain as an update that worked once will fail on all subsequent runs. Why would they choose to do this? You wouldn't expect a standard DML UPDATE statement to fail if the new row data matched the existing ones, would you?

Anyway, I considered dropping the assembly if it exists and then issuing a CREATE ASSEMBLY statement each time but then there's the problem of the UDFs and Stored Procedures that depend on the installed assembly - forcing the eventual owners of this project to manually manage all these CREATE/DROPs wouldn't be very friendly so I had to find another way.

In the end I found the built in ASSEMBLYPROPERTY(N'asm-name', 'property-name') function that returns metadata from an installed assembly. The 'MvID' property can be used to extract the stored module version identifier for comparison with the one provided by the candidate version of the assembly:


// using a previously created SqlCommand
cmd.CommandText = "SELECT ASSEMBLYPROPERTY(N'SearchTools', 'MvID')";

var currentId = (Guid)cmd.ExecuteScalar();
var moduleId = typeof(SearchProcs).Assembly.ManifestModule.ModuleVersionId;

if (moduleId != currentId)
{
  log.WriteLine("Updating assembly ...");
  var raw = File.ReadAllBytes(typeof(SearchProcs).Assembly.Location);
  var hex = String.Join("", raw.Select(b => b.ToString("x2")).ToArray());
  cmd.CommandText = String.Format("ALTER ASSEMBLY SearchTools FROM 0x{0}", hex);
  cmd.ExecuteNonQuery();
}
else
{
  log.WriteLine("Assembly already up to date");
}

As a bonus the ASSEMBLYPROPERTY function will return NULL for the MvID property if the assembly named does not exist - this allows for CREATE/ALTER selection.

Cool.

Wednesday, 22 January 2014

SQL Debugging Gotcha

While trying to debug a table trigger (shudder) in SQL Server Management Studio I encountered the following error message:

Unable to start T-SQL Debugging. Could not connect to computer '.'. This is usually a temporary error during hostname resolution and means that the local server did not receive a response from an authoritative server.

It's actually as simple as the fact that you used '.' to mean 'this machine'. Using your actual machine name, or even 'localhost' will have the same effect as the dot but will also let the debugger connect to the server instance.

This wasn't obvious from the error message and hopefully this will help someone else.

Wednesday, 18 December 2013

I wanted to confirm the ordering of the invocation list of a multicast delegate created by concatenating two delegates so I put this quick test together. The results were reassuringly unsurprising:

using System;

static class prog
{
  static void Main()
  {
    Action a = () => { Console.Write("a"); };
    Action b = () => { Console.Write("b"); };

    // prints 'ab'
    ((Action)Delegate.Combine(a, b))();

    Console.WriteLine();

    // prints 'ba'
    ((Action)Delegate.Combine(b, a))();
  }
}

Thursday, 21 November 2013

C++ friends for C#

A mate of mine asked me about C++ style 'friends' for C# and I thought I'd lay out the nearest approximation I could make to this C++ language feature in C#.

On the face of it it may look as though this sort of feature just makes it easy for you to violate encapsulation in your code but on closer inspection it's a perfectly valid way of compartmentalising different aspects of one logical unit of code into a set of related classes. To be honest though, I didn't really want to get into that here.

What I wanted to get across is that you can achieve the same effect in C# as declaring a friend in C++, with the help of nested types and partial classes:

public partial class MasterCounter
{
  public int Count { get; private set; }

  public Counter CreateCounter()
  {
    return new Counter(this);
  }

  public partial class Counter { }
}

// and then in a separate file ...

partial class MasterCounter
{
  partial class Counter
  {
    private readonly MasterCounter master;

    public Counter(MasterCounter master)
    {
      this.master = master;
    }

    public void Click()
    {
      master.Counter += 1;     
    }
  }
}

Having to nest the 'friend' class and make both classes partial are not the greatest compromises and you don't even have to do the latter if both class definitions fit comfortably in the same file - arguably having access to the same private state makes them, logically, parts of the same class. If you squint a bit you sort of can't see the declaration of the enclosing class in the second file.

Anyway, not rocket science, but interesting all the same.


Sunday, 10 February 2013

417 when accessing Visual Studio Extensions Gallery

If, while working behind a proxy, you click Tools > Extensions and Updates ... in VS 2012 and then select 'Online' on the left hand side you may get a 417 Error - this is caused by the proxy server not handling the 100 Continue response properly, luckily you can configure Visual Studio to not try the header-only check and get around the problem.
  1. Find the VS config file (devenv.exe.config) - the simplest way is to use Task Manager (Open File Location on the process context menu)
  2. Locate the section that configures network settings:
      <settings>
        <ipv6 enabled="true">
      </settings>
    
  3. Add a line telling VS to skip the header-only check
      <settings>
        <ipv6 enabled="true">
        <serviceManager expect100Continue="false"/>
      </settings>
    
Then you should be up and running again

Wednesday, 15 August 2012

C++ ENSURE macro

C++ doesn't provide a finally clause for structured exception handling and it doesn't need to. The deterministic object destruction of C++ provides the perfect way to ensure that your cleanup code is executed - tying your resource management to an object's lifetime ensures that it will take place when the memory that object occupies is reclaimed; for local objects this corresponds to control hitting the end of the lexical scope in which the object is declared, whether that scope is left via normal flow or due to an exception.
There are numerous Scope Guard or Scope Exit constructs around, including one in the Boost library and the D Language's scope(exit) construct, that aim to tidy up this pattern, making it quicker to write and easier to read. My good friend Steve recently sent me his version of this idea - it was characteristically brilliant and I decided to have a go myself.
Using the example of a wrapper for FormatMessage (a Windows function which I personally can never remember how to call without consulting documention), we can see how RAII can be gainfully employed. The flags I'm passing in tell FormatMessage to allocate a buffer big enough for the data returned, that allocation is done using LocalAlloc and it's up to us to clean up by using LocalFree. Here's how you might go about this (console output added for illustration)

#include <tchar.h>
#include <string>

typedef std::basic_string<TCHAR> tstring;

namespace manual
{
  tstring MessageFromHR( HRESULT hr )
  {
    LPTSTR ptr = NULL;
    struct cleanup {
      LPTSTR& p;
      ~cleanup() {
        cout << "about to free pointer 0x" << hex << (int)p << endl;
        LocalFree( p );
        cout << "done" << endl;
      }
    } cu = { ptr };

    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
      , NULL
      , hr
      , MAKELANGID( LANG_NEUTRAL, SUBLANG_NEUTRAL )
      , (LPTSTR)&ptr
      , 0
      , NULL
      );

    return tstring( ptr );
  }
}

This approach is very wordy but it does nicely put the cleanup code right next to the declaration of the variable that represents the leak-prone resource. This lexical locality has a huge effect on readability and hence ultimately on reliability.
What can be done about the wordiness though? Any syntactic sweetener for this pattern will have to simplify usage, obviously, or what's the point? Well, thanks to some of the new features introduced with C++ 11 we can wrap the whole affair up nicely in a macro that's simple to write and clear when read. Let's build it up bit by bit.
The main thing we want to achieve is ease of use, and hence readability (and then onto reliability) - this means keeping the number of parameters to a minimum. So what is the minimum? Arbitrary cleanup code could involve an arbitrary number of parameters and so to avoid hand-cranking each and every reference we'd employ a lambda, closing around any variables we need. This neatly brings the maximum number of parameters to our macro down to one - the body of that lambda.
We have no way of knowing, up front, what the type of such a construct will be called, and so we turn to the tools of type inference, auto and decltype. These keywords allow us to declare a variable of fixed but unknown type and, crucially, refer to that type later on

#include <tchar.h>
#include <string>

typedef std::basic_string<TCHAR> tstring;

namespace lambda
{
  tstring MessageFromHR( HRESULT hr )
  {
    LPTSTR ptr = NULL;
    auto __l = [&]() {
      cout << "about to free pointer 0x" << hex << (int)ptr << endl;
      LocalFree( ptr );
      cout << "done" << endl;
    };
    struct cleanup {
      decltype( __l )& l;
      ~cleanup() { l(); }
    } __i = { __l };

    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
      , NULL
      , hr
      , MAKELANGID( LANG_NEUTRAL, SUBLANG_NEUTRAL )
      , (LPTSTR)&ptr
      , 0
      , NULL
      );

    return tstring( ptr );
  }
}

Turning it into a macro is pretty simple

#define SIMPLE_ENSURE( routine ) auto __l = [&]() { routine; };\
                                 struct __s {\
                                   decltype( __l )& l;\
                                   ~__s() { l(); }\
                                 } __i = { __l };

But we're not quite done here - given that we're defining named types and instances we'll be limited to one per lexical scope. We can fix this by using the __LINE__ macro to generate unique names. Note the ID macro and inner implementation ENSURE_ - this is necessary due to the way macro expansion works. Note also that the instance variable r in the struct is a reference to the lambda.

#define ID( base, unique ) base##unique
#define ENSURE_( routine, unique ) auto ID( r, unique ) = [&]() { routine; };\
                                    struct ID( e, unique ) {\
                                      decltype( ID( r, unique ) )& r;\
                                      ID( ~e, unique )() { r(); }\
                                    } ID( ei, unique ) = { ID( r, unique ) };
#define ENSURE( routine ) ENSURE_( routine, __LINE__ )

Here's the FormatMessage wrapper again, this time using the ENSURE macro

#include <tchar.h>
#include <string>

typedef std::basic_string<TCHAR> tstring;

namespace macro
{
  tstring MessageFromHR( HRESULT hr )
  {
    LPTSTR ptr = NULL;
    ENSURE(
      cout << "about to free pointer 0x" << hex << (int)ptr << endl;
      LocalFree( ptr );
      cout << "done" << endl;
    )

    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
      , NULL
      , hr
      , MAKELANGID( LANG_NEUTRAL, SUBLANG_NEUTRAL )
      , (LPTSTR)&ptr
      , 0
      , NULL
      );

    return tstring( ptr );
  }
}

All these examples yield the same output (pointers may vary, but notice it's no longer NULL by the time it's freed - that's because the lambda captures by reference)

about to free pointer 0x4888e0
done

And all return the correct message

No such interface supported

And here's an example of multiple instances in the same scope

int main( int argc, const char* argv[] )
{
  try
  {
    cout << "one" << endl;
    ENSURE( cout << "four" << endl )
    ENSURE( cout << "three" << endl )
    cout << "two" << endl;
    throw std::exception();
  }
  catch ( const std::exception& e )
  {
    cout << "five" << endl;
  }
}

This illustrates how the execution of ENSURE blocks is deferred until the end of the current scope and also the fact that they run in reverse order, as per normal object destruction. And here's what the preprocessor chucks out (line breaks added)

int main( int argc, const char* argv[] )
{
  try
  {
    cout << "one" << endl;
    auto r141 = [&]() { cout << "four" << endl; }; struct e141
    { decltype( r141 )& r; ~e141() { r(); } } ei141 = { r141 };
    auto r142 = [&]() { cout << "three" << endl; }; struct e142
    { decltype( r142 )& r; ~e142() { r(); } } ei142 = { r142 };
    cout << "two" << endl;
    throw std::exception();
  }
  catch ( const std::exception& e )
  {
    cout << "five" << endl;
  }
}

Of course in production code you wouldn't have all the console output and it would look like this

#include <tchar.h>
#include <string>

typedef std::basic_string<TCHAR> tstring;

namespace production
{
  tstring MessageFromHR( HRESULT hr )
  {
    LPTSTR ptr = NULL;
    ENSURE( LocalFree( ptr ) )

    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
      , NULL
      , hr
      , MAKELANGID( LANG_NEUTRAL, SUBLANG_NEUTRAL )
      , (LPTSTR)&ptr
      , 0
      , NULL
      );

    return tstring( ptr );
  }
}

I should mention that this sort of in-line cleanup code is not always appropriate - sometimes what you need is a proper class, defined in its own file, that wraps up a resource and manages its life time. This gives you testability and separation of concerns. However, as with all things, it's a trade off and I feel that the lexical locality wins out in the case of that one little call to LocalFree.