Category Archives: Coding

Parsing source maps in .NET

When we minify JavaScript source, or write code in TypeScript or CoffeeScript and compile it down to JavaScript our debugging experience would be difficult without tools that support source maps.

I’m currently modifying Chutzpah to address a tiny gap in its handling of code coverage for generated source files like those output by the TypeScript compiler, and needed exactly that – a way for .NET code to parse a source map file, then query it to find out which original source line numbers map to a generated source line that’s been covered or not by a unit test.

SourceMapDotNet is my initial, bare-bones attempt at a partial port of the the excellent Mozilla source-map library, but intended only to handle that one type of query – not full parsing, definitely not generation.

It’s also up on NuGet.

SonarQube TypeScript plugin

I use SonarQube (live demo) a fair bit to monitor code quality metrics, but there’s no in-built support nor published community plugins for TypeScript analysis – so I’m writing one.

I intend two core features:

  • Measure code quality by running against TsLint
  • Measure unit test coverage by processing an LCOV file
Running an alpha version of SonarTsPlugin against a random TypeScript project from GitHub shows code issues but no code coverage - yet

Running an alpha version of SonarTsPlugin against a random TypeScript project from GitHub shows code issues but no code coverage – yet

The first of those two goals isn’t that far away at all – above is a screenshot from the alpha version running locally. If you’re interested in helping, drop me an email!

gh-ticker – a simple ticker for your public GitHub activity

With a spare weekend I put together the ticker widget you can see at the top of the screen just now – iterating through my most recent GitHub activity items every few seconds.

It is, fittingly, available on GitHub for forking and customisation licensed under the BSD 3-Clause.

How it works

The GitHub API is very straightforward, and data that’s already public (such as what appears on your Public Activity tab) can be accessed without authentication and with JSONP – ideal for client-side hackery.

The widget’s architected as a couple of JS files (taking a dependency on jQuery and Handlebars for now), one which contains Handlebars precompiled templates and the other that makes the API call and renders partials befitting the type of each activity item.

Setting it up’s pretty simple – reference the JS and CSS, make sure Handlebars and jQuery are in there too and then whack a DIV somewhere on your page with id ‘gh-ticker’.

<div id="gh-ticker" data-user="pablissimo" data-interval-ms="5000" />

The user whose data is pulled and the interval between ticker item flips are configurable as data attributes.

The GitHub Events API

The Events API knows about a set number of event types – for each event type, there’s a Handlebars partial. When we’re wondering how to render an item we look up the relevant partial and whack it into the page.

Since that’s a fair few partials (neat for development in isolation, bad for request count overhead) those partials are precompiled using the Handlebars CLI and put into a single gh-templates.js file.

Improvements

The ticker’s very basic – it just hides or shows the items as required, without any pretty transitions. It also takes a dependency on jQuery which it needn’t, since it’s only using it for the AJAX call and element manipulation both of which are easily covered off by existing browser functionality.

Still – it can be easily styled to be fairly unobtrusive and has at least taught me a little about Handlebars.

NRConfig 1.4.0.0 for New Relic released

I’ve spent a little time working on NRConfig, the tool that generates custom instrumentation files for .NET projects using New Relic, after a bug report that pointed out that the tool was unable to run for an assembly for which dependencies weren’t available. This isn’t likely in production code as you’d likely need the dependencies available to run, but can happen when you want to do an offline run of instrumentation generation against a third-party library.

To this end, NRConfig’s been changed pretty substantially under the hood to support alternatives to .NET reflection for discovering instrumentable types, and Microsoft’s Common Compiler Infrastructure (or CCI) library drafted in as the default discovery provider.

CCI’s slower than reflection by quite a margin – it can now take several seconds to produce instrumentation configuration for large or complex assemblies, but I’m hoping to improve that if it becomes a problem.

Also introduced is support for MSBuild in a new NuGet package, NRConfig.MSBuild. This should make generating instrumentation files for your own code a lot less work – simply add the NRConfig.MSBuild package to any project containing code you want to instrument and mark up the assembly, types or methods with [Instrument] attributes to control the output. On build, a custom instrumentation file is generated in your output directory for you to deploy wherever.

Enabling CORS on your ASP.NET output-cached webservice? Don’t forget to change your varyByHeaders…

If you’re enabling CORS on your ASP.NET web service, you’ll be receiving an ‘Origin’ header and outputting an Access-Control-Allow-Origin header if you’re happy to receive the request. If you’re being strict about your access control policy, you’ll be returning the same origin you got rather than * so that the user agent knows to let the call continue.

This poses a bit of an obstacle when combined with ASP.NET Output Caching, as unless you either tell it to vary its output by all headers or explicitly call out the Origin header you may find that accessing your service from two URLs within your cache lifetime period will see one call succeed and the other fail.

The failing call is because the Access-Control-Allow-Origin header’s being sent from the cache, but for the broken site won’t match the Origin that was sent to it and since we’ve not configured output caching to vary by the Origin header it assumes the requests from the two different origins are the same and responds accordingly.So, we just need to tack in the Origin header into our cache configuration’s varyByHeader attribute (separated from other headers with a semicolon, if any others exist) and bingo! The two sites result in correct responses.

 

Hottest stands at the RMW Whisky Fringe 2012

While I’m not sure if I’m going to re-run the Whisky Fringe Tasting Tracker from last year, I saw heatmap.js for the first time the other day and thought it’d be fun to make a Mansfield Traquair heatmap showing dram-sampling by stand. Here’s the result:

Heatmap of drams sampled during the 2012 RMW Whisky Fringe

The 675 samplings recorded by www.wf2012.co.uk over the 2012 Whisky Fringe

Not bad for a first attempt. That’s 675 samplings tracked by stand – of course, some stands had appreciably more drams to sample than others but there were definite hotspots. Given that we have opinion data too, we can also plot the hotspots of most-liked drams:

Positive opinions recorded at each stand during the 2012 Whisky Fringe

Positive opinions recorded at each stand during the 2012 Whisky Fringe – broadly similar but with some interesting detail

If I do run it again this year it’d be great to get heatmap.js combined with the above floorplan image and Pusher for some real-time updates…

Fun with sometimes.rb – in .NET…

Sometimes.rb is a fun set of helpers that give you the ability to express a degree of fuzziness in your Ruby logic. A couple of examples from the docs:

15.percent_of_the_time do
  puts "Howdy, Don't forget to register!"  # be annoying, but only 15% of the time
end
(4..10).times do
  pick_nose  # between 4 and 10 boogers made, it's unpredictable!
end

Given ten minutes and a small Aberlour I thought I’d have a bash at emulating some of it in .NET just for fun:

“Object reference not set to an instance of an object” exception when deploying Azure project

Scenario:

  • Created a new cloud project into which I wanted to deploy an existing bit of code (a new staging service for an existing production system for testing)
  • Right-click Publish… and after a few seconds of thinking deploy fails with NullReferenceException (Object reference not set to an instance of an object exception) and reports of a fatal error but no other diagnostic information

Problem was that the existing service had an HTTPS endpoint defined using a certificate that I’d not uploaded to my brand-new staging service. Deleting the endpoint (or uploading the certificate) does the trick.

Instrument specific types using wildcards with nrconfig

I just pushed version 1.3.0.0 of the NRConfig.Tool NuGet package and the associated project site – the binary is also available as a direct download.

Only two changes:

  • A fix for nested types showing duplicate method signatures in the output XML file
  • Introduction of the /w flag for wildcard matching of type names to be included in the New Relic custom instrumentation file

The /w switch is pretty straightforward – specify one or more wildcard filter strings that identify types to be included in the output file. So, if we had a project using the Repository pattern we could instrument the public methods of all of our concrete repositories:

nrconfig /i MyAssy.dll /f methods+ /w *Repository

which would match any type whose full name ends with Repository. Or we could instrument types in a specific namespace:

nrconfig /i MyAssy.dll /f methods+ /w MyAssy.Utils.* MyAssy.Controller.*

or limit ourselves to specific types:

nrconfig /i MyAssy.dll /f methods+ /w MyAssy.Controller.HomeController

Determine element visibility in WatiN with jQuery

This Stack Overflow post by MrBlueSky describes how to determine element visibility in a WatiN test case. As a convenience, here’s that code refactored as an extension method on Browser:

public static class BrowserExtensions
{
    public static bool IsElementVisible(this Browser browser, Element element)
    {
        var command = string.Format("$('#{0}').is(':visible');", element.Id);
        return browser.Eval(command) == "true";
    }
}

Usage:

            using (var browser = new IE("http://example.com/login.aspx"))
            {
                var page = browser.Page<Login>();

                page.LoginButton.Click();

                Assert.IsTrue(browser.IsElementVisible(page.UsernameRequiredMessage));
                Assert.IsTrue(browser.IsElementVisible(page.PasswordRequiredMessage));
            }