Thursday, 13 May 2010

Converting MP3 to WAV with NAudio

One of the more common support requests with NAudio is how to convert MP3 files to WAV. Here’s a simple function that will do just that:

public static void Mp3ToWav(string mp3File, string outputFile)
{
    using (Mp3FileReader reader = new Mp3FileReader(mp3File))
    {
        using (WaveStream pcmStream = WaveFormatConversionStream.CreatePcmStream(reader))
        {
            WaveFileWriter.CreateWaveFile(outputFile, pcmStream);
        }
    }
}

… and that’s all there is to it.

Notes:

  1. There is no need to wrap pcmStream with a BlockAlignReductionStream since we are not repositioning the MP3 file, just reading it from start to finish.
  2. It uses the ACM MP3 decoder that comes with Windows to decompress the MP3 data.
  3. To be able to pass the MP3 data to the ACM converter we need to do some parsing of the MP3 file itself (specifically the MP3 frames and ID3 tags). Unfortunately, there are some MP3 files that NAudio cannot parse (notably the sample ones that come with Windows 7). My attempts at tracking down the cause of this problem have so far failed. (the basic issue is that after reading the ID3v2 tag, we don’t end up in the right place in the MP3 file to read a valid MP3Frame – see MP3FileReader.cs). Please let me know if you think you have a solution to this.

Wednesday, 12 May 2010

LINQ to General Election Part 2 – LINQ to XLS

In my previous post, I demonstrated how to run LINQ queries against the UK general election data the Guardian newspaper in JSON format. They additionally made a Google spreadsheet available which not only has the winners in every constituency but the number of votes for each candidate that stood.

Now it might be possible to run LINQ queries directly against the Google spreadsheet using the Google Data APIs (perhaps an experiment for another day), but I chose instead to download the spreadsheet as a Microsoft Excel spreadsheet and run my LINQ queries against that instead.

First of all, I needed a LINQ to Excel provider and found linqtoexcel. Unfortunately, it requires you to reference several DLLs, but once you have done so, it is pretty straightforward to use.

Mapping the Spreadsheet

One nice feature of linqtoexcel is that it makes it easy to map your spreadsheet data onto a strongly typed class. By default it will simply look for properties matching the column names. Here’s my election result class:

public class Result
{
    public string Seat { get; set; }
    public string Candidate { get; set; }
    public string Party { get; set; }
    public int Vote { get; set; }
    public double VotePercent { get; set; }
    public string Winner { get; set; }
}

Now I can open the XLS file using the ExcelQueryFactory class and I also need to add a custom mapping since the title of the VotePercent column is not a valid C# identifier. Note that you don’t have to map all the fields. I have just picked out the six that I needed for my queries.

var repo = new ExcelQueryFactory();
repo.FileName = @"..\..\..\Data\General election 2010 results.xls";
repo.AddMapping<Result>(x => x.VotePercent, "%Vote");
Querying the Data

Having done this, we are now in a position to perform any queries. We can specify the worksheet name from which our data comes (in this case “FULL CONSTITUENCY DATA”). Having the use of strongly typed classes makes the LINQ much more readable than in the JSON example.

var unluckyLosers = from p in repo.Worksheet<Result>("FULL CONSTITUENCY DATA")
                       where (p.Party != p.Winner) && (p.VotePercent > 42)
                       orderby p.VotePercent ascending
                       select p;
Console.WriteLine("Unlucky Losers:");
foreach (var winner in unluckyLosers)
{
    Console.WriteLine(String.Format("{2}%: {0} ({1})", winner.Candidate, winner.Party, winner.VotePercent));
}

Unfortunately, there seems to be a bug in that the orderby clause seems to be ignored. I tried a few different sort fields but with no success. The output from the above query is as follows:

Unlucky Losers:
44.52%: King, Nick (C)
45.51%: Connor, Rodney (Ind)
43.79%: Kelley, Claire (LD)
42.11%: Dismore, Andrew (Lab)
42.01%: Harris, Evan (LD)
42.81%: Kramer, Susan (LD)
42.55%: Throup, Maggie (C)
44.51%: Rees-Mogg, Annunziata (C)
42.36%: Stroud, Philippa (C)
42.2%: Formosa, Mark (C)
42.53%: Heathcoat-Amory, David (C)
43.08%: Tod, Martin (LD)

Patently, they have not been sorted in the requested order. I have filed a bug against linqtoexcel. Hopefully it can be resolved soon. Update: A fix was released shortly after my bug report - linqtoexcel 1.3.70 works fine.

Tuesday, 11 May 2010

LINQ to General Election Part 1 – LINQ to JSON

I discovered this week that the Guardian newspaper is making the UK General Election results available in JSON format. Their politics API gives access to all kinds of results, party and candidate information.

What I wanted to do was to be able to quickly and easily perform some of my own queries on the election results. Having not worked with JSON, I needed something that could parse it and allow me to run LINQ queries on it. My search led me to Json.NET, which is a very easy to use library that allows you to parse JSON into an object that you can run LINQ queries against.

Visualising JSON

When working with JSON, you need to have some kind of tool that will let you explore the structure of the JSON data. I found a handy utility called JsonViewer that parses it into a tree format. Alternatively, you can use this online JSON formatter.

Parsing JSON

The first step is to download the JSON and parse it into a JObject:

string url = "http://www.guardian.co.uk/politics/api/general-election/2010/results/json";
WebClient wc = new WebClient();
string json = wc.DownloadString(url); 
JObject o = JObject.Parse(json);

LINQ Queries

Now it is straightfoward to write queries against the object. Notice that you can use Children() to select all the children under a specific node (useful for arrays).

var unpopularWinners = from winningMp in o["results"]["called-constituencies"].Children()["result"]["winning-mp"]
    where (decimal)winningMp["votes-as-percentage"] < (100 / 3M)
    orderby (decimal)winningMp["votes-as-percentage"] ascending
    select winningMp;

To get the values out of the instances of JToken returned, you have to remember to cast them to the appropriate type (e.g. int, string, decimal):

Console.WriteLine("Unpopular Winners:");
foreach (var winner in unpopularWinners)
{
    Console.WriteLine("{0:F1}% {1} ({2})", (decimal)winner["votes-as-percentage"], (string)winner["name"], (string)winner["party"]["name"]);
}

LINQ to JSON seems to support the full range of LINQ operations, including grouping:

var seatsPerParty = from winningMp in o["results"]["called-constituencies"].Children()["result"]["winning-mp"]
    group winningMp by (string)winningMp["party"]["name"] into g
    orderby g.Count() descending
    select new { Party = g.Key, Seats = g.Count(), TotalVotes = g.Sum(c => (int)c["votes-as-quantity"]) 
};

Unfortunately, the Guardian do not provide one JSON file that contains the votes for all candidates, although it looks like you can get that information if you follow another link for each one. However, they did make the full results available in a Google spreadsheet, so I plan to follow up shortly with another post on how to perform LINQ queries against Excel data.

Tuesday, 20 April 2010

Technical Debt Interest Rates

I’ve been thinking a lot about “technical debt” recently. The metaphor is a helpful one – every poor design decision, every compromise, every quick and dirty hack results in technical debt which must be repaid at some point in the future.

Or must it? The reality is that some technical debt, possibly quite a large percentage of it, never actually incurs substantial repayments. This is quite different from real-world financial debt, which must always eventually be paid in full.

Consider the following example. You rush to get feature X out the door. A customer is paying big money for it, and you end up making all sorts of compromises to get it done in time. The code is a mess, a maintenance nightmare. You dread the day when you have to revisit it to make a tweak or add another feature. But that day never comes. For whatever reason, no support cases come in, no enhancements are requested. Maybe the customer never used it at all. What has happened is that you have effectively been let off your debt. Ironically, the decision to do it the “quick way” rather than the “right way” turned out to be a smart move.

At the opposite end of the spectrum there is that code change you rushed in to meet a relatively unimportant milestone. You knew at the time it wasn’t quite the best way, but it worked, and that’s all that really matters, right? The trouble comes when on top of that rather shaky foundation is built layer upon layer of new code, all inheriting its inherent weaknesses and design flaws. Maybe at first the interest rate on that debt is quite low – it doesn’t slow you down too much. But several years later, once it is far too late to go back on the original decision, you begin paying dearly for the technical debt you introduced.

The basic trouble is, when you introduce technical debt you typically have no idea what interest rate you are borrowing at. If you are lucky, its 0% – and your shortcut won’t cost you a penny. In fact, it could save the company time and money. In other cases it will be a modest 5-10%. Future development is slowed down a little by your past indiscretions, but not by much. But sometimes you take out a debt whose interest rate is astronomical (or more commonly, starts out small but grows rapidly). It is not uncommon for it to reach to levels above 500%. In other words, new development is taking five times longer than it ought to simply because of the mess that the codebase is in.

I think technical debt is inevitable. Developers, let alone management, simply do not have the foresight to see the full future implications of all their decisions. But the moment you detect that you are building heavily on top of code that contains technical debt, alarm bells should be ringing. Address it early or it will be too late.

Thursday, 25 March 2010

NAudio x64 Testing Needed

After a bit of a blogging break, I think it is time to give a brief status update. I have been trying to keep up with the constant stream of support requests coming in through the NAudio forums and comments on posts here but the reality is that there has been more than I can handle so please accept my apologies if your query has gone unanswered.

I do continue to make slow progress on NAudio. Today I checked in a changeset that should hopefully give us proper x64 support. My only trouble is that I do not have an x64 machine to test on (next PC I buy will be x64 but that may not be for another year). If anyone has a 64 bit OS and is willing to help me out with a quick test then please do the following:

  1. Download the latest NAudio source code and load it up in Visual Studio 2008
  2. Go to the NAudio project settings, and on the Build tab set the Platform target to Any CPU (it is currently set to “x86”)
  3. Run the NAudioDemo application and attempt to play an MP3 file
  4. Comment here letting me know how you got on

It would be great to be able to properly support x64 as currently you are forced to set your calling application to x86 only as well.

Tuesday, 17 November 2009

.NET Gotcha – Static Initialiser Ordering

Last week I had to troubleshoot a strange problem. A developer had broken up the source code for a large class of constants (defining various colours) into separate files using the partial keyword, and all of a sudden our Windows Forms controls were painting themselves black instead of the correct colour. Put them back into one file again and the problem went away.

Eventually we tracked the problem down due to the order in which the fields were being initialised by the static constructor. Consider the following code and unit test (which passes):

static class MyConstants
{
    public static readonly int MyNumber = 5;
    public static readonly int MyOtherNumber = MyNumber;
}

[TestFixture]
public class MyConstantsTests
{
    [Test]
    public void ConstantsAreInitialisedCorrectly()
    {
        Assert.AreEqual(5, MyConstants.MyNumber);
        Assert.AreEqual(5, MyConstants.MyOtherNumber);
    }
}

Now if we simply change the ordering of the statements in MyConstants…

static class MyConstants
{
    public static readonly int MyOtherNumber = MyNumber;
    public static readonly int MyNumber = 5;
}

… the test will fail as MyOtherNumber will be 0. Obviously if the two definitions exist in different source files, this type of problem is much harder to spot. The test does pass if we use the const keyword instead of static readonly, but since we were initialising using the Color.FromArgb function, this was not an option for us.

The moral of the story is to avoid setting static read-only fields to values dependent on other fields. Or at least be aware of the problems that can arise from doing so.

Friday, 23 October 2009

The “Unlegacy my Code” Kata

Daily TDD Kata

I’ve read a number of blog posts recommending doing a daily TDD ‘kata’ recently. For those unfamiliar with the concept, essentially you attempt to solve a simple programming task using TDD. The problems are often simple mathematical challenges, such as finding the prime factors of a number, or creating a calculator.

You limit yourself to 30 minutes to work on the problem. One of the goals of doing this is to speed up the way you work. For this reason, many people recommend doing the same kata many times, just like a musician would practice the same piece daily, gradually improving in speed, fluency and accuracy.

Benefits

There are several benefits to taking the time each day for a coding warm-up.

  • Learning the TDD way of working: red, green, refactor
  • Learning a unit testing or mocking framework
  • Stretching your brain to see if you can come up with an even more elegant solution than last time
  • Mouseless programming (learning to use keyboard shortcuts)
  • Solving a familiar problem in a new language
  • Learning how to apply a design pattern
A Possible Weakness?

While I think these benefits are great, I do think most of the kata examples I have seen suffer from a weakness. And that is that you are always testing something that is inherently easy to test. After all, what could be easier to write unit tests for than an Add method? This can mean that when you transition to attempting to write tests for your “real” code, you can fall at the first hurdle, as the “arrange” part of your test is horribly complicated, and you have no idea what to do for the “assert” part.

Introducing the “Unlegacy my code” Kata

Legacy code has been described as “code without tests”. Which means that unless your your development team is comprised of TDD champions, you likely have a lot of “legacy code”. Recently I decided I would try my own variation on a daily kata, that would go like this:

  1. Load up the source code of the application you are working on.
  2. Choose a class or method that is not covered by any existing unit tests (preferably something you are currently working on).
  3. Give yourself a maximum of 30 minutes to create a meaningful unit test.
  4. If it passes, check it in, and congratulations, you now have slightly less legacy code than before.
  5. If it fails, rollback and get on with your day’s work. Hopefully you learned something from the experience. You could write up a memo on what is wrong with the design of the class you tried to test. And you could always have another go at it tomorrow.
Problems you will run into

This kata will not necessarily be straightforward. Here’s the two main difficulties you will encounter:

1. Tight Coupling & Hidden Dependencies.

You may find that it is almost impossible to instantiate an instance of the class you want to test because of its dependencies (often hidden through the use of singletons). Sometimes your 30 minutes is up before you have even managed to successfully instantiate the class.

2. Multiple Responsibility Syndrome.

Classes that fail to adhere to the “Single Responsibility Principle” often fail spectacularly. They are responsible for everything from the printout of wage slips to the launching of nuclear warheads. They talk to the database, the file system, the network, the registry, and create a few background threads too. This means that they typically have dozens of dependencies unrelated to the behaviour you want to test. And when you call a single method you aren’t doing one thing, you are doing 100 additional things, one of which is bound to throw an exception. The best course of action is to extract a single, isolated responsibility and move it into its own testable class.

Give it a try

I’ve been doing this “unlegacy my code” kata for a couple of weeks now, and am (very) slowly seeing the unit test coverage rise. The fact that it is directly related to what you are working on also makes it much easier to justify the 30 minute daily investment to your manager.