Monday, 27 February 2012

Visual Studio external tool output

The Problem
Imagine the scene; you've created a class library with a test project. There's an internal method you need to test (yes, you are aware of SRP, you have considered it and you have made a conscious decision to use an internal method), but because you've decorated the assembly with the InternalsVisibleTo attribute:
everything builds and runs.

Then your pairing buddy suggests you sign your class library with a strong name. You consider this suggestion and agree it's a brilliant idea, so you do it. You sign both projects with the same key:
You build the project and:
At this point you know you have to extract the public key from your executable and add it to the constructor of the attribute. You know the public key is over 300 characters and you're unlikely to be able to guess it. You remember that it's sn.exe you need to run to do extract the key, but struggle to remember the parameters or even, if you're honest, the location of the exe.

The Solution
Use the External Tools facility within Visual Studio. This allows you to specify a command line to run, with optional parameters that can contain certain Visual Studio values such as the solution path, the project path or, more interestingly for us, the path to the compiled executable for the project.
Under the Tools menu, click on External Tools... This opens a dialog that allows you to specify your external tool:
From the top, the inputs are:

  • Title. What's displayed in the Tools menu. Note the & character before the P; this is a throwback to the early 90s when you navigated Windows 3.1 with a keyboard. It allocates a hotkey to the menu item when you press the Alt key
  • Command. The path and file name of the executable (sn.exe in this example).
  • Arguments. The command line arguments to pass to the command.
  • Initial Directory. The directory to run the executable in.
  • Use Output Window. The "wow factor" point of this post. This redirects the output to the Visual Studio output window, so the public key can be easily copied and pasted into the attribute's constructor.
When this external tool is run, assuming you have the correct project selected, now produces this in the VS output window:

A job for another day is to write a simple app to wrap sn.exe and copy the public key above, minus its spaces, into the clipboard to make life even easier. Keep an eye on GitHub for some code, possibly coming soon.

Further command line arguments are listed here.

No comments:

Post a Comment