<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:georss="http://www.georss.org/georss" xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr="http://purl.org/syndication/thread/1.0" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0"><channel><atom:id>tag:blogger.com,1999:blog-6822536077160579260</atom:id><lastBuildDate>Fri, 27 Jan 2012 18:54:00 +0000</lastBuildDate><category>SOLID</category><category>Python</category><category>merging</category><category>SubSonic</category><category>DVCS</category><category>interop</category><category>Visual Studio</category><category>AIFF</category><category>kata</category><category>Windows 8</category><category>MVVM</category><category>SQL</category><category>complexity</category><category>Mercurial</category><category>ASP.NET MVC</category><category>XAML</category><category>ASP.NET</category><category>audio</category><category>MEF</category><category>TDD</category><category>PowerShell</category><category>Code Reviews</category><category>Dependency Inversion Principle</category><category>templating engine</category><category>Unity</category><category>IronPython</category><category>JSON</category><category>HOWTO</category><category>NUnit</category><category>Threading</category><category>LINQ</category><category>Windows Forms</category><category>branching</category><category>nupack</category><category>Windows Vista</category><category>Subversion</category><category>IoC</category><category>Version Control</category><category>TFS</category><category>Technical Debt</category><category>Software Development</category><category>Developer Principles</category><category>MP3</category><category>MSBuild</category><category>Refactoring</category><category>Liskov Substitution Principle</category><category>C#</category><category>NuGet</category><category>Live Mesh</category><category>Open Closed Principle</category><category>clean code</category><category>coding dojo</category><category>book review</category><category>NAudio</category><category>Data Binding</category><category>unit testing</category><category>VistaDB</category><category>architecture</category><category>WPF</category><category>Interface Segregation Principle</category><category>Single Responsibility Principle</category><category>Silverlight</category><category>screencast</category><category>Excel</category><title>Sound Code</title><description>a place for me to talk about programming and .NET ... because my friends and family aren't interested</description><link>http://mark-dot-net.blogspot.com/</link><managingEditor>noreply@blogger.com (Mark H)</managingEditor><generator>Blogger</generator><openSearch:totalResults>183</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/markdotnet" /><feedburner:info uri="markdotnet" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6822536077160579260.post-5869493954836763128</guid><pubDate>Fri, 27 Jan 2012 18:54:00 +0000</pubDate><atom:updated>2012-01-27T18:54:00.440Z</atom:updated><category domain="http://www.blogger.com/atom/ns#">NAudio</category><title>Handling multi-channel audio in NAudio</title><description>&lt;p&gt;One of the recurring questions on the &lt;a href="http://naudio.codeplex.com"&gt;NAudio&lt;/a&gt; support forums is to do with how you can route different sounds to different outputs in a multi-channel soundcard setup. For example, can you play one MP3 file out of one speaker and a different one out of the other? If you have four outputs, can you route a different signal to each one?&lt;/p&gt; &lt;p&gt;The first issue to deal with is that just because your soundcard has multiple outputs, doesn’t mean you can necessarily open WaveOut with multiple outs. That depends on how the writers of the device driver have chosen to present the card’s capabilities to Windows. For example a four output card may appear as though it were two separate stereo soundcards. The good news is that if you have an ASIO driver, you ought to be able to open it and address all the outputs.&lt;/p&gt; &lt;p&gt;Having got that out of the way, in NAudio it is possible for audio streams to have any number of channels. The WaveFormat class has a channel count, and though this is normally set at 1 or 2, there is no reason why you can’t set it to 8.&lt;/p&gt; &lt;p&gt;What would be useful is an implementation of IWaveProvider that allows us to connect different inputs to particular outputs, kind of like a virtual patch bay. For example, if you had two Mp3FileReaders, and wanted to connect the left channel of the first to output 1 and the left channel of the second to output 2, this class would let you do that.&lt;/p&gt; &lt;p&gt;So I’ve created something I’ve called the &lt;strong&gt;MultiplexingWaveProvider&lt;/strong&gt; (if you can think of a better name, let me know in the comments). In the constructor, you simply provide all the inputs you wish to use, and specify the number of output channels you would like. By default the inputs will be mapped directly onto the outputs (and wrap round if there are less outputs than inputs – so a single mono input would be automatically copied to every output), but these can be changed.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Creating and Configuring MultiplexingWaveProvider&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;In the following example, we create a new four-channel WaveProvider, so the first two outputs will play left and right channel from &lt;strong&gt;input1&lt;/strong&gt; and the second two outputs will have the left and right channels from &lt;strong&gt;input2&lt;/strong&gt;.&lt;strong&gt; &lt;/strong&gt;Note that input1 and input2 must be at the same sample rate and bit depth.&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;var input1 = new Mp3FileReader("test1.mp3");
var input2 = new Mp3FileReader("test2.mp3");
var waveProvider = new MultiplexingWaveProvider(new IWaveProvider[] { input1, input2 }, 4));
&lt;/pre&gt;
&lt;p&gt;Then you can configure the outputs, which is done using &lt;strong&gt;ConnectInputToOutput&lt;/strong&gt;:&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;waveProvider.ConnectInputToOutput(2,0);
waveProvider.ConnectInputToOutput(3,1);
waveProvider.ConnectInputToOutput(1,2);
waveProvider.ConnectInputToOutput(1,3);
&lt;/pre&gt;
&lt;p&gt;The numbers used are zero-based, so connecting inputs 2 and 3 to outputs 0 and 1 means that test2.mp3 will now play out of the first two outputs instead of the second two. In this example I have connected input 1 (i.e. the right channel of test1.mp3) to both outputs 2 and 3. So you can copy the same input to multiple output channels, and not all input channels need a mapping.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Implementation of MultiplexingWaveProvider&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The bulk of the work to achieve this is performed in the Read method of MultiplexingWaveProvider. The first task is to work out how many “sample frames” are required. A sample frame is a single sample in a mono signal, a left and right pair in a stereo signal, and so on. Once we have worked out how many sample frames we need, we then attempt to read that many sample frames from every one of the input WaveProviders (irrespective of whether they are connected to an output – we want to keep them in sync). Then, using our mappings dictionary, work out if any of the channels from this input WaveProvider are needed in the output. Since samples are interleaved in both input and output waveproviders, we can’t do just one Array.Copy – we must copy each sample across individually and put it into the right place.&lt;/p&gt;
&lt;p&gt;A well behaved Read method will always return count unless it has reached the end of its available data (and then it should always return 0 in every subsequent call). The way we do this is work out the maximum number of sample frames read out of any of the inputs, and use that to report back the count that is read. This means that we will keep going until we have reached the end of all of our inputs. Because buffers might be reused, it is important that we zero out the output buffer if there was no available input data. &lt;/p&gt;
&lt;p&gt;Here’s the implementation as it currently stands:&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;public int Read(byte[] buffer, int offset, int count)
{
    int sampleFramesRequested = count / (bytesPerSample * outputChannelCount);
    int inputOffset = 0;
    int sampleFramesRead = 0;
    // now we must read from all inputs, even if we don't need their data, so they stay in sync
    foreach (var input in inputs)
    {
        int bytesRequired = sampleFramesRequested * bytesPerSample * input.WaveFormat.Channels;
        byte[] inputBuffer = new byte[bytesRequired];
        int bytesRead = input.Read(inputBuffer, 0, bytesRequired);
        sampleFramesRead = Math.Max(sampleFramesRead, bytesRead / (bytesPerSample * input.WaveFormat.Channels));

        for (int n = 0; n &amp;lt; input.WaveFormat.Channels; n++)
        {
            int inputIndex = inputOffset + n;
            for (int outputIndex = 0; outputIndex &amp;lt; outputChannelCount; outputIndex++)
            {
                if (mappings[outputIndex] == inputIndex)
                {
                    int inputBufferOffset = n * bytesPerSample;
                    int outputBufferOffset = offset + outputIndex * bytesPerSample;
                    int sample = 0;
                    while (sample &amp;lt; sampleFramesRequested &amp;amp;&amp;amp; inputBufferOffset &amp;lt; bytesRead)
                    {
                        Array.Copy(inputBuffer, inputBufferOffset, buffer, outputBufferOffset, bytesPerSample);
                        outputBufferOffset += bytesPerSample * outputChannelCount;
                        inputBufferOffset += bytesPerSample * input.WaveFormat.Channels;
                        sample++;
                    }
                    // clear the end
                    while (sample &amp;lt; sampleFramesRequested)
                    {
                        Array.Clear(buffer, outputBufferOffset, bytesPerSample);
                        outputBufferOffset += bytesPerSample * outputChannelCount;
                        sample++;
                    }
                }
            }
        }
        inputOffset += input.WaveFormat.Channels;
    }

    return sampleFramesRead * bytesPerSample * outputChannelCount;
}
&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Performance&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Looking at the code above, you will probably notice that this could be made more efficient if we knew in advance whether we were dealing with 16, 24 or 32 bit input audio (it currently has lots of calls to Array.Copy to copy just 2, 3 or 4 bytes). And I might make three versions of this class at some point, to ensure that this performs a bit better. Another weakness in the current design is the creation of buffers every call to Read, which is something that I generally avoid since it gives work to the garbage collector (&lt;em&gt;update – this is fixed in the latest code&lt;/em&gt;).&lt;/p&gt;
&lt;p&gt;I have written a full suite of unit tests for this class, so if it does need some performance tuning, there is a safety net to ensure nothing gets broken along the way.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;MultiplexingSampleProvider&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;NAudio 1.5 also has a ISampleProvider interface, which is a much more programmer friendly way of dealing with 32 bit floating point audio. I have also made &lt;strong&gt;MultiplexingSampleProvider &lt;/strong&gt;for the next version of NAudio. One interesting possibility would be then to build on that to create a kind of bus matrix, where every input can be mixed by different amounts into each of the output channels.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Uses&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;This class actually has uses beyond supporting soundcards with more than 2 outputs. You could use it to swap left and right channels in a stereo signal, or provide a simple switch that selects between several mono inputs.&lt;/p&gt;
&lt;p&gt;You also don’t need to output to the soundcard. The WaveFileReader will happily write multi-channel WAV files. However, there are no guarantees about how other programs will deal with WAVs that have more than two channels in them.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Availability&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;I’ve already checked in the initial version to the latest codebase, so expect this to be part of NAudio 1.6. The only caution is that I might change the class name if I come up with a better idea. &lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6822536077160579260-5869493954836763128?l=mark-dot-net.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/markdotnet/~4/OszJpoJBHJk" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/markdotnet/~3/OszJpoJBHJk/handling-multi-channel-audio-in-naudio.html</link><author>noreply@blogger.com (Mark H)</author><thr:total>0</thr:total><feedburner:origLink>http://mark-dot-net.blogspot.com/2012/01/handling-multi-channel-audio-in-naudio.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6822536077160579260.post-8487178062693912691</guid><pubDate>Tue, 10 Jan 2012 19:34:00 +0000</pubDate><atom:updated>2012-01-10T19:34:00.054Z</atom:updated><category domain="http://www.blogger.com/atom/ns#">Interface Segregation Principle</category><category domain="http://www.blogger.com/atom/ns#">Unity</category><category domain="http://www.blogger.com/atom/ns#">Software Development</category><category domain="http://www.blogger.com/atom/ns#">IoC</category><category domain="http://www.blogger.com/atom/ns#">Dependency Inversion Principle</category><title>10 Commandments of Inversion of Control Containers</title><description>&lt;p&gt;&lt;a href="http://en.wikipedia.org/wiki/Inversion_of_control"&gt;Inversion of Control containers&lt;/a&gt; can be a very powerful tool for decoupling spaghetti code in large software systems. However, with any power tool, you can hurt yourself badly if you don’t use it correctly. In this post, I present “10 commandments” to help you avoid causing problems with IoC, with a particular focus on very large software systems with many developers and hundreds of interfaces. I am currently using &lt;a href="http://unity.codeplex.com/"&gt;Unity&lt;/a&gt;, but these tips apply to pretty much any IoC container.&lt;/p&gt; &lt;h3&gt;1. Configure everything before your first resolve&lt;/h3&gt; &lt;p&gt;It is possible to ask the IoC container to resolve an interface before you have finished configuring the container. So long as it knows how to make the interface you asked for and its dependencies, it will have no problem fulfilling your request. But if your application hasn’t yet finished configuring the container yet, you run the risk of getting the wrong thing. Consider the following simple example:&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;IUnityContainer container = new UnityContainer();
container.RegisterType&amp;lt;IFoo, Foo&amp;gt;(new ContainerControlledLifetimeManager());
var f1 = container.Resolve&amp;lt;IFoo&amp;gt;();
&lt;/pre&gt;
&lt;p&gt;Fairly straightforward, we ask for IFoo and get an instance of Foo. But what if we hadn’t quite finished configuring the container, and some other part in your app attempts to override the registration for IFoo:&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;container.RegisterType&amp;lt;IFoo, Foo2&amp;gt;(new ContainerControlledLifetimeManager());
&lt;/pre&gt;
&lt;p&gt;Now, whenever we attempt to resolve IFoo, we get Foo2. But the initial component that did an early resolve is using the wrong implementation. This can make for horrible debugging sessions. Configure your container completely, &lt;em&gt;before &lt;/em&gt;you start to resolve things from it. Which leads us to our second commandment…&lt;/p&gt;
&lt;h3&gt;2. Don’t pass the container around&lt;/h3&gt;
&lt;p&gt;What I mean here, is don’t pass around the top-level interface that allows further configuration of the container. In Unity, this is the IUnityContainer interface. It might feel very powerful to send it around, since it allows other parts of your application register new rules, but it opens the door for the kind of bugs we just discussed.&lt;/p&gt;
&lt;p&gt;But what about just a &lt;a href="http://commonservicelocator.codeplex.com/"&gt;Service Locator interface&lt;/a&gt;. Can I pass one of those around? Onto commandment 3…&lt;/p&gt;
&lt;h3&gt;3. Avoid passing an IServiceLocator around&lt;/h3&gt;
&lt;p&gt;Passing a service locator in as a dependency gives your class great power. It can ask for anything it wants, which is super convenient. But it also introduces some problems.&lt;/p&gt;
&lt;p&gt;First, it means your class no longer advertises what it needs in the constructor. Without examining the code you can’t be sure what needs to be in the container for the class to work correctly. It means that unit tests, or callers of your class that aren’t using a container, will have to mock a container just to instantiate your class.&lt;/p&gt;
&lt;p&gt;This has been called &lt;a href="http://stackoverflow.com/questions/2045904/dependency-inject-di-friendly-library/2047657#2047657"&gt;the “Hollywood principle”&lt;/a&gt; – Don’t call the DI Container, it’ll call you. Just put the interfaces you really need in your constructor. &lt;/p&gt;
&lt;h3&gt;4. Avoid making the container a singleton&lt;/h3&gt;
&lt;p&gt;Making your container a singleton is the quickest route to providing access to all your services everywhere in your application. It can seem like a great idea because wherever you are, you can just do this to get whatever interface you like:&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;var foo = MyContainer.Instance.Resolve&amp;lt;IFoo&amp;gt;();
&lt;/pre&gt;
&lt;p&gt;But there are two big problems. First, this introduces hidden dependencies into your class. Instead of your constructor advertising its dependencies, we again must examine the code to know what needs to be set up in the container.&lt;/p&gt;
&lt;p&gt;Second, it assumes that all parts of your application will work with the same container, and the same implementations of each interface. This may be true for small applications, but in large enterprise systems, there may well be the need for multiple IoC containers. In our systems, we make use of &lt;a href="http://www.pnpguidance.net/post/UnityNestedContainersIUnityParentContainerCreateChildContainer.aspx"&gt;Unity child containers&lt;/a&gt;, allowing different sections of the application get access to their own implementations of interfaces. With a singleton container, this is impossible.&lt;/p&gt;
&lt;h3&gt;5. Avoid constructor bloat&lt;/h3&gt;
&lt;p&gt;One of the great things about IoC containers is that you don’t have to call constructors yourself – the container does the hard work for you. This means you can have a dozen constructor parameters, each representing a different dependency, and yet without ever having to write code that calls it.&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;public MyClass(IFoo foo, IFoo2 foo2, ILog log, IExporter exporter, IEmailer emailer, ISettings settings, IAudit audit)
{
}
&lt;/pre&gt;
&lt;p&gt;That is, until you want to test it. Then you have to mock up all of those interfaces. And probably you will find that your class only needs to call one or two methods on each. This is the time to apply the &lt;a href="http://en.wikipedia.org/wiki/Interface_segregation_principle"&gt;Interface Segregation Principle&lt;/a&gt; and replace them with one or two more focussed interfaces that represent the real dependencies of your class under test. &lt;/p&gt;
&lt;h3&gt;6. Avoid property injection&lt;/h3&gt;
&lt;p&gt;Most IoC containers offer a way to let you put attributes on properties in order to tell the container that it needs to set that property after constructing the object. In Unity you use the Dependency attribute:&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;class Bar
{
    [Dependency]
    public IFoo Foo { get; set; }

    public Bar()
    {
    }
}
&lt;/pre&gt;
&lt;p&gt;Although this seems like a great feature, it has the effect of hiding this dependency from anyone who is constructing your object without an IoC container. At the very least, your class should report a good error message if someone forgets to set up a property dependency.&lt;/p&gt;
&lt;h3&gt;7. Document your interfaces&lt;/h3&gt;
&lt;p&gt;If you are using an IoC container, chances are you are working on a large system, and other developers are resolving interfaces that you put in the container.&lt;/p&gt;
&lt;p&gt;Often developers will add good comments to the concrete implementation of a class, but spend very little time commenting the interface (who likes to write the same comments twice?). So in the concrete class we might have a comment like this:&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;/// &amp;lt;summary&amp;gt;
/// Call this to process all the files in the InputFiles collection, using the rules from the Rules collection
/// &amp;lt;/summary&amp;gt;
/// &amp;lt;param name="mode"&amp;gt;Processing mode, 0 = replace, 1 = update, 2 = overwrite, 3 = test only&amp;lt;/param&amp;gt;
public void Process(int mode)

&lt;/pre&gt;
&lt;p&gt;but in the interface, we couldn’t be bothered to type that all again (and we hate cutting and pasting anyway) so we just have this:&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;/// &amp;lt;summary&amp;gt;
/// Process
/// &amp;lt;/summary&amp;gt;
void Process(int mode);
&lt;/pre&gt;
&lt;p&gt;But it is the interface that is the public API for your service. The comments on the interface will be used to display Intellisense to the user. The caller may not even have access to the code for the concrete implementation. If you are going to spend time writing good comments, write them on the interface. Here’s the difference in intellisense experience:&lt;/p&gt;
&lt;p&gt;&lt;a href="http://lh6.ggpht.com/-ZBEOlAPPC6M/Twx2pubrrnI/AAAAAAAAAto/tXHJP2G-lAM/s1600-h/bad-intellisense%25255B2%25255D.png"&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="bad-intellisense" border="0" alt="bad-intellisense" src="http://lh4.ggpht.com/-15336uLarxQ/Twx2qBxnQ-I/AAAAAAAAAts/fQNof5NSZZs/bad-intellisense_thumb.png?imgmax=800" width="229" height="76"&gt;&lt;/a&gt; &lt;/p&gt;
&lt;p&gt;versus:&lt;/p&gt;
&lt;p&gt;&lt;a href="http://lh6.ggpht.com/-WWC3t6vOHMY/Twx2qpJXDFI/AAAAAAAAAt0/GNYqaJ_ombA/s1600-h/good-intellisense%25255B3%25255D.png"&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="good-intellisense" border="0" alt="good-intellisense" src="http://lh5.ggpht.com/--Hxqng4KCRA/Twx2rBz0SpI/AAAAAAAAAt8/sPlFD-wtCEw/good-intellisense_thumb%25255B1%25255D.png?imgmax=800" width="566" height="84"&gt;&lt;/a&gt; &lt;/p&gt;
&lt;h3&gt;8. Don’t depend on Dispose in a specific order&lt;/h3&gt;
&lt;p&gt;When you Dispose your IoC container, it will go through all of the IDisposable instances it knows about and call Dispose on them. But this can introduce a problem, because we cannot guarantee the order the services are disposed in. If you make a call into another service in your Dispose method, how do you know that service hasn’t already been Disposed? &lt;/p&gt;
&lt;p&gt;Instead, design your services in such a way that they can be disposed in any order, and use events or some other form of messaging to report to your system that a shutdown is about to happen, allowing any last minute logging, saving etc to be done beforehand, while all the services are still up and running.&lt;/p&gt;
&lt;h3&gt;9. Make sure Lifetime Management is communicated&lt;/h3&gt;
&lt;p&gt;If you call &lt;strong&gt;Resolve&amp;lt;IFoo&amp;gt;&lt;/strong&gt; twice on your IoC container, you &lt;em&gt;might &lt;/em&gt;get two new instances of the Foo class, or you might get the same one twice. Without looking at how your container is configured, you have no way of knowing. But this can be a real headache if IFoo implements IDisposable. How do you know whether you ought to call Dispose on it or not? &lt;/p&gt;
&lt;p&gt;I don’t know of any slick solution to this, but I would typically avoid instances where a Resolve gives you something you need to Dispose yourself. Instead I would return a factory object that makes it very clear you are building a new instance that you are in control of its lifetime yourself. Whatever approach you use, make sure your whole development team understands it. You don’t want someone Disposing a service too early, resulting in the next person to use it getting a nasty exception.&lt;/p&gt;
&lt;h3&gt;10. Document your public API&lt;/h3&gt;
&lt;p&gt;In a large system, a container can easily fill up with a lot of interfaces. The trouble is, not all of these are at the same level. Some are high-level interfaces, allowed to be called from anywhere, whilst other things are only in the container so they can fulfil the dependencies of those high-level interfaces. It means that you run the risk of developers guessing incorrectly about which interface they are supposed to call to achieve a particular task. They will assume that if they can get at it from the container, then they must be allowed to call it.&lt;/p&gt;
&lt;p&gt;Now there are ways of having interfaces defined in your container that people can’t get at from the wrong place by making good use of assemblies and the &lt;strong&gt;internal &lt;/strong&gt;keyword, but really, you need to make it easy for developers to know what is in the container and how they are intended to use it. This may well involve maintaining an API document, and also means writing good comments on the interface. If you don’t do this, don’t be surprised to see code that inadvertently circumvents key functionality by calling into a component at too low a level, or the wheel being reinvented, simply because a developer didn’t know the container included a service that had the desired behaviour.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Do you have any tips for getting the best out of IoC containers? Please let me know in the comments.&lt;/em&gt;&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6822536077160579260-8487178062693912691?l=mark-dot-net.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/markdotnet/~4/O35FKIcGXJg" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/markdotnet/~3/O35FKIcGXJg/10-commandments-of-inversion-of-control.html</link><author>noreply@blogger.com (Mark H)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://lh4.ggpht.com/-15336uLarxQ/Twx2qBxnQ-I/AAAAAAAAAts/fQNof5NSZZs/s72-c/bad-intellisense_thumb.png?imgmax=800" height="72" width="72" /><thr:total>20</thr:total><feedburner:origLink>http://mark-dot-net.blogspot.com/2012/01/10-commandments-of-inversion-of-control.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6822536077160579260.post-3731424803493113304</guid><pubDate>Sun, 18 Dec 2011 22:15:00 +0000</pubDate><atom:updated>2011-12-18T22:15:23.247Z</atom:updated><category domain="http://www.blogger.com/atom/ns#">NAudio</category><title>NAudio 1.5 Released</title><description>&lt;p&gt;I have finally got round to releasing the long overdue version 1.5 of &lt;a href="http://naudio.codeplex.com"&gt;NAudio&lt;/a&gt;. There are loads of bugfixes and improvements, so I recommend upgrading if possible. Here’s the highlights.&lt;/p&gt; &lt;ul&gt; &lt;li&gt;Now &lt;a href="https://nuget.org/packages/NAudio/1.5"&gt;available on NuGet&lt;/a&gt;!&lt;/li&gt; &lt;li&gt;Numerous bugfixes mean we are now working fully in x64 as well as x86, so NAudio.dll is now marked as AnyCPU. (&lt;em&gt;You can still force x86 by marking your own executable as x86 only.)&lt;/em&gt;&lt;/li&gt; &lt;li&gt;WaveOutEvent – a new WaveOut mode with event callback, highly recommended instead of WaveOut with function callbacks&lt;/li&gt; &lt;li&gt;24 bit ASIO driver mode (LSB) &lt;/li&gt; &lt;li&gt;Float LSB ASIO driver mode&lt;/li&gt; &lt;li&gt;WaveFileWriter has had a general code review and API cleanup&lt;/li&gt; &lt;li&gt;Preview of new &lt;strong&gt;ISampleProvider&lt;/strong&gt; interface making it much easier to write custom 32 bit IEEE (float) audio pipeline components, without the need to convert to byte[]. Lots of examples in NAudioDemo of using this and more documentation will follow in future.&lt;/li&gt; &lt;li&gt;Several ISampleProvider implementations to get you started. Expect plenty more in future NAudio versions:&lt;/li&gt; &lt;ul&gt; &lt;li&gt;PanningSampleProvider&lt;/li&gt; &lt;li&gt;MixingSampleProvider&lt;/li&gt; &lt;li&gt;MeteringSampleProvider&lt;/li&gt; &lt;li&gt;MonoToStereoSampleProvider&lt;/li&gt; &lt;li&gt;NotifyingSampleProvider&lt;/li&gt; &lt;li&gt;Pcm16BitToSampleProvider&lt;/li&gt; &lt;li&gt;Pcm8BitToSampleProvider&lt;/li&gt; &lt;li&gt;Pcm24BitToSampleProvider&lt;/li&gt; &lt;li&gt;SampleChannel&lt;/li&gt; &lt;li&gt;SampleToWaveProvider&lt;/li&gt; &lt;li&gt;VolumeSampleProvider&lt;/li&gt; &lt;li&gt;WaveToSampleProvider&lt;/li&gt;&lt;/ul&gt; &lt;li&gt;Added AiffFileReader courtesy of Giawa&lt;/li&gt; &lt;li&gt;AudioFileReader to simplify opening any supported file, easy volume control, read/reposition locking&lt;/li&gt; &lt;li&gt;BufferedWaveProvider uses CircularBuffer instead of queue (less memory allocations)&lt;/li&gt; &lt;li&gt;CircularBuffer is now thread-safe&lt;/li&gt; &lt;li&gt;MP3Frame code cleanup&lt;/li&gt; &lt;li&gt;MP3FileReader throws less exceptions&lt;/li&gt; &lt;li&gt;ASIOOut bugfixes for direct 16 bit playback&lt;/li&gt; &lt;li&gt;Some Demos added to NAudioDemo to give simple examples of how to use the library&lt;/li&gt; &lt;ul&gt; &lt;li&gt;NAudioDemo has an ASIO Direct out form, mainly for testing the AsioOut class at different bit depths (still recommended to convert to float before you get there).&lt;/li&gt; &lt;li&gt;NAudioDemo has simple MP3 streaming form (play MP3s while they download)&lt;/li&gt; &lt;li&gt;NAudioDemo has simple network streaming chat application&lt;/li&gt; &lt;li&gt;NAudioDemo playback form uses MEF to make it much more modular and extensible (new output drivers, new file formats etc)&lt;/li&gt; &lt;li&gt;NAudioDemo can play aiff&lt;/li&gt;&lt;/ul&gt; &lt;li&gt;GSM 6.10 ACM codec support&lt;/li&gt; &lt;li&gt;DSP Group TrueSpeech ACM codec support&lt;/li&gt; &lt;li&gt;Fully managed G.711 a-law and mu-law codecs (encode &amp;amp; decode)&lt;/li&gt; &lt;li&gt;Fully managed G.722 codec (encode &amp;amp; decode)&lt;/li&gt; &lt;li&gt;Example of integration with NSpeex&lt;/li&gt; &lt;li&gt;Fix to PlaybackStopped using SyncContext for thread safety&lt;/li&gt; &lt;li&gt;Obsoleted IWavePlayer.Volume (can still set volume on WaveOut directly if you want)&lt;/li&gt; &lt;li&gt;Improved FFT display in WPF demo&lt;/li&gt; &lt;li&gt;WaveFileReader - tolerate junk after data chunk&lt;/li&gt; &lt;li&gt;WaveOut constructor detects if no sync context &amp;amp; choose func callbacks&lt;/li&gt; &lt;li&gt;WaveOut function mode callbacks hopefully chased out the last of the hanging bugs &lt;em&gt;(if in a WaveOutWrite at same time as WaveOutReset, bad things happen - so need locks, but if WaveOutReset called during a previous func callback that is about to call waveOutWrite we deadlock)&lt;/em&gt;&lt;/li&gt; &lt;li&gt;Now has an msbuild script allowing me to more easily create releases, run tests etc&lt;/li&gt; &lt;li&gt;Now using Mercurial for source control, hopefully making bug fixing old releases and accepting user patches easier. n.b. this unfortunately means all old submitted patches are no longer available for download on the CodePlex page.&lt;/li&gt; &lt;li&gt;WPF Demo enhancements:&lt;/li&gt; &lt;ul&gt; &lt;li&gt;WPF Demo is now .NET 4, allowing us to use MEF, and will be updated hopefully with more examples of using NAudio. &lt;/li&gt; &lt;li&gt;WPF Demo uses windowing before FFT for a more accurate spectrum plot &lt;/li&gt; &lt;li&gt;WPF Demo has visualization plugins, allowing me to trial different drawing mechanisms &lt;/li&gt; &lt;li&gt;WPF Demo has a (very basic) drum machine example&lt;/li&gt;&lt;/ul&gt;&lt;/ul&gt; &lt;p&gt;I also intend that this will be the last NAudio that targets .NET 2.0 (1.6 will be .NET 3.5). Let me know if you have any objections. &lt;p&gt;Hope you have fun using it, and do send me the links to any cool stuff you make with it.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6822536077160579260-3731424803493113304?l=mark-dot-net.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/markdotnet/~4/wvgtuVUJHxY" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/markdotnet/~3/wvgtuVUJHxY/naudio-15-released.html</link><author>noreply@blogger.com (Mark H)</author><thr:total>7</thr:total><feedburner:origLink>http://mark-dot-net.blogspot.com/2011/12/naudio-15-released.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6822536077160579260.post-7583712626874141027</guid><pubDate>Tue, 29 Nov 2011 16:11:00 +0000</pubDate><atom:updated>2011-11-29T16:11:21.120Z</atom:updated><category domain="http://www.blogger.com/atom/ns#">MSBuild</category><category domain="http://www.blogger.com/atom/ns#">IronPython</category><category domain="http://www.blogger.com/atom/ns#">Python</category><title>Creating Zip Files with IronPython</title><description>&lt;p&gt;I’ve been working on automating some of the parts of the release process for &lt;a href="http://naudio.codeplex.com"&gt;NAudio&lt;/a&gt;, as I always seem to forget something or make a mistake. One of the tasks was to create a “demo” zip file containing the demo applications together with their supporting files.&lt;/p&gt; &lt;p&gt;I initially attempted to do this with MSBuild and the Zip task from &lt;a href="http://msbuildtasks.tigris.org/"&gt;MSBuild Community Extensions&lt;/a&gt;, but I ended up double-adding a number of files, as well as struggling to get exactly the right folder structure.&lt;/p&gt; &lt;p&gt;This is exactly the sort of task that Python excels at, and Python comes with the &lt;a href="http://docs.python.org/library/zipfile.html"&gt;zipfile module&lt;/a&gt; built in, meaning that the script I wrote is not &lt;a href="http://ironpython.net"&gt;IronPython&lt;/a&gt; specific. Here’s what I came up with:&lt;/p&gt;&lt;pre class="brush: py;"&gt;import zipfile
import os

folders = ['AudioFileInspector','NAudioDemo','NAudioWpfDemo']
files = {}

def exclude(filename):
    return filename.endswith('.pdb') or ('nunit' in filename)

for folder in folders:
    fullpath = folder + "\\bin\\debug\\"
    for filename in os.listdir(fullpath):
        if not exclude(filename):
            files[filename] = fullpath + filename

zip = zipfile.ZipFile("BuildArtefacts\\test.zip", "w")

for filename, fullpath in files.iteritems():
    if os.path.isdir(fullpath):
        for subfile in os.listdir(fullpath):
            zip.write(fullpath + "\\" + subfile, filename + "\\" + subfile)
    else:
        zip.write(fullpath, filename)

zip.close()&lt;/pre&gt;
&lt;p&gt;There's not a lot to it really. I first build up a dictionary containing the files I want in my zip, using the filename to exclude duplicates. Then I use the &lt;strong&gt;write &lt;/strong&gt;method on &lt;strong&gt;zipfile&lt;/strong&gt; to specify the file I want to add, and the folder it belongs in.&lt;/p&gt;
&lt;p&gt;My Python skills are a bit rusty, so the code above would probably benefit from being refactored a little, but as you can see, it is very easy, and much simpler than fighting MSBuild to make it do what I want.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6822536077160579260-7583712626874141027?l=mark-dot-net.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/markdotnet/~4/dStvDlQk00c" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/markdotnet/~3/dStvDlQk00c/creating-zip-files-with-ironpython.html</link><author>noreply@blogger.com (Mark H)</author><thr:total>1</thr:total><feedburner:origLink>http://mark-dot-net.blogspot.com/2011/11/creating-zip-files-with-ironpython.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6822536077160579260.post-8009932982967367472</guid><pubDate>Mon, 11 Jul 2011 17:09:00 +0000</pubDate><atom:updated>2011-07-11T18:09:00.399+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">MVVM</category><category domain="http://www.blogger.com/atom/ns#">WPF</category><category domain="http://www.blogger.com/atom/ns#">screencast</category><title>Screencast: Modular WPF with MEF &amp; MVVM Tutorial Part 2</title><description>&lt;p&gt;In &lt;a href="http://mark-dot-net.blogspot.com/2011/07/screencast-modular-wpf-with-mef-mvvm.html"&gt;Part 1&lt;/a&gt;, I showed how to create a very simple modular WPF application, and introduced MEF to allow us to easily add modules without changing any existing code.&lt;/p&gt; &lt;p&gt;In part 2, I introduce the &lt;a href="http://en.wikipedia.org/wiki/Model_View_ViewModel"&gt;MVVM&lt;/a&gt; pattern to show how we can make our applications more easily unit testable, by separating the view from the business logic. I also create some unit tests using the Microsoft unit testing framework and &lt;a href="http://code.google.com/p/moq/"&gt;moq&lt;/a&gt;, and show how to perform code coverage analysis.&lt;/p&gt;&lt;iframe height="300" src="http://player.vimeo.com/video/26202598?title=0&amp;amp;byline=0&amp;amp;portrait=0" frameborder="0" width="400"&gt;&lt;/iframe&gt; &lt;p&gt;&lt;em&gt;Incidentally, I normally use &lt;/em&gt;&lt;a href="http://www.nunit.org/"&gt;&lt;em&gt;NUnit&lt;/em&gt;&lt;/a&gt;&lt;em&gt; and &lt;a href="http://www.testdriven.net/"&gt;TestDriven.NET&lt;/a&gt; instead of the Microsoft unit testing framework, which I find much simpler to use, and also supports code coverage analysis using &lt;a href="http://www.ncover.com/"&gt;NCover&lt;/a&gt; or the Visual Studio code coverage.&lt;/em&gt;&lt;/p&gt; &lt;p&gt;I do plan to follow this up with a third video, in which I replace the modules ListBox with some buttons to switch modules and show some of the typical problems you might run into when using MVVM.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6822536077160579260-8009932982967367472?l=mark-dot-net.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/markdotnet/~4/40LeHd0og50" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/markdotnet/~3/40LeHd0og50/screencast-modular-wpf-with-mef-mvvm_11.html</link><author>noreply@blogger.com (Mark H)</author><thr:total>8</thr:total><feedburner:origLink>http://mark-dot-net.blogspot.com/2011/07/screencast-modular-wpf-with-mef-mvvm_11.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6822536077160579260.post-6763879437828650902</guid><pubDate>Sat, 09 Jul 2011 16:57:00 +0000</pubDate><atom:updated>2011-07-09T21:00:54.333+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">C#</category><title>10 C# keywords you should be using</title><description>&lt;p&gt;Most developers who learn C# pick up the basic keywords quite quickly. Within a few weeks of working with a typical codebase you’ll have come across around a third of the C# keywords, and understand roughly what they do. You should have no trouble explaining what the following keywords mean:  &lt;blockquote&gt; &lt;p&gt;public, private, protected, internal, class, namespace, interface, get, set, for, foreach .. in, while, do, if, else, switch, break, continue, new, null, var, void, int, bool, double, string, true, false, try, catch&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;However, while doing code reviews I have noticed that some developers get stuck with a limited vocabulary of keywords and never really get to grips with some of the less common ones, and so miss out on their benefits. So here’s a list, in no particular order, of some keywords that you should not just understand, but be using on a semi-regular basis in your own code.&lt;/p&gt; &lt;h3&gt;is &amp;amp; as&lt;/h3&gt; &lt;p&gt;Sometimes I come across a variation of the following code, where we want to cast a variable to a different type but would like to check first if that cast is valid:&lt;pre class="brush: csharp;"&gt;if (sender.GetType() == typeof(TextBox))
{
   TextBox t = (TextBox)sender;
   ...
}&lt;/pre&gt;
&lt;p&gt;While this works fine, the &lt;strong&gt;is&lt;/strong&gt; keyword could be used to simplify the if clause:&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;if (sender is TextBox)
{
   TextBox t = (TextBox)sender;
   ...
}&lt;/pre&gt;
&lt;p&gt;We can improve things further by using the &lt;strong&gt;as &lt;/strong&gt;keyword, which is like a cast, but doesn’t throw an exception if the conversion is not valid – it just returns null instead. This means we can write code in a way that doesn’t require the .NET framework to check the type of our sender variable twice:&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;TextBox t = sender as TextBox;
if (t != null)
{
   ...
}
&lt;/pre&gt;
&lt;p&gt;I feel obliged to add that if your code contains a lot of casts, you are probably doing something wrong, but that is a discussion for another day.&lt;/p&gt;
&lt;h3&gt;using&lt;/h3&gt;
&lt;p&gt;Most developers are familiar with the &lt;strong&gt;using&lt;/strong&gt; keyword for importing namespaces, but a surprising number do not make regular use of it for dealing with objects that implement IDisposable. For example, consider the following code:&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;var writer = new StreamWriter("test.txt");
writer.WriteLine("Hello World");
writer.Dispose();
&lt;/pre&gt;
&lt;p&gt;What we have here is a potential resource leak if there is an exception thrown between opening the file and closing it. The using keyword ensures that Dispose will always be called if the writer object was successfully created.&lt;/p&gt;
&lt;p&gt;&lt;pre class="brush: csharp;"&gt;using (var writer = new StreamWriter("test.txt"))
{
   writer.WriteLine("Hello World");
}
&lt;/pre&gt;
&lt;p&gt;Make it a habit to check whether the classes you create implement IDisposable, and if so, make use of the using keyword.&lt;/p&gt;
&lt;h3&gt;finally&lt;/h3&gt;
&lt;p&gt;Which brings us onto our next keyword, &lt;strong&gt;finally&lt;/strong&gt;. Even developers who know and use &lt;strong&gt;using &lt;/strong&gt;often miss appropriate scenarios for using a finally block. Here’s a classic example:&lt;pre class="brush: csharp;"&gt;public void Update()
{   
    if (this.updateInProgress)
    {    
        log.WriteWarning("Already updating");    
        return;
    } 
    this.updateInProgress = true;
    ...
    DoUpdate();
    ...
    this.updateInProgress = false;

}&lt;/pre&gt;
&lt;p&gt;The code is trying to protect us from some kind of re-entrant or multithreaded scenario where an Update can be called while one is still in progress (please ignore the potential race condition for the purposes of this example). But what happens if there is an exception thrown within DoUpdate? Now we are never able to call Update again because our updateInProgress flag never got unset. A finally block ensures we can’t get into this invalid state:&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;public void Update()
{   
    if (this.updateInProgress)
    {    
        log.WriteWarning("Already updating");    
        return;
    } 
    try
    {
        this.updateInProgress = true;
        ...
        DoUpdate();
        ...
    }
    finally
    {
        this.updateInProgress = false;
    }
}&lt;/pre&gt;
&lt;h3&gt;readonly &lt;/h3&gt;
&lt;p&gt;OK, this one is a fairly simple one, and you could argue that code works just fine without it. The &lt;b&gt;readonly&lt;/b&gt; keyword says that a field can only be written to from within the constructor. It’s handy from a code readability point of view, since you can immediately see that this is a field whose value will never change during the lifetime of the class. It also becomes a more important keyword as you begin to appreciate the benefits of immutable classes. Consider the following class:&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;public class Person
{
    public string FirstName { get; private set; }
    public string Surname { get; private set; }

    public Person(string firstName, string surname)
    { 
        this.FirstName = firstName;
        this.Surname = surname;
    }
}
&lt;/pre&gt;
&lt;p&gt;Person is certainly immutable from the outside – no one can change the FirstName or Surname properties. But nothing stops me from modifying those properties within the class. In other words, my code doesn’t advertise that I intend this to be an immutable class. Using the &lt;strong&gt;readonly &lt;/strong&gt;keyword, we can express our intent better:&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;public class Person
{
    private readonly string firstName;
    private readonly string surname;

    public string FirstName { get { return firstName; } }
    public string Surname { get { return surname; } }

    public Person(string firstName, string surname)
    { 
        this.firstName = firstName;
        this.surname = surname;
    }
}&lt;/pre&gt;
&lt;p&gt;Yes, it’s a shame that this second version is a little more verbose than the first, but it makes it more explicit that we don’t want firstName or surname to be modified during the lifetime of the class. (Sadly C# doesn’t allow the readonly keyword on properties).&lt;/p&gt;
&lt;h3&gt;yield&lt;/h3&gt;
&lt;p&gt;This is a very powerful and yet rarely used keyword. Suppose we have a class that searches our hard disk for all MP3 files and returns their paths. Often we might see it written like this:&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;public List&amp;lt;string&amp;gt; FindAllMp3s()
{
   var mp3Paths = List&amp;lt;string&amp;gt;();
   ... 
   // fill the list
   return mp3Paths;
}
&lt;/pre&gt;
&lt;p&gt;Now we might use that method to help us search for a particular MP3 file we had lost:&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;foreach(string mp3File in FindAllMp3s())
{
   if (mp3File.Contains("elvis"))
   {
       Console.WriteLine("Found it at: {0}", mp3File);
       break;
   }  
}
&lt;/pre&gt;
&lt;p&gt;Although this code seems to work just fine, it’s performance is sub-optimal, since we first find &lt;em&gt;every &lt;/em&gt;MP3 file on the disk, and then search through that list. We could save ourselves a lot of time if we checked after each file we found and aborted the search at that point.&lt;/p&gt;
&lt;p&gt;The &lt;strong&gt;yield&lt;/strong&gt; keyword allows us to fix this without changing our calling code at all. We modify FindAllMp3s to return an IEnumerable&amp;lt;string&amp;gt; instead of a List. And now every time it finds a file, we return it using the yield keyword. So with some rather contrived example helper functions (.NET 4 has already added &lt;a href="http://msdn.microsoft.com/en-us/library/dd383458.aspx"&gt;a method&lt;/a&gt; that does exactly this) our FindAllMp3s method looks like this: &lt;/p&gt;&lt;pre class="brush: csharp;"&gt;public IEnumerable&amp;lt;string&amp;gt; FindAllMp3s()
{
   var mp3Paths = List&amp;lt;string&amp;gt;();
   
   for (var dir in GetDirs())
   {
       for (var file in GetFiles(dir))
       {
           if (file.EndsWith(".mp3")
           {
               yield return file;
           }
       }
   }      
}&lt;/pre&gt;
&lt;p&gt;This not only saves us time, but it saves memory too, since we now don’t need to store the entire collection of mp3 files in a List.&lt;/p&gt;
&lt;p&gt;It can take a little while to get used to debugging this type of code since you jump in and out of a function that uses yield repeatedly as you walk through the sequence, but it has the power to greatly improve the design and performance of the code you write and is worth mastering.&lt;/p&gt;
&lt;h3&gt;select&lt;/h3&gt;
&lt;p&gt;OK, this one is cheating since this is a whole family of related keywords. I won’t attempt to explain LINQ here, but it is one of the best features of the C# language, and you owe it to yourself to learn it. It will revolutionise the way you write code. Download &lt;a href="http://www.linqpad.net/"&gt;LINQPad&lt;/a&gt; and start working through the tutorials it provides.&lt;/p&gt;
&lt;h3&gt;interface&lt;/h3&gt;
&lt;p&gt;So you already know about this keyword. But you probably aren’t using it nearly enough. The more you write code that is testable and adheres to the &lt;a href="http://en.wikipedia.org/wiki/Dependency_inversion_principle"&gt;Dependency Inversion Principle&lt;/a&gt;, the more you will need it. In fact at some point you will grow to hate how much you are using it and wish you were using a dynamic language instead. (&lt;strong&gt;dynamic&lt;/strong&gt; is itself another very interesting new C# keyword, but I feel that the C# community is only just beginning to discover how we can best put it to use).&lt;/p&gt;
&lt;h3&gt;throw &lt;/h3&gt;
&lt;p&gt;You do know you are allowed to &lt;strong&gt;throw&lt;/strong&gt; as well as catch exceptions right? Some developers seem to think that a function should never let any exceptions get away, and so contain a generic &lt;strong&gt;catch &lt;/strong&gt;block which writes an error to the log and returns giving the caller no indication that things went wrong.&lt;/p&gt;
&lt;p&gt;This is almost always wrong. Most of the time your methods should simply allow exceptions to propagate up to the caller. If you are using the &lt;strong&gt;using &lt;/strong&gt;keyword correctly, you are probably already doing all the cleanup you need to. &lt;/p&gt;
&lt;p&gt;But you can and should sometimes throw exceptions. An exception thrown at the point you realise something is wrong with a good error message can save hours of debugging time.&lt;/p&gt;
&lt;p&gt;Oh, and if you really do need to catch an exception and re-throw it, make sure you use do it &lt;a href="http://stackoverflow.com/questions/178456/what-is-the-proper-way-to-re-throw-an-exception-in-c"&gt;the correct way&lt;/a&gt;.&lt;/p&gt;
&lt;h3&gt;goto&lt;/h3&gt;
&lt;p&gt;Only joking, pretend you didn’t see this one. Just because a keyword is in the language, doesn’t mean it is a good idea to use it. &lt;strong&gt;out &lt;/strong&gt;and &lt;strong&gt;ref &lt;/strong&gt;usually fall into this category too – there are better ways to write your code.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6822536077160579260-6763879437828650902?l=mark-dot-net.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/markdotnet/~4/keW98cFsD_c" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/markdotnet/~3/keW98cFsD_c/10-c-keywords-you-should-be-using.html</link><author>noreply@blogger.com (Mark H)</author><thr:total>2</thr:total><feedburner:origLink>http://mark-dot-net.blogspot.com/2011/07/10-c-keywords-you-should-be-using.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6822536077160579260.post-7208772274541314267</guid><pubDate>Fri, 08 Jul 2011 17:02:00 +0000</pubDate><atom:updated>2011-07-08T18:02:00.881+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">WPF</category><category domain="http://www.blogger.com/atom/ns#">MEF</category><category domain="http://www.blogger.com/atom/ns#">screencast</category><title>Screencast: Modular WPF with MEF &amp; MVVM Tutorial Part 1</title><description>&lt;p&gt;A while ago I began to write a blog tutorial about how to create a modular WPF application using MVVM and &lt;a href="http://mef.codeplex.com/"&gt;MEF&lt;/a&gt;. I have decided to present it as a screencast instead, so here is the first part. It uses WPF, but a lot of the techniques I show apply equally well to Silverlight.&lt;/p&gt; &lt;p&gt;My approach is not to start off using MVVM and MEF (or any of the more fully featured WPF frameworks), but to introduce these libraries and design patterns at the point at which they make sense. Hopefully this will make it clearer why we might actually want to use them in the first place.&lt;/p&gt; &lt;p&gt;In this first video I create a very simple application with a menu allowing you to switch between two modules, and show how MEF enables us to work around violations of the “&lt;a href="http://en.wikipedia.org/wiki/Open/closed_principle"&gt;Open Closed Principle&lt;/a&gt;”.&lt;/p&gt;&lt;iframe height="300" src="http://player.vimeo.com/video/26149952?title=0&amp;amp;byline=0&amp;amp;portrait=0" frameborder="0" width="400"&gt;&lt;/iframe&gt; &lt;p&gt;I’ve got at least one more episode planned which hopefully will appear shortly and introduce MVVM to make our application more easily testable. If there is demand, I may also post my notes and upload my mercurial repository to bitbucket.&lt;/p&gt; &lt;p&gt;Another reason for presenting this as a screencast is that I am planning to create some &lt;a href="http://naudio.codeplex.com"&gt;NAudio&lt;/a&gt; screencasts in the future, and so I need to get some practice in. This one is a little raw as I didn’t do a practice beforehand, but I have tried to keep things flowing along at a reasonable pace. I also know the sound quality isn’t brilliant. Let me know if you think the resolution is acceptable. &lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6822536077160579260-7208772274541314267?l=mark-dot-net.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/markdotnet/~4/4-aOP-CW110" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/markdotnet/~3/4-aOP-CW110/screencast-modular-wpf-with-mef-mvvm.html</link><author>noreply@blogger.com (Mark H)</author><thr:total>7</thr:total><feedburner:origLink>http://mark-dot-net.blogspot.com/2011/07/screencast-modular-wpf-with-mef-mvvm.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6822536077160579260.post-5701080541314575753</guid><pubDate>Wed, 06 Jul 2011 21:36:00 +0000</pubDate><atom:updated>2011-07-06T22:36:54.204+01:00</atom:updated><title>One Language to Rule them All</title><description>&lt;p&gt;You may have heard the story of the “&lt;a href="http://www.biblegateway.com/passage/?search=Genesis+11%3A1-9&amp;amp;version=NIV"&gt;tower of Babel&lt;/a&gt;”. The story goes that one day, the people of the earth decided to build a great tower. It would be a monument to the greatness of humanity. But God objected to their pride and intervened to thwart their building program. His technique was not to strike the tower down with an earthquake, or strike the builders down with illness. Instead, he opted for a simple yet effective solution: he “confused the language” and the building project was soon abandoned. &lt;em&gt;Inability to communicate doomed the project to failure.&lt;/em&gt;&lt;/p&gt; &lt;p&gt;This ancient tale is a remarkably fitting parable for the state of modern programming. Even the smallest of miscommunications, such as requirements not properly understood, or two components in the system using different units of measure can cause the premature demise of entire software projects.&lt;/p&gt; &lt;p&gt;The analogy works on a wider scale too. Imagine what we as a software development community could build if we shared a common programming language. All the wastage of ‘porting’ libraries from one framework to another would be eliminated. Instead of reinventing the same development tools over and over for every new language, we could focus on genuine innovation.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;The Last Programming Language&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;And this is the point made by Robert C Martin at the NDC 2011 conference, in a fascinating talk entitled “&lt;a href="http://ndc2011.macsimum.no/SAL7/Onsdag/1020-1120.wmv"&gt;Clojure – The Last Programming Language&lt;/a&gt;”. &lt;/p&gt; &lt;p&gt;He begins by arguing that &lt;strong&gt;we’ve already fully explored the domain of programming languages&lt;/strong&gt;. In other words, we have experimented with all the &lt;em&gt;types &lt;/em&gt;of languages that there are. Or to put it another way, the new languages we keep inventing are just refinements or rearrangements of ideas from existing languages. It’s a slightly depressing thought in some ways – expect no new revolutionary paradigms – we’ve tried it all already.&lt;/p&gt; &lt;p&gt;Whether or not he is right about his first claim, his proposal for the development community to &lt;strong&gt;standardise on a single language &lt;/strong&gt;certainly grabbed my attention. Before dismissing it out of hand as a pipe dream, it is worth pondering the many benefits it would bring.&lt;/p&gt; &lt;ul&gt; &lt;li&gt;You would not need to hire a C#/Java/Ruby/C programmer. You’d just need to hire a programmer.  &lt;li&gt;All platforms and frameworks would be built in that language. No need for all this NUnit, JUnit, PyUnit, Runit business. We’d build on top of what had gone before instead of continually having to reinvent it for every new language. &lt;li&gt;Articles with example code would be immediately understandable to all developers&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;&lt;strong&gt;Can we agree on anything?&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;But could developers really agree on one programming language? The idea seems almost preposterous. Uncle Bob counters that other industries have gone through the same transition (e.g. biologists, chemists, medicine, mathematics). Eventually the benefits of a lingua franca win through despite the attachment people inevitably feel to their native tongue.&lt;/p&gt; &lt;p&gt;He also points out that this already happened once with C, which is one of those few languages that can genuinely be used to develop on almost every platform. This for me is the big sticking point in seeing Uncle Bob’s vision become a reality. The one language must be able to develop for every platform, server, client, embedded, handheld. It must be usable for every type of development – desktop apps, websites, games, services, device drivers, nuclear power stations. I’m not sure such a language exists.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Features of the final language&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;But let’s suspend disbelief for a moment and ask what features the final language should have. Uncle Bob’s wishlist included features such as:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;Not controlled by a corporation.  &lt;li&gt;Garbage collected. (I have mixed feelings on this one given .NET’s inability to do low latency audio well) &lt;li&gt;Polymorphic  &lt;li&gt;Runs on a virtual machine  &lt;li&gt;Able to modify itself at runtime like Ruby (homoiconic)  &lt;li&gt;Pared down syntax  &lt;li&gt;Functional  &lt;li&gt;Hybrid, i.e. Multi-paradigm (support, don’t enforce paradigms)  &lt;li&gt;Simple  &lt;li&gt;Provide access to existing frameworks  &lt;li&gt;Structured (no goto)  &lt;li&gt;Fast  &lt;li&gt;Textual  &lt;li&gt;Dynamically typed (the talk includes an interesting discussion on this).&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;His proposed language was &lt;a href="http://clojure.org/"&gt;Clojure&lt;/a&gt;. It seems an interesting enough language, although I can’t say I warm to all the parentheses. &lt;/p&gt; &lt;p&gt;&lt;strong&gt;A step in the right direction…&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;In any case, I think that if his vision were to become a reality, we would first have to pick a virtual machine. The two most obvious candidates are the &lt;a href="http://en.wikipedia.org/wiki/Java_Virtual_Machine"&gt;JVM&lt;/a&gt; and the &lt;a href="http://en.wikipedia.org/wiki/Common_Language_Runtime"&gt;CLR&lt;/a&gt;, both of which now support a whole host of languages (Clojure can run on either). The CLR may even have the upper hand due to products like &lt;a href="http://www.mono-project.com/Main_Page"&gt;Mono&lt;/a&gt; which makes it a genuine open source option and available on a very broad range of platforms, although I suspect its ties with Microsoft would generate a lot of resistance. &lt;/p&gt; &lt;p&gt;Libraries that are compiled for a virtual machine like the CLR effectively appear as native libraries for all languages that compile to the same byte code, meaning that there is at least some reduction in the amount of reinvention and relearning required when you switch languages – the libraries can come with you even if the language syntax doesn’t. Another benefit is that often the byte code for a VM can be translated into other languages by a tool, allowing at least some level of automated translation between languages. Maybe someone could invent a browser plugin that automatically converts any code you view in a web-page into the language of your choice – a kind of Google translate for programming languages.&lt;/p&gt; &lt;p&gt;What do you think? Could we agree on a virtual machine, and then get to work on picking a smaller subset of languages to program it with? Or is Uncle Bob’s idea a pipedream? Will we ever get to one common language or will God step in and mix it all up again, just to keep us humble.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6822536077160579260-5701080541314575753?l=mark-dot-net.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/markdotnet/~4/dcWvWZmIGJE" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/markdotnet/~3/dcWvWZmIGJE/one-language-to-rule-them-all.html</link><author>noreply@blogger.com (Mark H)</author><thr:total>1</thr:total><feedburner:origLink>http://mark-dot-net.blogspot.com/2011/07/one-language-to-rule-them-all.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6822536077160579260.post-884964089854856573</guid><pubDate>Tue, 05 Jul 2011 21:04:00 +0000</pubDate><atom:updated>2011-07-05T22:04:58.303+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Threading</category><category domain="http://www.blogger.com/atom/ns#">unit testing</category><title>Test Resistant Code #5–Threading</title><description>&lt;p&gt;I want to wrap up my test-resistant code series with one final type of code that proves hard to test, and that is multi-threaded code. We’ll just consider two scenarios, one that proves easy to test, another that proves very complex.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Separate out thread creation&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;A common mistake is to include the code that creates a thread (or queues a background worker) in the same class that contains the code for the actual work to be performed by the thread. This is a violation of “separation of concerns” In the following trivial example, the function we really need to unit test, &lt;strong&gt;DoStuff&lt;/strong&gt;, is private, and the public interface is not helpful for unit testing.&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;public void BeginDoStuff()
{
    ThreadPool.QueueUserWorkItem((o) =&amp;gt; DoStuff("hello world"));
}

private void DoStuff(string message)
{
    Console.WriteLine(message);
}&lt;/pre&gt;
&lt;p&gt;Fixing this is not hard. We separate the concerns by making the DoStuff method a public member of a different class, leaving the original class simply to manage the asynchronous calling and reporting of results (which you may find can be refactored into a more &lt;a href="http://mark-dot-net.blogspot.com/2008/09/don-repeat-your-threading-code.html"&gt;generic threading helper class&lt;/a&gt;).&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Locks and race conditions&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;But what about locking? Consider a very simple circular buffer class I wrote for NAudio. In the normal use case, one thread writes bytes to it while another reads from it. Here’s the current code for the Read and Write methods (which I’m sure could be refactored down to something much shorter):&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;/// &amp;lt;summary&amp;gt;
/// Write data to the buffer
/// &amp;lt;/summary&amp;gt;
/// &amp;lt;param name="data"&amp;gt;Data to write&amp;lt;/param&amp;gt;
/// &amp;lt;param name="offset"&amp;gt;Offset into data&amp;lt;/param&amp;gt;
/// &amp;lt;param name="count"&amp;gt;Number of bytes to write&amp;lt;/param&amp;gt;
/// &amp;lt;returns&amp;gt;number of bytes written&amp;lt;/returns&amp;gt;
public int Write(byte[] data, int offset, int count)
{
    lock (lockObject)
    {
        int bytesWritten = 0;
        if (count &amp;gt; buffer.Length - this.byteCount)
        {
            count = buffer.Length - this.byteCount;
        }
        // write to end
        int writeToEnd = Math.Min(buffer.Length - writePosition, count);
        Array.Copy(data, offset, buffer, writePosition, writeToEnd);
        writePosition += writeToEnd;
        writePosition %= buffer.Length;
        bytesWritten += writeToEnd;
        if (bytesWritten &amp;lt; count)
        {
            // must have wrapped round. Write to start
            Array.Copy(data, offset + bytesWritten, buffer, writePosition, count - bytesWritten);
            writePosition += (count - bytesWritten);
            bytesWritten = count;
        }
        this.byteCount += bytesWritten;
        return bytesWritten;
    }
}

/// &amp;lt;summary&amp;gt;
/// Read from the buffer
/// &amp;lt;/summary&amp;gt;
/// &amp;lt;param name="data"&amp;gt;Buffer to read into&amp;lt;/param&amp;gt;
/// &amp;lt;param name="offset"&amp;gt;Offset into read buffer&amp;lt;/param&amp;gt;
/// &amp;lt;param name="count"&amp;gt;Bytes to read&amp;lt;/param&amp;gt;
/// &amp;lt;returns&amp;gt;Number of bytes actually read&amp;lt;/returns&amp;gt;
public int Read(byte[] data, int offset, int count)
{
    lock (lockObject)
    {
        if (count &amp;gt; byteCount)
        {
            count = byteCount;
        }
        int bytesRead = 0;
        int readToEnd = Math.Min(buffer.Length - readPosition, count);
        Array.Copy(buffer, readPosition, data, offset, readToEnd);
        bytesRead += readToEnd;
        readPosition += readToEnd;
        readPosition %= buffer.Length;

        if (bytesRead &amp;lt; count)
        {
            // must have wrapped round. Read from start
            Array.Copy(buffer, readPosition, data, offset + bytesRead, count - bytesRead);
            readPosition += (count - bytesRead);
            bytesRead = count;
        }

        byteCount -= bytesRead;
        return bytesRead;
    }
}
&lt;/pre&gt;
&lt;p&gt;The fact that I take a lock for the entirety of both methods makes me confident that the internal state will not get corrupted by one thread calling Write while another calls Read; the threads simply have to take it in turns. But what if I had a clever idea for optimising this code that only involved me locking for part of the time. Maybe I want to do the Array.Copy’s outside the lock since they potentially take the longest. How could I write a unit test that ensured my code remained thread-safe?&lt;/p&gt;
&lt;p&gt;Short of firing up two threads reading and writing with random sleep times inserted here and there, I’m not sure I know how best to prove the correctness of this type of code. Locking issues and race conditions can be some of the hardest to track down bugs. I once spent a couple of weeks locating a bug that only manifest itself on a dual processor system (back in the days when those were few and far between). The code had been thoroughly reviewed by all the top developers at the company and yet no one saw the problem.&lt;/p&gt;
&lt;p&gt;Here’s another example, based on some code I saw in a product I worked on. A method kicks off two threads to do some long-running tasks and attempts to fire a finished event when both have completed. We want to ensure that the SetupFinished event always fires, and only fires once. You might be able to spot a race condition by examining the code, but how would we write a unit test to prove we had fixed it?&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;private volatile bool eventHasBeenRaised;

public void Init()
{    
    ThreadPool.QueueUserWorkItem((o) =&amp;gt; Setup1());
    ThreadPool.QueueUserWorkItem((o) =&amp;gt; Setup2());    
}

private void Setup1()
{
    Thread.Sleep(500);
    RaiseSetupFinishedEvent();
}

private void Setup2()
{
    Thread.Sleep(500);
    RaiseSetupFinishedEvent();
}

private void RaiseSetupFinishedEvent()
{
    if (!eventHasBeenRaised)
    {
        eventHasBeenRaised = true;
        SetupFinished(this, EventArgs.Empty);
    }
}&lt;/pre&gt;
&lt;p&gt;The only tool for .NET I have heard of that might begin to address this shortcoming is &lt;a href="http://research.microsoft.com/en-us/projects/chess/"&gt;Microsoft CHESS&lt;/a&gt;. It seems a very promising tool although it seems to have stalled somewhat – the only integration is with VS2008; VS2010 is not supported. I’d love to hear of other tools or clever techniques for unit testing multi-threaded code effectively. I haven’t delved too much into the C# 5 async stuff yet, but I’d be interested to know how well it plays with unit tests.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6822536077160579260-884964089854856573?l=mark-dot-net.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/markdotnet/~4/32E3XTJO60o" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/markdotnet/~3/32E3XTJO60o/test-resistant-code-5threading.html</link><author>noreply@blogger.com (Mark H)</author><thr:total>0</thr:total><feedburner:origLink>http://mark-dot-net.blogspot.com/2011/07/test-resistant-code-5threading.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6822536077160579260.post-8838148806228391866</guid><pubDate>Mon, 04 Jul 2011 16:31:00 +0000</pubDate><atom:updated>2011-07-04T17:31:34.908+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">TFS</category><title>Visualizing TFS Repositories with Gource</title><description>&lt;p&gt;I recently came across the &lt;a href="http://code.google.com/p/gource/"&gt;gource&lt;/a&gt; project, which creates stunning visualizations of your source control history. It doesn’t include built-in support for TFS repositories, but its custom log file format makes it quite simple to work with.&lt;/p&gt; &lt;p&gt;Since the project I worked on recently hit 1,000,000 lines of code (yes, I know that means it needs to be mercilessly refactored), I thought I would create a gource visualization. My example code below has a regular expression to allow me to filter out the bits in source control I am interested in. It also deals with the fact that we imported our solution from SourceSafe, so it needs to get the real commit dates for early items out of the comments.&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;public void CreateGourceLogFile(string outputFile)
{
    TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri("http://mytfsserver:8080/"));
    tpc.EnsureAuthenticated();
    VersionControlServer vcs = tpc.GetService&amp;lt;VersionControlServer&amp;gt;();
    int latestChangesetId = vcs.GetLatestChangesetId();
    Regex regex = new Regex(sourceFileRegex); // optional - a regular expression to match source files you want to include in the gource visualisation
    Regex sourceSafeImportComment = new Regex(@"^\{\d\d/\d\d/\d\d\d\d \d\d:\d\d:\d\d\}");
    int lines = 0;
    using (var writer = new StreamWriter(outputFile))
    {
        for (int changesetId = 1; changesetId &amp;lt; latestChangesetId; changesetId++)
        {
            var changeset = vcs.GetChangeset(changesetId);
            var devEdits = from change in changeset.Changes
                           where
                           ((change.ChangeType &amp;amp; ChangeType.Edit) == ChangeType.Edit
                           || (change.ChangeType &amp;amp; ChangeType.Add) == ChangeType.Add
                           || (change.ChangeType &amp;amp; ChangeType.Delete) == ChangeType.Delete)
                           &amp;amp;&amp;amp; regex.IsMatch(change.Item.ServerItem)
                           select change;
            foreach (var change in devEdits)
            {
                DateTime creationDate = changeset.CreationDate;
                var commentMatch = sourceSafeImportComment.Match(changeset.Comment);
                if (commentMatch.Success)
                {
                    creationDate = DateTime.ParseExact(commentMatch.Value,"{dd/MM/yyyy HH:mm:ss}", CultureInfo.InvariantCulture);
                }

                int unixTime = (int)(creationDate - new DateTime(1970, 1, 1)).TotalSeconds;
                writer.WriteLine("{0}|{1}|{2}|{3}", unixTime, changeset.Committer,
                    GetChangeType(change.ChangeType), change.Item.ServerItem);
            }
        }
    }
}

private string GetChangeType(ChangeType changeType)
{
    if ((changeType &amp;amp; ChangeType.Edit) == ChangeType.Edit)
    {
        return "M";
    }
    if ((changeType &amp;amp; ChangeType.Add) == ChangeType.Add)
    {
        return "A";
    }
    if ((changeType &amp;amp; ChangeType.Delete) == ChangeType.Delete)
    {
        return "D";
    }
    throw new ArgumentException("Unsupported change type");
}
&lt;/pre&gt;
&lt;p&gt;Once you have your log file created, just run gource to see an amazing replay of the history of your project:&lt;/p&gt;&lt;pre&gt;
gource custom.log

&lt;font face="Arial"&gt;Here’s a screenshot:&lt;/font&gt;&lt;/pre&gt;&lt;pre&gt;&lt;a href="http://lh5.ggpht.com/-n4ZhYgjTfI4/ThHq33PUyGI/AAAAAAAAAr4/3ipI7F7R354/s1600-h/image%25255B6%25255D.png"&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Gource screenshot" border="0" alt="Gource screenshot" src="http://lh6.ggpht.com/-JdcK4wFidbY/ThHq5tQyBPI/AAAAAAAAAr8/vNHOm_XCYxA/image_thumb%25255B4%25255D.png?imgmax=800" width="622" height="484"&gt;&lt;/a&gt; &lt;/pre&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6822536077160579260-8838148806228391866?l=mark-dot-net.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/markdotnet/~4/dy86aFc9PEw" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/markdotnet/~3/dy86aFc9PEw/visualizing-tfs-repositories-with.html</link><author>noreply@blogger.com (Mark H)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://lh6.ggpht.com/-JdcK4wFidbY/ThHq5tQyBPI/AAAAAAAAAr8/vNHOm_XCYxA/s72-c/image_thumb%25255B4%25255D.png?imgmax=800" height="72" width="72" /><thr:total>1</thr:total><feedburner:origLink>http://mark-dot-net.blogspot.com/2011/07/visualizing-tfs-repositories-with.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6822536077160579260.post-529296708900335867</guid><pubDate>Sun, 03 Jul 2011 16:47:00 +0000</pubDate><atom:updated>2011-07-03T17:47:54.109+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Silverlight</category><title>Silverlight Music Rating App for KVR One Synth Challenge</title><description>&lt;p&gt;After &lt;a href="http://www.spotify.com"&gt;Spotify&lt;/a&gt; announced that you only got 10 hours free listening a month, I went in search of some new and interesting sources of music, and one of the things I stumbled across was the monthly &lt;a href="http://sites.google.com/site/kvrosc/"&gt;KVR One Synth Challenge&lt;/a&gt;. Basically the idea is that you have to create an entire track using a single freeware virtual instrument – a different one each month. Despite this limitation, the quality of submissions is consistently impressive.&lt;/p&gt; &lt;p&gt;Voting is done by the community – you have to list your top five tracks. Each month I would download all the tracks and gradually eliminate them from a playlist, making notes on what I liked about each one as I went. This made me wonder if I could create a simple rating tool in Silverlight to help me do this – storing my comments and ratings, and allowing me to easily eliminate tracks from my shortlist.&lt;/p&gt; &lt;p&gt;So I created a simple application called “&lt;a href="https://bitbucket.org/markheath/musicrater"&gt;MusicRater&lt;/a&gt;”. At the moment the paths for each KVR OSC contest are hard-coded and I update it each month to point to the new one, but I have plans to make it more configurable in the future. The application makes use of my &lt;a href="http://mark-dot-net.blogspot.com/2011/06/silverlight-star-rating-control.html"&gt;Silverlight star rating control&lt;/a&gt;.&lt;/p&gt; &lt;p&gt;Here’s a screenshot:&lt;/p&gt; &lt;p&gt;&lt;a href="http://lh3.ggpht.com/-jlKuCi2szMU/ThCdNTRlTPI/AAAAAAAAAko/AXVngeXlcb4/s1600-h/MusicRater%25255B3%25255D.png"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="MusicRater" border="0" alt="MusicRater" src="http://lh6.ggpht.com/-QJInZDio9dM/ThCdOP1xQeI/AAAAAAAAAks/Xb_xvWz03-I/MusicRater_thumb%25255B1%25255D.png?imgmax=800" width="505" height="493"&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;You can try it out &lt;a href="http://www.wordandspirit.co.uk/software/MusicRaterTestPage.html"&gt;here&lt;/a&gt;, and install it as an out of browser app if that is convenient for you. As of the time of posting, the version at this address is set up to return the tracks for &lt;a href="http://sites.google.com/site/kvrosc/osc-29"&gt;OSC 29&lt;/a&gt;, which uses a synth called &lt;a href="http://www.ugoaudio.com/"&gt;String Theory&lt;/a&gt;, which poses an interesting challenge to the contestants since it is a physical modelling synth. If you enjoy listening, make sure you head over to the &lt;a href="http://www.kvraudio.com/forum/viewtopic.php?t=322473"&gt;voting thread&lt;/a&gt; and cast your votes.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6822536077160579260-529296708900335867?l=mark-dot-net.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/markdotnet/~4/mgfJVUuiS1M" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/markdotnet/~3/mgfJVUuiS1M/silverlight-music-rating-app-for-kvr.html</link><author>noreply@blogger.com (Mark H)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://lh6.ggpht.com/-QJInZDio9dM/ThCdOP1xQeI/AAAAAAAAAks/Xb_xvWz03-I/s72-c/MusicRater_thumb%25255B1%25255D.png?imgmax=800" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://mark-dot-net.blogspot.com/2011/07/silverlight-music-rating-app-for-kvr.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6822536077160579260.post-7285121125821495604</guid><pubDate>Sat, 02 Jul 2011 08:31:00 +0000</pubDate><atom:updated>2011-07-02T09:31:01.693+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">kata</category><category domain="http://www.blogger.com/atom/ns#">IronPython</category><category domain="http://www.blogger.com/atom/ns#">Python</category><title>Yahtzee Kata in IronPython</title><description>&lt;p&gt;I did another simple kata in &lt;a href="http://ironpython.net/"&gt;IronPython&lt;/a&gt; recently, to refresh my memory since I haven’t done much with Python recently. I used my &lt;a href="http://mark-dot-net.blogspot.com/2010/09/autotest-for-ironpython.html"&gt;AutoTest for IronPython&lt;/a&gt; utility again, and again found myself wanting to invent an equivalent of NUnit’s [TestCase] attribute for Python. The kata is to implement the &lt;a href="http://en.wikipedia.org/wiki/Yahtzee"&gt;Yahtzee&lt;/a&gt; scoring rules, although the &lt;a href="http://codingdojo.org/cgi-bin/wiki.pl?KataYahtzee"&gt;specific instructions&lt;/a&gt; I followed describe a different scoring scheme than the most familiar one (seems to be a Scandinavian version). &lt;/p&gt;&lt;pre class="brush: py;"&gt;import unittest

#helpers
def Count(dice, number):
    return len([y for y in dice if y == number])

def HighestRepeated(dice, minRepeats):
    unique = set(dice)
    repeats = [x for x in unique if Count(dice, x) &amp;gt;= minRepeats]
    return max(repeats) if repeats else 0

def OfAKind(dice, n):
    return HighestRepeated(dice,n) * n

def SumOfSingle(dice, selected):
    return sum([x for x in dice if x == selected])

#strategies
def Chance(dice):
    return sum(dice)

def Pair(dice):
    return OfAKind(dice, 2)

def ThreeOfAKind(dice):
    return OfAKind(dice, 3)

def FourOfAKind(dice):
    return OfAKind(dice, 4)
    
def SmallStraight(dice):
    return 15 if tuple(sorted(dice)) == (1,2,3,4,5) else 0

def LargeStraight(dice):
    return 20 if tuple(sorted(dice)) == (2,3,4,5,6) else 0

def Ones(dice):
    return SumOfSingle(dice,1)

def Twos(dice):
    return SumOfSingle(dice,2)

def Threes(dice):
    return SumOfSingle(dice,3)

def Fours(dice):
    return SumOfSingle(dice,4)

def Fives(dice):
    return SumOfSingle(dice,5)

def Sixes(dice):
    return SumOfSingle(dice,6)

def Yahtzee(dice):
    return 50 if len(dice) == 5 and len(set(dice)) == 1 else 0

class YahtzeeTest(unittest.TestCase):
    testCases = (
        ((1,2,3,4,5), 1, Ones),
        ((1,2,3,4,5), 2, Twos),
        ((3,2,3,4,3), 9, Threes),
        ((3,2,3,4,3), 0, Sixes),
        ((1,2,3,4,5), 0, Pair), # no pairs found
        ((1,5,3,4,5), 10, Pair), # one pair found
        ((2,2,6,6,4), 12, Pair), # picks highest
        ((2,3,1,3,3), 6, Pair), # only counts two
        ((2,2,6,6,6), 18, ThreeOfAKind), 
        ((2,2,4,6,6), 0, ThreeOfAKind), # no threes found
        ((5,5,5,5,5), 15, ThreeOfAKind), # only counts three
        ((6,2,6,6,6), 24, FourOfAKind), 
        ((2,6,4,6,6), 0, FourOfAKind), # no fours found
        ((5,5,5,5,5), 20, FourOfAKind), # only counts four
        ((1,2,5,4,3), 15, SmallStraight),
        ((1,2,5,1,3), 0, SmallStraight),
        ((6,2,5,4,3), 20, LargeStraight),
        ((1,2,5,1,3), 0, LargeStraight),
        ((5,5,5,5,5), 50, Yahtzee),
        ((1,5,5,5,5), 0, Yahtzee), 
        ((1,2,3,4,5), 15, Chance),
        )

    def testRunAll(self):
        for (dice, expected, strategy) in self.testCases:
            score = strategy(dice)
            self.assertEquals(expected, score, "got {0} expected {1}, testing with {2} on {3}".format(score, expected, strategy.__name__, dice))
        print 'ran {0} test cases'.format(len(self.testCases))
        
if __name__ == '__main__':
    unittest.main()
&lt;/pre&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6822536077160579260-7285121125821495604?l=mark-dot-net.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/markdotnet/~4/VSFjceXBqj0" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/markdotnet/~3/VSFjceXBqj0/yahtzee-kata-in-ironpython.html</link><author>noreply@blogger.com (Mark H)</author><thr:total>0</thr:total><feedburner:origLink>http://mark-dot-net.blogspot.com/2011/07/yahtzee-kata-in-ironpython.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6822536077160579260.post-8396929992581961230</guid><pubDate>Fri, 01 Jul 2011 19:48:00 +0000</pubDate><atom:updated>2011-07-02T07:54:05.747+01:00</atom:updated><title>Blogger Users Beware - Google+ Can Delete Your Blog Images</title><description>&lt;p&gt;I was given an invite to Google+ today. I thought it would be interesting to see what the fuss is about, so I signed up. It asked me if I wanted to import any pictures from Picasa. I didn’t think I had any pictures on there – I certainly never visit the site, but I clicked yes anyway just in case there was some stuff I had forgotten about on there. And indeed there was. It imported a couple of random photos I had taken of door hinges to email to my dad, plus a whole bunch of screenshots.&lt;/p&gt;
&lt;p&gt;Obviously, that’s not the kind of stuff I want on my Google+ profile, so I deleted the photo albums from my profile page. What I hadn’t realised is that Picassa was where Windows Live Writer had been storing all the images for this blog. And instead of just deleting the albums from my Google+ profile, it also deleted them from Picassa. Not into some kind of recycle bin. Deleted permanently.&lt;/p&gt;
&lt;p&gt;Clearly Google have committed a cardinal sin of user interface design – don’t make it easy to accidentally and irrevocably delete all your data. And the data stored on Picassa should only be deleteable from Picassa, not from another completely separate website, even if it is run by the same company.&lt;/p&gt;
&lt;p&gt;They have also committed the cardinal sin of customer support – utter unresponsiveness. I guess they can get away with this because they are so big and I’m not paying them any money. Even if they can’t recover my data, a response of some kind would be nice. I’ve already come across several other people who’ve done similar things, leaving blogs that have been running several years completely broken.&lt;/p&gt;
&lt;p&gt;&lt;b&gt;Update:&lt;/b&gt; they have now responded to say:&lt;/p&gt;
&lt;blockquote&gt;
 Our team can't undelete your photos, but we'll make it clearer that your
 Picasa photos themselves are displayed on Google+ and not copied. It's 
the same backend, so photos you upload in Picasa are visible from 
Google+, and vice versa.&lt;/blockquote&gt;
&lt;p&gt;The upshot of that is that this blog is missing all its screenshots and diagrams, almost 100 of them. Some of them I might be able to recover from my PC, although my usual way of taking screenshots and adding them through Windows Live Writer only involves the clipboard so there is no physical file on my machine that I can use to recover the images with. I can only apologise, particularly if you came here to read the NAudio documentation, only to find it missing its architecture diagrams.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6822536077160579260-8396929992581961230?l=mark-dot-net.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/markdotnet/~4/kJcDy28TDoo" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/markdotnet/~3/kJcDy28TDoo/blogger-users-beware-google-can-delete.html</link><author>noreply@blogger.com (Mark H)</author><thr:total>2</thr:total><feedburner:origLink>http://mark-dot-net.blogspot.com/2011/07/blogger-users-beware-google-can-delete.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6822536077160579260.post-2951461746933745086</guid><pubDate>Thu, 30 Jun 2011 22:28:00 +0000</pubDate><atom:updated>2011-06-30T23:28:00.870+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">unit testing</category><category domain="http://www.blogger.com/atom/ns#">TDD</category><title>Test-Resistant Code #4–Third Party Frameworks</title><description>&lt;p&gt;This one might seem like a repeat of my &lt;a href="http://mark-dot-net.blogspot.com/2011/06/test-resistant-code-and-battle-for-tdd.html"&gt;first post&lt;/a&gt; in this series, where I talked about dependencies being the biggest barrier to unit testing, and the challenge of creating abstraction layers for everything just to make things testable. However, even if we manage to isolate our third party framework entirely behind an abstraction layer, it still doesn’t eliminate a few conundrums when it comes to actually testing what we have done. I’ll just focus on two example scenarios:&lt;/p&gt; &lt;h3&gt;Magic Invocations&lt;/h3&gt; &lt;p&gt;Writing code that consumes a third party API can be one of the most difficult developer experiences. You write the code you think &lt;em&gt;ought &lt;/em&gt;to work, based on the somewhat unreliable documentation, and it fails with some bizarre error. You then spend the next few days trying every possible combination of parameters, ordering of method calls, and scouring the web for any help you can get. Eventually you stumble across the “magic invocation” – the perfect combination of method calls and parameters that makes it work. You might have no clue why, but you are just relieved to be finally done with this part of the development experience, and ready to move onto something else.&lt;/p&gt; &lt;p&gt;As an example, consider this code I wrote once that attempts to find set the recording level for a given sound card input. It’s pretty hacky stuff, with a different codepath for different versions of Windows. It “works on my machine”, but I’m sure there are some systems on which it does the wrong thing.&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;private void TryGetVolumeControl()
{
    int waveInDeviceNumber = waveIn.DeviceNumber;
    if (Environment.OSVersion.Version.Major &amp;gt;= 6) // Vista and over
    {
        var mixerLine = waveIn.GetMixerLine();
        //new MixerLine((IntPtr)waveInDeviceNumber, 0, MixerFlags.WaveIn);
        foreach (var control in mixerLine.Controls)
        {
            if (control.ControlType == MixerControlType.Volume)
            {
                this.volumeControl = control as UnsignedMixerControl;
                MicrophoneLevel = desiredVolume;
                break;
            }
        }
    }
    else
    {
        var mixer = new Mixer(waveInDeviceNumber);
        foreach (var destination in mixer.Destinations)
        {
            if (destination.ComponentType == MixerLineComponentType.DestinationWaveIn)
            {
                foreach (var source in destination.Sources)
                {
                    if (source.ComponentType == MixerLineComponentType.SourceMicrophone)
                    {
                        foreach (var control in source.Controls)
                        {
                            if (control.ControlType == MixerControlType.Volume)
                            {
                                volumeControl = control as UnsignedMixerControl;
                                MicrophoneLevel = desiredVolume;
                                break;
                            }
                        }
                    }
                }
            }
        }
    }
}&lt;/pre&gt;
&lt;p&gt;Having finally made this wretched thing work, does it matter whether I have any “unit tests” for it or not? I could write an “integration test” for this code which actually opens an audio device for recording and attempts to set the microphone level. But to know whether it worked or not would not be automatically verifiable. You would have to manually examine the recorded audio to see if the volume had been adjusted.&lt;/p&gt;
&lt;p&gt;What about real “unit tests”? Is it possible to unit test this? Well in one sense, yes. I could wrap an abstraction layer around all the third party framework calls and the operating system version checking. Then I could test that my foreach loops are indeed picking out the “mixer control” I think they should in both cases, and that the desired level was set on that control.&lt;/p&gt;
&lt;p&gt;But supposing I did write that unit test. What would it prove? It would prove little more than my code does what it does. It doesn’t prove that it does the right thing. The best it can do is demonstrate that the behaviour that I know “works on my machine”, is still working. In other words I could create mocks that return data that mimics my own soundcard’s controls and ensure that the algorithm always picks the same mixer control for that particular test case.&lt;/p&gt;
&lt;p&gt;However, I this that this sort of testing fails the cost-benefit analysis. It requires a lot of abstraction layers to be created just for the purpose of creating a test that has dubious value. Tests should verify that requirements are being met, not check up on &lt;em&gt;how &lt;/em&gt;they are implemented.&lt;/p&gt;
&lt;h3&gt;Writing Plugins&lt;/h3&gt;
&lt;p&gt;Another common scenario is when you are writing code that will be called by a third party framework – as a plugin of sorts. In this case, you are often inheriting from a base class. The public interface has already been decided for you, for better or worse. Also, depending on the framework, you may not be entirely sure what the possible inputs to your overridden functions might be, or in what order they might be called.&lt;/p&gt;
&lt;p&gt;The approach I tend to take here is to put as little code in the derived class as possible. Instead it calls out into my own, more testable classes. This works quite well, and leaves you with the choice of how much effort you want to go to to test the derived plugin class itself, which may be best left to a proper integration test with the real system.&lt;/p&gt;
&lt;p&gt;One place this approach doesn’t work well for me is with my own framework, NAudio. In NAudio, you often create small classes that inherit from IWaveProvider or WaveStream. These return audio out of a Read method in a byte array, which is great for the soundcard, but not at all friendly for writing unit tests against. I could again move my logic out into a separate, testable class, but this doubles my number of classes and reduces performance (which is a very important consideration in streaming audio). Add to that that audio effects and processors tend to be hard to automatically verify, and I wonder whether this is another case where the effort to write &lt;em&gt;everything&lt;/em&gt; in a strictly TDD manner doesn’t really pay off.&lt;/p&gt;
&lt;p&gt;Anyway, I’m nearly at the end of this series now. Just one more form of test-resistant code left to discuss, before I move on to share some ideas I’ve had on how to better automate the testing of some of this code.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6822536077160579260-2951461746933745086?l=mark-dot-net.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/markdotnet/~4/7A-ZJBqt1YU" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/markdotnet/~3/7A-ZJBqt1YU/test-resistant-code-4third-party.html</link><author>noreply@blogger.com (Mark H)</author><thr:total>0</thr:total><feedburner:origLink>http://mark-dot-net.blogspot.com/2011/06/test-resistant-code-4third-party.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6822536077160579260.post-6876647239168453910</guid><pubDate>Wed, 29 Jun 2011 22:11:00 +0000</pubDate><atom:updated>2011-06-29T23:11:58.062+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">unit testing</category><category domain="http://www.blogger.com/atom/ns#">TDD</category><title>Test-Resistant Code #3–Algorithms</title><description>&lt;p&gt;&lt;em&gt;This is the third part in a mini-series on code that is hard to test (and therefore hard to develop using TDD). &lt;/em&gt;Part 1: &lt;a href="http://mark-dot-net.blogspot.com/2011/06/test-resistant-code-and-battle-for-tdd.html"&gt;Test-Resistant Code and the battle for TDD&lt;/a&gt;, Part 2: &lt;a href="http://mark-dot-net.blogspot.com/2011/06/test-resistant-code-2markup-is-code-too.html"&gt;Test-Resistant Code – Markup is Code Too&lt;/a&gt;&lt;/p&gt; &lt;p&gt;You may have seen Uncle Bob solve the prime factors kata using TDD. It is a great demonstration of the power of TDD to allow you to think through an algorithm in small steps. In a recent talk at NDC2011 entitled, “The Transformation Priority Premise” he gave some guidelines to help prevent creating bad algorithms. In other words, following the right rules you can use TDD to make quick sort, instead of bubble sort (I tried this briefly and failed miserably). It seems likely that all sorts of algorithms can be teased out with TDD (although I did read of someone trying to create a Sudoku solver this way and finding it got them nowhere).&lt;/p&gt; &lt;p&gt;However suitable or not TDD is for tackling those three problems (prime factors, list sorting, sudoku), they share one common attribute: they are easily &lt;em&gt;verifiable &lt;/em&gt;algorithms. I know the expected outputs for all my test cases.&lt;/p&gt; &lt;p&gt;Not all algorithms are like that – we don’t always know what the correct output is. And as clever as the transformation priority premise might be for iterating towards optimal algorithms, I am not convinced that it is an appropriate attack vector for many of the algorithms we typically require in real-world projects. Let me explain with a few simple examples of algorithms I have needed for various projects.&lt;/p&gt; &lt;h3&gt;Example 1 – Shuffle&lt;/h3&gt; &lt;p&gt;My first example is a really basic one. I needed to shuffle a list. Can this be done with TDD? The first two cases are easy enough – we know what the result should be if we shuffle an empty list, or shuffle a list containing one item. But when I shuffle a list with two items, what should happen? Maybe I could have a unit test that kept going until it got both possibilities. I could even shuffle my list of two items 100 times and check that the number of times I got each combination was within a couple of standard deviations of the expected answer of 50. Then when I pass my list of three items in, I can do the same again, checking that all 6 possible results can occur, followed by more tests checking that the distribution of shuffles is evenly spread.&lt;/p&gt; &lt;p&gt;So it &lt;em&gt;is &lt;/em&gt;TDDable then. But really, is that a sensible way to approach a task like this? The statistical analysis required to prove the algorithm requires more development effort than writing the algorithm in the first place.&lt;/p&gt; &lt;p&gt;But there is a deeper problem. Most sensible programmers know that the best approach to this type of problem is to use someone else’s solution. There’s a &lt;a href="http://stackoverflow.com/questions/1287567/c-is-using-random-and-orderby-a-good-shuffle-algorithm"&gt;great answer on stackoverflow&lt;/a&gt; that I used. But that violates the principles of TDD: instead of writing small bits of code to pass simple tests, I jumped straight to the solution. Now we have a chunk of code that doesn’t have unit tests. Should we retro-fit them? We’ll come back to that.&lt;/p&gt; &lt;h3&gt;Example 2 – Low Pass Filter&lt;/h3&gt; &lt;p&gt;Here’s another real-world example. I needed a low pass filter that could cut all audio frequencies above 4kHz out of an audio file sampled at 16kHz. The ideal low pass filter has unity gain for all frequencies below the cut-off frequency, and completely removes all frequencies above. The only trouble is, such a filter is impossible to create – you have to compromise.&lt;/p&gt; &lt;p&gt;A bit of research revealed that I probably wanted a Chebyshev filter with a low pass-band ripple and a fairly steep roll-off of 18dB per octave or more. Now, can TDD help me out making this thing? Not really. First of all, it’s even harder than the shuffle algorithm to verify in code. I’d need to make various signal generators such as sine wave and white noise generators, and then create Fast Fourier Transforms to measure the frequencies of audio that had been passed through the filter. Again, far more work than actually creating the filter.&lt;/p&gt; &lt;p&gt;But again, what is the sane approach to a problem like this? It is to port someone else’s solution (in my case I found some C code I could use) and then perform &lt;em&gt;manual &lt;/em&gt;testing to prove the correctness of the code.&lt;/p&gt; &lt;h3&gt;Example 3 – Fixture Scheduler&lt;/h3&gt; &lt;p&gt;My third example is of an algorithm I have attempted a few times. It is to generate fixture lists. In many sports leagues, each team must play each other team twice a season – once home, once away. Ideally each team should normally alternate between playing at home and then away. Two home or away games in a row is OK from time to time, three is bad, and four in a row is not acceptable. In addition it is best if the two games between the same teams are separated by at least a month or two. Finally, there may be some additional constraints. Arsenal and Tottenham cannot both play at home in the same week. Same for Liverpool and Everton, and for Man Utd and Man City.&lt;/p&gt; &lt;p&gt;What you end up with is a problem that has multiple &lt;em&gt;valid &lt;/em&gt;solutions, but not all solutions are equally good. For example, it would not go down too well if one team’s fixtures went HAHAHAHA while another’s went HHAAHHAAHHAA.&lt;/p&gt; &lt;p&gt;So we could (and should) certainly write unit tests that check that the generated fixtures meet the requirements without breaking any of the constraints. But fine tuning this algorithm is likely to at least be a partially manual process, as we tweak various aspects of it and then compare results to see if we have improved things or not. In fact, I can imagine the final solution to this containing some randomness, and you might run the fixture generator a few times, assigning a “score” to each solution and pick the best.&lt;/p&gt; &lt;h3&gt;Should you use TDD for algorithms?&lt;/h3&gt; &lt;p&gt;When you can borrow a ready-made and reliable algorithm, then retro-fitting a comprehensive unit test suite to it may actually be a waste of time better spent elsewhere. &lt;/p&gt; &lt;p&gt;Having said that, if you &lt;em&gt;can&lt;/em&gt; write unit tests for an algorithm you need to develop yourself, then do so. One of TDD’s key benefits is simply that of helping you come up with a good public API, so even if you can’t work out how to thoroughly validate the output, it can still help you design the interface better. Of course, a test without an assert isn’t usually much of a test at all, it’s more like a code sample. But at the very least running it assures that it doesn’t crash, and there is usually &lt;em&gt;something&lt;/em&gt; you can check about its output. For example, the filtered audio should be the same duration as the input, and not be entirely silent.&lt;/p&gt; &lt;p&gt;So we could end up with tests for our algorithm that don’t fully prove that our code is correct. It means that the refactoring safety net that a thorough unit test suite offers isn’t there for us. But certain classes of algorithms (such as my shuffle and low pass filter examples) are inherently unlikely to change. Once they work, we are done. Business rules and customer specific requirements on the other hand, can change repeatedly through the life of a system. Focus on testing those thoroughly and don’t worry too much if some of your algorithms cannot be verified automatically.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6822536077160579260-6876647239168453910?l=mark-dot-net.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/markdotnet/~4/Nw3-nzRjo-o" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/markdotnet/~3/Nw3-nzRjo-o/test-resistant-code-3algorithms.html</link><author>noreply@blogger.com (Mark H)</author><thr:total>0</thr:total><feedburner:origLink>http://mark-dot-net.blogspot.com/2011/06/test-resistant-code-3algorithms.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6822536077160579260.post-3087708872560348158</guid><pubDate>Tue, 28 Jun 2011 17:27:00 +0000</pubDate><atom:updated>2011-07-04T16:03:25.199+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">unit testing</category><category domain="http://www.blogger.com/atom/ns#">Silverlight</category><category domain="http://www.blogger.com/atom/ns#">HOWTO</category><title>How to Unit Test Silverlight Apps</title><description>&lt;p&gt;I recently tried writing some unit tests for a Silverlight 4 project. The first barrier I ran into is that the typical way of creating unit tests – create a DLL, reference NUnit and your assembly to test, doesn’t work, since you can’t mix Silverlight assemblies with standard .NET assemblies.&lt;/p&gt; &lt;p&gt;The next hurdle is that fact that the Silverlight developer tools do not include a unit testing framework, and searching for Silverlight unit testing tools on the web can lead you down a few dead ends. It turns out that the thing you need is the &lt;a href="http://silverlight.codeplex.com/"&gt;Silverlight Toolkit&lt;/a&gt;. If you are just doing Silverlight 4, you only need the April 2010 toolkit.&lt;/p&gt; &lt;p&gt;Once this is installed, you get a template that allows you to add a “Silverlight Unit Test Application” to your project. This is a separate Silverlight application that contains a custom UI just to run unit tests.&lt;/p&gt; &lt;p&gt;Now you can get down to business writing your unit tests. You have to use the Microsoft unit testing attributes, i.e. [TestClass], [TestMethod], [TestInitialize]. You can also use the [Tag] attribute, which is the equivalent of NUnit’s [Category] to group your unit tests, allowing you to run a subset of tests easily.&lt;/p&gt; &lt;p&gt;It has a fairly nice GUI (though not without a few quirks) that displays the outcome of your tests for you, and allows you to copy the test results to your clipboard:&lt;/p&gt; &lt;p&gt;&lt;a href="http://lh3.ggpht.com/-DMVxtmto8r0/ThHWOVF0tQI/AAAAAAAAAkw/Ur4Pp-XyTbc/s1600-h/image%25255B8%25255D.png"&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://lh5.ggpht.com/-sefZl04cCAU/ThHWPL4zTmI/AAAAAAAAAk0/viJatnE0WHs/image_thumb%25255B5%25255D.png?imgmax=800" width="511" height="368"&gt;&lt;/a&gt; &lt;/p&gt; &lt;p&gt;Unfortunately it doesn’t support Assert.Inconclusive (gets counted as a failure), but apart from that it works as expected.&lt;/p&gt; &lt;h3&gt;Testing GUI Components&lt;/h3&gt; &lt;p&gt;Another interesting capability that the Silverlight Unit Testing framework offers is that it can actually host your user controls and run tests against them.  &lt;p&gt;Unfortunately some of the documentation that is out there is a little out of date, so I’ll run through the basics here.  &lt;p&gt;You start off by creating a test class that inherits from the &lt;strong&gt;SilverlightTest&lt;/strong&gt; base class. Then in a method decorated with the &lt;strong&gt;TestInitialize&lt;/strong&gt; attribute, create an instance of your user control and add it to the TestPanel (a property on the base class, note that it has changed name since a lot of older web tutorials were written).&lt;pre class="brush: csharp;"&gt;[TestInitialize]
public void SetUp()
{
    var control = new MyUserControl();
    this.TestPanel.Children.Add(control);
}&lt;/pre&gt;
&lt;p&gt;Note that if you don’t do this in the TestInitialize method and try to do it in your test method itself, the control won’t have time to actually load. 
&lt;p&gt;There is a nasty gotcha. If you user control uses something from a resource dictionary, then the creation of your control will fail in the TestInitialize method, but for some reason the test framework ploughs on and calls the TestMethod anyway, resulting in a confusing failure message. You need to get the contents of your app.xaml into the unit test application. 
&lt;p&gt;I already had my resource dictionaries split out into multiple files, which helped a lot. I added the resource xaml files to the test application as linked files, and then just referenced them as Merged dictionaries in my app.xaml:&lt;pre class="brush: xml;"&gt;&amp;lt;Application.Resources&amp;gt;
    &amp;lt;ResourceDictionary&amp;gt;
        &amp;lt;ResourceDictionary.MergedDictionaries&amp;gt;
            &amp;lt;ResourceDictionary Source="MarkRoundButton.xaml"/&amp;gt;
        &amp;lt;/ResourceDictionary.MergedDictionaries&amp;gt;
    &amp;lt;/ResourceDictionary&amp;gt;
&amp;lt;/Application.Resources&amp;gt;
&lt;/pre&gt;
&lt;p&gt;Now in your actual test method, you can now perform tests on your user control, knowing that it has been properly created and sized.&lt;pre class="brush: csharp;"&gt;[TestMethod]
public void DisplayDefaultSize()
{
    Assert.IsTrue(tc.ActualWidth &amp;gt; 0);
}
&lt;/pre&gt;
&lt;p&gt;There are also some powerful capabilities in there to allow you to run “asynchronous” tests, but I will save that for a future blog post as I have a few interesting ideas for how they could be used.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6822536077160579260-3087708872560348158?l=mark-dot-net.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/markdotnet/~4/LSH1c-4DsmE" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/markdotnet/~3/LSH1c-4DsmE/how-to-unit-test-silverlight-apps.html</link><author>noreply@blogger.com (Mark H)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://lh5.ggpht.com/-sefZl04cCAU/ThHWPL4zTmI/AAAAAAAAAk0/viJatnE0WHs/s72-c/image_thumb%25255B5%25255D.png?imgmax=800" height="72" width="72" /><thr:total>3</thr:total><feedburner:origLink>http://mark-dot-net.blogspot.com/2011/06/how-to-unit-test-silverlight-apps.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6822536077160579260.post-710243599032379510</guid><pubDate>Mon, 27 Jun 2011 21:51:00 +0000</pubDate><atom:updated>2011-07-05T10:28:53.922+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">TDD</category><title>Test Resistant Code #2–Markup is Code Too</title><description>&lt;p&gt;After blogging about &lt;a href="http://mark-dot-net.blogspot.com/2011/06/test-resistant-code-and-battle-for-tdd.html"&gt;one of the biggest obstacles to doing TDD&lt;/a&gt;, I thought I’d follow up with another form of test resistant code, and that is &lt;strong&gt;markup&lt;/strong&gt;. &lt;/p&gt; &lt;p&gt;Now calling markup ‘code’ might seem odd, because we have been led to believe that these are two completely different things. After all &lt;em&gt;applications = code + markup&lt;/em&gt; right? It’s the code that has the logic and all the important stuff to test in. Markup is just structured data. &lt;/p&gt; &lt;p&gt;But of course, we all know that you can have bugs in markup. 100% test coverage of your code alone does not guarantee that your customer will have a happy experience. In fact, I would go so far as to say, my experience with Silverlight and WPF programming is that the &lt;strong&gt;vast majority&lt;/strong&gt; of the bugs are to do with me getting the markup wrong in some way. 100% unit coverage of my ViewModels is nice, but doesn’t really help me solve the most challenging problems I face. If I declare an animation in XAML, I have to &lt;em&gt;watch&lt;/em&gt; it to know if I got it right. If I get it wrong, I see nothing, and I have no idea why.&lt;/p&gt; &lt;h3&gt;Exhibit A – XAML&lt;/h3&gt; &lt;p&gt;Here’s a bunch of XAML I wrote for a Silverlight star rating control I made recently:&lt;/p&gt;&lt;pre class="brush: xml;"&gt;&amp;lt;UserControl x:Class="MarkHeath.StarRating.Star"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="34" d:DesignWidth="34" Foreground="#C0C000"&amp;gt;
    &amp;lt;Canvas x:Name="LayoutRoot"&amp;gt;
        &amp;lt;Canvas.RenderTransform&amp;gt;
            &amp;lt;ScaleTransform x:Name="scaleTransform" /&amp;gt;
        &amp;lt;/Canvas.RenderTransform&amp;gt;
        &amp;lt;Path x:Name="Fill" Fill="{Binding Parent.StarFillBrush, ElementName=LayoutRoot}" 
                Data="M 2,12 l 10,0 l 5,-10 l 5,10 l 10,0 l -7,10 l 2,10 l -10,-5 l -10,5 l 2,-10 Z" /&amp;gt;

        &amp;lt;Path x:Name="HalfFill" Fill="{Binding Parent.HalfFillBrush, ElementName=LayoutRoot}"                
                Data="M 2,12 l 10,0 l 5,-10 v 25 l -10,5 l 2,-10 Z M 34,34" /&amp;gt;

        &amp;lt;Path x:Name="Outline" Stroke="{Binding Parent.Foreground, ElementName=LayoutRoot}"     
                StrokeThickness="{Binding Parent.StrokeThickness, ElementName=LayoutRoot}" 
                StrokeLineJoin="{Binding Parent.StrokeLineJoin, ElementName=LayoutRoot}"
                Data="M 2,12 l 10,0 l 5,-10 l 5,10 l 10,0 l -7,10 l 2,10 l -10,-5 l -10,5 l 2,-10 Z" /&amp;gt;
        &amp;lt;!-- width and height of this star is 34--&amp;gt;
    &amp;lt;/Canvas&amp;gt;
&amp;lt;/UserControl&amp;gt;
&lt;/pre&gt;
&lt;p&gt;Does this XAML have any ‘bugs’ in it? Well, not that I know of, but in the process of developing it, I ran into a bunch of problems. For a long time the top level element was a Grid rather than a Canvas, but strange things were happening when I resized it. I also resisted putting the ScaleTransform in there for a while, convinced I could do something with the Stretch properties on the Path objects to get the resizing to happen automatically (it was the half star that spoiled it).&lt;/p&gt;
&lt;p&gt;Was this ‘real’ development? I think it was. XAML is after all just a way of writing creating objects and setting properties on them with a syntax that is more convenient for designer tools to work with. I could create exactly the same effect by creating a UserControl class, and setting its Content property to an instance of Canvas and so on.&lt;/p&gt;
&lt;p&gt;Could I have developed this using TDD? Hmmm. Well you can always &lt;em&gt;write&lt;/em&gt; a test for a piece of code. The trouble comes when you try to decide whether that test has passed or not. For this code, the only sane way of validating it was for me to visually inspect it at various sizes and see if it looked right.&lt;/p&gt;
&lt;h3&gt;Exhibit B – Build Scripts&lt;/h3&gt;
&lt;p&gt;I recently had the misfortune of having to do some work on MSBuild scripts. Don’t get me wrong, MSBuild is a powerful and feature complete build framework. It’s just that I had to resort to books and StackOverflow every time I attempted the simplest of tasks.&lt;/p&gt;
&lt;p&gt;It is not long before it becomes clear that a build script is a program, and not simply structured data. In MSBuild, you can declare variables, call subroutines (‘Targets’), and write if statements (‘Conditions’). A build script is a program with a very important task – it creates the application you ship to customers. Can there be bugs in a build script? Yes. Can those bugs affect the customer? Yes. Would it be useful to be able to test the build script too? Yes.&lt;/p&gt;
&lt;p&gt;Which is why felt a bit jealous when I watched a &lt;a href="http://www.ndc2011.no/agenda.aspx?cat=1071&amp;amp;id=-1&amp;amp;day=3727"&gt;recent presentation&lt;/a&gt; from Shay Friedman on IronRuby, and discovered that with &lt;a href="http://rake.rubyforge.org/"&gt;rake&lt;/a&gt; you can write your build scripts in Ruby. I’ve not learned the Ruby language myself yet, but I would love my build processes to be defined using IronPython instead of some XML monstrosity. Not only would it be far more productive, it would be &lt;em&gt;testable&lt;/em&gt; too.&lt;/p&gt;
&lt;h3&gt;Exhibit C – P/Invoke&lt;/h3&gt;
&lt;p&gt;My final example might take you by surprise. As part of NAudio, I write a lot of P/Invoke wrappers. It is a laborious, error-prone process. A bug in one of those wrappers can cause bad things to happen, like crash your application, or even reboot your PC if your soundcard drivers are not well behaved.&lt;/p&gt;
&lt;p&gt;Now although these wrappers are written in C#, they are not ‘code’ in the classic sense. They are just a bunch of class and method definitions. There is no logic and there are no expressions in there at all. In fact, it is the attributes that they are decorated with that do a lot of the work. Here’s a relatively straightforward example that someone else contributed recently:&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;[StructLayout(LayoutKind.Explicit)]
struct MmTime
{
    public const int TIME_MS = 0x0001;
    public const int TIME_SAMPLES = 0x0002;
    public const int TIME_BYTES = 0x0004;

    [FieldOffset(0)]
    public UInt32 wType;
    [FieldOffset(4)]
    public UInt32 ms;
    [FieldOffset(4)]
    public UInt32 sample;
    [FieldOffset(4)]
    public UInt32 cb;
    [FieldOffset(4)]
    public UInt32 ticks;
    [FieldOffset(4)]
    public Byte smpteHour;
    [FieldOffset(5)]
    public Byte smpteMin;
    [FieldOffset(6)]
    public Byte smpteSec;
    [FieldOffset(7)]
    public Byte smpteFrame;
    [FieldOffset(8)]
    public Byte smpteFps;
    [FieldOffset(9)]
    public Byte smpteDummy;
    [FieldOffset(10)]
    public Byte smptePad0;
    [FieldOffset(11)]
    public Byte smptePad1;
    [FieldOffset(4)]
    public UInt32 midiSongPtrPos;
}
&lt;/pre&gt;
&lt;p&gt;Can classes like this be written with TDD? Well sort of, but the tests wouldn’t really test anything, except that I wrote the code I thought I should write. How would I verify it? I can only prove these wrappers really work by actually calling the real Windows APIs – i.e. by running integration tests. &lt;/p&gt;
&lt;p&gt;Now as it happens I can (and do) have a bunch of automated integration tests for NAudio. But it gets worse. Some of these wrappers I can only properly test by running them on Windows XP &lt;em&gt;and &lt;/em&gt;Windows 7, in a 32 bit process &lt;em&gt;and&lt;/em&gt; a 64 bit process, and with a bunch of different soundcards configured for every possible bit depth and byte ordering. Maybe in the future, virtualization platforms and unit test frameworks will become so integrated that I can just use attributes to tell NUnit to run the test on a whole host of emulated operating systems, processor architectures, and soundcards. But even that wouldn’t get me away from the fact that I actually have to &lt;em&gt;hear&lt;/em&gt; the sound coming out of the speakers to know for sure that my test worked.&lt;/p&gt;
&lt;h3&gt;Has TDD over-promised?&lt;/h3&gt;
&lt;p&gt;So are these examples good counter-points to TDD? Or are they things that TDD never promised to solve in the first place? &lt;a href="http://www.objectmentor.com/omTeam/martin_r.html"&gt;Uncle Bob&lt;/a&gt; may be able to run his test suite and ship &lt;a href="http://fitnesse.org/"&gt;Fitnesse&lt;/a&gt; if it goes green without checking anything else at all. But I can’t see how I could ever get to that point with NAudio. Maybe the majority of code we do in markup can’t be tested without manual tests. And if they can’t be tested without manual tests, does TDD even make sense as a practice for developing them in the first place?&lt;/p&gt;
&lt;p&gt;For TDD to truly “win the war”, it needs needs to come clean about what problems it can solve for us, and what problems are left unsolved. Some test-resistant code (such as &lt;a href="http://mark-dot-net.blogspot.com/2011/06/test-resistant-code-and-battle-for-tdd.html"&gt;tightly coupled code&lt;/a&gt;) can be made testable. Other test-resistant code will always need an amount of manual test and verification. The idea that we could get to the point of “not needing a QA department” does not seem realistic to me. TDD may mean a smaller QA department, but we cannot get away from the need for real people to verify things with their eyes and ears, and to verify them on a bunch of different hardware configurations that cannot be trivially emulated. &lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6822536077160579260-710243599032379510?l=mark-dot-net.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/markdotnet/~4/sHTkctJJz9E" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/markdotnet/~3/sHTkctJJz9E/test-resistant-code-2markup-is-code-too.html</link><author>noreply@blogger.com (Mark H)</author><thr:total>0</thr:total><feedburner:origLink>http://mark-dot-net.blogspot.com/2011/06/test-resistant-code-2markup-is-code-too.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6822536077160579260.post-585958396083018380</guid><pubDate>Fri, 24 Jun 2011 19:34:00 +0000</pubDate><atom:updated>2011-07-01T21:20:12.978+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Dependency Inversion Principle</category><category domain="http://www.blogger.com/atom/ns#">TDD</category><title>Test resistant code and the battle for TDD</title><description>&lt;p&gt;I have been watching a number of videos from the &lt;a href="http://ndc2011.no/index.aspx"&gt;NDC 2011&lt;/a&gt; conference recently, and noticed a number of speakers expressing the sentiment that &lt;strong&gt;TDD has won.&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;By “won”, they don’t mean that everyone is using it, because true TDD practitioners are still very much in the minority, Even those who claim to be doing TDD are in reality only doing it &lt;em&gt;sometimes&lt;/em&gt;. In fact, I would suggest that even the practice of writing unit tests for everything, let alone writing them first, is far from being the norm in the industry.&lt;/p&gt; &lt;p&gt;Of course, what they mean is that &lt;em&gt;the argument has been won&lt;/em&gt;. No prominent thought-leaders are speaking out against TDD; its benefits are clear and obvious. The theory is that, it is only a matter of time before we know no other way of working.&lt;/p&gt; &lt;p&gt;Or is it?&lt;/p&gt; &lt;p&gt;There is a problem with doing TDD in languages like C# that its most vocal proponents are not talking enough about. And that is that a lot of the code we write is &lt;em&gt;test resistant&lt;/em&gt;. By test resistant, I don’t mean “impossible to test”. I just mean that the effort required to shape it into a form that can be tested is so great that even if we are really sold on the idea of TDD, we give up in frustration once we actually try it. &lt;/p&gt; &lt;p&gt;I’ve got a whole list of different types of code that I consider to be “test-resistant”, but I’ll just focus in on one for the purposes of this post. And that is code that has lots of &lt;strong&gt;external dependencies&lt;/strong&gt;. TDD is quite straightforward if you happen to be writing a program to calculate the prime factors of a number; you don’t have any significant external dependencies to worry about. The same is largely true if you happen to be writing a unit testing framework or an IoC container. But for many, and quite probably the majority of us, the code we write interacts with all kinds of nasty hard to test external &lt;em&gt;stuff&lt;/em&gt;. And that stuff is what gets in our way.&lt;/p&gt; &lt;h3&gt;External dependencies&lt;/h3&gt; &lt;p&gt;External dependencies come in many flavours. Does your class talk to the file-system or to a database? Does it inherit from a UserControl base class? Does it create threads? Does it talk across the network? Does it use a third party library of any sort? If the answer to any of these questions is yes, the chances are your class is test-resistant.&lt;/p&gt; &lt;p&gt;Such classes can of course be constructed and have their methods called by an automated testing framework, but those tests will be “integration” tests. Their success depends on the environment in which they are run. Integration tests have their place, but if large parts of our codebase can only be covered by integration tests, then we have lost the benefits of TDD. We can’t quickly run the tests and prove that our system is still working.&lt;/p&gt; &lt;p&gt;Suppose we draw a dependency diagram of all the classes in our application arranged inside a circle. If a class has any external dependencies we’ll draw it on the edge of the circle. If a class only depends on other classes &lt;em&gt;we &lt;/em&gt;wrote, we’ll draw it in the middle. We might end up with something looking like this:&lt;/p&gt; &lt;p&gt;&lt;a href="http://lh5.ggpht.com/-R1EI1B3UZtA/Tg4r9c1tP_I/AAAAAAAAAec/Q384nfutwuM/s1600-h/external-dependencies%25255B3%25255D.png"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="external-dependencies" border="0" alt="Dependencies Diagram" src="http://lh5.ggpht.com/-y528HKk46WY/Tg4r-9_rekI/AAAAAAAAAeg/u4LWgpG29qA/external-dependencies_thumb%25255B1%25255D.png?imgmax=800" width="556" height="368"&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;In my diagram, the green squares in the middle are the classes that we will probably be able to unit test without too much pain. They depend only on other code we have written (or on trivial to test framework classes like String, TimeSpan, Point etc).&lt;/p&gt; &lt;p&gt;The orange squares represent classes that we &lt;em&gt;might&lt;/em&gt; be able to ‘unit’ test, since file systems and databases are reasonably predictable. We could create a test database to run against, or use temporary files that are deleted after the test finishes.&lt;/p&gt; &lt;p&gt;The red squares represent classes that will be a real pain to test. If we must talk to a web-service, what happens when it is not available? If we are writing a GUI component, we probably have to use some kind of unwieldy automation tool to create it and simulate mouse-clicks and keyboard presses, and use bitmap comparisons to see if the right thing happened.&lt;/p&gt; &lt;h3&gt;DIP to the rescue?&lt;/h3&gt; &lt;p&gt;But hang on a minute, don’t we have a solution to this problem already? It’s called the “Dependency Inversion Principle”. Each and every external dependency should be hidden behind an &lt;em&gt;interface&lt;/em&gt;. The concrete implementers of those interfaces should write the absolute minimal code to fulfil those interfaces, with no logic whatsoever.&lt;/p&gt; &lt;p&gt;Now suddenly all our business logic has moved inside the circle. The remaining concrete classes on the edge still need to be covered by integration tests, but we can verify all the decisions, algorithms and rules that make up our application using fast, repeatable, in-memory unit tests.&lt;/p&gt; &lt;p&gt;All’s well then. External dependencies are not a barrier to TDD after all. Or are they?&lt;/p&gt; &lt;p&gt;How many interfaces would you actually need to create to get to this utopian state where &lt;em&gt;all &lt;/em&gt;your logic is testable? If the applications you write are anything like the ones I work on, the answer is, a lot.&lt;/p&gt; &lt;h3&gt;IFileSystem &lt;/h3&gt; &lt;p&gt;Let’s work through the file system as an example. We could create IFileSystem and decree that every class in our application that needs to access the disk goes via IFileSystem. What methods would it need to have? A quick scan through the application I am currently working on reveals the following dependencies on static methods in the System.IO namespace:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;File.Exists  &lt;li&gt;File.Delete  &lt;li&gt;File.Copy  &lt;li&gt;File.OpenWrite  &lt;li&gt;File.Open  &lt;li&gt;File.Move  &lt;li&gt;File.Create  &lt;li&gt;File.GetAttributes  &lt;li&gt;File.SetAttributes  &lt;li&gt;File.WriteAllBytes  &lt;li&gt;File.ReadLines  &lt;li&gt;File.ReadAllLines  &lt;li&gt;Directory,Exists  &lt;li&gt;Directory.CreateDirectory  &lt;li&gt;Directory.GetFiles  &lt;li&gt;Directory.GetDirectories  &lt;li&gt;Directory.Delete  &lt;li&gt;DriveInfo.GetDrives&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;There’s probably some others that I missed, but that doesn’t seem &lt;em&gt;too &lt;/em&gt;bad. Sure it would take a long time to go through the entire app and make everyone use IFileSystem, but if we had used TDD, then IFileSystem could have been in there from the beginning. We could start off with just a few methods, and then add new ones in on an as-needed basis.&lt;/p&gt; &lt;p&gt;The trouble is, our abstraction layer needs to go deeper than just wrappers for all the static methods on System.IO. For example, Directory.GetFiles returns a FileInfo object. But the &lt;a href="http://msdn.microsoft.com/en-us/library/system.io.fileinfo.aspx"&gt;FileInfo&lt;/a&gt; class has all kinds of methods on it that allow external dependencies to sneak back into our classes via the back door. What’s more, it’s a sealed class, so we can’t fake it for our unit tests anyway. So now we need to create IFileInfo for our IFileSystem to return when you ask for the files in a folder. If we keep going in this direction it won’t be long before we end up writing an abstraction layer for the entire .NET framework class library.&lt;/p&gt; &lt;h3&gt;Interface Explosion&lt;/h3&gt; &lt;p&gt;This is a problem. You could blame Microsoft. Maybe the BCL/FCL should have come with interfaces for &lt;em&gt;everything &lt;/em&gt;that was more than just a trivial data transfer object. That would certainly have made life easier for unit testing. But this would also add literally &lt;em&gt;thousands&lt;/em&gt; of interfaces. And if we wanted to apply the “interface segregation principle” as well, we’d end up needing to make even more interfaces, because the ones we had were a bad fit for the classes that need to consume them.&lt;/p&gt; &lt;p&gt;So for us to do TDD properly in C#, we need to get used to the idea of making &lt;em&gt;lots&lt;/em&gt; of interfaces. It will be like the good old days of C/C++ programming all over again. For every class, you also need to make a header / interface file.&amp;nbsp; &lt;/p&gt; &lt;h3&gt;Mocks to the Rescue?&lt;/h3&gt; &lt;p&gt;Is there another way? Well I suppose we could buy those commercial tools that have the power to replace any concrete dependency with a mock object. Or maybe Microsoft’s &lt;a href="http://research.microsoft.com/en-us/projects/moles/"&gt;Moles&lt;/a&gt; can dig us out of this hole. But are these frameworks solutions to problems we shouldn’t be dealing with in the first place?&lt;/p&gt; &lt;p&gt;There is of course a whole class of languages that doesn’t suffer from this problem at all. And that is &lt;strong&gt;dynamic languages&lt;/strong&gt;. Mocking a dependency is trivial with a dynamically typed language. The concept of interfaces is not needed at all. &lt;/p&gt; &lt;p&gt;This makes me think that &lt;strong&gt;if TDD really is going to win, dynamically typed languages need to win. &lt;/strong&gt;The limited class of problems that a statically typed language can protect us from can quite easily be detected with a good suite of unit tests. It leaves us in a kind of catch 22 situation. Our statically typed languages are hindering us from embracing TDD, but until we are really doing TDD, we’re not ready to let go of the statically typed safety net.&lt;/p&gt; &lt;p&gt;Maybe language innovations like C# 4’s dynamic or the coming compiler as a service in the next .NET will afford enough flexibility to make TDD flow more naturally. But I get the feeling that TDD still has a few battles to win before the war can truly be declared as over.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6822536077160579260-585958396083018380?l=mark-dot-net.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/markdotnet/~4/Xr4LhuQ0bCs" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/markdotnet/~3/Xr4LhuQ0bCs/test-resistant-code-and-battle-for-tdd.html</link><author>noreply@blogger.com (Mark H)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://lh5.ggpht.com/-y528HKk46WY/Tg4r-9_rekI/AAAAAAAAAeg/u4LWgpG29qA/s72-c/external-dependencies_thumb%25255B1%25255D.png?imgmax=800" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://mark-dot-net.blogspot.com/2011/06/test-resistant-code-and-battle-for-tdd.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6822536077160579260.post-6222765153303415123</guid><pubDate>Sat, 18 Jun 2011 18:28:00 +0000</pubDate><atom:updated>2011-06-18T19:28:25.962+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Open Closed Principle</category><category domain="http://www.blogger.com/atom/ns#">Liskov Substitution Principle</category><category domain="http://www.blogger.com/atom/ns#">Single Responsibility Principle</category><category domain="http://www.blogger.com/atom/ns#">merging</category><category domain="http://www.blogger.com/atom/ns#">Dependency Inversion Principle</category><category domain="http://www.blogger.com/atom/ns#">branching</category><category domain="http://www.blogger.com/atom/ns#">SOLID</category><title>SOLID Code is Mergeable Code</title><description>&lt;p&gt;Not every developer I speak to is convinced of the importance of adhering to the &lt;a href="http://en.wikipedia.org/wiki/Solid_%28object-oriented_design%29"&gt;“SOLID” principles&lt;/a&gt;. They can seem a bit too abstract and “computer sciency” and disconnected from the immediate needs of delivering working software on time. “SOLID makes writing unit tests easier? So what, the customer didn’t ask for unit tests, they asked for an order billing system”.  &lt;p&gt;But one of the very concrete benefits of adhering to SOLID is that it eases merging for projects that require parallel development on multiple branches. Many of the commercial products I have worked on have required old versions to be supported with bug fixes and new features for many years. It is not uncommon to have more than 10 active branches of code. As nice as it would be to simply require every customer to upgrade to the latest version, that is not possible in all commercial environments. &lt;p&gt;One customer took well over a year to roll out our product to all their numerous sites. During that time we released two new major versions of our software. Another customer requires a rigorous and lengthy approval testing phase before they will accept anything new at all. The result is that features and bug fixes often have to be merged through multiple branches, some of which have diverged significantly over the years. &lt;p&gt;&lt;i&gt;So how do the SOLID principles aid merging?&lt;/i&gt; &lt;p&gt;The &lt;b&gt;Single Responsibility Principle&lt;/b&gt; states that each class should only have a single reason to change. If you have a class that constantly requires changing on every branch, creating regular merge conflicts, the chances are it violates SRP. If each class has only a single responsibility there is only a merge conflict if both branches genuinely need to modify that single responsibility. &lt;p&gt;Classes that adhere to the &lt;b&gt;Open Closed Principle &lt;/b&gt;don’t need to be changed at all (except to fix bugs). Instead, they can be extended from the &lt;i&gt;outside&lt;/i&gt;. Two branches can therefore extend the same class in completely different ways without any merge conflict at all – each branch simply adds a new class to the project. &lt;p&gt;Designs that violate the &lt;b&gt;Liskov Substitution Principle&lt;/b&gt; result in lots of switch and if statements littered throughout the code, that must be modified every time we introduce a new subclass into the system. In the canonical ‘shapes’ example, when the Triangle class is introduced on one branch, and the Hexagon class is created on another, the merge is trivial if the code abides by LSP. If the code doesn’t, you can expect a &lt;i&gt;lot&lt;/i&gt; of merge conflicts as every place in the code that uses the Shape base class is likely to have been modified in both branches. &lt;p&gt;The &lt;b&gt;Interface Segregation Principle &lt;/b&gt;is in some ways the SRP for interfaces. If you adhere to ISP, you have many small, focused interfaces instead of few large, bloated interfaces. And the more your codebase is broken down into smaller parts, the lower the chances of two branches both needing to change the same files. &lt;p&gt;Finally, the &lt;b&gt;Dependency Inversion Principle&lt;/b&gt; might not at first glance seem relevant to merges. But every application of DIP is in fact also a separation of concerns. The concern of creating your dependencies is separated away from actually using them. So applying DIP is always a step in the direction of SRP, which means you have smaller classes with more focused responsibilities. But DIP has another power that turns out to be very relevant for merging. &lt;p&gt;Code that adheres to the Dependency Inversion Principle is &lt;i&gt;much&lt;/i&gt; easier to unit test. And a good suite of unit tests is an invaluable tool when merging lots of changes between parallel branches. This is because it is quite easily possible for merged code to compile and yet still be broken. When merges between branches are taking place on a weekly basis, there is simply not enough time to run a full manual regression test each time. Unit tests can step into the breach and give a high level of confidence that a merge has not broken existing features. This benefit alone repays the time invested in creating unit tests. &lt;p&gt;In summary, SOLID code is mergeable code. SOLID code is also unit testable code, and merges verified by unit tests are the safest kind of merges. If your development process involves working on parallel branches, you will save yourself a lot of pain by mastering the SOLID principles, and protecting legacy features with good unit test coverage.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6822536077160579260-6222765153303415123?l=mark-dot-net.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/markdotnet/~4/nJwvofWIzG8" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/markdotnet/~3/nJwvofWIzG8/solid-code-is-mergeable-code.html</link><author>noreply@blogger.com (Mark H)</author><thr:total>0</thr:total><feedburner:origLink>http://mark-dot-net.blogspot.com/2011/06/solid-code-is-mergeable-code.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6822536077160579260.post-8375684424703621116</guid><pubDate>Thu, 16 Jun 2011 21:18:00 +0000</pubDate><atom:updated>2011-06-16T22:18:53.141+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Developer Principles</category><title>Essential Developer Principles #2–Don’t Reinvent the Wheel</title><description>&lt;p&gt;For some reason, developers have a tendency towards a “&lt;a href="http://en.wikipedia.org/wiki/Not_Invented_Here"&gt;not invented here&lt;/a&gt;” mentality. Sometimes it is simply because we are unaware of any pre-existing solutions that address out problem. But very often, we suspect that it will be far too complicated to use a third-party framework, and much quicker and simpler to write our own. After all, if we write our own we can make it work &lt;em&gt;exactly &lt;/em&gt;how we want it to.  &lt;p&gt;&lt;b&gt;Reinventing the Framework&lt;/b&gt;&amp;nbsp; &lt;p&gt;The arguments for reinventing the wheel initially seem compelling, mainly because most programming problems seem a lot simpler at first than they really are.  &lt;p&gt;So we head off to create our own chart library, our own deployment mechanism, our own XML parser, our own 3D rendering engine, our own unit test framework, our own database, and so on.  &lt;p&gt;Months later we realise that our own custom framework is incomplete, undocumented and bug ridden. Instead of working on features that our customers have actually asked for, all our effort and attention has been diverted into maintaining these supporting libraries.  &lt;p&gt;It is almost always the right choice to take advantage of a mature, well documented, existing framework, instead of deciding to create a bespoke implementation.  &lt;p&gt;&lt;b&gt;Repeatedly Reinventing&lt;/b&gt;  &lt;p&gt;Another variation on the reinventing the wheel problem is when a single (often enterprise scale) application contains multiple solutions to the same problem. For example, there might be two separate bits of code devoted to reading and writing CSV files. Or several different systems for messaging between threads. This usually happens because the the logic is so tightly coupled to its context that we can’t reuse it even if we want to. &lt;/p&gt; &lt;p&gt;&lt;b&gt;... except when ...&lt;/b&gt;  &lt;p&gt;As with most developer principles, this one has some exceptions. I think there are three main cases in which it is OK to reinvent the wheel. These are… &lt;p&gt;&lt;b&gt;1. Reinvent to learn&lt;/b&gt;  &lt;p&gt;We don’t need another blog engine, but we do need more developers who &lt;a href="http://blog.wekeroad.com/2009/08/10/be-a-good-jedi-build-your-own-blog"&gt;know how to build one&lt;/a&gt;. Likewise, we probably don’t need yet another ORM, or yet another IoC container, or yet another MVVM or MVC framework. But the process of building one, even if it is never completed, is an invaluable learning exercise. So go ahead, invent your own version control system, encryption algorithm or operating system. Just don’t use it in your next commercial product unless you have a &lt;em&gt;lot&lt;/em&gt; of spare time on your hands.  &lt;p&gt;&lt;b&gt;2. Reinvent a simpler wheel&lt;/b&gt;  &lt;p&gt;There are times when the existing offerings are &lt;i&gt;so&lt;/i&gt; powerful and feature-rich that it seems overkill to drag a huge framework into your application just to use a fraction of its powers. In these cases it &lt;em&gt;might&lt;/em&gt; make sense to make your own lean, stripped down, focused component that does only what you need.  &lt;p&gt;However, &lt;em&gt;beware of feature creep&lt;/em&gt;, and beware of problems that seem simple until you begin to tackle them. A good example of creating simpler alternatives is &lt;a href="http://www.hanselman.com/blog/HanselminutesPodcast262TheRiseOfTheMicroORMWithSamSaffronAndRobConery.aspx"&gt;Micro-ORMs&lt;/a&gt;, which are just a few hundred lines of code, stripped down to the bare essentials of what is actually needed for the task at hand. &lt;p&gt;&lt;b&gt;3. Reinvent a better wheel&lt;/b&gt;  &lt;p&gt;There are those rare people who can look at the existing frameworks, see a limitation with them, imagine a better alternative, and build it. It takes a &lt;i&gt;lot&lt;/i&gt; of time to pull this off, so it doesn’t make sense if you only need it for one project. If however, you are building a framework to base &lt;i&gt;all&lt;/i&gt; the applications you ever write on, there is a chance that it will pay for itself over time.  &lt;p&gt;An example of this in action is &lt;a href="http://fubumvc.com/"&gt;FubuMVC&lt;/a&gt;, an alternative to ASP.NET MVC that was designed to work &lt;i&gt;exactly&lt;/i&gt; the way its creators wanted. The key is to realise that they have gone on to build a lot of commercial applications on that framework. &lt;p&gt;In summary, &lt;em&gt;don’t reinvent the wheel &lt;/em&gt;unless you have a &lt;em&gt;really &lt;/em&gt;good reason to. You’ll end up wasting a lot of time and resources on development that is only tangentially related to your business goals. &lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6822536077160579260-8375684424703621116?l=mark-dot-net.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/markdotnet/~4/rDKUc3oYBKg" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/markdotnet/~3/rDKUc3oYBKg/essential-developer-principles-2dont.html</link><author>noreply@blogger.com (Mark H)</author><thr:total>0</thr:total><feedburner:origLink>http://mark-dot-net.blogspot.com/2011/06/essential-developer-principles-2dont.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6822536077160579260.post-4334080136219405590</guid><pubDate>Wed, 15 Jun 2011 21:08:00 +0000</pubDate><atom:updated>2011-07-01T21:26:53.598+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Developer Principles</category><category domain="http://www.blogger.com/atom/ns#">Single Responsibility Principle</category><title>Essential Developer Principles #1–Divide and Conquer</title><description>&lt;p&gt;&lt;em&gt;With this post I am starting a new series in which I intend to cover a miscellany of developer ‘principles’. They are in no particular order, and I’m not promising any great regularity but I am intending to use some of the material I present here as part of the developer training where I work, so please feel free to suggest improvements or offer counterpoints.&lt;/em&gt;&lt;/p&gt; &lt;p&gt;The essence of software development is divide and conquer. You take a large problem, and break it into smaller pieces. Each of those smaller problems is broken into further pieces until you finally get down to something you can actually solve with lines of code.&lt;/p&gt; &lt;p&gt;If you can’t break problems down into constituent parts, you don’t have what it takes to be a programmer. Apparently some who purport to be developers &lt;a href="http://www.codinghorror.com/blog/2007/02/why-cant-programmers-program.html"&gt;can’t even solve trivial problems like FizzBuzz&lt;/a&gt;. They can’t see that to solve FizzBuzz (the “big” problem), all they need to do is solve a few much simpler problems (count from 1 to 100, see if a number is divisible by three, see if a number is divisible by 5, print a message). Once you have done that, the pieces aren’t too hard to put together into a solution to the big problem.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Cutting the Cake&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;But being a good developer is not just about being able to decompose problems. If you need to cut a square birthday cake into four equal pieces there are several ways of doing it. You could cut it into four squares, four triangles, or four rectangles, to name just a few of the options. Which is best? Well that depends on whether there are chocolate buttons on top of the cake. You’d better make sure everyone gets an equal share of those too or there will be trouble.&lt;/p&gt; &lt;p&gt;A good developer doesn’t just see that a problem &lt;em&gt;can &lt;/em&gt;be broken down; they see &lt;em&gt;several ways &lt;/em&gt;to break it down and select the most appropriate.&lt;/p&gt; &lt;p&gt;For example, you can slice your ASP.NET application up by every web page having all its logic and database access in the code behind – vertical slices if you like. Or you can slice it up in a different way and have your presentation, your business logic, and your database access as horizontal slices. Both are ways of taking a big problem and cutting it into smaller pieces. Hopefully I don’t need to tell you which of those is a better choice.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Keep Cutting&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;Alongside the mistake of cutting a problem up in the wrong way likes the equally dangerous mistake of failing to cut the problem up small enough.&lt;/p&gt; &lt;p&gt;In the world of .NET you might decide that for a particular problem you need two &lt;strong&gt;applications&lt;/strong&gt; – a client and a server. Then you decide that the client needs two &lt;strong&gt;assemblies&lt;/strong&gt;, or DLLs. And inside each of those modules you create a couple of &lt;strong&gt;classes.&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;&lt;a href="http://lh5.ggpht.com/-UukI85IUPRI/Tg4tgF9GArI/AAAAAAAAAek/7efGnyQGyI0/s1600-h/divide-and-conquer-1%25255B4%25255D.png"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="divide-and-conquer-1" border="0" alt="divide-and-conquer-1" src="http://lh4.ggpht.com/-OxUk5SnfL2I/Tg4tgp9nBVI/AAAAAAAAAeo/Q1BHMZMFB58/divide-and-conquer-1_thumb%25255B2%25255D.png?imgmax=800" width="377" height="180"&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;All this is well and good, but it means that your tree of hierarchy has only got three levels. As your implementation progresses, &lt;em&gt;something &lt;/em&gt;has to receive all the new code you will write. Unless you are willing to break the problem up further, what will happen is that those classes on the third level will grow to contain hundreds of long and complicated methods. In other words, our classes bloat:&lt;/p&gt; &lt;p&gt;&lt;a href="http://lh5.ggpht.com/-MxM4h_LA7ik/Tg4thNGunrI/AAAAAAAAAes/XO-j8IZdR1I/s1600-h/divide-and-conquer-2%25255B3%25255D.png"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="divide-and-conquer-2" border="0" alt="divide-and-conquer-2" src="http://lh5.ggpht.com/-DWCK9tRIBVk/Tg4thrtcQoI/AAAAAAAAAew/iC1bWHBawI0/divide-and-conquer-2_thumb%25255B1%25255D.png?imgmax=800" width="555" height="283"&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;It doesn’t need to be this way. We can almost always divide the problem that a class solves into two or more smaller, more focussed problems. Understanding the divide and conquer principle means we keep breaking the problem down until we have classes that adhere to the “single responsibility principle” – they do just one thing. These classes will be made up of a small number of short methods. Essentially, we add extra levels to our hierarchy, each one breaking the problem down smaller until we reach an appropriately simple, understandable, and testable chunk:&lt;/p&gt; &lt;p&gt;&lt;a href="http://lh3.ggpht.com/-5IxSfvkZ2rg/Tg4tioHC8VI/AAAAAAAAAe0/mPncq-kWokA/s1600-h/divide-and-conquer-3%25255B3%25255D.png"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="divide-and-conquer-3" border="0" alt="divide-and-conquer-3" src="http://lh4.ggpht.com/-GNgu9SzGXRY/Tg4tjAFRieI/AAAAAAAAAe4/_365ng6RqJg/divide-and-conquer-3_thumb%25255B1%25255D.png?imgmax=800" width="287" height="281"&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;I’ve not shown it on my diagram, but an important side benefit is that a lot of the small components we create when we break our problems up like this turn out to be reusable. We’ve actually made some of the other problems in our application easier to solve, by virtue of breaking things down to an appropriate level of granularity. There are more classes, but less code.&lt;/p&gt; &lt;p&gt;And that’s it. Divide and conquer is all it takes to be a programmer. But to be a great programmer, you need to &lt;strong&gt;know where to cut&lt;/strong&gt;, and to &lt;strong&gt;keep on cutting &lt;/strong&gt;until you’ve got everything into bite-sized chunks.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6822536077160579260-4334080136219405590?l=mark-dot-net.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/markdotnet/~4/n1LqDT-NwkU" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/markdotnet/~3/n1LqDT-NwkU/essential-developer-principles-1divide.html</link><author>noreply@blogger.com (Mark H)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://lh4.ggpht.com/-OxUk5SnfL2I/Tg4tgp9nBVI/AAAAAAAAAeo/Q1BHMZMFB58/s72-c/divide-and-conquer-1_thumb%25255B2%25255D.png?imgmax=800" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://mark-dot-net.blogspot.com/2011/06/essential-developer-principles-1divide.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6822536077160579260.post-3295183070994594175</guid><pubDate>Mon, 13 Jun 2011 20:41:00 +0000</pubDate><atom:updated>2011-07-01T21:28:08.131+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">XAML</category><category domain="http://www.blogger.com/atom/ns#">Silverlight</category><title>Silverlight Star Rating Control</title><description>&lt;p&gt;I found myself needing a star rating control for a Silverlight application recently, and although I found a few open source ones, none of them worked quite how I wanted them to. Besides, I designed my own &lt;a href="http://mark-dot-net.blogspot.com/2008/02/xaml-star-rating.html"&gt;star shape in XAML&lt;/a&gt; a while ago and wanted to use that as the basis.&lt;/p&gt; &lt;p&gt;&lt;a href="http://lh6.ggpht.com/-wzAVvoaYMMc/Tg4t1Hs3JTI/AAAAAAAAAe8/eS8IeNY2SOE/s1600-h/StarRating%25255B3%25255D.png"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="StarRating" border="0" alt="StarRating" src="http://lh5.ggpht.com/-MQtr2XO8a6k/Tg4t16lrmVI/AAAAAAAAAfA/BgBXrKcU8i0/StarRating_thumb%25255B1%25255D.png?imgmax=800" width="186" height="97"&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;In particular I wanted the ability to have half-star ratings. I thought at first it would require me to use some kind of complicated clipping construct, with a rectangle hidden behind my star, but I realised I could cheat by creating a half-star shape. Each star is a UserControl made up of three shapes – a star fill, a half star on top and then an outline on top. &lt;/p&gt; &lt;p&gt;I also wanted the colours to change as you hovered the mouse over it, indicating what rating would be given were you to click at any moment. This required the background of the control to be painted with a transparent brush, otherwise mouse events are only received while you are over stars and not in between them.&lt;/p&gt; &lt;p&gt;The biggest difficulty was making resize work. Path objects can be a pain to resize. I ended up putting them on a Canvas and using a ScaleTransform to get them the right size. All the brushes are customisable (six of them), plus you can change the number of stars, the line joins (pointy or round edged stars) and the line thicknesses. You can also turn off editing to simply display a star rating.&lt;/p&gt; &lt;p&gt;The &lt;a href="http://starratingcontrol.codeplex.com/"&gt;Silverlight Star Rating Control&lt;/a&gt; is open source and available on CodePlex. The easiest way to install it is &lt;a href="http://nuget.org/List/Packages/MarkHeath.StarRating"&gt;using NuGet&lt;/a&gt;.&lt;/p&gt; &lt;p&gt;To have a play with the star rating control, you can try it in my (rather chaotic looking) test harness below:&lt;/p&gt; &lt;div style="width: 592px; height: 430px" id="silverlightControlHost"&gt;&lt;object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%"&gt;     &lt;param name="source" value="http://www.wordandspirit.co.uk/software/SilverlightStarRatingControl.xap" /&gt;     &lt;param name="onError" value="onSilverlightError" /&gt;     &lt;param name="background" value="white" /&gt;     &lt;param name="minRuntimeVersion" value="4.0.50826.0" /&gt;     &lt;param name="autoUpgrade" value="true" /&gt;     &lt;a href="http://go.microsoft.com/fwlink/?LinkID=149156&amp;amp;v=4.0.50826.0" style="text-decoration:none"&gt;       &lt;img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none" /&gt;     &lt;/a&gt;      &lt;/object&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6822536077160579260-3295183070994594175?l=mark-dot-net.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/markdotnet/~4/8cv8zKSV3YI" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/markdotnet/~3/8cv8zKSV3YI/silverlight-star-rating-control.html</link><author>noreply@blogger.com (Mark H)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://lh5.ggpht.com/-MQtr2XO8a6k/Tg4t16lrmVI/AAAAAAAAAfA/BgBXrKcU8i0/s72-c/StarRating_thumb%25255B1%25255D.png?imgmax=800" height="72" width="72" /><thr:total>1</thr:total><feedburner:origLink>http://mark-dot-net.blogspot.com/2011/06/silverlight-star-rating-control.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6822536077160579260.post-8226335336828888980</guid><pubDate>Sat, 11 Jun 2011 10:26:00 +0000</pubDate><atom:updated>2011-06-11T11:26:34.211+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">MSBuild</category><title>MSBuild task to update AssemblyVersion and AssemblyFileVersion in C# files</title><description>&lt;p&gt;A while ago I decided I needed an MSBuild task that could update the version numbers in my AssemblyInfo.cs file. I had a search around the web, but all the custom tasks I found seemed to work in a different way to what I wanted. So I created my own.&lt;/p&gt; &lt;p&gt;What I wanted was a simple way to say “increment the revision number but leave other numbers the same”, or “set the version to exactly this”. So I came up with a simple syntax to let me do just that. For example:&lt;/p&gt;&lt;pre class="brush: xml;"&gt;&amp;lt;SetVersion FileName="AssemblyInfo.cs" AssemblyVersion="1.2.+.=" /&amp;gt;&lt;/pre&gt;
&lt;p&gt;This means, set the major version to 1, set the minor version to 2, increment the revision number and leave the build number at whatever it was before. You can also specify a rule for AssemblyFileVersion if you want to keep them both in sync.&lt;/p&gt;
&lt;p&gt;&lt;a href="https://bitbucket.org/markheath/setversiontask"&gt;SetVersionTask&lt;/a&gt; is open source, and hosted on BitBucket. You can download the build of the latest version there, and read &lt;a href="https://bitbucket.org/markheath/setversiontask/wiki/Home"&gt;more detailed instructions&lt;/a&gt; on how to set it up in your MSBuild script.&lt;/p&gt;
&lt;p&gt;I had originally planned to make it work for nuspec files too, but I don’t have a pressing need for that just yet. Shouldn’t be too hard to add though. Feel free to make use of it if it does what you need.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6822536077160579260-8226335336828888980?l=mark-dot-net.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/markdotnet/~4/o-M_LmGvndA" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/markdotnet/~3/o-M_LmGvndA/msbuild-task-to-update-assemblyversion.html</link><author>noreply@blogger.com (Mark H)</author><thr:total>2</thr:total><feedburner:origLink>http://mark-dot-net.blogspot.com/2011/06/msbuild-task-to-update-assemblyversion.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6822536077160579260.post-7787075972951197568</guid><pubDate>Mon, 06 Jun 2011 11:05:00 +0000</pubDate><atom:updated>2011-06-06T12:05:48.631+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">WPF</category><category domain="http://www.blogger.com/atom/ns#">Windows Forms</category><category domain="http://www.blogger.com/atom/ns#">Windows 8</category><category domain="http://www.blogger.com/atom/ns#">Silverlight</category><title>So … is Silverlight dead then?</title><description>&lt;p&gt;Microsoft’s Windows 8 announcement has generated a surprising amount of controversy given that what was shown (a fancy new start menu that can be navigated using touch alone) was exactly what everyone was expecting. The only thing that could conceivably be described as a surprise was that Microsoft’s offering for the slate will be the “full” Windows OS, rather than the Windows Phone 7 OS adapted for a larger screen.&lt;/p&gt; &lt;p&gt;Apparently you will be able to make stuff for this new touch interface with HTML5 and JavaScript. Quite how that makes Silverlight dead I am not sure. I certainly don’t see any reason to panic. Given that it is full Windows, you will be able to write apps for it in VB6, Delphi or QBasic if you really want to. If you can’t write Windows 8 apps in Silverlight I’ll eat my hat. And if there is, as expected, a Windows 8 app store, you can be sure you’ll be able to sell Silverlight apps on it (in fact, if they base it on the Windows Phone app store, then Silverlight might even be the preferred/required dev platform).&lt;/p&gt; &lt;p&gt;I suppose it is possible that you won’t be able to make “tiles” using Silverlight (though they haven’t announced that you can’t), but I can’t get too worked up about that. I don’t want my applications consuming loads of memory and CPU cycles &lt;em&gt;before&lt;/em&gt; I load them. Tiles should only be doing minimal processing.&lt;/p&gt; &lt;p&gt;Which brings us to the question everyone is asking. Is Silverlight dead? &lt;/p&gt; &lt;p&gt;When people call a technology “dead”, what they often really mean is “stable” and “mature”. I still develop &lt;strong&gt;WinForms &lt;/strong&gt;apps on a daily basis. The API is effectively complete. It hasn’t had any meaningful new features for years. But it is a mature framework. It does what it does well enough, and if Microsoft were still actively trying to shoehorn new features into it that would be a bad thing. After a while, what is needed is not new features, but a new development paradigm.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;WPF &lt;/strong&gt;was, at first, that new paradigm, making it easy to do what was a nightmare in WinForms. And it followed a similar path to maturity. It’s got all the main capabilities you need to build impressive looking LOB apps. Microsoft got some things right with WPF, but like WinForms, it too has its limitations. I am not concerned that there isn’t a vast number of new features being announced for it every six months.&lt;/p&gt; &lt;p&gt;And guess what, &lt;strong&gt;Silverlight&lt;/strong&gt; is on the same trajectory. Early releases picked up new capabilities at rapid pace. The fact it was chosen as the Windows Phone 7 dev platform has given it a new lease of life. But already it is reaching the stage where new versions are more incremental than revolutionary. That’s a good thing – the technology is approaching maturity.&lt;/p&gt; &lt;p&gt;To summarise: no need to panic. Keep building apps with the most appropriate technology that is available &lt;em&gt;now&lt;/em&gt;. Those apps will continue to work just fine for years to come. Don’t worry that new technologies come along every few years that seem to “kill” older ones. I for one am glad that I am not currently developing using Visual Basic 16 or MFC version 23. And in 5 years time, I fully expect that there will be something even better than Silverlight to write Windows apps in. If there isn’t, it will be Microsoft, not Silverlight that is dead.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6822536077160579260-7787075972951197568?l=mark-dot-net.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/markdotnet/~4/pvrpQ7FHEig" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/markdotnet/~3/pvrpQ7FHEig/so-is-silverlight-dead-then.html</link><author>noreply@blogger.com (Mark H)</author><thr:total>0</thr:total><feedburner:origLink>http://mark-dot-net.blogspot.com/2011/06/so-is-silverlight-dead-then.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6822536077160579260.post-2298485895364052243</guid><pubDate>Sun, 29 May 2011 18:38:00 +0000</pubDate><atom:updated>2011-05-29T19:38:27.266+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">clean code</category><category domain="http://www.blogger.com/atom/ns#">Software Development</category><title>Development process signal to noise ratio (a rant)</title><description>&lt;p&gt;In the world of audio recording, maintaining a high signal to noise ratio (SNR) is vital. Signal is the singer’s voice; noise is the traffic on the road outside. Signal is what we want to record; noise is what we don’t.&lt;/p&gt; &lt;p&gt;Just as noise can get introduced at any stage in the audio recording process, degrading the signal quality; the software development lifecycle has many points at which noise can be introduced. The only difference is, that the signal is &lt;em&gt;information&lt;/em&gt; rather than &lt;em&gt;sound&lt;/em&gt;. In software development, signal is information that is of use to me; noise is information that wastes my time.&lt;/p&gt; &lt;p&gt;In the audio world, if the signal to noise ratio is too low, it becomes simply too difficult or distracting to keep listening. The same is true with information. A low SNR to ratio bores people into switching off.&lt;/p&gt; &lt;p&gt;Here’s five areas in the software development / business process that you need to watch your SNR in…&lt;/p&gt; &lt;h3&gt;Meetings&lt;/h3&gt; &lt;p&gt;As a general rule, I dread meetings. They get me away from what I would rather be doing (coding). A meeting is maximally useful if the information that flows within it is relevant to all those present. Meetings to tell people things they already know, or that they don’t need to know, or that only one or two people need to know, are invitations to daydream, resulting in attendees missing the little that could have benefitted them.&lt;/p&gt; &lt;p&gt;The worst offenders are the “weekly” meetings, or meetings that are required by some kind of process (“kick off” meeting, “release” meeting, “checklist checker checking meeting”). If you attend a 90 minute meeting with only 5-10 minutes having relevance to you, something is wrong.&lt;/p&gt; &lt;p&gt;Talking in detail through &lt;em&gt;everyone’s &lt;/em&gt;weekly progress, or &lt;em&gt;everyone’s &lt;/em&gt;holiday plans, or &lt;em&gt;everyone’s &lt;/em&gt;tasks for next week, or &lt;em&gt;every &lt;/em&gt;open bug, or &lt;em&gt;every &lt;/em&gt;support case, is likely to be relevant only to the person who organized the meeting. For &lt;em&gt;everyone &lt;/em&gt;else, the meeting SNR is minimal.&lt;/p&gt; &lt;h3&gt;Documents&lt;/h3&gt; &lt;p&gt;Software documents, particularly those created from templates, also often suffer from poor SNR. Instead of getting right down to business telling us the crucial facts, we have to wade through pages of boilerplate sections marked “Not applicable”. &lt;/p&gt; &lt;p&gt;In one company I worked for, there were several pages in every software design document we ever produced devoted to the utterly irrelevant topic of PCB layout. If the first section of your document that contains useful information is numbered 4.6.12.5, something is wrong.&lt;/p&gt; &lt;p&gt;Documents with low SNR actively discourage people from reading. And the less likely anyone is to consult your document, the less motivated you are to write good documentation, resulting in a vicious cycle.&lt;/p&gt; &lt;h3&gt;Presentations&lt;/h3&gt; &lt;p&gt;Presentations can have terribly low SNR. A favourite example is presenters who try to follow the rule that says: &lt;em&gt;“Tell people what you are going to tell them, then tell them, then tell them what you told them”. &lt;/em&gt;&lt;/p&gt; &lt;p&gt;Fine advice, but not when they interpret this as &lt;em&gt;“tell people that you are telling them what it is that you are going to tell them, then tell them that you are telling them the things you told them you were going to tell them, and then tell them that you are telling them that you have finished telling them the things you told them you told them you were going to tell them.”&lt;/em&gt; Instead, use your introduction to make us &lt;em&gt;want &lt;/em&gt;to hear what is coming next.&lt;/p&gt; &lt;p&gt;As with meetings, any attempt to exhaustively cover a topic in a presentation is a mistake. Don’t show me &lt;em&gt;every &lt;/em&gt;possible graph and chart from last quarter’s financial results. Don’t show me &lt;em&gt;every &lt;/em&gt;feature and configuration option.&lt;em&gt;&amp;nbsp;&lt;/em&gt;Show me something interesting. Leave me wanting more at the end of your presentation, not praying for it to end. &lt;/p&gt; &lt;h3&gt;Comments&lt;/h3&gt; &lt;p&gt;Comments in source code are also prime offenders for low SNR. Comments that state the obvious, or are sources of misinformation soon train the developer to completely ignore comments. It’s like the boy who cries wolf. Soon no one is listening anymore. The one really helpful comment you write might as well be invisible. No one will read it.&lt;/p&gt; &lt;p&gt;Comments are like footnotes in a book. Most readers will pause to see what a footnote says the first time they encounter one. But if what they find there is of no relevance or interest to them, they will soon train themselves to stop looking.&lt;/p&gt; &lt;h3&gt;Code&lt;/h3&gt; &lt;p&gt;What about your code? Surely that is all signal right? After all, we can’t delete 50% of the lines and leave the behaviour of the code intact. But the truth is that code can be written in a very noisy way. This happens when so much code for logging, or caching, or error handling, (or whatever) is mixed in that the structure and intent of the method in question is obscured from view. &lt;/p&gt; &lt;p&gt;The solution is simple: write clean code. Extract each task out into small, well-named helper methods or dependencies. This allows people to see the “signal” of what is going on, and only delve into the details that are of interest to them. Implementation details are usually noise.&lt;/p&gt; &lt;h3&gt;Summary&lt;/h3&gt; &lt;p&gt;Stop writing comments that are just noise. Delete comments that are wrong. Refactor “noisy” code out into helper methods. Learn what &lt;a href="http://www.amazon.co.uk/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882"&gt;clean code&lt;/a&gt; is. Hold fewer and shorter meetings. Write shorter documents. Tell me what I need to know. Stop wasting my time.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6822536077160579260-2298485895364052243?l=mark-dot-net.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/markdotnet/~4/XPzX4elYP9k" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/markdotnet/~3/XPzX4elYP9k/development-process-signal-to-noise.html</link><author>noreply@blogger.com (Mark H)</author><thr:total>1</thr:total><feedburner:origLink>http://mark-dot-net.blogspot.com/2011/05/development-process-signal-to-noise.html</feedburner:origLink></item></channel></rss>

