<?xml version="1.0" encoding="utf-8"?><rss version="2.0"><channel><title>Digital Tapestry Blog</title><link>http://www.digitaltapestry.net:80/blog</link><description>Digital Tapestry Blog</description><item><title>Surface Pro Review</title><link>http://www.digitaltapestry.net:80/blog/surface-pro-review</link><description>&lt;p&gt;Well, I could no longer wait for &lt;a href="http://digitaltapestry.net/blog/looking-for-a-windows-8-device"&gt;“the perfect Windows 8 device”&lt;/a&gt; and I purchased a Microsoft Surface Pro. Lots of reviews of this device have already been&amp;nbsp; written, but to be honest, I don’t think many of them have been all that unbiased, one way or the other. I’m going to try and give my own personal review, trying to keep the bias to a minimum, and point out where my own bias is likely to be coloring my thinking.&lt;/p&gt; &lt;p&gt;To start off with, it’s best to explain what I wanted out of the device, as that’s where many biases will come from. I want a device that’s going to enable me to do many diverse tasks. I want a device that’s very good at taking notes in meetings, that I can use as a laptop, that is powerful enough to use for development work and with the help of a docking station can even replace a desktop machine. In other words, I want it all.&lt;/p&gt; &lt;p&gt;Many of you will already be thinking I want too much out of a single device. There’s no way a device can do all of those things optimally. Well, that depends on what you mean by “optimally”. I’m not deluded, I know there has to be compromises made to make a device work for all of these tasks. However, I believe that it is possible to get a reasonable experience for all of these uses out of a single device. Did Microsoft design the Surface Pro well enough for this?&lt;/p&gt; &lt;p&gt;I’ve been using the Surface Pro for only about 3 days now. At this point, I can’t give any final verdicts, but I can record my initial thoughts.&lt;/p&gt; &lt;h1&gt;Build Quality&lt;/h1&gt; &lt;p&gt;There is no arguing about this one… the build quality is very high with the Surface Pro. It’s a beautiful looking device, with a very good display. Touch is accurate and very smooth. Pen input is nearly magical (more on that later). The Type Cover functions very well for such a tiny keyboard, but keep in mind there were compromises made when making the keyboard so small. I’m a fair touch typist, and in general I’m pretty picky about my keyboards. I much prefer full size keyboards over laptop keyboards, for instance. I’d say the keyboard experience on the Type Cover is as good as that of many keyboards on budget laptops, but not as good as on higher end laptops and certainly not comparable to a desktop keyboard of any kind. The keys aren’t really all that cramped, the layout isn’t bad, though it is something I’ll have to adjust to. There’s good tactile feedback and very descent travel considering the unbelievable thinness of the whole keyboard. There does seem to be a minor delay between pressing the keys and the input being accepted, but it’s not affected my typing speed. I’m certainly quicker on my desktop keyboard, but it’s acceptable.&lt;/p&gt; &lt;p&gt;The one very valid complaint you can have with the Type Cover is with the track pad. I’m very budget conscious normally, so all of the laptops I’ve owned (not used) have had lower end track pads. I’ve certainly used track pads that are far worse because of this, but there is no denying that the track pad is “OK” at best. It’s not overly accurate, it doesn’t seem to support multi-touch gestures and it’s very small, requiring multiple gestures to move the cursor across the full screen. On the plus side, it hasn’t annoyed me with many “false clicks” why typing. I hate touch pads to begin with, and this track pad works better than the track pad on my last budget laptop, so I have no complaints, but I know there are many of you out there for whom this will be a major issue.&lt;/p&gt; &lt;h1&gt;Battery Life&lt;/h1&gt; &lt;p&gt;I’ve not used it enough to give any final verdicts here, but I’ve been getting between 3.5-4.5 hours of battery, with some pretty heavy usage (not just browsing the web). That’s not great, but it’s certainly better than I’m used to from my budget laptops. I want more, but it’s enough to get through my use cases. Some people won’t be happy with this, but I’m fine with it when you consider what I want to use the device for. That said, I am hoping the rumored “keyboard dock with battery” does come out. If I could get 6-8 hours when using the device like a laptop it would be an even better experience. Of course, that’s not going to help you if what you want to deal is your typical tablet stuff. If you’re looking for a good tablet, know this is one area where they compromised and you will find better devices for that.&lt;/p&gt; &lt;h1&gt;Screen Size&lt;/h1&gt; &lt;p&gt;This is an area where some reviews have criticized the Surface, and Windows 8 tablets in general. When using it as a tablet, the 16:9 aspect ratio is a little odd. I’ve got smaller hands, and it’s basically impossible for me to reach the center parts of the screen without holding the device in a single hand. It is awkward to hold in portrait mode, and so you wonder why you’d ever want to use it that way. I have found one scenario where portrait mode is great… taking notes in meetings. It’s basically like taking notes on a legal size pad of paper when you use the stylus in portrait mode (more on that later).&lt;/p&gt; &lt;p&gt;The aspect ratio is ideal, though, when watching videos, using the device as a laptop replacement, and surprisingly even when reading eBooks. That one really surprised me. I’ve been reading on NOOK eInk devices for some time now, and until I tried reading on the Surface you never would have convinced me that the 16:9 display would work at all, but in many ways I find I prefer it. On the Surface both the NOOK and the Kindle apps display two pages side by side on the wide display, and I find this to be much closer to the experience you get when reading a real book. The weight of the Surface Pro and the fact that I do prefer reading books on eInk displays means I’m not going to give up my NOOK anytime soon, but I will use the Surface for this from time to time and am excited that I have a device that will work better for text/reference books.&lt;/p&gt; &lt;h1&gt;Note Taking and Ink&lt;/h1&gt; &lt;p&gt;I’ve gotten to take notes twice now, and though I’m still learning the ropes I think this is the killer feature of Windows 8 over the competition. Students and enterprise employees should be aware of the advantages here! The stylus is nearly magical in use. I’ve always had horrible handwriting, and years of neglect thanks to electronic devices it’s only gotten worse. Despite this, the handwriting recognition hardly ever gets it wrong. This morning I was even playing around and used Ink with my finger instead of a stylus, making the handwriting even worse, and yet it recognized nearly everything I wrote.&lt;/p&gt; &lt;p&gt;I’m still learning how to use this type of input, and so I’m not all that efficient at it. Knowing how to make corrections was not intuitive to me, and I didn’t have time in meetings to figure it out, so I took “sloppy” notes and corrected them later. Today, though, I realized there’s very good “tutorial” style help built-in, and I have a much better grasp now on how to use the stylus effectively. I’d strongly suggest playing around with this for a bit before going to your first meeting/class &lt;img class="wlEmoticon wlEmoticon-winkingsmile" style="border-top-style: none; border-left-style: none; border-bottom-style: none; border-right-style: none" alt="Winking smile" src="http://digitaltapestry.net/Media/Default/Windows-Live-Writer/Surface-Pro-Review_6243/wlEmoticon-winkingsmile_2.png"&gt;.&lt;/p&gt; &lt;p&gt;The truth is, a touch typist is always going to be faster with a keyboard than with a pen, but there are so many advantages to taking notes with a pen. You can make drawings, add annotations, and even “organize” things in “mind map” sort of ways that you can’t do with a keyboard. I’m really looking forward to gaining experience in this area.&lt;/p&gt; &lt;h1&gt;“Laptop Mode”&lt;/h1&gt; &lt;p&gt;Lots of people have discussed this one. The “kickstand” does make it awkward to use “in your lap”. That’s probably something that will be completely solved if the rumored “keyboard with battery dock” does come out, but until then there’s a simple fix. Use a lapdesk. Since I prefer a mouse over the track pad I’ve been using one with my laptops for some time now, and the one I currently have (&lt;a title="http://www.amazon.com/Logitech-939-000181-Portable-Lapdesk-N315/dp/B002NTADVW/ref=sr_1_14?ie=UTF8&amp;amp;qid=1368879251&amp;amp;sr=8-14&amp;amp;keywords=laptop+desk" href="http://www.amazon.com/Logitech-939-000181-Portable-Lapdesk-N315/dp/B002NTADVW/ref=sr_1_14?ie=UTF8&amp;amp;qid=1368879251&amp;amp;sr=8-14&amp;amp;keywords=laptop+desk"&gt;http://www.amazon.com/Logitech-939-000181-Portable-Lapdesk-N315/dp/B002NTADVW/ref=sr_1_14?ie=UTF8&amp;amp;qid=1368879251&amp;amp;sr=8-14&amp;amp;keywords=laptop+desk&lt;/a&gt;) works really well. Ideally I’d love to see someone come out with something similar but “optimized” for the Surface (a little deeper and a lot less wide, and if they could figure out how to make it fit in a bag sized for the Surface it would be even better). This is certainly a “compromise” and some won’t care for it, but for most this is probably a very good solution. It works great for me.&lt;/p&gt; &lt;h1&gt;&lt;/h1&gt; &lt;h1&gt;Just a Beginning&lt;/h1&gt; &lt;p&gt;I’ll wrap up for now, as I don’t have enough experience yet for much more than this, but I’ll follow up with other posts as I learn more. Right now, I’d conclude that this isn’t a perfect device, but then none are. It is, however, a very good device, and depending on what you want the device for, I can recommend it. I’m enjoying using it so far.&lt;/p&gt;</description><pubDate>Sat, 18 May 2013 12:18:52 GMT</pubDate><guid isPermaLink="true">http://www.digitaltapestry.net:80/blog/surface-pro-review</guid></item><item><title>Writing PowerShell About Help Topics</title><link>http://www.digitaltapestry.net:80/blog/writing-powershell-about-help-topics</link><description>&lt;p&gt;In my last post one of the best practices I mentioned was including about help topic documentation in your modules. What wasn’t covered there was what your “about_ModuleName.help.txt” file should contain. There doesn’t seem to be much documentation about this anywhere. Basically, this file can contain anything, but you’ll generally want it be similar to other about help topic entries. Luckily, there are quite a few included with PowerShell for us to learn from.&lt;/p&gt; &lt;p&gt;&lt;pre class="brush: powershell"&gt;gci $PSHome -inc *.help.txt -rec&lt;/pre&gt;
&lt;p&gt;This command will show you all of the about help topic files included with PowerShell. By inspecting them we can come up with a few rules to follow when writing our own.&lt;/p&gt;
&lt;p&gt;Each about help topic should include the following sections: TOPIC, SHORT DESCRIPTION, LONG DESCRIPTION and SEE ALSO. Contents of these sections should be indented by 4 characters. Subsections can be included, with their header indented by 2 characters and their contents indented by 6 characters. Lines should not exceed 80 characters in length. Paragraphs should be delimited by blank lines. The first paragraph in the main sections should not have any blank lines between it and the header, while subsections should have a single blank line between the header and the first paragraph. Main section headers should be in all capitals, while subsection headers should be title-cased.&lt;/p&gt;
&lt;p&gt;TOPIC should contain a single line indicating the topic the user used to display this help (e.x. “about_ModuleName”).&lt;/p&gt;
&lt;p&gt;SHORT DESCRIPTION should contain a single paragraph (and no subsections) summarizing the topic.&lt;/p&gt;
&lt;p&gt;LONG DESCRIPTION should contain the full description of the topic and can contain subsections.&lt;/p&gt;
&lt;p&gt;SEE ALSO should contain “links” to other information sources, one per line. Usually this will be other names that can be supplied to Get-Help, but you can also include URLs to online information or other sources.&lt;/p&gt;
&lt;p&gt;Here’s an example format template:&lt;/p&gt;
&lt;p&gt;&lt;pre&gt;TOPIC
    about_TopicTitle

SHORT DESCRIPTION
    One paragraph description of the topic.

LONG DESCRIPTION
    Longer descrition of the topic. This can contain multiple paragrahs and
    subsections. Be sure to manually wrap within 80 columns.

  Some Subheading

      Indent subsections by 6 characters.

SEE ALSO
    http://example.com
    about_SomeOtherTopic
    Get-Foo&lt;/pre&gt;
&lt;p&gt;I'm sure there's other "rules" I've missed, but this is a good starting place.&lt;/p&gt;</description><pubDate>Sat, 06 Apr 2013 13:35:50 GMT</pubDate><guid isPermaLink="true">http://www.digitaltapestry.net:80/blog/writing-powershell-about-help-topics</guid></item><item><title>PowerShell Script Module Best Practices</title><link>http://www.digitaltapestry.net:80/blog/powershell-script-module-best-practices</link><description>&lt;p&gt;I’ve been creating PowerShell script modules a lot lately (more on that later). Doing so, I’ve been learning a lot more about PowerShell and discovering some best practices.&lt;/p&gt; &lt;h1&gt;1. Include a Module Manifest&lt;/h1&gt; &lt;p&gt;Proper script modules should include a module manifest (.psd1) file. The easiest way to create one is with the New-ModuleManifest command. The module manifest file describes everything there is to describe about your module. Failing to include a module manifest is like failing to define assembly info in your .NET projects. You might get away with doing either if the module/assembly were something for your use only, but if you’re going to publish/deploy them, you’d better not forget this. Unfortunately, most of the modules I’ve found that other people have published fail to include a manifest. This is very bad form. It takes only a few seconds to create and edit a manifest file, so if you’re s module publisher, please do so.&lt;/p&gt; &lt;h1&gt;2. Provide About Help Topics&lt;/h1&gt; &lt;p&gt;Many people aren’t aware that you can provide about help topics with modules. It’s actually quite easy to do. About help topics in modules are simply text files with the naming convention about_%topic%.help.txt (where %topic% is replaced with the topic you want to provide help for). You can include any number of these about help topics that you want, but at a minimum you should include an about_%modulename%.help.txt that describes your module. If you create a MediaTags module include a text file named about_MediaTags.help.txt and your users can run the command ‘help about_MediaTags’ to read it. Simple as that. I post another blog post with more details.&lt;/p&gt; &lt;h1&gt;3. Don’t Export Too Much&lt;/h1&gt; &lt;p&gt;Your modules should be focused. If you’re creating a MediaTags module for reading and writing media tags in MP3 files, don’t export a command that’s used to pull an image from a website, even if you use that command internally to the module to say, pull down album art. PowerShell doesn’t provide any sort of namespacing for commands so it’s highly likely that generic commands that aren’t specific to what your module is focused on will clash with commands exported by other modules. This can cause all sorts of confusion to users when they add, remove or reorder import-module commands in their profile. Export the very bare minimum necessary to provide the functionality your focused module demands.&lt;/p&gt; &lt;h1&gt;4. Define Commands as Full Cmdlets&lt;/h1&gt; &lt;p&gt;This means including help document comments, using the [CmdletBinding()] attribute, and using the [Parameter()] attribute when appropriate. If you’re new to this, the easiest thing to do is use the ISE snippets included in PowerShell 3 (you are on version 3, right?). In ISE just press Ctrl+J to access the snippet menu. For the first few commands you create this way I’d suggest using the “Cmdlet (advanced function) – complete” snippet. Once you think you understand how all of this fancy stuff works, you can switch to “Cmdlet (advanced function)” if you’d prefer. I think it’s faster to start with that and add what I need rather than start with the complete version and pare it down. &lt;/p&gt; &lt;p&gt;There’s a couple of reasons why this is a best practice. First, it gives your users the ability to use Get-Help to learn everything there is to know about the commands in your module. Second, it gives you access to some of the advanced PowerShell features that your commands really should be using.&lt;/p&gt; &lt;h1&gt;5. Enable the Pipeline in your Commands&lt;/h1&gt; &lt;p&gt;Using the “ValueFromPipeline” and “ValueFromPipelineByPropertyName” flags of the [Parameter()] attribute you can easily allow your users to pipe values to your commands. Piping is one of the most powerful ways a user can compose commands, and writing a command that doesn’t allow them to do that just makes the command much harder to use. I’m not going to talk about how to write cmdlets that use the pipeline here, as that topic is too complex, but for more information you could start &lt;a href="http://blogs.technet.com/b/heyscriptingguy/archive/2011/05/10/use-the-pipeline-to-create-robust-powershell-functions.aspx"&gt;here&lt;/a&gt;.&lt;/p&gt; &lt;h1&gt;6. Support the Common Parameters&lt;/h1&gt; &lt;p&gt;PowerShell defines a set of common parameters (-Verbose, –Debug, –WarningAction, –WarningVariable, –ErrorAction, –ErrorVariable, –OutVariable, –OutBuffer, –WhatIf and –Confirm). In particular you should support –Verbose (use Write-Verbose liberally) and –Debug (use Write-Debug to put in debugging traces). If your command has any side effects you should also support –WhatIf and –Confirm (another very complex topic, but you can start &lt;a href="http://jdhitsolutions.com/blog/2011/12/add-whatif-support-to-your-powershell-scripts/"&gt;here&lt;/a&gt;).&lt;/p&gt; &lt;h1&gt;7. Perform Error Handling&lt;/h1&gt; &lt;p&gt;Error handling is never easy. In PowerShell, I find it to be even harder. There are so many ways to handle errors, and the default behaviors are so often not what I’d expect coming from a C# programming background. But just like with production code, if you’re going to release a module it’s very important that you handle errors appropriately. Once again, this is a topic that’s too big for this blog post, but you can start learning about error handling in PowerShell &lt;a href="http://blogs.technet.com/b/heyscriptingguy/archive/2011/05/12/powershell-error-handling-and-why-you-should-care.aspx"&gt;here&lt;/a&gt;.&lt;/p&gt; &lt;h1&gt;8. Do Not Use Aliases&lt;/h1&gt; &lt;p&gt;That’s not the same as don’t provide aliases. Aliases are good to have when you’re typing on the command line. But using them within your scripts can make your scripts brittle. Even the built-in aliases, like ‘cd’ can be dangerous to use. Why? Because a user can remove these aliases and break your scripts.&lt;/p&gt; &lt;h1&gt;9. Use Only Allowed Verbs&lt;/h1&gt; &lt;p&gt;PowerShell has a very interesting naming convention. All PowerShell commands provided by modules should follow this naming convention. This means the commands should be in the form Verb-Noun, and the Verb should be from the list of allowed verbs. Don’t know what those verbs are? Type ‘Get-Verb’ at the command line to get a full list. Your commands are much more discoverable if they follow this naming convention, so don’t stray from it.&lt;/p&gt; &lt;p&gt;I use a naming trick in my own modules. Commands that are going to be publicly exported follow the common naming convention very strictly. Commands that I call internally and won’t export I use a more traditional naming convention for. Get-MediaTag would be an exported command, while GetMediaTag would be an internal command.&lt;/p&gt; &lt;h1&gt;10. Use Common Parameter Names and Types&lt;/h1&gt; &lt;p&gt;It’s not a coincidence that many of the parameter names for the out of the box commands are the same. Names like Path, LiteralPath, Recurse, Include, Exclude, etc. are all common across each of the commands. In our hypothetical MediaTag module you would not use a FilePath parameter, but rather a Path parameter in order to keep things consistent (though you could provide an alias). This again makes your commands easier for users to use. Also, it makes it easier to use those parameters in the pipeline with ValueFromPipelineByPropertyName.&lt;/p&gt; &lt;h1&gt;11. Consider Using Arrays for Parameters&lt;/h1&gt; &lt;p&gt;This is an easy one to forget. If you look closely at the built-in commands you’ll notice that a lot of them take arrays for parameters where you might not have expected it. For instance, the –Path parameter on Get-ChildItem is specified as a [string[]]. This provides the user a lot more flexibility in how they use the command.&lt;/p&gt; &lt;h1&gt;12. Validate Parameters&lt;/h1&gt; &lt;p&gt;This is such an important thing to do, but so rarely do I see scripts actually do this. Before doing anything else every parameter should be validated. The worst thing a command could do is get halfway through running before realizing the user gave us bad input and failing. There’s a little known feature of PowerShell that can help make this easy to do, as well. There are several attributes that can be applied to parameters that will cause the input to be validated by PowerShell directly rather than having to do the validation in your command. Check out this &lt;a href="http://blogs.technet.com/b/heyscriptingguy/archive/2011/05/15/simplify-your-powershell-script-with-parameter-validation.aspx"&gt;blog post&lt;/a&gt; to learn more.&lt;/p&gt; &lt;h1&gt;13. Strongly Consider Not Requiring Other Modules&lt;/h1&gt; &lt;p&gt;Modules are harder to use if they require other modules. The module manifest makes it possible to load required modules, but it does nothing to help you ensure that the required modules are available. If you absolutely must require another module, by all means declare so in the manifest, but you’ll be doing your users a favor if they don’t require any other modues.&lt;/p&gt; &lt;h1&gt;14. Test With –NoProfile&lt;/h1&gt; &lt;p&gt;You need to ensure your module works without the requirement of other modules (or at least that required modules are loaded correctly by the manifest), so test this by running PowerShell with the –NoProfile parameter. You can do this directly within a PowerShell session… just type exit when you’re done to return to your original session.&lt;/p&gt; &lt;h1&gt;15. Consider Using Git&lt;/h1&gt; &lt;p&gt;So, your going to publish your module for others to use. Or maybe you just want to be able to use a personal module on multiple machines. Probably the best thing you could do in these scenarios is use Git to publish your module. OK, that’s a bit specific. There are other options here, and using them are fine. I’m suggesting Git for the following reasons. Other options may hit all of these points as well, in which case, sure, use what you like.&lt;/p&gt; &lt;ol&gt; &lt;li&gt;Git provides version control, something critical for any code, and scripts are code.  &lt;li&gt;Git is a DVCS, making it easy for you to use even without a network connection.  &lt;li&gt;Git is quickly being adopted as the DVCS of choice, even on Windows. Even Microsoft has embraced Git nearly everywhere.  &lt;li&gt;Git repositories can easily be cloned into your modules directory for “installation”.  &lt;li&gt;GitHub, Bitbucket, Google Code, CodePlex and others all provide convenient and free hosting of Git projects.&lt;/li&gt;&lt;/ol&gt; &lt;p&gt;If you use Git, consider including a readme.md file, as many of the hosting sites use this file on a project’s landing page to display information about the project to users. The purpose is similar to the about_Module.help.txt, but is viewable before the user ever installs the module.&lt;/p&gt;</description><pubDate>Sat, 06 Apr 2013 12:57:16 GMT</pubDate><guid isPermaLink="true">http://www.digitaltapestry.net:80/blog/powershell-script-module-best-practices</guid></item><item><title>Dispose Pattern Considered Harmful</title><link>http://www.digitaltapestry.net:80/blog/dispose-pattern-considered-harmful</link><description>&lt;h1&gt;Summary (AKA, TLDR)&lt;/h1&gt; &lt;ol&gt; &lt;li&gt;An unmanaged resource should be wrapped in a managed object whose sole purpose is to manage the lifetime of the unmanaged resource. We’ll call this an UnmanagedHandle, and provide a base class that handles the lifetime logic.  &lt;li&gt;Unless a managed type represents an UnmanagedHandle it should contain only managed resources.  &lt;li&gt;If a type contains any IDisposable instances, it should implement IDisposable and implement a simple Dispose that calls Dispose on each of the contained IDisposable instances.&lt;/li&gt;&lt;/ol&gt; &lt;h1&gt;&lt;/h1&gt; &lt;h1&gt;Why is the Dispose Pattern Considered Harmful?&lt;/h1&gt; &lt;p&gt;If you’ve been coding in .NET for any length of time, I’m sure you’ve learned the dispose pattern as it’s documented in the &lt;a href="http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx"&gt;MSDN&lt;/a&gt;. For many I’m sure you’ve committed the pattern to memory without really understanding why it’s written the way it is. Just in case there’s anyone out there that doesn’t know the pattern yet, here’s roughly what it looks like.&lt;/p&gt; &lt;p&gt;&lt;pre class="brush: csharp"&gt;class DisposableType : IDisposable
{
    ~DisposableType()
    {
        this.Dispose(false);
    }

    public void Dispose()
    {
        this.Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            // Dispose managed resources
        }

        // Dispose unmanaged resources
    }
}&lt;/pre&gt;
&lt;p&gt;I've glossed over a lot of details in the above example. Calling Dispose multiple times should be a no-op and calling methods on a disposed object should throw an ObjectDisposedException, so we should include a flag for handling these scenarios. Also, if the type is sealed then Dispose(bool) doesn’t have to be virtual. Further, if the class is sealed and there are no unmanaged types you don’t need Dispose(bool), the finalizer or the call to GC.SuppressFinalize.&lt;/p&gt;
&lt;p&gt;Isn’t that a lot to memorize? I’m sure many of you have managed to do so, but if you’ve memorized it and not figured out why the pattern is the way it is I’m sure you struggle every single time to remember which type of resource is disposed in the ‘if (disposing)’ statement: managed or unmanaged?&lt;/p&gt;
&lt;p&gt;This pattern is just too complicated for all but the most elite (that’s possibly read “arrogant”) of developers. However, in and of itself, that doesn’t constitute enough to call the pattern “harmful”. If all of these rules were strictly necessary to write “correct” disposable objects, then it would be unfortunate but not harmful. However, these rules simply aren’t necessary and there’s a much simpler pattern that could be used instead. If you haven’t already spoiled the article by reading the TLDR summary above, then I’m about to introduce you to the better pattern. Before I do, however, I’ll give credit where credit is due. I didn’t come up with this. I was introduced to the idea by Stephen Cleary in a &lt;a href="http://blog.stephencleary.com/2009/08/how-to-implement-idisposable-and.html"&gt;blog post&lt;/a&gt; rant he wrote about IDisposable and finalizers. While I can’t fully get behind everything in his rant, the idea that there’s a better way to handle IDisposable is undeniable.&lt;/p&gt;
&lt;h1&gt;&lt;/h1&gt;
&lt;h1&gt;What’s the New Pattern?&lt;/h1&gt;
&lt;ol&gt;
&lt;li&gt;An unmanaged resource should be wrapped in a managed object whose sole purpose is to manage the lifetime of the unmanaged resource. We’ll call this an UnmanagedHandle, and provide a base class that handles the lifetime logic. 
&lt;li&gt;Unless a managed type represents an UnmanagedHandle it should contain only managed resources. 
&lt;li&gt;If a type contains any IDisposable instances, it should implement IDisposable and implement a simple Dispose that calls Dispose on each of the contained IDisposable instances.&lt;/li&gt;&lt;/ol&gt;
&lt;h2&gt;&lt;/h2&gt;
&lt;h2&gt;Wrap Unmanaged Resources&lt;/h2&gt;
&lt;p&gt;First, be aware that it’s highly unlikely you’ll need to do anything about this step. Most unmanaged resources you’ll want to use already have managed counterparts. I/O, sockets, databases and many other things already have managed counterparts in the framework. Use those, don’t reinvent the wheel.&lt;/p&gt;
&lt;p&gt;Even if there’s not a managed counterpart, there may well already be a wrapper that can manage the lifetime. Since .NET 2.0 we’ve had SafeHandle. Any OS handle can be wrapped in a SafeHandle to manage the lifetime of the resource, and you should. Don’t roll your own, use the carefully constructed wrapper provided for you.&lt;/p&gt;
&lt;p&gt;If you still need to handle some unmanaged resource yourself, it’s time to create a wrapper. The rules here are very simple. Your wrapper should handle the lifetime of the unmanaged resource, and that is &lt;strong&gt;all&lt;/strong&gt; it should do. In other words, it’s a variation on the SafeHandle, and that’s it. This is SRP (single responsibility principle) at its finest. You’ll use this wrapper in one or more other types that actually use the resource in some way, but this wrapper is solely interested in handling the lifetime.&lt;/p&gt;
&lt;p&gt;This wrapper needs to implement IDisposable, include a finalizer and suppress finalization if the consuming code manually disposes of the object. So implementing this wrapper would be the most complex of all of the IDisposable code you should ever have to write. But remember that I said you probably don’t have to write one of these, and if you do a base class could handle many of the details.&lt;/p&gt;
&lt;p&gt;&lt;pre class="brush: csharp"&gt;public abstract class UnmanagedHandle&amp;lt;ThandleType&amp;gt; : IDisposable
{
    private readonly THandleType nativeHandle;

    protected UnmanagedHandle(THandleType nativeHandle)
    {
        this.nativeHandle = nativeHandle;
    }

    ~UnmanagedHandle()
    {
        this.Dispose();
    }

    public THandleType NativeHandle
    {
        get { return this.nativeHandle; }
    }

    void Dispose()
    {
        this.CloseHandle();
        GC.SuppressFinalize(this);
    }

    protected abstract void CloseHandle();
}&lt;/pre&gt;

&lt;p&gt;With this base class, all you have to do is override the CloseHandle() method. All of the other details are handled for you.&lt;/p&gt;
&lt;h2&gt;Other Managed Types Should NOT Include Unmanaged Resources&lt;/h2&gt;
&lt;p&gt;If you’re not wrapping an unmanaged resource in one of the wrapper types we discussed above, you’re not including it in your code. This means other than your wrapper types no other IDisposable type you ever write will ever have to be concerned (directly) with unmanaged resources. This rule is key to the simplified pattern. When you follow this rule your other IDisposable types never have to have a finalizer, they never have to suppress finalization and you don’t have to have different code paths for disposing and finalizing your object. This means your other IDisposable types are extremely simple to implement. Dispose simply disposes all other IDisposable types it owns and does any other logic you want to do when a user disposes of the object. If the type isn’t sealed, you make Dispose virtual, otherwise you don’t. Done. It’s no longer magical with lots of confusing rules. It’s no different than any other method you’d implement, in fact. Further, since this is likely the only type of IDisposable you’ll ever implement, this means you don’t have to learn a lot of complex rules.&lt;/p&gt;
&lt;h2&gt;Types that Own other IDisposable Types Should be IDisposable&lt;/h2&gt;
&lt;p&gt;This particular rule isn’t new, and doesn’t change the code, but it’s still important to call this rule out in our new pattern. If your new type contains an IDisposable but doesn’t implement IDisposable itself, you have the potential for leaking unmanaged resources or other bad behavior.&lt;/p&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;Ok, this was insightful. If you follow this new pattern you can be sure your code is “correct”, and it’s a lot easier to understand and implement. Even if you’re using IDisposable objects from somewhere else, you can be sure that if you follow these rules your code will be correct. What about other people using your code, though?&lt;/p&gt;
&lt;p&gt;There’s a slight danger here. If you create an IDisposable object other than an UnmanagedHandle and the IDisposable type isn’t sealed, it’s possible that someone will inherit from your type and include an unmanaged resource in their derived type. Because you followed these new rules and not the traditional dispose pattern this means the unmanaged resource won’t be cleaned up by any finalizer. If you follow the new rules you know better than to ever do this, but that doesn’t mean someone that’s not enlightened won’t “do the wrong thing” here. However, in the real world the chances of that happening are really very slim. I mean, you probably have a better chance of winning the lottery. After all we already pointed out how unlikely it is you’ll ever have to create an UnmanagedHandle type. The chances of someone adding an unmanaged resource to a derived IDisposable type are at least as slim as that, and quite likely much slimmer yet. I’m not convinced this is something you really need to worry about. Hopefully the new rules get spread and we simply forget the old rules ever existed, making this a non-concern. Besides, unless you’re writing a framework you have no reason to be concerned in the first place. Application developers can enforce the new rules within their application easily enough.&lt;/p&gt;
&lt;p&gt;The real problem today is with tooling. In particular, I’m going to pick on FxCop/Code Analysis. If you try to follow the new rules but also run Code Analysis you’ll find that the two don’t mix well. Code Analysis really wants you to follow the old rules, even though you should now agree with me that those rules should be considered harmful. Other than just turning that rule off, or suppressing it every time, I’m not sure what to say about this. Hopefully at some point enough people with the power to change things will come to agree, and tools will stop pushing the dispose pattern on us.&lt;/p&gt;</description><pubDate>Fri, 15 Mar 2013 14:27:00 GMT</pubDate><guid isPermaLink="true">http://www.digitaltapestry.net:80/blog/dispose-pattern-considered-harmful</guid></item><item><title>Looking for a Windows 8 Device</title><link>http://www.digitaltapestry.net:80/blog/looking-for-a-windows-8-device</link><description>&lt;p&gt;I really think there’s a reason that Windows 8 isn’t selling like mad, and it has little to do with the typical complaints from the pundits. It’s all about the devices, really. See, I’m really wanting to purchase a new device, and I don’t think what I want is at all unreasonable, but I just can’t find anything in the marketplace that will work, much less that I’d want to spend money on.&lt;/p&gt; &lt;p&gt;Here’s what I want, broken down into Must Have (won’t even consider something that doesn’t meet these requirements), Should Have (if I absolutely have to compromise I can, but I won’t be at all happy about) and Want (I’ll compromise on these, but I shouldn’t have to).&lt;/p&gt; &lt;h1&gt;Must Have&lt;/h1&gt; &lt;ul&gt; &lt;li&gt;Tablet usage&lt;/li&gt; &lt;li&gt;Core i5 or better with Hyper-V capabilities&lt;/li&gt; &lt;li&gt;128GB or better SSD&lt;/li&gt; &lt;li&gt;4GB or better RAM&lt;/li&gt; &lt;li&gt;1366x768 or better resolution (hard minimum for Snap)&lt;/li&gt; &lt;li&gt;IPS display&lt;/li&gt; &lt;li&gt;USB 3.0&lt;/li&gt; &lt;li&gt;Bluetooth&lt;/li&gt; &lt;li&gt;HDMI (micro is OK) and/or Display Port&lt;/li&gt; &lt;li&gt;WiFi&lt;/li&gt; &lt;li&gt;Keyboard (laptop-style usage)&lt;/li&gt;&lt;/ul&gt; &lt;h2&gt;Should Have&lt;/h2&gt; &lt;ul&gt; &lt;li&gt;Digitizer pen support&lt;/li&gt; &lt;li&gt;Extended battery life (want real 6-9 hours of use between charges)&lt;/li&gt; &lt;li&gt;Tablet weight less than 2.5 pounds (obviously less than 2 pounds would be preferred, not as concerned about overall weight if/when docked to a keyboard)&lt;/li&gt;&lt;/ul&gt; &lt;h1&gt;Want&lt;/h1&gt; &lt;ul&gt; &lt;li&gt;Discrete GPU&lt;/li&gt; &lt;li&gt;Full HD 1080p&lt;/li&gt; &lt;li&gt;GPS&lt;/li&gt; &lt;li&gt;NFC&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;Final price should be less than $1500 USD. Having seen the options that are out there, all of the above is realistic at this price point. Realistic doesn’t mean such a device exists, though. There’s a few options that come close, but none quite do it. Here’s the long list of the options I’ve looked at and what I think of them.&lt;/p&gt; &lt;h1&gt;&lt;a href="http://www.microsoft.com/Surface/en-US/surface-with-windows-8-pro/home"&gt;Surface Pro&lt;/a&gt;&lt;/h1&gt; &lt;p&gt;Very nice device with excellent build quality. This is probably the closest device to what I want. Main issues are: battery life is probably between 4-5 hours and I’m not convinced I can use the device as a laptop. It’s the device on the market right now I can most see myself compromising for… but why should I compromise?&lt;/p&gt; &lt;h1&gt;&lt;a href="http://www.asus.com/Notebooks/Superior_Mobility/ASUS_Transformer_Book_TX300/#specifications"&gt;Asus Transformer Book TX300&lt;/a&gt;&lt;/h1&gt; &lt;p&gt;Man, do I want to pull the trigger on this one. Design wise, this is closer to what I want than the Surface is. In fact, the only reason this one doesn’t automatically qualify is that it doesn’t have digitizer pen support. I really don’t want to compromise on that. Because the Surface has a digitizer pen I’m ever so slightly leaning towards it instead of this one. But if you want to know what I’d love to own, it’s this with a digitizer pen. It doesn’t have the things on my want list, but I’ll gladly do without those for everything this offers.&lt;/p&gt; &lt;h1&gt;&lt;a href="http://www.pcmag.com/article2/0,2817,2413883,00.asp"&gt;Lenovo Helix&lt;/a&gt;&lt;/h1&gt; &lt;p&gt;Technically, this is the only device that meets all of my requirements (except maybe battery life). Design wise, though, this thing is a dog. The dock is ugly, they keys look awkward, and I can’t stand “eraser head” mouse devices. Tell me why I need a touch screen, touchpad AND eraser head? Maybe I’m being too critical, and I am considering this device because it does meet my requirements, but when people say the existing devices underwhelm you need look no further than this one to understand what they mean.&lt;/p&gt; &lt;h1&gt;&lt;a href="http://www.asus.com/Notebooks/Superior_Mobility/ASUS_TAICHI_21/#specifications"&gt;Asus Taichi&lt;/a&gt;&lt;/h1&gt; &lt;p&gt;This one is interesting, but I just don’t think the design is as nice as the Transformer Book. I guess this one technically meets my requirements, but the dual display concept is a little off putting. I might be convinced to compromise for this one, except the inner screen isn’t touch capable. Still in the running, but I’d rather have the Transformer Book design.&lt;/p&gt; &lt;h1&gt;&lt;a href="http://www.dell.com/us/p/xps-12-l221x/pd"&gt;Dell XPS 12&lt;/a&gt;&lt;/h1&gt; &lt;p&gt;This one is really not too bad. I’d prefer a detachable tablet over the flip screen design. It’s unclear to me if this has pen support, though. This is in the running, but down the list.&lt;/p&gt; &lt;h1&gt;&lt;a href="http://www.toshibadirect.com/td/b2c/pdet.to?poid=2000040279"&gt;Toshiba Satellite U925T-S2300&lt;/a&gt;&lt;/h1&gt; &lt;p&gt;I love Toshiba laptops, and this one has most of the features I want (pretty sure it’s also missing the pen input) at a really great price. So I should be excited about this one. However, I’d still prefer a detachable tablet and I’ve read some reviews that say the touch screen isn’t sensitive enough, so I’m not sure this one is even in the running.&lt;/p&gt; &lt;h1&gt;Lenovo Yoga&lt;/h1&gt; &lt;p&gt;This is certainly an interesting device. The recently announced 11” version that will sport the newer Intel chips (with 9 hour battery life in an i5) is certainly something I’m considering. The 13” version is better as a laptop, but laptop usage is secondary to me. I’ll more often be using the device as a laptop or docked to full monitors/keyboards/mice as a desktop replacement. The tablet mode for these devices is a bit compromised, since the keyboard not only isn’t detachable, but the keys are exposed in the back. Like I said, worth considering since I believe the new 11” version has everything I want, but I much prefer the Transformer Book design.&lt;/p&gt; &lt;h1&gt;&lt;a href="http://store.sony.com/webapp/wcs/stores/servlet/CategoryDisplay?catalogId=10551&amp;amp;storeId=10151&amp;amp;langId=-1&amp;amp;categoryId=8198552921644884501"&gt;Sony VAIO Duo 11&lt;/a&gt;&lt;/h1&gt; &lt;p&gt;Don’t like the design at all. Not only does this not have a detachable tablet design, the “slider” design results in a fixed angle display in laptop mode, with a terrible keyboard design. This may be for some people, but not me.&lt;/p&gt; &lt;h1&gt;&lt;a href="http://www.samsung.com/us/computer/tablet-pcs/XE700T1C-A01US"&gt;Samsung ATIV Smart PC Pro 700T&lt;/a&gt;&lt;/h1&gt; &lt;p&gt;This is another one that’s oh so close, yet isn’t really there. The design is very similar to the Transformer Book, and does include digitizer pen support! However, the keyboard dock design isn’t anywhere near as good, and doesn’t give you any extra battery life. Worse, this means the keyboard doesn’t have as much weight, making the overall design a bit top heavy in laptop mode. Certainly in the running, but every time I come back to this all I can think is that it’s not the Transformer Book. I’m pretty sure that if I bought this device I’d always be wondering if I made the right choice. Is the pen worth the build quality and battery life compromises? In case you haven’t seen the trend here, I really want that Transformer Book with pen support!&lt;/p&gt; &lt;h1&gt;&lt;a href="http://www.razerzone.com/gaming-systems/razer-edge-pro"&gt;Razer Edge Pro&lt;/a&gt;&lt;/h1&gt; &lt;p&gt;This is a very good design, especially if you’re a gamer. I would expect a lot of people to be excited about this device. It’s not got the build quality of a Surface, or even of the Transformer Book. It’s your typical “plastic” design, actually. But it’s a power horse that includes a discrete GPU capable of playing all your PC games. There’s a very interesting “Mobile Console Mode” dock that gives you on the go game controls. There’s also a really nice “Home Console Mode” dock that gives you plenty of ports for all of your peripherals and allows this to easily replace a desktop system. There’s even a “Keyboard Mode” dock that gives you laptop capabilities. I’m not thrilled by the keyboard dock, though. There’s no touchpad on the keyboard, and the keys look a little cramped. Worse, I can’t tell for sure but it looks like the screen might be at a fixed angle when docked to this keyboard. However, it does look passable in design. Once again, what’s leaving it out of consideration by me is the lack of digitizer pen support. If they both had pen support I don’t know if I’d rather pay the extra $300 for the Transformer Book design and quality or save the money for the gaming capabilities of this guy. Really, did I just say you’d save money getting gaming capabilities in a mobile device? That goes to show you how the current devices are all over the map and never hitting the sweet spot. &lt;img class="wlEmoticon wlEmoticon-sadsmile" style="border-top-style: none; border-left-style: none; border-bottom-style: none; border-right-style: none" alt="Sad smile" src="http://digitaltapestry.net/Media/Default/Windows-Live-Writer/1deb7f182eaf_C9E4/wlEmoticon-sadsmile_2.png"&gt;&lt;/p&gt; &lt;h1&gt;Conclusion&lt;/h1&gt; &lt;p&gt;There’s devices that come close, but every last one falls short in one way or another, and there’s simply no reason for this to be the case. It’s frustrating, really.&lt;/p&gt; &lt;p&gt;Anyone know if there’s any devices out there that I’ve overlooked? Even if you don’t know of one that you think exactly fits what I’m looking for, I’d love to know about any devices that come close. If you’ve got any experience with any of this and would like to chime in about my analysis, I’d love that as well. If I’m going to spend this kind of money, I want to be sure I’ll be happy with the purchase.&lt;/p&gt;</description><pubDate>Thu, 10 Jan 2013 21:11:58 GMT</pubDate><guid isPermaLink="true">http://www.digitaltapestry.net:80/blog/looking-for-a-windows-8-device</guid></item><item><title>Parsing Monads Part 3</title><link>http://www.digitaltapestry.net:80/blog/parsing-monads-part-3</link><description>&lt;p&gt;I learned something new recently, and it’s something that has me so excited I had to blog about it. Actually, I learned two things. I learned about a really cool functional way of writing parsers, and in the process finally learned what a monad is. It’s going to take a lot to fully blog about this, so this is going to be a series of blog posts.  &lt;ul&gt; &lt;li&gt;&lt;a href="http://digitaltapestry.net/blog/parsing-monads-part-1"&gt;Parsing Monads Part 1&lt;/a&gt;  &lt;li&gt;&lt;a href="http://digitaltapestry.net/blog/parsing-monads-part-2"&gt;Parsing Monads Part 2&lt;/a&gt;  &lt;li&gt;&lt;strong&gt;Parsing Monads Part 3&lt;/strong&gt;  &lt;li&gt;&lt;em&gt;more to come… stay tuned&lt;/em&gt;&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;Last time we implemented the bare essentials for a parsing monad, and showed how this basis could be used to write more complex parsers through functional composition. However, for most C# developers the idea of functional composition is probably a little foreign. The syntax used when building our simple “ab” parser probably was hard to understand for some because of this.&lt;/p&gt; &lt;p&gt;Well, if you were in that camp it might surprise you to learn that actually you probably do write code that uses functional composition. LINQ in C# brought functional composition and even monads into our language and every day usage. In doing so they brought in some syntactic changes as well, but the code from last time didn’t take advantage of. In this post we’ll rectify that, and make our code more idiomatic for C# developers.&lt;/p&gt; &lt;p&gt;We’ll start with the easy stuff. Names like Unit, Bind, etc. just aren’t familiar names for us. We can go a long way towards helping the code be more understandable just by changing a few names.&lt;/p&gt; &lt;table cellspacing="0" cellpadding="2" width="400" border="1"&gt; &lt;tbody&gt;&lt;tr&gt;&lt;th&gt;Old Name&lt;/th&gt;&lt;th&gt;New Name&lt;/th&gt;&lt;/tr&gt; &lt;tr&gt; &lt;td valign="top" width="200"&gt;Unit&lt;/td&gt; &lt;td valign="top" width="200"&gt;Return&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt; &lt;td valign="top" width="200"&gt;Bind&lt;/td&gt; &lt;td valign="top" width="200"&gt;Then&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt; &lt;td valign="top" width="200"&gt;Zero&lt;/td&gt; &lt;td valign="top" width="200"&gt;Fail&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt; &lt;td valign="top" width="200"&gt;Item&lt;/td&gt; &lt;td valign="top" width="200"&gt;Char&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt; &lt;p&gt;With those changes we can see our “ab” parser start to look just a little more meaningful.&lt;/p&gt; &lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:098acf35-f36c-4bd5-83b3-eaec38201b6a" class="wlWriterSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px"&gt;&lt;pre class="brush: c#;"&gt;            var a = Then(Char(), c =&amp;gt;
                c == 'a' ?
                    Return(c) :
                    Fail&amp;lt;char&amp;gt;());
            var b = Then(Char(), c =&amp;gt;
                c == 'b' ?
                    Return(c) :
                    Fail&amp;lt;char&amp;gt;());
            var parser = Then(a, ar =&amp;gt; 
                Then(b, br =&amp;gt;
                    Return(string.Format("{0},{1}", ar, br))));
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The biggest thing that sticks out now is how Then seems inverted. We can fix that by turning Then into an extension method.&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:d9ad58e3-d8ca-4a68-b6e7-2d6261c300a9" class="wlWriterSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px"&gt;&lt;pre class="brush: c#;"&gt;        public static Parser&amp;lt;U&amp;gt; Then&amp;lt;T, U&amp;gt;( // Bind
            this Parser&amp;lt;T&amp;gt; parser,
            Func&amp;lt;T, Parser&amp;lt;U&amp;gt;&amp;gt; binder)
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Now our grammar is really starting to become easier to read.&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:17e5445b-5b95-4a77-8514-2eee89ca2b1c" class="wlWriterSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px"&gt;&lt;pre class="brush: c#;"&gt;            var a = Char().Then(c =&amp;gt;
                c == 'a' ?
                    Return(c) :
                    Fail&amp;lt;char&amp;gt;());
            var b = Char().Then(c =&amp;gt;
                c == 'b' ?
                    Return(c) :
                    Fail&amp;lt;char&amp;gt;());
            var parser = a.Then(ar =&amp;gt; 
                b.Then(br =&amp;gt;
                    Return(string.Format("{0},{1}", ar, br))));
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;We can do even better though. By defining Where, Select and SelectMany extension methods we can actually use the LINQ query comprehension syntax to make our grammar even easier to understand.&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:34c22b64-24a2-4775-81da-c034c3cdff3f" class="wlWriterSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px"&gt;&lt;pre class="brush: c#;"&gt;        public static Parser&amp;lt;T&amp;gt; Where&amp;lt;T&amp;gt;(
            this Parser&amp;lt;T&amp;gt; parser,
            Predicate&amp;lt;T&amp;gt; predicate)
        {
            return parser.Then(t =&amp;gt; predicate(t) ? Return(t) : Fail&amp;lt;T&amp;gt;());
        }

        public static Parser&amp;lt;U&amp;gt; Select&amp;lt;T, U&amp;gt;(
            this Parser&amp;lt;T&amp;gt; parser,
            Func&amp;lt;T, U&amp;gt; selector)
        {
            return parser.Then(t =&amp;gt; Return(selector(t)));
        }

        public static Parser&amp;lt;V&amp;gt; SelectMany&amp;lt;T, U, V&amp;gt;(
            this Parser&amp;lt;T&amp;gt; parser,
            Func&amp;lt;T, Parser&amp;lt;U&amp;gt;&amp;gt; parserSelector,
            Func&amp;lt;T, U, V&amp;gt; resultSelector)
        {
            return parser.Then(t =&amp;gt;
                parserSelector(t).Then(u =&amp;gt;
                    Return(resultSelector(t, u))));
        }
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Where and Select are pretty straightforward. SelectMany may throw some people off. Some people may not even be aware of Enumerable.SelectMany, and those that are familiar with it probably aren’t familiar with the overload that takes three parameters. If you stop and think about it for a bit though maybe you’ll see that SelectMany with two parameters is the Bind operation for IEnumerable&amp;lt;T&amp;gt; while the SelectMany with three parameters combines Bind and Unit into a single operation. What the query comprehension syntax needs is the three parameter version of SelectMany and we’ll opt to keep the name Then for the two parameter version for our parsing monad.&lt;/p&gt;
&lt;p&gt;For those not familiar with SelectMany, this is the operation that allows you to combine multiple from statements in your query comprehension. As we’ll see next when we transform our “ab” parser to use the LINQ syntax, this makes our parsers a lot easier to write and understand for those new to functional programming but comfortable with LINQ.&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:5c7a0c69-e143-4423-8b90-45a054c8545a" class="wlWriterSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px"&gt;&lt;pre class="brush: c#;"&gt;            var a = from c in Char()
                    where c == 'a'
                    select c;
            var b = from c in Char()
                    where c == 'b'
                    select c;
            var parser = from ar in a
                         from br in b
                         select string.Format("{0},{1}", ar, br);
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;To me at least, that’s very understandable. It might seem a little magical how it works (though if you’ve understood the code up to this point, hopefully it’s not too magical), but I can easily read that code and understand the grammar being defined here. More importantly, it should be pretty easy to use this very limited basis for a parsing monad to write some pretty complex parsers. Before tackling a more complicated grammar, though, there’s a few more things we need to address, so this blog series shall continue. For now, here’s the complete code from this post.&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:9c0df1c9-b2d5-4cc5-a106-da47295d1e83" class="wlWriterSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px"&gt;&lt;pre class="brush: c#;"&gt;using System;

namespace Parsing
{
    static class Program
    {
        public interface IInput
        {
            bool IsAtEnd { get; }
            char Current { get; }
            IInput Consume();
        }
        
        public class StringInput : IInput
        {
            private readonly string source;
            private readonly int pos;
            
            public StringInput(string source)
                : this(source, 0)
            {
            }
            
            private StringInput(string source, int pos)
            {
                this.source = source;
                this.pos = pos;
            }
            
            public bool IsAtEnd
            {
                get
                {
                    return this.pos == this.source.Length;
                }
            }
            
            public char Current
            {
                get { return this.source[this.pos]; }
            }
            
            public IInput Consume()
            {
                return new StringInput(this.source, this.pos + 1);
            }
        }
        
        public class ParseResult&amp;lt;T&amp;gt;
        {
            private readonly T value;
            private readonly IInput remainingInput;
            
            public ParseResult(T value, IInput remainingInput)
            {
                this.value = value;
                this.remainingInput = remainingInput;
            }
            
            public T Value
            {
                get { return this.value; }
            }
            
            public IInput RemainingInput
            {
                get { return this.remainingInput; }
            }
            
            public override string ToString()
            {
                return this.Value.ToString();
            }
        }
        
        public delegate ParseResult&amp;lt;T&amp;gt; Parser&amp;lt;T&amp;gt;(IInput input);
        
        public static Parser&amp;lt;T&amp;gt; Return&amp;lt;T&amp;gt;(T value) // Unit
        {
            return input =&amp;gt; new ParseResult&amp;lt;T&amp;gt;(value, input);
        }
        
        public static Parser&amp;lt;U&amp;gt; Then&amp;lt;T, U&amp;gt;( // Bind
            this Parser&amp;lt;T&amp;gt; parser,
            Func&amp;lt;T, Parser&amp;lt;U&amp;gt;&amp;gt; binder)
        {
            return input =&amp;gt;
            {
                var result = parser(input);
                return result == null ?
                    null :
                    binder(result.Value)(result.RemainingInput);
            };
        }
        
        public static Parser&amp;lt;T&amp;gt; Fail&amp;lt;T&amp;gt;() // Zero
        {
            return input =&amp;gt; null;
        }
        
        public static Parser&amp;lt;char&amp;gt; Char() // Item
        {
            return input =&amp;gt; input.IsAtEnd ?
                null :
                new ParseResult&amp;lt;char&amp;gt;(input.Current, input.Consume());
        }

        public static Parser&amp;lt;T&amp;gt; Where&amp;lt;T&amp;gt;(
            this Parser&amp;lt;T&amp;gt; parser,
            Predicate&amp;lt;T&amp;gt; predicate)
        {
            return parser.Then(t =&amp;gt; predicate(t) ? Return(t) : Fail&amp;lt;T&amp;gt;());
        }

        public static Parser&amp;lt;U&amp;gt; Select&amp;lt;T, U&amp;gt;(
            this Parser&amp;lt;T&amp;gt; parser,
            Func&amp;lt;T, U&amp;gt; selector)
        {
            return parser.Then(t =&amp;gt; Return(selector(t)));
        }

        public static Parser&amp;lt;V&amp;gt; SelectMany&amp;lt;T, U, V&amp;gt;(
            this Parser&amp;lt;T&amp;gt; parser,
            Func&amp;lt;T, Parser&amp;lt;U&amp;gt;&amp;gt; parserSelector,
            Func&amp;lt;T, U, V&amp;gt; resultSelector)
        {
            return parser.Then(t =&amp;gt;
                parserSelector(t).Then(u =&amp;gt;
                    Return(resultSelector(t, u))));
        }
        
        static void Main(string[] args)
        {
            var a = from c in Char()
                    where c == 'a'
                    select c;
            var b = from c in Char()
                    where c == 'b'
                    select c;
            var parser = from ar in a
                         from br in b
                         select string.Format("{0},{1}", ar, br);
            
            Display(parser, "ab");
            Display(parser, "a");
            
            Console.WriteLine();
            Console.WriteLine("Press any key");
            Console.ReadKey();
        }
        
        static void Display&amp;lt;T&amp;gt;(Parser&amp;lt;T&amp;gt; parser, string input)
        {
            var result = parser(new StringInput(input));
            if (result != null)
            {
                Console.WriteLine(result);
            }
            else
            {
                Console.WriteLine("failure");
            }
        }
    }
}&lt;/pre&gt;&lt;/div&gt;</description><pubDate>Sat, 22 Sep 2012 11:50:04 GMT</pubDate><guid isPermaLink="true">http://www.digitaltapestry.net:80/blog/parsing-monads-part-3</guid></item><item><title>Parsing Monads Part 2</title><link>http://www.digitaltapestry.net:80/blog/parsing-monads-part-2</link><description>&lt;p&gt;I learned something new recently, and it’s something that has me so excited I had to blog about it. Actually, I learned two things. I learned about a really cool functional way of writing parsers, and in the process finally learned what a monad is. It’s going to take a lot to fully blog about this, so this is going to be a series of blog posts.  &lt;ul&gt; &lt;li&gt;&lt;a href="http://digitaltapestry.net/blog/parsing-monads-part-1"&gt;Parsing Monads Part 1&lt;/a&gt;  &lt;li&gt;&lt;strong&gt;Parsing Monads Part 2&lt;/strong&gt; &lt;li&gt;&lt;a href="http://digitaltapestry.net/blog/parsing-monads-part-3"&gt;Parsing Monads Part 3&lt;/a&gt; &lt;li&gt;&lt;em&gt;more to come… stay tuned&lt;/em&gt;&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;Last time I introduced you to monads and showed you how to define them in C# with the simple identity and maybe monadic types. This time I’m going to start creating a parsing monad that will allow you to use functional composition in order to build very sophisticated text parsers. Let’s get started.&lt;/p&gt; &lt;p&gt;We’ll start by defining our monadic type. If we think about what it is we need to do, parse some value from some given input text, we can fairly easily come up with this for our monadic type.&lt;/p&gt; &lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:209151e9-96de-4a0d-b353-f1b1aa757c12" class="wlWriterEditableSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px"&gt;&lt;pre class="brush: c#;"&gt;public delegate T Parser&amp;lt;T&amp;gt;(string input);&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;This isn’t a bad start, however if you think about it a bit deeper you’ll realize that in order to compose these parsers we need them to not only return some value, but also return something to indicate the text remaining to parse. So, rather than returning T we’ll return a ParseResult&amp;lt;T&amp;gt; type that includes both the result value but also the remaining input. While we’re at it I’m also going to change the input type from string to an IInput interface. Not only will this allow us to accept input from different sources (such as a Stream) by supplying different implementations of the interface, it will also allow us to include other state information about the input stream. For now we’ll provide only a single StringInput implementation and minimal state information, but in the future the decision to use this interface will be important. So, with these changes we’ll modify our Parser monad.&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:2089fb47-e59d-425c-815e-a10591c507dd" class="wlWriterEditableSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px"&gt;&lt;pre class="brush: c#;"&gt;public delegate ParseResult&amp;lt;T&amp;gt; Parser&amp;lt;T&amp;gt;(IInput input);&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;For now I’m going to gloss over IInput and ParseResult&amp;lt;T&amp;gt; in order to just focus on the monadic parser. You can see the implementation of these types in the code at the end of this post.&lt;/p&gt;
&lt;p&gt;So, to complete our Kleisli triple for the parsing monad we need Unit and Bind operations.&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:5b82263f-49e3-4deb-981c-78eb5c3f22a2" class="wlWriterEditableSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px"&gt;&lt;pre class="brush: c#;"&gt;        public static Parser&amp;lt;T&amp;gt; Unit&amp;lt;T&amp;gt;(T value)
        {
            return input =&amp;gt; new ParseResult&amp;lt;T&amp;gt;(value, input);
        }

        public static Parser&amp;lt;U&amp;gt; Bind&amp;lt;T, U&amp;gt;(Parser&amp;lt;T&amp;gt; parser, Func&amp;lt;T, Parser&amp;lt;U&amp;gt;&amp;gt; binder)
        {
            return input =&amp;gt;
            {
                var result = parser(input);
                return result == null ?
                    null :
                    binder(result.Value)(result.RemainingInput);
            };
        }
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Unit was really simple. It just returns a ParseResult&amp;lt;T&amp;gt; with the specified value and the initial input (i.e. it returns a value without consuming any input). Bind is fairly simple as well. For now we’re going to return null from any Parser&amp;lt;T&amp;gt; that fails to parse. So we first call the initial parser. If it returns null, we also return null, otherwise we use the Func&amp;lt;T, Parser&amp;lt;U&amp;gt;&amp;gt; to obtain the next parser and call it with the remaining input.&lt;/p&gt;
&lt;p&gt;Right now this may seem way too simple, but this is actually all that’s needed to implement all the other compositional operations for our parsing needs. We really only need one more building block to get started parsing text. Unit returns a value without actually consuming or parsing any of the input. We need some way to actually consume and parse something. For this we’ll define an Item operation that will create a Parser&amp;lt;T&amp;gt; that will consume a single character from the input.&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:8f0ae979-a362-459b-b906-e67d3abb0afe" class="wlWriterEditableSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px"&gt;&lt;pre class="brush: c#;"&gt;        public static Parser&amp;lt;char&amp;gt; Item()
        {
            return input =&amp;gt; input.IsAtEnd ?
                null :
                new ParseResult&amp;lt;char&amp;gt;(input.Current, input.Consume());
        }
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;I said we only needed one more thing, but to simplify some of the code to come we’re also going to define a Zero operation. Zero will return us a Parser&amp;lt;T&amp;gt; that always fails.&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:d1e506a9-93cf-4e6f-8ff8-b339b22e87d7" class="wlWriterEditableSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px"&gt;&lt;pre class="brush: text;"&gt;        public static Parser&amp;lt;T&amp;gt; Zero&amp;lt;T&amp;gt;()
        {
            return input =&amp;gt; null;
        }
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;There we have it. A parsing monad. To illustrate its use we’ll create a very simple parser that simply parses the text “ab” (an ‘a’ followed by a ‘b’). This is a very trivial and meaningless parser, but it does illustrate how we can user our parser monad to compose larger parsers.&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:ad59b5e1-fe7b-48d6-a87b-d88347dfd0b7" class="wlWriterEditableSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px"&gt;&lt;pre class="brush: text;"&gt;            var a = Item().Bind(c =&amp;gt; c == 'a' ? Unit(c) : Zero&amp;lt;char&amp;gt;());
            var b = Item().Bind(c =&amp;gt; c == 'b' ? Unit(c) : Zero&amp;lt;char&amp;gt;());
            var parser = a.Bind(ar =&amp;gt; b.Bind(br =&amp;gt; Unit(string.Format("{0},{1}", ar, br))));

            Display(parser, "ab");
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;This will parse “ab” and display “a,b” to the console as a result. Here’s the complete code listing.&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:01f77daa-aae5-42b7-b91a-cae9a7abdd5e" class="wlWriterEditableSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px"&gt;&lt;pre class="brush: c#;"&gt;using System;

namespace Parsing
{
    static class Program
    {
        public interface IInput
        {
            bool IsAtEnd { get; }
            char Current { get; }
            IInput Consume();
        }

        public class StringInput : IInput
        {
            private readonly string source;
            private readonly int pos;

            public StringInput(string source)
                : this(source, 0)
            {
            }

            private StringInput(string source, int pos)
            {
                this.source = source;
                this.pos = pos;
            }

            public bool IsAtEnd
            {
                get { return this.pos == this.source.Length; }
            }

            public char Current
            {
                get { return this.source[this.pos]; }
            }

            public IInput Consume()
            {
                return new StringInput(this.source, this.pos + 1);
            }
        }

        public class ParseResult&amp;lt;T&amp;gt;
        {
            private readonly T value;
            private readonly IInput remainingInput;

            public ParseResult(T value, IInput remainingInput)
            {
                this.value = value;
                this.remainingInput = remainingInput;
            }

            public T Value
            {
                get { return this.value; }
            }

            public IInput RemainingInput
            {
                get { return this.remainingInput; }
            }

            public override string ToString()
            {
                return this.Value.ToString();
            }
        }

        public delegate ParseResult&amp;lt;T&amp;gt; Parser&amp;lt;T&amp;gt;(IInput input);

        public static Parser&amp;lt;T&amp;gt; Unit&amp;lt;T&amp;gt;(T value)
        {
            return input =&amp;gt; new ParseResult&amp;lt;T&amp;gt;(value, input);
        }

        public static Parser&amp;lt;U&amp;gt; Bind&amp;lt;T, U&amp;gt;(
            Parser&amp;lt;T&amp;gt; parser,
            Func&amp;lt;T, Parser&amp;lt;U&amp;gt;&amp;gt; binder)
        {
            return input =&amp;gt;
            {
                var result = parser(input);
                return result == null ?
                    null :
                    binder(result.Value)(result.RemainingInput);
            };
        }

        public static Parser&amp;lt;T&amp;gt; Zero&amp;lt;T&amp;gt;()
        {
            return input =&amp;gt; null;
        }

        public static Parser&amp;lt;char&amp;gt; Item()
        {
            return input =&amp;gt; input.IsAtEnd ?
                null :
                new ParseResult&amp;lt;char&amp;gt;(input.Current, input.Consume());
        }

        static void Main(string[] args)
        {
            var a = Item().Bind(c =&amp;gt; c == 'a' ? Unit(c) : Zero&amp;lt;char&amp;gt;());
            var b = Item().Bind(c =&amp;gt; c == 'b' ? Unit(c) : Zero&amp;lt;char&amp;gt;());
            var parser = a.Bind(ar =&amp;gt;
                b.Bind(br =&amp;gt; Unit(string.Format("{0},{1}", ar, br))));

            Display(parser, "ab");
            Display(parser, "a");

            Console.WriteLine();
            Console.WriteLine("Press any key");
            Console.ReadKey();
        }

        static void Display&amp;lt;T&amp;gt;(Parser&amp;lt;T&amp;gt; parser, string input)
        {
            var result = parser(new StringInput(input));
            if (result != null)
            {
                Console.WriteLine(result);
            }
            else
            {
                Console.WriteLine("failure");
            }
        }
    }
}
&lt;/pre&gt;&lt;/div&gt;</description><pubDate>Sat, 22 Sep 2012 11:43:54 GMT</pubDate><guid isPermaLink="true">http://www.digitaltapestry.net:80/blog/parsing-monads-part-2</guid></item><item><title>Parsing Monads Part 1</title><link>http://www.digitaltapestry.net:80/blog/parsing-monads-part-1</link><description>&lt;p&gt;I learned something new recently, and it’s something that has me so excited I had to blog about it. Actually, I learned two things. I learned about a really cool functional way of writing parsers, and in the process finally learned what a monad is. It’s going to take a lot to fully blog about this, so this is going to be a series of blog posts.&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;strong&gt;Parsing Monads Part 1&lt;/strong&gt;  &lt;li&gt;&lt;a href="http://digitaltapestry.net/blog/parsing-monads-part-2"&gt;Parsing Monads Part 2&lt;/a&gt;  &lt;li&gt;&lt;a href="http://digitaltapestry.net/blog/parsing-monads-part-3"&gt;Parsing Monads Part 3&lt;/a&gt; &lt;li&gt;&lt;em&gt;more to come… stay tuned&lt;/em&gt;&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;I’ve written my fair share of parsers in the past, as I’m sure you have as well. There’s simply no end to the things we wind up having to parse in our field. I’ve written parsers in most of the traditional ways: as a Regex, hand coded unstructured logic, hand coded recursive descent logic, and using “compiler compilers” such as Yacc or ANTLR. Each has their own pros and cons. Regex parsing is super simple, but really only works for trivial parsing chores and results in hard to comprehend code (I had a problem, so I solved it with Regex, now I have two problems). Unstructured hand coded parsers are only a little bit easier to understand, but also don’t scale well. Recursive descent parsers are easy to understand and the scale really well, but they are not so easy to write. Compiler compilers are easy to understand and work well for even the most complex of parsing tasks, but they require tricky modifications to your build process and generally produce code that’s difficult to understand and debug.&lt;/p&gt; &lt;p&gt;Recently I had a project in which I’d developed a domain specific language using a compiler compiler approach. I needed to make this project “portable”, though, and the code produced by the compiler compiler didn’t fit the definition. I was also frustrated by the complicated build required of this approach. So, I decided I’d have to turn to a hand coded parser instead. A recursive descent parser seemed like the only viable option there, but again, coding such a parser isn’t exactly trivial. So even though I’d done this before, I decided to do a web search and see if I could find “a better way” of doing this in C#. That’s when I ran across the idea of a “Monadic Parser Combinator.” The idea here really appealed to me. Rather than coding a parser in an imperative fashion you used a functional approach with higher order functions and functional composition. In fact, there was a really nifty library available for doing just this, written by the well known Nicholas Blumhardt of &lt;a href="http://code.google.com/p/autofac/"&gt;autofac&lt;/a&gt; fame, called &lt;a href="http://code.google.com/p/sprache/"&gt;Sprache&lt;/a&gt;.&lt;/p&gt; &lt;p&gt;You can look at the Sprache examples to get a high level idea of how you use a Monadic Parser Combinator, even if that name scares you to death. Most of us have heard of Monads at this point, but so very few “normal developers” quite understand them. I’ve tried a few times to understand the concept, but never really quite got it. However, while studying Sprache something happened for me. Like Despicable Me says, “Light bulb!” I think I finally get monads. So the title of this series is a bit of a play on words… I’m going to “parse monads”, i.e. try and understand them, while using monads for parsing. Ahh… yes, pardon this horrible play on words. Let’s get down to it.&lt;/p&gt; &lt;p&gt;Let’s try and understand the lowly monad. Here’s what Wikipedia has to say about the monad.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;In functional programming, a monad is a structure that represents computations. A type with a monad structure defines what it means to chain operations of that type together. This allows the programmer to build pipelines that process data in steps, in which each action is decorated with additional processing rules provided by the monad. A pithy description, referring to the syntax for statements in several languages, is that monads are a "programmable semicolon"—that is, a monad specifies what a statement is.&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Yeah, OK. That mostly makes sense, though that last sentence sounds like someone is trying to be cute. What the heck is a “programmable semicolon” for heaven’s sake? In any case, this might be a high level description, but you just know a monad is something much deeper than that. Maybe the formal definition further down the page will enlighten us.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;A monad is a construction that, given an underlying type system, embeds a corresponding type system (called the monadic type system) into it (that is, each monadic type acts as the underlying type). This monadic type system preserves all significant aspects of the underlying type system, while adding features particular to the monad.A monad is a construction that, given an underlying type system, embeds a corresponding type system (called the monadic type system) into it (that is, each monadic type acts as the underlying type). This monadic type system preserves all significant aspects of the underlying type system, while adding features particular to the monad.&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;OK, maybe not. I know that’s English, and I understand every single word. Unfortunately, I don’t think I understand a single sentence. &lt;img class="wlEmoticon wlEmoticon-smilewithtongueout" style="border-top-style: none; border-left-style: none; border-bottom-style: none; border-right-style: none" alt="Smile with tongue out" src="http://digitaltapestry.net/Media/Default/Windows-Live-Writer/Parsing-Monads_15046/wlEmoticon-smilewithtongueout_2.png"&gt;&lt;/p&gt; &lt;p&gt;They go on to say that “the usual formulation of a monad for programming is known as a Kleisli triple, having three components.” That’s probably where we’ll get a real understanding here, but if you’re like me the description of the three components is still confusing, in large part because the notation and terms used are foreign. So let me attempt to butcher things further by “translating” it to something more familiar to C# developers.&lt;/p&gt; &lt;ol&gt; &lt;li&gt;Yeah, OK, even though I think I get it, I have problems explaining this one in C# terms. “A type constructor that defines, for every underlying type, how to obtain a corresponding monadic type.” Uh huh. Sorry, can’t really translate that. However, I can translate the notation: M t can be loosely translated to M&amp;lt;T&amp;gt; for us C# developers.  &lt;li&gt;“A unit function that maps a value in an underlying type to a value in the monadic type.” So, if we said the notation for a monadic type is M&amp;lt;T&amp;gt;, the notation for a unit function in C# would be Func&amp;lt;T, M&amp;lt;T&amp;gt;&amp;gt;.  &lt;li&gt;“A binding operation of polymorphic type (M t) –&amp;gt; (t –&amp;gt; M u) –&amp;gt; M u.” Wow, that one’s a mouthful. However, unraveling it with the notations we’ve given so far, you can come up with the C# notation for bind of Func&amp;lt;M&amp;lt;T&amp;gt;, Func&amp;lt;T, M&amp;lt;U&amp;gt;&amp;gt;, M&amp;lt;U&amp;gt;&amp;gt;.&lt;/li&gt;&lt;/ol&gt; &lt;p&gt;OK, that might have made things clear as mud. Guess it’s time to try and make things a bit more concrete. Let’s see some C# code for a “well known” monad. We’ll pick the easiest such monad, the identity monad. We’ll start by giving a concrete M&amp;lt;T&amp;gt;. We’ll represent the identity monad as a generic class type.&lt;/p&gt; &lt;p&gt;&lt;pre class="brush: csharp"&gt;    public class Identity&amp;lt;T&amp;gt;
    {
        public Identity(T value)
        {
            this.Value = value;
        }

        public T Value { get; private set; }
    }
&lt;/pre&gt;
&lt;p&gt;Yeah, I know, this is very unexciting code and it's hard to see the point of it. Don’t try and over think it, just accept it for what it is, an extremely trivial type. This is going to be our monad, but for it to be a monad we have two more things we need. The first is a unit function. We’ll declare it as a static method on a non-generic Identity static class for convenience.&lt;/p&gt;
&lt;p&gt;&lt;pre class="brush: csharp"&gt;    public static class Identity
    {
        public static Identity&amp;lt;T&amp;gt; Unit&amp;lt;T&amp;gt;(T value)
        {
            return new Identity&amp;lt;T&amp;gt;(value);
        }
    }
&lt;/pre&gt;
&lt;p&gt;That's not too bad. Let's tackle the third component and define a bind function. We'll define it as a static method on the non-generic Identity class as well.&lt;/p&gt;
&lt;p&gt;&lt;pre class="brush: csharp"&gt;        public static Identity&amp;lt;U&amp;gt; Bind&amp;lt;T, U&amp;gt;(
            Identity&amp;lt;T&amp;gt; identity, Func&amp;lt;T, Identity&amp;lt;U&amp;gt;&amp;gt; func)
        {
            return func(identity.Value);
        }
&lt;/pre&gt;
&lt;p&gt;Here's some code that puts all of this together.&lt;/p&gt;
&lt;p&gt;&lt;pre class="brush: csharp"&gt;    class Program
    {
        static void Main(string[] args)
        {
            var result = Identity.Bind(Identity.Unit(5), x =&amp;gt;
                Identity.Bind(Identity.Unit(6), y =&amp;gt;
                    Identity.Unit(x.ToString() + y.ToString())));
            Console.WriteLine(result.Value);
        }
    }
&lt;/pre&gt;
&lt;p&gt;This writes "56" to the console. OK, I get it. This example is so pointless that you’re over thinking it and trying to figure out how any of this is useful. Trust me for now, and don’t. Just try and understand what the code does, not why it does it or how you can make use of the concepts presented just yet. Does the code make sense even if the concepts don’t yet? Good, you’re one step closer. Let’s do this exercise again with something just a little more useful… the maybe monad. The maybe monad represents either a value, or the lack of a value. Applying what we did above for this new type we get something like this:&lt;/p&gt;
&lt;p&gt;&lt;pre class="brush: csharp"&gt;    public class Maybe&amp;lt;T&amp;gt;
    {
        private Maybe()
        {
            this.HasValue = false;
        }

        public Maybe(T value)
        {
            this.Value = value;
            this.HasValue = true;
        }

        public T Value { get; private set; }

        public bool HasValue { get; private set; }

        public static readonly Maybe&amp;lt;T&amp;gt; Nothing = new Maybe&amp;lt;T&amp;gt;();
    }

    public static class Maybe
    {
        public static Maybe&amp;lt;T&amp;gt; Unit&amp;lt;T&amp;gt;(T value)
        {
            return new Maybe&amp;lt;T&amp;gt;(value);
        }

        public static Maybe&amp;lt;U&amp;gt; Bind&amp;lt;T, U&amp;gt;(Maybe&amp;lt;T&amp;gt; maybe, Func&amp;lt;T, Maybe&amp;lt;U&amp;gt;&amp;gt; func)
        {
            if (!maybe.HasValue)
            {
                return Maybe&amp;lt;U&amp;gt;.Nothing;
            }

            return func(maybe.Value);
        }
    }
&lt;/pre&gt;
&lt;p&gt;Now let's do something a bit interesting with this.&lt;/p&gt;
&lt;p&gt;&lt;pre class="brush: csharp"&gt;    class Program
    {
        static void Main(string[] args)
        {
            var result = Maybe.Bind(Maybe.Unit(5), x =&amp;gt;
                Maybe.Bind(Maybe.Unit(6), y =&amp;gt;
                    Maybe.Unit(x + y)));
            Console.WriteLine(
                result.HasValue ? result.Value.ToString() : "nothing");
            result = Maybe.Bind(Maybe&amp;lt;int&amp;gt;.Nothing, x =&amp;gt;
                Maybe.Bind(Maybe.Unit(6), y =&amp;gt;
                    Maybe.Unit(x + y)));
            Console.WriteLine(
                result.HasValue ? result.Value.ToString() : "nothing");
        }
    }
&lt;/pre&gt;
&lt;p&gt;This outputs "11" and "nothing". Can you see why? Maybe you also recognize that Maybe&amp;lt;T&amp;gt; is basically Nullable&amp;lt;T&amp;gt; and the second Bind operation chain is what the compiler would have done if you’d added a null Nullable&amp;lt;int&amp;gt; with another that has the value of 6? That realization should help you to make the second baby step in understanding the monad.&lt;/p&gt;
&lt;p&gt;In the second part of this series we’ll start to define a parsing monad which will illustrate a more complex and yet more practical use of monads, at which point you’ll hopefully start to have the “Light bulb!” moment like I did.&lt;/p&gt;</description><pubDate>Sat, 22 Sep 2012 11:43:13 GMT</pubDate><guid isPermaLink="true">http://www.digitaltapestry.net:80/blog/parsing-monads-part-1</guid></item><item><title>Waiting for Nirvana</title><link>http://www.digitaltapestry.net:80/blog/waiting-for-nirvana</link><description>&lt;p&gt;Want to see something cool? Do you have Visual Studio 2011 installed? Create a new “Portable Class Library” project in a new solution. Now open the project properties to the “Library” tab and click the “Change…” button. In the “Change Target Frameworks” dialog be sure to select “.NET Framework 4.5” and "Windows Phone 7 and higher" then click “OK”. Now add a “MainViewModel” class with the following code.&lt;/p&gt;&lt;pre class="brush: csharp"&gt;    public class MainViewModel
    {
        private readonly ObservableCollection&amp;lt;string&amp;gt; data
            = new ObservableCollection&amp;lt;string&amp;gt;();

        public IEnumerable&amp;lt;string&amp;gt; Data
        {
            get { return this.data; }
        }

        public ICommand TestCommand { get; private set; }

        public string Title
        {
            get { return "main view"; }
        }
    }&lt;/pre&gt;
&lt;p&gt;If you're familiar with the “Portable Library Tools” available as an extension to Visual Studio 2010 you’ll recognize that what we’ve just done is created a class library that can be portably used in all of the selected runtime environments, i.e. on the desktop and the phone. The APIs you’ll have available to you are restricted to those that exist on all of the selected platforms. This is a handy way to create portable libraries. Now, if you’re really familiar with the “Portable Library Tools” available in Visual Studio 2010 you’ve probably spotted the awesomeness in the above code already. Yep, portable libraries now have access to APIs such as &lt;code&gt;ICommand&lt;/code&gt; and &lt;code&gt;ObservableCollection&lt;/code&gt;. This means we can create assemblies to hold our non-UI specific code, such as ViewModels and Models, which we can directly reuse in applications that target specific platforms! (Yes, I know there’s hacky work-arounds such as using a factory to create your collections, but I’m not really willing to go through those kind of hoops when the APIs do exist on all the platforms being targeted.)&lt;/p&gt;
&lt;p&gt;Now, read the title of this blog post again. I said “&lt;strong&gt;Waiting&lt;/strong&gt; for Nirvana”. No, this isn’t a reference to the IDE being in beta. I can live with that. No, there’s real problems that make this awesomeness not so awesome today. Let’s see the first problem. Add a “Windows Phone Application” project to the solution. Oh, sorry, you can’t currently do that with Visual Studio 2011. &lt;img style="border-bottom-style: none; border-left-style: none; border-top-style: none; border-right-style: none" class="wlEmoticon wlEmoticon-sadsmile" alt="Sad smile" src="http://digitaltapestry.net/Media/Default/Windows-Live-Writer/Waiting-for-Nirvana_8FC4/wlEmoticon-sadsmile_2.png"&gt;&lt;/p&gt;
&lt;p&gt;OK, here’s a fun workaround for today. Visual Studio 2011 allows you to “round trip” solutions with Visual Studio 2010. So with Visual Studio 2010 installed side by side with Visual Studio 2011 open up that solution in Visual Studio 2010 (this requires the “Portable Library Tools” for Visual Studio 2010 to be installed). Wow, lookee there! It opens just fine and you have no problems with compiling the code. As far as I can figure out you’ll need to create (or at least configure) the portable libraries in Visual Studio 2011 in order to select “.NET Framework 4.5”, which is necessary to get those “fancy” APIs such as &lt;code&gt;ICommand&lt;/code&gt; and &lt;code&gt;ObservableCollection&lt;/code&gt;. Once configured, however, you’ll have no problems working with the projects in Visual Studio 2010. At this point we can create a “Windows Phone Application” that references and uses the portable library. Not only will this application compile, it will deploy and run just fine.&lt;/p&gt;
&lt;p&gt;This is pretty close to Nirvana, so what am I complaining about? Let’s take the next step and see, shall we? You see, I want to be able to test these portable libraries. One of my biggest complaints with Silverlight and Windows Phone development is that the unit testing sucks, quite frankly. The most often used solution is to use the “Silverlight Unit Test Framework”. This works, but it doesn’t use the IDEs test runner. In fact, it requires that you run a Silverlight/Phone application to do the testing. I’ve never been a fan of external test runners, because they simply aren’t as efficient as an integrated test runner. But at least most other external unit test runners can be left up and running. These test applications require you to launch them every time you want to test. This is just way too much effort to really use in a TDD fashion. No, if I’m going to follow the “red/green/refactor” cycle of TDD I need something more like the integrated unit testing available out of the box with Visual Studio and MSTest or available with TestDriven.NET or ReSharper when using other unit testing frameworks. Well, this is a portable library, so why not just use one of those unit testing frameworks and test runners? Good idea! In Visual Studio 2010 create a unit test project and reference the portable library.&lt;/p&gt;
&lt;p&gt;Oh snap! You can’t reference the portable library, because the portable library is only compatible with “.NET Framework 4.5” and the unit test library targets “.NET Framework 4”. OK, let’s try and work around that by having the unit test library target “.NET Framework 4.5”. Can’t do that within Visual Studio 2010, so open the solution back up in Visual Studio 2011. In Visual Studio 2011 the “Windows Phone Application” project won’t load, but that’s OK. Use the project properties to have the unit test project target the “.NET Framework 4.5”, then reference the portable library and add a simple unit test to test our “MainViewModel”. Compile and run the tests just to verify everything is working. All seems great, except the phone project is not loaded in Visual Studio 2011. OK, try to open the solution in Visual Studio 2010 now. We have the opposite problem there, where the test project doesn’t load. All of the code works great and does just what we want, but you’re going to have to jump back and forth between the IDEs to have access to either the phone project or the test project (the portable library is accessible from both IDEs). I may live with this in order to be able to unit test my code (nearly) “friction free”, but you can see how we’ve not yet reached Nirvana. Now, as soon as I can use Visual Studio 2011 to do Windows Phone development…&lt;/p&gt;</description><pubDate>Mon, 02 Apr 2012 15:17:46 GMT</pubDate><guid isPermaLink="true">http://www.digitaltapestry.net:80/blog/waiting-for-nirvana</guid></item><item><title>Writing (Correct) Multi-Threaded Code is Hard!</title><link>http://www.digitaltapestry.net:80/blog/writing-correct-multi-threaded-code-is-hard</link><description>&lt;p&gt;If you don’t believe writing multi-threaded code is hard, do everyone a favor and don’t write any multi-threaded code. Really. Stop writing that sort of code immediately and start doing some &lt;strong&gt;real&lt;/strong&gt; research on the topic. Reading one or two blogs or books won’t cut it, as everyone likes to talk about this topic when so few are qualified to do so. You’ll need to verify what you learn. That goes for anyone reading this blog entry as well. While I believe I am qualified to talk about this subject and can provide some proof for that, you should still verify anything I say and do further research. You can’t read this blog entry and say “OK, I understand, now it’s safe to write multi-threaded code.”&lt;/p&gt; &lt;p&gt;I’ve joked with co-workers that the only developers I want to see writing multi-threaded code are those that don’t want to, and I’m more than half serious about that.&lt;/p&gt; &lt;p&gt;Let me illustrate why writing multi-threaded code is hard. In the early days of .NET smart people understood it was hard to write multi-threaded code so they tried to help us out. A great example of where they tried to help us out was in the design of the .NET collection classes. All of them were “thread-safe”, doing internal synchronization. You were guaranteed that calling List.Add() on two threads wouldn’t cause memory corruption on the internal state of the List, for example. Life should be good, right?&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Edit:&lt;/strong&gt; I wrote this too quickly. Actually, the collections weren’t synchronized by default. You obtained synchronized wrappers for the collections when needed instead. This isn’t a detail that’s overly important in this discussion, but I know someone will point out this mistake, so I’m correcting it myself.&lt;/p&gt; &lt;p&gt;Well, they were smart enough to know that wasn’t enough. This internal synchronization did just that, synchronized internally. It provided no synchronization externally. Code that consumed the collection couldn’t, for example, rely on testing if a key were in a HashTable before adding it, as this required two external calls and thus wouldn’t be synchronized. So, they provided a solution for this problem and exposed an ICollection.SyncRoot property that external code could use for synchronization in these scenarios. Now life would be great, right?&lt;/p&gt; &lt;p&gt;Sadly, no. First there’s the problem that simply can’t be solved at the library design level: developers didn’t understand how to write correct multi-threaded code. Despite the presence of ICollection.SyncRoot, no one really used it. They instead just wrote the incorrect code that did no synchronization, assuming there was no problem because .NET collections were “thread-safe”… the documentation said so. I really can’t tell you how often I saw such code and had arguments with people who were sure they were correct, the collection was “thread-safe” so their code was as well.&lt;/p&gt; &lt;p&gt;Let’s not focus too much on this fact, though, because while it’s a great example of why I joke about not writing multi-threaded code unless you know enough to not want to, it can still just be considered something that should be fixed through education. It doesn’t go far enough to illustrate the bigger point: this stuff is &lt;strong&gt;HARD&lt;/strong&gt;. No, we’ll move on to the bigger problem here. If you were knowledgeable enough to know the dangers here and were aware of the ICollection.SyncRoot solution, you still had a problem. See, it’s very dangerous to publicly expose the synchronization object. When you do this you have no control over who locks the object, or when. Often this will lead to deadlock. (Remember, verify what I tell you here. A great start is &lt;a href="http://msdn.microsoft.com/en-us/magazine/cc188793.aspx"&gt;this article&lt;/a&gt; by Jeffrey Richter, an expert on the matter. In particular, read the section “Why the Great Idea isn’t So Great" which covers this topic quite well.)&lt;/p&gt; &lt;p&gt;Microsoft learned from this mistake and the newer generic interfaces for collections didn’t include the SyncRoot property.&lt;/p&gt; &lt;p&gt;OK, let me rephrase that. Some developers at Microsoft learned from this mistake. Unfortunately, not everyone did, as history may repeat itself with the next release of WPF. Seems a lot of developers find the whole multi-threaded coding to be as difficult as I said it is, and they want some silver bullets to make their lives easier. One particular area they struggle with is how INotificyCollectionChange works with data binding. Modify an ObservableCollection&amp;lt;T&amp;gt; from any thread other than the “UI thread” and you’ll get an exception in the data binding framework telling you not to do that. That means the developers have to write code to marshal all collection access onto the “UI thread”, which is just too hard. Can’t Microsoft fix that? Well, they’re attempting to do so with a “wonderful” little &lt;strong&gt;hack&lt;/strong&gt; that &lt;a href="http://10rem.net/blog/2012/01/20/wpf-45-cross-thread-collection-synchronization-redux?utm_source=feedburner&amp;amp;utm_medium=feed&amp;amp;utm_campaign=Feed%3A+PeteBrown+%28Pete+Brown%27s+Blog%29&amp;amp;utm_content=Google+Reader"&gt;you can find on the BindingOperations class in WPF 4.5&lt;/a&gt;. There’s a lot of problems with this hack, though. This hack requires you to expose the synchronization object publicly. I’ll grant you that it’s constrained… you’re only exposing it to the WPF binding framework, but that’s still not good practice. It’s dangerous, and simply not a good idea.&lt;/p&gt; &lt;p&gt;There’s other problems here as well, though. First, it seems everyone assumes this magically makes the collection “thread-safe”. There’s not a lot blogged about this feature yet, but every single one of the examples I could find include code where the collection is updated without locking the synchronization object. Honestly, I don’t know why people assume this, but obviously at least some will, making this a dangerous little bit of framework code.&lt;/p&gt; &lt;p&gt;It gets worse, though. The only reason to use this API is if you’re going to data bind to the collection. This means the collection has to be exposed publicly. However, the collection is only synchronized internally. This means we’ve got yet another gaping hole in our design allowing external code to screw things up and lead to race conditions and data corruption.&lt;/p&gt; &lt;p&gt;Am I overselling this? I don’t think so. A design like this is something I’d question in application code, where you can reason about how the code is used. See, someone could still screw up in maintenance. However, this isn’t application code. This is framework code. There’s no telling how it’s going to be used. Worse, it’s framework code that people assume to be quality framework code. They’ll pass other designs on this, probably in scenarios that are less constrained and a lot more dangerous.&lt;/p&gt; &lt;p&gt;I think the word should be spread that this new feature is one you should not use, and I’m going to work on spreading that word, starting with this blog post.&lt;/p&gt;</description><pubDate>Fri, 27 Jan 2012 15:00:23 GMT</pubDate><guid isPermaLink="true">http://www.digitaltapestry.net:80/blog/writing-correct-multi-threaded-code-is-hard</guid></item><item><title>Weak Events</title><link>http://www.digitaltapestry.net:80/blog/weak-events</link><description>&lt;p&gt;I’ve &lt;a href="http://digitaltapestry.net/blog/weakeventmanager"&gt;blogged before&lt;/a&gt; about the well known issue where events in .NET can lead to memory leaks due to the strong reference the InvocationList maintains to any listeners and how WPF introduced the WeakEventManager class as a solution to this problem. There are a few problems with WeakEventManager, however. The first is one of performance. Periodically the WeakEventManager must step through it’s list of known listeners and “purge” them if the target no longer exists. This purging process in some situations can be very computationally expensive, impacting the performance of your application. Then there’s just the sheer drudgery involved in creating new WeakEventManager types for new event types and implementing IWeakEventListener on all target objects.&lt;/p&gt; &lt;p&gt;Well, I’ve got a solution to both problems. Let me introduce you to a WeakEventListener base class.&lt;/p&gt; &lt;p&gt;&lt;pre class="brush: csharp; toolbar: false;"&gt;    public abstract class WeakEventListener&amp;lt;TSource, TArgs&amp;gt; : IDisposable
        where TArgs : EventArgs
    {
        private readonly WeakReference weakSource;
        private readonly WeakReference weakTarget;
        private readonly MethodInfo method;

        protected WeakEventListener(TSource source, Delegate handler)
        {
            this.weakSource = new WeakReference(source);
            if (handler.Target != null)
            {
                this.weakTarget = new WeakReference(handler.Target);
            }

            this.method = handler.Method;
        }

        ~WeakEventListener()
        {
            this.Dispose(false);
        }

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            object source = this.weakSource.Target;
            if (source != null)
            {
                this.StopListening((TSource)source);
            }
        }

        protected abstract void StopListening(TSource source);

        protected void OnEvent(object sender, TArgs args)
        {
            object target = null;
            if (this.weakTarget != null)
            {
                target = this.weakTarget.Target;
                if (target == null)
                {
                    this.Dispose();
                    return;
                }
            }

            this.method.Invoke(target, new object[] { sender, args });
        }
    }
&lt;/pre&gt;
&lt;p&gt;Much like with the WeakEventManager we’ll need to implement a WeakEventListener for every event type we want to listen to, but it’s a whole lot easier to implement.&lt;/p&gt;
&lt;p&gt;&lt;pre class="brush: csharp; toolbar: false;"&gt;    public class PropertyChangedEventListener
        : WeakEventListener&amp;lt;INotifyPropertyChanged, PropertyChangedEventArgs&amp;gt;
    {
        public PropertyChangedEventListener(
            INotifyPropertyChanged source,
            PropertyChangedEventHandler handler)
            : base(source, handler)
        {
            source.PropertyChanged += this.OnEvent;
        }

        protected override void StopListening(INotifyPropertyChanged source)
        {
            source.PropertyChanged -= this.OnEvent;
        }
    }
&lt;/pre&gt;
&lt;p&gt;Listening to events with the WeakEventListener is a whole lot easier than using an IWeakEventListener as well.&lt;/p&gt;
&lt;p&gt;&lt;pre class="brush: csharp; toolbar: false;"&gt;        private readonly IDisposable listener;

        public Target(Source source)
        {
            this.listener = new PropertyChangedEventListener(
                source,
                this.source_PropertyChanged);
        }
&lt;/pre&gt;

&lt;p&gt;Simply create a new instance of the WeakEventListener and be sure to keep a reference to it (in the example I did so as an IDisposable reference). When you no longer want to listen to the event simply Dispose of the listener.&lt;/p&gt;
&lt;p&gt;Using the WeakEventListener the event never maintains a strong reference to the target. It does maintain a strong reference to the WeakEventListener but this is likely a much smaller object than the target object. Further, if you fail to Dispose the WeakEventListener the strong reference to the WeakEventListener will be removed the next time the event is raised, so there’s never any “memory leak”.&lt;/p&gt;
&lt;p&gt;I think the usage of this WeakEventListener is much easier than using a WeakEventManager and IWeakEventListener. It also should perform better in some situations, and probably at least as well in the rest. I’d be interested in hearing your thoughts on this.&lt;/p&gt;</description><pubDate>Thu, 17 Nov 2011 03:47:18 GMT</pubDate><guid isPermaLink="true">http://www.digitaltapestry.net:80/blog/weak-events</guid></item><item><title>Contract Violations</title><link>http://www.digitaltapestry.net:80/blog/contract-violations</link><description>&lt;p&gt;Pete Brown wrote a &lt;a href="http://10rem.net/blog/2011/10/03/choices-i-hate-to-make-constructor-exceptions-vs-initialize-patterns"&gt;blog post&lt;/a&gt; asking what the best design was for handling a particular situation he had where he didn’t like any of the solutions he saw: throw an exception from a constructor, throw from an initialize method, or throw from a factory method. I’m not going to go over this topic in any depth, but I did post a response that I think deserves more clarification than I gave it in the comments on his blog. I stated, with little clarification, “Contract violations are software bugs. You don’t catch such exceptions.” That’s rather opinionated, and not entirely accurate, so let me try and explain in more detail what I meant.&lt;/p&gt; &lt;p&gt;Software APIs have contracts. They require you to call them in specific ways, and if and only if you do, they promise to behave in certain ways, returning certain values, etc. These contracts in many languages are implicit. At best, if you’re lucky, the contract is spelled out in the documentation. In .NET it has been traditional for at least part of the contract to be more explicit. If you call the API incorrectly an ArgumentException, InvalidOperationException, NotSupportedException or some other such exception would be thrown. With Code Contracts we now have the ability to fully detail the contract’s pre-conditions, post-conditions and invariants, and when they are violated a ContractException can be thrown. In all of these cases, these exception types are in a special category. Every single one of these exceptions occurs only when consumers of an API violate the contract. Any violation of the contract is a &lt;strong&gt;BUG&lt;/strong&gt;. It means the consumer code is wrong and needs to be fixed.&lt;/p&gt; &lt;p&gt;When I stated “don’t catch such exceptions” I was making a very extreme statement. Of course I don’t mean this literally. Critical software, such as heart monitors and air traffic controllers, must not crash, but rather need to safely recover in some fashion, which means they’re going to need to catch these exception types. Even non-critical software should at the very least catch these exception in order to log what occurred before terminating. My point really was that these special exceptions clearly indicate software bugs and so should be treated differently, and in many cases for many types of software, “failing fast” is the best thing you could do to ensure the bug is found and fixed. Even if you choose not to “fail fast”, these exceptions need to be handled in some manner that elevates them to the attention of the developer so that the bug can be fixed. Log them as critical, e-mail tech support, something. A developer has screwed up and needs to clean up his mess, because in properly written software, these exceptions will never occur!&lt;/p&gt;</description><pubDate>Tue, 04 Oct 2011 17:13:07 GMT</pubDate><guid isPermaLink="true">http://www.digitaltapestry.net:80/blog/contract-violations</guid></item><item><title>NCrunch</title><link>http://www.digitaltapestry.net:80/blog/ncrunch</link><description>&lt;p&gt;A colleague of mine pointed this one out. &lt;a href="http://www.ncrunch.net/"&gt;NCrunch&lt;/a&gt; is a “continuous testing” extension for Visual Studio. In the past I’ve been turned off by continuous testing tools, because they were clunky. They ran outside of the IDE and basically only ran in response to you doing a build, which often meant they were still running tests long after I’d moved on to something else. These tools just were not conducive to TDD, in my opinion.&lt;/p&gt; &lt;p&gt;NCrunch appears to be quite different. Like IntelliSense and code corrections, NCrunch compiles in the background &lt;em&gt;as you modify your code&lt;/em&gt;. It will compile and run your (relevant) tests in the background in response to you modifying code &lt;em&gt;even without you saving the file&lt;/em&gt;, much less in response to a compile. So, in exactly the same manner as I see when I write some code that won’t compile, I see whether or not a test will pass as I write it, or the code under test. In addition, you see (as you type) the test coverage. You can even navigate back and forth between the test code and the code under test through the test coverage UI. Seriously, watch the video on the project’s home page to marvel at what I’m doing a poor job of explaining in prose here.&lt;/p&gt; &lt;p&gt;My colleague called this half-baked-ware. It’s under heavy development and there are bugs. But he claims that despite the bugs, it does work quite nicely and delivers what’s promised. I’ll be giving it a spin and can provide a better review once I have, but it looks promising enough that I thought I needed to share. Surprisingly, despite the number of blogs I follow on a daily basis (over 200 tech blogs!), this was the first I’d heard of this tool, so I’m sure many of my followers will not have heard of it either.&lt;/p&gt;</description><pubDate>Thu, 22 Sep 2011 20:45:14 GMT</pubDate><guid isPermaLink="true">http://www.digitaltapestry.net:80/blog/ncrunch</guid></item><item><title>Reflecting on Code</title><link>http://www.digitaltapestry.net:80/blog/reflecting-on-code</link><description>&lt;div id="msgcns!D18C3EC06EA971CF!694" class="bvMsg"&gt; &lt;p&gt;Static reflection. It’s all the rage.  &lt;p&gt;What is static reflection? It’s obtaining type information at compile time instead of runtime, typically by using LINQ expression trees. Here’s my take on providing a static helper to do this. &lt;pre class="brush: csharp; toolbar: false;"&gt;public static class Reflect
{
    public static MemberInfo GetMember(Expression&amp;lt;Action&amp;gt; expression)
    {
        if (expression == null)
        {
            throw new ArgumentNullException(
                GetMember(() =&amp;gt; expression).Name);
        }

        return GetMemberInfo(expression as LambdaExpression);
    }

    public static MemberInfo GetMember&amp;lt;T&amp;gt;(Expression&amp;lt;Func&amp;lt;T&amp;gt;&amp;gt; expression)
    {
        if (expression == null)
        {
            throw new ArgumentNullException(
                GetMember(() =&amp;gt; expression).Name);
        }

        return GetMemberInfo(expression as LambdaExpression);
    }

    public static MethodInfo GetMethod(Expression&amp;lt;Action&amp;gt; expression)
    {
        MethodInfo method = GetMember(expression) as MethodInfo;
        if (method == null)
        {
            throw new ArgumentException(
                "Not a method call expression", GetMember(() =&amp;gt; expression).Name);
        }

        return method;
    }

    public static PropertyInfo GetProperty&amp;lt;T&amp;gt;(Expression&amp;lt;Func&amp;lt;T&amp;gt;&amp;gt; expression)
    {
        PropertyInfo property = GetMember(expression) as PropertyInfo;
        if (property == null)
        {
            throw new ArgumentException(
                "Not a property expression", GetMember(() =&amp;gt; expression).Name);
        }

        return property;
    }

    public static FieldInfo GetField&amp;lt;T&amp;gt;(Expression&amp;lt;Func&amp;lt;T&amp;gt;&amp;gt; expression)
    {
        FieldInfo field = GetMember(expression) as FieldInfo;
        if (field == null)
        {
            throw new ArgumentException(
                "Not a field expression", GetMember(() =&amp;gt; expression).Name);
        }

        return field;
    }

    internal static MemberInfo GetMemberInfo(LambdaExpression lambda)
    {
        if (lambda == null)
        {
            throw new ArgumentNullException(
                GetMember(() =&amp;gt; lambda).Name);
        }

        MemberExpression memberExpression = null;
        if (lambda.Body.NodeType == ExpressionType.Convert)
        {
            memberExpression = ((UnaryExpression)lambda.Body).Operand as MemberExpression;
        }
        else if (lambda.Body.NodeType == ExpressionType.MemberAccess)
        {
            memberExpression = lambda.Body as MemberExpression;
        }
        else if (lambda.Body.NodeType == ExpressionType.Call)
        {
            return ((MethodCallExpression)lambda.Body).Method;
        }

        if (memberExpression == null)
        {
            throw new ArgumentException(
                "Not a member access", GetMember(() =&amp;gt; lambda).Name);
        }

        return memberExpression.Member;
    }
}
&lt;/pre&gt;
&lt;p&gt;If you look closely, the code itself shows you a use for the idea. Yep, it’s definitely dogfood. Pay attention to how we raise ArgumentNullExceptions in this code. No “magic strings” for us. This is compiled code. If I use the wonderful IDE refactoring capabilities to rename the argument, the string passed to the ArgumentNullConstructor is also refactored, because it’s static code and not a string literal. 
&lt;p&gt;There’s also situations where you don’t have an instance of data to use for reflecting, and the above code isn’t so useful in this case. That’s where it’s big brother comes in. &lt;pre class="brush: csharp; toolbar: false"&gt;public static class ReflectOn&amp;lt;T&amp;gt;
{
    public static MemberInfo GetMember(Expression&amp;lt;Action&amp;lt;T&amp;gt;&amp;gt; expression)
    {
        if (expression == null)
        {
            throw new ArgumentNullException(Reflect.GetMember(() =&amp;gt; expression).Name);
        }

        return Reflect.GetMemberInfo(expression as LambdaExpression);
    }

    public static MemberInfo GetMember&amp;lt;TResult&amp;gt;(Expression&amp;lt;Func&amp;lt;T, TResult&amp;gt;&amp;gt; expression)
    {
        if (expression == null)
        {
            throw new ArgumentNullException(Reflect.GetMember(() =&amp;gt; expression).Name);
        }

        return Reflect.GetMemberInfo(expression as LambdaExpression);
    }

    public static MethodInfo GetMethod(Expression&amp;lt;Action&amp;lt;T&amp;gt;&amp;gt; expression)
    {
        MethodInfo method = GetMember(expression) as MethodInfo;
        if (method == null)
        {
            throw new ArgumentException(
                "Not a method call expression",
                Reflect.GetMember(() =&amp;gt; expression).Name);
        }

        return method;
    }

    public static PropertyInfo GetProperty&amp;lt;TResult&amp;gt;(Expression&amp;lt;Func&amp;lt;T, TResult&amp;gt;&amp;gt; expression)
    {
        PropertyInfo property = GetMember(expression) as PropertyInfo;
        if (property == null)
        {
            throw new ArgumentException(
                "Not a property expression", Reflect.GetMember(() =&amp;gt; expression).Name);
        }

        return property;
    }

    public static FieldInfo GetField&amp;lt;TResult&amp;gt;(Expression&amp;lt;Func&amp;lt;T, TResult&amp;gt;&amp;gt; expression)
    {
        FieldInfo field = GetMember(expression) as FieldInfo;
        if (field == null)
        {
            throw new ArgumentException(
                "Not a field expression", Reflect.GetMember(() =&amp;gt; expression).Name);
        }

        return field;
    }
}
&lt;/pre&gt;
&lt;p&gt;Now I can do something like this.&lt;pre class="brush: csharp; toolbar: false;"&gt;class Program
{
    public void Foo()
    {
    }

    static void Main(string[] args)
    {
        Console.WriteLine(ReflectOn&amp;lt;Program&amp;gt;.GetMethod(p =&amp;gt; p.Foo()).Name);
    }
}
&lt;/pre&gt;
&lt;p&gt;Want another, more practical use? &lt;pre class="brush: csharp; toolbar: false;"&gt;public abstract class ObservableObject : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged = delegate { };

    protected void OnPropertyChanged() // All properties changed
    {
        OnPropertyChanged(null);
    }

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    protected void OnPropertyChanged&amp;lt;T&amp;gt;(Expression&amp;lt;Func&amp;lt;T&amp;gt;&amp;gt; expression)
    {
        OnPropertyChanged(Reflect.GetProperty(expression).Name);
    }
}
&lt;/pre&gt;
&lt;p&gt;Which is used like this. &lt;pre class="brush: csharp; toolbar=false;"&gt;public class Foo : ObservableObject
{
    private string message;

    public string Message
    {
        get
        {
            return this.message;
        }

        set
        {
            this.message = value;
            OnPropertyChanged(() =&amp;gt; Message);
        }
    }
}
&lt;/pre&gt;
&lt;p&gt;No more magic strings when raising PropertyChanged from INotifyPropertyChanged implementations. 
&lt;p&gt;The performance here is obviously worse than using the magic string, but it’s a &lt;strong&gt;lot&lt;/strong&gt; better than using actual runtime reflection. &lt;/p&gt;&lt;/div&gt;</description><pubDate>Thu, 25 Aug 2011 15:00:21 GMT</pubDate><guid isPermaLink="true">http://www.digitaltapestry.net:80/blog/reflecting-on-code</guid></item><item><title>Easy Modeling</title><link>http://www.digitaltapestry.net:80/blog/easy-modeling</link><description>&lt;p&gt;Like everyone else, I find the amount of ceremony necessary to implement a class using the &lt;code&gt;INotifyPropertyChanged&lt;/code&gt; interface to be tedious at best. Let’s look at a simple example.&lt;/p&gt;&lt;pre class="brush: csharp; toolbar: false;"&gt;public class Employee : INotifyPropertyChanged
{
    private string firstName;
    private string lastName;

    public string FirstName
    {
        get
        {
            return this.firstName;
        }

        set
        {
            if (this.firstName != value)
            {
                this.firstName = value;
                OnPropertyChanged("FirstName");
            }
        }
    }

    public string LastName
    {
        get
        {
            return this.lastName;
        }

        set
        {
            if (this.lastName != value)
            {
                this.lastName = value;
                OnPropertyChanged("LastName");
            }
        }
    }
    
    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string propertyName)
    {
        var handler = this.PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName);
        }
    }
}
&lt;/pre&gt;
&lt;p&gt;That’s a lot of code for a simple class with two properties. Compare this to what you could write if you didn’t support &lt;code&gt;INotifyPropertyChanged&lt;/code&gt;.&lt;/p&gt;&lt;pre class="brush: csharp; toolbar: false;"&gt;public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}&lt;/pre&gt;
&lt;p&gt;I "cheated" a little here by using auto-properties, but that’s still an amazing difference.&lt;/p&gt;
&lt;p&gt;I know that it’s been the “holy grail” to figure out a way to fix the numerous problems that exist when implementing this interface: the amount of code required, the use of magic strings, and the details like ensuring thread safety when raising the event and in not raising the event if the property is set but not changed. Well, I think I’ve come up with an interesting solution. Let’s look at how we could implement our simple class again, but using my solution.&lt;/p&gt;&lt;pre class="brush: csharp; toolbar: false"&gt;public class Employee : INotifyPropertyChanged
{
    public Employee()
    {
        this.RegisterPropertyChangedHandler(() =&amp;gt; this.PropertyChanged));
    }

    public string FirstName
    {
        get { return this.GetBackingValue(() =&amp;gt; this.FirstName); }
        set { this.SetBackingValue(() =&amp;gt; this.FirstName, value); }
    }

    public string LastName
    {
        get { return this.GetBackingValue(() =&amp;gt; this.LastName); }
        set { this.SetBackingValue(() =&amp;gt; this.LastName, value); }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}
&lt;/pre&gt;
&lt;p&gt;That's it. Not quite as short as the version that doesn’t implement &lt;code&gt;INotifyPropertyChanged&lt;/code&gt;, but still pretty short. It’s also doesn’t require the attention to the little details or use magic strings. Obviously there’s some magic going on here, though. Where are the values stored? What are the &lt;code&gt;RegisterPropertyChangedHandler&lt;/code&gt;, &lt;code&gt;GetBackingValue&lt;/code&gt; and &lt;code&gt;SetBackingValue&lt;/code&gt; methods? How does this all work? Well, here’s the code behind the curtain.&lt;/p&gt;
&lt;p&gt;&lt;pre class="brush: csharp; toolbar: false;"&gt;public static class BackingStore
{
    private static ConditionalWeakTable&amp;lt;object, Dictionary&amp;lt;PropertyInfo, object&amp;gt;&amp;gt; store =
        new ConditionalWeakTable&amp;lt;object, Dictionary&amp;lt;PropertyInfo, object&amp;gt;&amp;gt;();
    private static ConditionalWeakTable&amp;lt;object, Action&amp;lt;string&amp;gt;&amp;gt; propertyChangedHandlers =
        new ConditionalWeakTable&amp;lt;object, Action&amp;lt;string&amp;gt;();

    public static void RegisterPropertyChangedHandler&amp;lt;TOwner&amp;gt;(this TOwner self, Action&lt;string&gt; handler)
    {
        propertyChangedHandlers.Add(self, handler);
    }

    public static void RegisterPropertyChangedHandler&amp;lt;TOwner&amp;gt;(this TOwner self, Func&amp;lt;PropertyChangedEventHandler&amp;gt; handlerFunc)
    {
        self.RegisterPropertyChangedHandler(propertyName =&amp;gt;
            {
                var handler = handlerFunc();
                if (handler != null)
                {
                    handler(self, new PropertyChangedEventArgs(propertyName));
                }
            });
    }

    public static void RaisePropertyChanged&amp;lt;TOwner, T&amp;gt;(this TOwner self, Expression&amp;lt;Func&amp;lt;T&amp;gt;&amp;gt; propertyExpression)
    {
        var propertyInfo = Reflect.GetProperty(propertyExpression);
        self.RaisePropertyChanged(propertyInfo);
    }

    public static T GetBackingValue&amp;lt;TOwner, T&amp;gt;(this TOwner self, Expression&amp;lt;Func&amp;lt;T&amp;gt;&amp;gt; propertyExpression)
    {
        var values = GetValues(self);
        var propertyInfo = Reflect.GetProperty(propertyExpression);
        object value;
        if (!values.TryGetValue(propertyInfo, out value))
        {
            return default(T);
        }

        return (T)value;
    }

    public static void SetBackingValue&amp;lt;TOwner, T&amp;gt;(this TOwner self, Expression&amp;lt;Func&amp;lt;T&amp;gt;&amp;gt; propertyExpression, T value)
    {
        var values = GetValues(self);
        var propertyInfo = Reflect.GetProperty(propertyExpression);
        object oldValue;
        if (!values.TryGetValue(propertyInfo, out oldValue))
        {
            oldValue = default(T);
        }

        if (!object.Equals(value, oldValue))
        {
            values[propertyInfo] = value;
            self.RaisePropertyChanged(propertyInfo);
        }
    }

    private static Dictionary&amp;lt;PropertyInfo, object&amp;gt; GetValues(object owner)
    {
        return store.GetValue(owner, delegate { return new Dictionary&amp;lt;PropertyInfo, object&amp;gt;(); });
    }

    private static void RaisePropertyChanged&amp;lt;TOwner&amp;gt;(this TOwner self, PropertyInfo propertyInfo)
    {
        Action&amp;lt;string&amp;gt; propertyChanged;
        if (propertyChangedHandlers.TryGetValue(self, out propertyChanged))
        {
            propertyChanged(propertyInfo.Name);
        }
    }
}
&lt;/pre&gt;
&lt;p&gt;This uses “static reflection” (the details behind the &lt;code&gt;Reflect&lt;/code&gt; class in the code above and discussed in &lt;a href="http://digitaltapestry.net/blog/reflecting-on-code"&gt;this blog post&lt;/a&gt;) to obtain &lt;code&gt;PropertyInfo&lt;/code&gt; from an expression. It also uses a little known class &lt;code&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/dd287757.aspx"&gt;ConditionalWeakTable&lt;/a&gt;&lt;/code&gt; to associate data with the object using a &lt;code&gt;WeakReference&lt;/code&gt; in order to not prevent the object from being garbage collected. The code probably uses some concepts your not familiar with, but it should still be easy to understand. Thanks to the &lt;code&gt;ConditionalWeakTable&lt;/code&gt; we are able to write extension methods that can associate data with any object. With that capability we’re able to write extension methods that use static reflection to get and set values associated with a property on any object, and when setting the value we’re able to raise property changed events through registered handlers.&lt;/p&gt;
&lt;p&gt;Is this the holy grail? No. There is some definite overhead involved in using this in your class implementations. That’s one of the reasons we recommend not using &lt;code&gt;DependencyObject&lt;/code&gt; to implement your &lt;code&gt;ViewModels&lt;/code&gt; (the other reason being that &lt;code&gt;DependencyProperties&lt;/code&gt; are even more complex to implement than &lt;code&gt;INotifyPropertyChanged&lt;/code&gt;). However, we all know the old saw about premature optimization, and this technique is a bit easier to refactor if you determine later (through profiling) that there’s a need to optimize. In most cases I think you’ll be fine using this technique.&lt;/p&gt;
&lt;p&gt;What are your thoughts on this?&lt;/p&gt;</description><pubDate>Thu, 25 Aug 2011 14:27:37 GMT</pubDate><guid isPermaLink="true">http://www.digitaltapestry.net:80/blog/easy-modeling</guid></item><item><title>ThreadPool vs. Tasks</title><link>http://www.digitaltapestry.net:80/blog/threadpool-vs.-tasks</link><description>&lt;p&gt;Paul Stovell wrote a blog post with &lt;a href="http://www.paulstovell.com/threadpool-vs-tasks"&gt;the same name&lt;/a&gt; yesterday, and it’s one of the few posts from Paul I’ve ever felt was lacking. I think he was having a bad day and rather than think about the topic he just thought he’d ask the blogosphere “how would using Task make the examples above look better?” However, as presented it’s a little hard to really get at the answer that he’s really looking for, because reproducing the very contrived examples he has given produces code that is mostly the same with a few minor differences and you then have to go deeper to come to an understanding. I’m going to reproduce his examples with commentary and hopefully get to the crux of the answer he’s really looking for.&lt;/p&gt; &lt;h1&gt;Starting a task&lt;/h1&gt; &lt;p&gt;This particular example is about as simple as you can get, and therefore it’s going to look pretty much identical. There’s nothing here to help us understand why the Task class is so helpful.&lt;/p&gt;&lt;pre class="brush: csharp; toolbar: false;"&gt;Task.Factory.StartNew(delegate
{
    DoSomeWork();
});
&lt;/pre&gt;
&lt;h1&gt;Waiting for a task to complete&lt;/h1&gt;
&lt;p&gt;Now we start to see some minor differences, and the Task code is simpler though probably not enough to seem compelling.&lt;/p&gt;&lt;pre class="brush: csharp; toolbar: false;"&gt;var task = Task.Factory.StartNew(delegate
{
    DoSomeWork();
});
task.Wait();
&lt;/pre&gt;
&lt;p&gt;We’ve gone from 5 significant lines of code to 3. In Paul’s version he had to create a synchronization object manually in order to accomplish what we get for free with Task. (As an aside, while there’s no issues with Paul’s contrived example here, I still feel compelled to again point out that Event objects are often the &lt;a href="http://www.digitaltapestry.net/blog/eventwaithandle-considered-harmful"&gt;source of synchronization bugs&lt;/a&gt; and really should generally be avoided.)&lt;/p&gt;
&lt;h1&gt;&lt;/h1&gt;
&lt;h1&gt;Returning&lt;/h1&gt;
&lt;p&gt;I think this is a very good place to start really showing some differences.&lt;/p&gt;&lt;pre class="brush: csharp; toolbar: false;"&gt;var task = Task.Factory.StartNew(delegate
{
    DoSomeWork();
    return 42;
});
Console.WriteLine(task.Result);
&lt;/pre&gt;
&lt;p&gt;We’ve gone from 7 significant lines of code to 4. Further, the intent of the code I think is much easier to understand. Far more important, we actually did what the title of this section said we’d do, while Paul’s code cheats. He doesn’t return anything. Rather he modifies global state. In this contrived example that’s not all that significant, but it shouldn’t be too difficult to see the problems involved here when you move on to writing real code. Using shared state like this means you have to consider how to synchronize that state. In Paul’s contrived example everything is fine because this is really synchronous code masquerading as asynchronous code, but in real code you’ll usually not find it quite so easy to ensure access to the shared state is properly synchronized everywhere. Further, because we’re using shared state there’s a very tight coupling that makes it very difficult to actually reuse the asynchronous operation. In other words, it works OK-ish for one-off tasks but won’t work well when the operation is intended to be called from multiple clients. All of this is relatively simple to correct but doing so results in recreation of the Task concept!&lt;/p&gt;
&lt;h1&gt;&lt;/h1&gt;
&lt;h1&gt;Chaining tasks&lt;/h1&gt;
&lt;p&gt;Before going any further, I have to point out that Paul didn’t really chain tasks in his example. He wrote synchronous code in the guise of asynchronous code. He might as well have simplified the whole thing into a call to DoSomeWork() and DoSomeMoreWork() and never used the ThreadPool at all. With actual chaining of tasks you ensure that one task runs to completion before the next starts, but all of the code runs asynchronously. This is going to be a little hard to explain, so let’s start with the correct way to do this using Task.&lt;/p&gt;&lt;pre class="brush: csharp; toolbar: false;"&gt;var task = Task.Factory.StartNew(delegate
{
    DoSomeWork();
});

task = task.ContinueWith(t =&amp;gt;
{
    DoSomeWork();
});

task.Wait();
&lt;/pre&gt;
&lt;p&gt;What happens in Paul’s example is that DoSomeWork() is scheduled on the ThreadPool and then we block until it’s complete. After that DoSomeMoreWork() is scheduled on the ThreadPool and we again block. They key is that we blocked in between scheduling these tasks. In the Task example what happens is we schedule DoSomeWork() to run. Then we schedule DoSomeMoreWork() to run after DoSomeWork() without blocking. Finally we block waiting for DoSomeMoreWork() to finish. This may sound subtle but it’s a very significant difference. Paul’s example is entirely synchronous, while mine is asynchronous. If Paul hadn’t blocked waiting for DoSomeWork() to complete and had scheduled DoSomeMoreWork() within the first queued work item he would have actually chained the operations, but that sort of coding isn’t composable. This is like the difference between writing nested loops and composing LINQ queries. This is one of the fundamental benefits of Task over directly using the ThreadPool.&lt;/p&gt;
&lt;h1&gt;Waiting for multiple tasks to complete&lt;/h1&gt;
&lt;p&gt;We won’t see much difference here.&lt;/p&gt;&lt;pre class="brush: csharp; toolbar: false;"&gt;var task1 = Task.Factory.StartNew(delegate
{
    DoSomeWork();
});

var task2 = Task.Factory.StartNew(delegate
{
    DoSomeWork();
});

Task.WaitAll(task1, task2);
&lt;/pre&gt;
&lt;p&gt;Very similar code. The differences are the same ones we saw when waiting for a single task, and aren’t very compelling.&lt;/p&gt;
&lt;h1&gt;Exception handling&lt;/h1&gt;
&lt;p&gt;I struggled a bit with this one. There are a lot of different ways I could have done exception handling, and to be honest I don’t find any of them to be overly elegant. In the end I chose to write the example in a way that illustrates some of the differences that exist between the way Task does exception handling and propogation and the wayPaul did it.&lt;/p&gt;&lt;pre class="brush: csharp; toolbar: false;"&gt;var task = Task.Factory.StartNew(delegate
{
    DoSomeWork();
});

try
{
    task.Wait();
}
catch (AggregateException e)
{
    foreach (var ex in e.InnerExceptions)
    {
        Console.WriteLine("Error! " + ex);
    }
}
&lt;/pre&gt;
&lt;p&gt;Like I said, not pretty, though I don’t find it any worse than Paul’s code. It does, however, point out some significant things. First, exceptions are propogated across thread boundaries using Task. Waiting on the Task or trying to access the Result when the task threw will result in the exception being wrapped in an AggregateException and being thrown in the context of that thread. The fact that this is an AggregateException means we can obtain all of the exceptions that occurred in a deeply composed set of tasks. So, again, the composability of Task objects is the key differentiator here.&lt;/p&gt;
&lt;p&gt;I’d also like to point out that Paul’s word of caution doesn’t apply to Task which handles the exception propogation for you. So a very common programmer mistake made when using ThreadPool isn’t possible to make when using Task.&lt;/p&gt;
&lt;h1&gt;&lt;/h1&gt;
&lt;h1&gt;Cancellation&lt;/h1&gt;
&lt;p&gt;This one really bugged me. Paul ends this section with the comment “&lt;em&gt;Note: this is like a gazillion times more complex in Tasks”. &lt;/em&gt;That’s just simply not true. The equivalent code written using Task is nearly identical and a very far cry from “a gazillion times more complex”!&lt;/p&gt;&lt;pre class="brush: csharp; toolbar: false;"&gt;CancellationTokenSource cts = new CancellationTokenSource();
Task.Factory.StartNew(delegate
{
    while (true)
    {
        cts.Token.ThrowIfCancellationRequested();
        Thread.Sleep(100);
    }
});

cts.Cancel();
&lt;/pre&gt;
&lt;p&gt;The Task example has added a single extra significant line of code and really isn’t any more complex at all, much less “a gazillion times” more complex. I can point out some important differences, however. It’s very difficult to take Paul’s approach and use it when composing tasks. It works fine for one off code, but isn’t usable in library code because he is again relying on shared state. The CancellationToken abstraction, on the other hand, was designed with composability in mind. Entire sets of tasks can be composed and cancellation for all of them will be controlled through one token.&lt;/p&gt;
&lt;h1&gt;Dispatching to UI thread&lt;/h1&gt;
&lt;p&gt;I could have cheated here. I could have simply changed ThreadPool.QueueUserWorkItem to Task.Factory.StartNew and the code would have been nearly identical. I instead chose to write this in a way that appears to be a bit more complex, but it again shows the benefit of Task.&lt;/p&gt;&lt;pre class="brush: csharp; toolbar: false;"&gt;var task = Task.Factory.StartNew(delegate
{
    DoSomeWork();
});
task = task.ContinueWith(delegate
{
    progressBar.Value += 10;
}, TaskScheduler.FromCurrentSynchronizationContext());
task.ContinueWith(delegate
{
    DoSomeMoreWork();
});
task.ContinueWith(delegate
{
    progressBar.Value += 10;
}, TaskScheduler.FromCurrentSynchronizationContext());
&lt;/pre&gt;
&lt;p&gt;There’s several more significant lines of code here, but remember that I could have written nearly identical code with the exact same number of significant lines of code. I wrote it this way to again illustrate the composability of Task. For one off code like this contrived example, this is a horrible way of writing the code. However, imagine that DoSomeWork() and DoSomeMoreWork() were library methods designed to be async and returned Task objects. Now I hope you can see how being able to compose Task objects and control how they are scheduled is far more powerful than what you can easily do with ThreadPool.&lt;/p&gt;
&lt;h1&gt;&lt;/h1&gt;
&lt;h1&gt;Being notified when a task is complete without blocking&lt;/h1&gt;
&lt;p&gt;Ha! This isn’t really “being notified”, instead Paul is finally actually chaining tasks! The equivalent code is nearly identical.&lt;/p&gt;&lt;pre class="brush: csharp; toolbar: false;"&gt;var task = Task.Factory.StartNew(delegate
{
    DoSomeWork();
    return 42;
});
task.ContinueWith(t =&amp;gt; Console.WriteLine("Done! " + t.Result));
&lt;/pre&gt;
&lt;p&gt;Again, the manual code is fine but is akin to writing nested loops instead of composing queries using LINQ. I really can’t say enough about the composability of Task objects.&lt;/p&gt;
&lt;h1&gt;Other notes&lt;/h1&gt;
&lt;p&gt;If I ended here I think you’d see that a significant benefit of Task over ThreadPool is the composable nature of Task. However, this is only one of the benefits, and none of the example’s Paul gave will lead us to discover other advantages. So I’m going to spend a little time discussing a couple of them.&lt;/p&gt;
&lt;p&gt;One of the first things that jumped out at me when reading Paul’s post was the obvious connection he’s drawn between Task and ThreadPool. However, that connection is false. The ThreadPool is one very significant way one can schedule asynchronous tasks, but there are a lot of other ways. In addition to scheduling a ThreadPool work item some other asynchronous methods you can find in .NET include: dedicated threads, asynchronous methods using IAsyncResult, asynchronous I/O and events. Every one of these asynchronous methods can be wrapped inside of a Task object which can help to unify all of these patterns and make them all composable! For example, in order to turn WebClient.DownloadStringAsync into a version that uses Task and is composable we can create the following extension method.&lt;/p&gt;&lt;pre class="brush: csharp; toolbar: false;"&gt;private static Task&amp;lt;string&amp;gt; DownloadStringTaskAsync(this WebClient self, Uri address)
{
    TaskCompletionSource&amp;lt;string&amp;gt; tcs = new TaskCompletionSource&amp;lt;string&amp;gt;();
    DownloadStringCompletedEventHandler handler = null;
    handler = (s, args) =&amp;gt;
        {
            self.DownloadStringCompleted -= handler;
            if (args.Error != null)
            {
                tcs.TrySetException(args.Error);
            }
            else
            {
                tcs.TrySetResult(args.Result);
            }
        };
    self.DownloadStringCompleted += handler;
    self.DownloadStringAsync(address);
    return tcs.Task;
}
&lt;/pre&gt;
&lt;p&gt;The ThreadPool isn’t involved anywhere in that code at all. However, it’s now easy to compose the downloading of a string from the web with some other set of tasks that work with the string that is downloaded.&lt;/p&gt;
&lt;p&gt;This leads into another significant benefit related to the composability of Task objects: the ability to add language support like we’ve seen with the Async CTP! Giving up the “spaghetti code” nature of writing one-off asynchronous operations in favor of composing asynchronous tasks by utilizing the Async CTP, Parallel LINQ extensions and Rx are all reasons to stop being a fuddy-duddy and start using Task.&lt;/p&gt;</description><pubDate>Sat, 20 Aug 2011 13:43:16 GMT</pubDate><guid isPermaLink="true">http://www.digitaltapestry.net:80/blog/threadpool-vs.-tasks</guid></item><item><title>Look ma! No ViewModel!</title><link>http://www.digitaltapestry.net:80/blog/look-ma-no-viewmodel</link><description>&lt;p&gt;Ward Bell wrote a very interesting &lt;a href="http://neverindoubtnet.blogspot.com/2011/05/mvvm-backlash.html"&gt;blog post&lt;/a&gt; yesterday that raised many legitimate questions about the Model-View-ViewModel pattern. He outlined the following “hypothetical MVVM benefits” that are repeated over and over by the proponents of the pattern.&lt;/p&gt; &lt;ul&gt; &lt;li&gt;Separation of concerns (SoC)  &lt;li&gt;Loose coupling  &lt;li&gt;Data Binding  &lt;li&gt;Designer / developer symbiosis  &lt;li&gt;Reusability  &lt;li&gt;Avoid spaghetti code  &lt;li&gt;Consistent, maintainable, scalable  &lt;li&gt;Support for design time data  &lt;li&gt;Automated view-logic testing  &lt;li&gt;Multiple views over the same view logic&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;He then went on to rip most of these hypothetical benefits to shreds. Don’t get me wrong, Ward says he’s still an MVVM proponent. This is simply a thought exercise, and a very valid one at that. One should always question their beliefs. In any case, after ripping these apart he concluded that only three of the points hold up to this sort of scrutiny: Support for design time data, Automated view-logic testing and Multiple views over the same view logic.&lt;/p&gt; &lt;p&gt;I made a very quick reply to his blog post pointing out that if you really squint your eyes hard you might see the codebehind as a ViewModel. Granted, my response was so quick that what I was driving at isn’t obvious even to me now. So, let me clarify. Several things in the above list were ripped apart simply because it’s possible to realize the benefit even when putting the code in the codebehind. It “just” requires discipline and good programming practices. In the end Ward believes we’re only left with the 3 benefits, and being polite he points out that not everyone will be interested in those three benefits (as an aside, I’m not at all sure I want to be so forgiving of someone that’s OK with not testing the view-logic). What I was trying to point out is two things. First, looked at in that light, we can probably eliminate the three benefits as well. Second is that once you’ve done so, what you’ve managed to do is follow the MVVM pattern, you’ve just done so by utilizing the codebehind as your ViewModel! As evidence of this I suggested that if you treated the codebehind it “might even be possible to unit test it”. That sounds less confident than I actually was. I was nearly certain you could do this. Ward rightfully asked me to “prove” it, though. So, here we are. I’m going to prove it.&lt;/p&gt; &lt;p&gt;Ward was right about one thing: even though we always talk about unit testing as a benefit of MVVM, samples and tutorials never seem to include these mythical tests. Ward went so far as to say the following:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;Find me a demo with automated ViewModel tests. Do they even exist?The hypocrasy is mildly amusing.&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;How right he is! I didn’t want to create my own demo, I just wanted to adapt an existing one. However, locating a demo that did unit testing wasn’t easy. However, Ward, they do &lt;a href="http://www.codeproject.com/KB/silverlight/MVVMSilverlightHelloWorld.aspx"&gt;exist&lt;/a&gt;. I adapted this sample (it’s a great sample, but the code could use some serious work… even my adaptation is sloppy even after cleaning up a lot of things) to eliminate the ViewModel class and treat the codebehind as the ViewModel. Then I proceeded to unit test the Window itself.&lt;/p&gt; &lt;p&gt;Let me step back and talk about why many people consider UIs to not be unit testable. In the early days we’d use UI automation to test our UIs. Usually that meant we’d have to automate the application, navigate to the UI intended to be tested, and then automate the user interactions to test our UI. Anyone familiar with unit testing will spot the problem here immediately. First, we’re not testing a “unit” because we couldn’t test the screen/control whatever in isolation. We had to automate the entire application in order to navigate to the UI we intend to test. Along the way we probably had to do things like logon to a server, select items that change shared state used by the UI, etc. Worse, we’re working with “live” data (not production). So many things that have nothing to do with what we’re testing can go wrong here (Is the server up? Did our logon credentials change? Is the network down?). This is an integration test, not a unit test. It might be a valid test to make, and it might even be worth automating (though such tests are fragile due to the reliance on the environment), but it’s not a unit test and you won’t want to run it during development.&lt;/p&gt; &lt;p&gt;OK, but you can solve this issue with some effort. You can write tests that only instantiate the UI portion that you want to test. You can even do so in a way that enables you to “mock out” the environmental pieces (database access, etc.). Now all you have to do is some UI automation of on the isolated portion of the UI in order to test it. We’re good to go, right? Wrong. UI automation is fragile at best. It requires actually displaying the UI and automating the user interaction. This means if anyone actually hits some keys, moves the mouse or clicks the mouse button at the wrong time the automated UI test can fail even if there’s nothing wrong with the test. That might be acceptable in an integration test, but you don’t want this in a unit test that’s going to be run frequently by the developer while he’s sitting at the keyboard. There’s lots of other issues with UI automation as well, such as timing issues, the fact that UIs change frequently even when the UI logic doesn’t (changing a TextBox to a ComboBox or other such “minor” changes that don’t change the interaction logic by often do break the automation), etc.&lt;/p&gt; &lt;p&gt;No, UI automation is pretty much universally considered a bad practice in unit testing. This leads many to conclude you shouldn’t ever create a UI component in unit tests. However, this is “throwing the baby out with the bath water”. While following MVVM I’ve often found it convenient or even necessary to create some UI components, and as long as you’re not doing any UI automation on these components there’s no issue with doing so. For instance, in order to raise a RoutedCommand you have to have a UIElement. I know that most everyone avoids the RoutedCommand in MVVM, preferring an ICommand implementation like the DelegateCommand. However, I’ve found it necessary to use a RoutedCommand from time to time (such as when needing to handle an ApplicationCommands.Paste). &lt;a href="http://wpfonyx.codeplex.com/"&gt;Onyx&lt;/a&gt; provides a mechanism for handling a RoutedCommand but in order to unit test the ViewModel you’ll have to be able to execute the command, which means you’ll need a UIElement. Since we don’t do any UI automation with this element (in fact, it’s never displayed) there’s no problem with creating a UIElement in the unit test for this purpose.&lt;/p&gt; &lt;p&gt;It’s precisely my experience with Onyx testing that had me convinced it would be possible to treat the codebehind as a ViewModel and proceed to unit test it. So long as you write the codebehind in the same manner as you’d write a ViewModel, it can be unit tested in exactly the same fashion. In your unit tests instead of creating a ViewModel your create the actual View, but nothing else changes. You don’t actually show the View, and you don’t do any UI automation, but instead do all of the same things you’d do if it were a ViewModel you were testing. After all, it is a ViewModel!&lt;/p&gt; &lt;p&gt;I’ve attached a Zip file with the sample solution that illustrates how this works.&lt;/p&gt; &lt;p&gt;Do I think this is a good idea? Absolutely not! It’s too easy to write code that’s tightly coupled and not unit testable when you do this. Separating the code out into a “proper” ViewModel doesn’t magically lead to properly decoupled code, as Ward points out, and it’s very possible to write properly decoupled code in the codebehind, as demonstrated by this sample. However, the effort is actually worse when you use the codebehind. It’s too easy to accidently cause coupling issues, or even to intentionally cause coupling issues simply because you think the effort is too great when you can just easily write code that accesses the UI components.&lt;/p&gt; &lt;p&gt;So, while I think Ward has done an interesting thought exercise, I come to a different conclusion than he does. If you’re not concerned with SoC, testability, etc., then there’s no need for MVVM and you can go ahead and write the same kind of code we did for years with other UI frameworks. I think that’s a mistake, but go ahead an do so if that’s what you’re comfortable with. If you are concerned with SoC, testing, etc., it is perfectly possible to meet these goals while putting all of your code in the codebehind. However, the effort is the same, because what you’re really doing in this case still is MVVM, it’s just treating the codebehind as your ViewModel.&lt;/p&gt; &lt;p&gt;Download the &lt;a href="/Media/Default/Windows-Live-Writer/NoViewModel.zip"&gt;zip file&lt;/a&gt; for this article.&lt;/p&gt;</description><pubDate>Tue, 24 May 2011 14:59:58 GMT</pubDate><guid isPermaLink="true">http://www.digitaltapestry.net:80/blog/look-ma-no-viewmodel</guid></item><item><title>Testing</title><link>http://www.digitaltapestry.net:80/blog/testing</link><description>&lt;pre class="brush: csharp; toolbar: false;"&gt;public class Foo
{
}
&lt;/pre&gt;</description><pubDate>Fri, 08 Apr 2011 14:39:42 GMT</pubDate><guid isPermaLink="true">http://www.digitaltapestry.net:80/blog/testing</guid></item><item><title>Design by Contract in .NET 4 - Part II</title><link>http://www.digitaltapestry.net:80/blog/design-by-contract-in-.net-4-part-ii</link><description>&lt;p&gt;OK, &lt;a href="http://digitaltapestry.wordpress.com/2010/02/28/design-by-contract-in-net-4-part-i/"&gt;last time&lt;/a&gt; I went over a lot of Design by Contract (DbC) theory and how some of it applied to .NET 4, but didn&amp;rsquo;t get into any concrete information or code. Hopefully the post was coherent, as I wrote most of it with a house full of screaming kids :). Anyway, this time around I&amp;rsquo;m going to actually get into code and hopefully provide a solid introduction. Keep in mind, however, that I&amp;rsquo;m new to all of this as well.&lt;/p&gt;
&lt;p&gt;Most DbC tutorials introduce you to the concept by implementing a collection type. That&amp;rsquo;s fine, but I want to do something a bit more relevant. After thinking about it a while, I thought a good candidate would be to re-implement the &lt;a href="http://www.codeplex.com/CommonServiceLocator"&gt;Common Service Locator&lt;/a&gt; using DbC in .NET 4. The Common Service Locator is a small library that will be easy enough to re-implement as an exercise, and the documentation for it already comes very close to &lt;a href="http://commonservicelocator.codeplex.com/wikipage?title=API%20Reference&amp;amp;referringTitle=Home"&gt;specifying the contract&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Before you can follow along with me here, you&amp;rsquo;ll need to install &lt;a href="http://msdn.microsoft.com/en-us/vstudio/dd582936.aspx"&gt;Visual Studio 2010 RC&lt;/a&gt; and the &lt;a href="http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx"&gt;Code Contracts&lt;/a&gt; (.NET 4 contains the necessary Contract libraries, but the tools are separate).&lt;/p&gt;
&lt;p&gt;To start, using Visual Studio 2010 create a Class Library project called CommonServiceLocator.&lt;/p&gt;
&lt;p&gt;&lt;a href="http://localhost:5647/wp-content/uploads/2010/03/image61.png"&gt;&lt;img style="display: inline; border: 0;" title="image" src="http://localhost:5647/wp-content/uploads/2010/03/image_thumb6.png" border="0" alt="image" width="506" height="352" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Delete the Class1.cs file that was added to the project, and add the IServiceLocator interface, copying and pasting the code from the source code at CodePlex. At this time the project should compile, but we&amp;rsquo;ve not got anything exciting here.&lt;/p&gt;
&lt;p&gt;Now, we need to enable the Code Contract tools. In the Project properties, locate the Code Contracts tab and enable runtime and static contract checking.&lt;/p&gt;
&lt;p&gt;&lt;a href="http://localhost:5647/wp-content/uploads/2010/03/image7.png"&gt;&lt;img style="display: inline; border: 0;" title="image" src="http://localhost:5647/wp-content/uploads/2010/03/image_thumb7.png" border="0" alt="image" width="501" height="306" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;The static checking seems to be much more finicky then the rest of the DbC tooling. This is probably partially due to the nature of the tool (I draw this conclusion based on the documentation which recommends using it on only portions of your code, which is a subject I won&amp;rsquo;t go into here), though it may also be simply due to the beta nature of the tool. I&amp;rsquo;m not sure if I&amp;rsquo;d use static checking on a real project based on my preliminary attempts at using it, but we&amp;rsquo;ll turn it on here to give you a feel for it. Compile the project again and you should see an informational entry in the &amp;ldquo;Error List&amp;rdquo; stating that 0 assertions were checked. Not very exciting, but we know that we&amp;rsquo;ve got things configured correctly.&lt;/p&gt;
&lt;p&gt;Now we need to specify the contract for IServiceLocator. Normally, contract assertions would be placed directly in the source code for the type, but that&amp;rsquo;s not really possible for interfaces or abstract methods. In these scenarios, we instead create separate types used to specify the contract and use a pair of attributes to link the types. So, the first thing to do is create a class named ServiceLocatorContract (the name&amp;rsquo;s not important to the tools, but this name is meaningful to readers of the code) to specify the contract for the IServiceLocator interface. Explicitly implement IServiceLocator on this new class.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Note 1:&lt;/em&gt; The documentation claims that you must explicitly implement the interface, but I&amp;rsquo;ve found you can implicitly implement it instead. However, I wouldn&amp;rsquo;t recommend this, just because I don&amp;rsquo;t know why there&amp;rsquo;s a discrepancy between the documentation and what seems to be possible.&lt;/p&gt;
&lt;p&gt;Finally, you need to add a ContractClassAttribute to the IServiceLocator and a ContractClassForAttribute to the ServiceLocatorContract. Here&amp;rsquo;s how the ServiceLocatorContract should now look.&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;    [ContractClassFor(typeof(IServiceLocator))]
    internal abstract class ServiceLocatorContract : IServiceLocator
    {
        object IServiceLocator.GetInstance(Type serviceType)
        {
            throw new NotImplementedException();
        }

        object IServiceLocator.GetInstance(Type serviceType, string key)
        {
            throw new NotImplementedException();
        }

        IEnumerable&amp;lt;object&amp;gt; IServiceLocator.GetAllInstances(Type serviceType)
        {
            throw new NotImplementedException();
        }

        TService IServiceLocator.GetInstance&amp;lt;TService&amp;gt;()
        {
            throw new NotImplementedException();
        }

        TService IServiceLocator.GetInstance&amp;lt;TService&amp;gt;(string key)
        {
            throw new NotImplementedException();
        }

        IEnumerable&amp;lt;TService&amp;gt; IServiceLocator.GetAllInstances&amp;lt;TService&amp;gt;()
        {
            throw new NotImplementedException();
        }

        object IServiceProvider.GetService(Type serviceType)
        {
            throw new NotImplementedException();
        }
    }
&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;Note 2&lt;/em&gt;: I&amp;rsquo;ve made the class internal and abstract, because it should never be created or used.&lt;/p&gt;
&lt;p&gt;OK, now let&amp;rsquo;s supply the contract for the first GetInstance method. The &lt;a href="http://commonservicelocator.codeplex.com/wikipage?title=API%20Reference&amp;amp;referringTitle=Home"&gt;documentation&lt;/a&gt; gives us our first cut at this.&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;        object IServiceLocator.GetInstance(Type serviceType)
        {
            Contract.Ensures(Contract.Result&amp;lt;object&amp;gt;() != null);
            Contract.Ensures(serviceType.IsAssignableFrom(Contract.Result&amp;lt;object&amp;gt;().GetType()));
            throw new NotImplementedException();
        }
&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;Note 3&lt;/em&gt;: I&amp;rsquo;ve left in the &amp;ldquo;throw new NotImplementedException()&amp;rdquo; that was added by the IDE when I explicitly implemented the interface. Most blog posts I&amp;rsquo;ve seen on this subject return some arbitrary value instead (null or default(T), generally). However, this code should never be called, so I prefer to leave in the exception.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Note 4&lt;/em&gt;: The documentation also specifies what exception types are allowed to be thrown, but I don&amp;rsquo;t believe there&amp;rsquo;s anyway to specify this using the static &lt;em&gt;Contract&lt;/em&gt; class. If I&amp;rsquo;m wrong, I&amp;rsquo;d love to hear differently. I doubt it, though, as the Microsoft folks believe (and I think rightly so) that checked exceptions are a bad thing.&lt;/p&gt;
&lt;p&gt;Now, let&amp;rsquo;s think about this method further and see if there are other things we should specify the contract. The first thing that comes to my mind is that &lt;em&gt;serviceType&lt;/em&gt; should never be &lt;em&gt;null&lt;/em&gt;. I&amp;rsquo;d really like to throw an &lt;em&gt;ArgumentNullException&lt;/em&gt; in this case, but the documentation seems to disallow this as it says that only an &lt;em&gt;ActivationException&lt;/em&gt; should be thrown. However, it does make a very vague reference to &amp;ldquo;except for the usual CLR rules for things like ThreadAbortException&amp;rdquo;. I don&amp;rsquo;t think that &lt;em&gt;ArgumentException&lt;/em&gt;s fit into these rules, but I also think that the documentation here just failed to take this into account. I could follow the documentation strictly, but if I were implementing this from scratch I would do things differently, so let&amp;rsquo;s just specify this to throw an &lt;em&gt;ArgumentNullException&lt;/em&gt;.&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;        object IServiceLocator.GetInstance(Type serviceType)
        {
            Contract.Requires&amp;lt;ArgumentNullException&amp;gt;(serviceType != null, "serviceType");
            Contract.Ensures(Contract.Result&amp;lt;object&amp;gt;() != null);
            Contract.Ensures(serviceType.IsAssignableFrom(Contract.Result&amp;lt;object&amp;gt;().GetType()));
            throw new NotImplementedException();
        }
&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;Note 5&lt;/em&gt;: One might be tempted to add a &lt;em&gt;Requires&lt;/em&gt; that would specify that consumer has to specify a &lt;em&gt;serviceType&lt;/em&gt; for a registered type, but this would be wrong. First, there&amp;rsquo;s no way to write such an assertion, because there&amp;rsquo;s no API exposed for determining what services are registered. Even if there were, however, I contend it would still be wrong to do this. We want the raising of an &lt;em&gt;ActivationException&lt;/em&gt; to be a normal possible result here, and not a contractual requirement.&lt;/p&gt;
&lt;p&gt;This seems to be a relatively complete contract specification to me. I&amp;rsquo;ll do the same for the rest of the methods.&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;    [ContractClassFor(typeof(IServiceLocator))]
    public class ServiceLocatorContract : IServiceLocator
    {
        object IServiceLocator.GetInstance(Type serviceType)
        {
            Contract.Requires&amp;lt;ArgumentNullException&amp;gt;(serviceType != null, "serviceType");
            Contract.Ensures(Contract.Result&amp;lt;object&amp;gt;() != null);
            Contract.Ensures(serviceType.IsAssignableFrom(Contract.Result&amp;lt;object&amp;gt;().GetType()));
            throw new NotImplementedException();
        }

        object IServiceLocator.GetInstance(Type serviceType, string key)
        {
            Contract.Requires&amp;lt;ArgumentNullException&amp;gt;(serviceType != null, "serviceType");
            Contract.Ensures(Contract.Result&amp;lt;object&amp;gt;() != null);
            Contract.Ensures(serviceType.IsAssignableFrom(Contract.Result&amp;lt;object&amp;gt;().GetType()));
            throw new NotImplementedException();
        }

        IEnumerable&amp;lt;object&amp;gt; IServiceLocator.GetAllInstances(Type serviceType)
        {
            Contract.Requires&amp;lt;ArgumentNullException&amp;gt;(serviceType != null, "serviceType");
            Contract.Ensures(Contract.Result&amp;lt;IEnumerable&amp;lt;object&amp;gt;&amp;gt;() != null);
            Contract.Ensures(Contract.ForAll&amp;lt;object&amp;gt;(Contract.Result&amp;lt;IEnumerable&amp;lt;object&amp;gt;&amp;gt;(), obj =&amp;gt; obj != null));
            Contract.Ensures(Contract.ForAll&amp;lt;object&amp;gt;(Contract.Result&amp;lt;IEnumerable&amp;lt;object&amp;gt;&amp;gt;(), obj =&amp;gt; serviceType.IsAssignableFrom(obj.GetType())));
            throw new NotImplementedException();
        }

        TService IServiceLocator.GetInstance&amp;lt;TService&amp;gt;()
        {
            Contract.Ensures(Contract.Result&amp;lt;TService&amp;gt;() != null);
            throw new NotImplementedException();
        }

        TService IServiceLocator.GetInstance&amp;lt;TService&amp;gt;(string key)
        {
            Contract.Ensures(Contract.Result&amp;lt;TService&amp;gt;() != null);
            throw new NotImplementedException();
        }

        IEnumerable&amp;lt;TService&amp;gt; IServiceLocator.GetAllInstances&amp;lt;TService&amp;gt;()
        {
            Contract.Ensures(Contract.Result&amp;lt;IEnumerable&amp;lt;TService&amp;gt;&amp;gt;() != null);
            Contract.Ensures(Contract.ForAll&amp;lt;TService&amp;gt;(Contract.Result&amp;lt;IEnumerable&amp;lt;TService&amp;gt;&amp;gt;(), obj =&amp;gt; obj != null));
            throw new NotImplementedException();
        }

        object IServiceProvider.GetService(Type serviceType)
        {
            Contract.Requires&amp;lt;ArgumentNullException&amp;gt;(serviceType != null, "serviceType");
            Contract.Ensures(Contract.Result&amp;lt;object&amp;gt;() == null || serviceType.IsAssignableFrom(Contract.Result&amp;lt;object&amp;gt;().GetType()));
            throw new NotImplementedException();
        }
    }
&lt;/pre&gt;</description><pubDate>Fri, 08 Apr 2011 14:14:13 GMT</pubDate><guid isPermaLink="true">http://www.digitaltapestry.net:80/blog/design-by-contract-in-.net-4-part-ii</guid></item><item><title>Spaces Rant</title><link>http://www.digitaltapestry.net:80/blog/spaces-rant</link><description>&lt;div id="msgcns!D18C3EC06EA971CF!1862" class="bvMsg"&gt;
&lt;p&gt;&lt;strong&gt;Note: &lt;/strong&gt;This was written on one of my old blogs hosted by Windows Live Spaces and subsequently imported here.&lt;/p&gt;
&lt;p&gt;Windows Live Spaces are driving me nuts. I&amp;rsquo;m going to be looking for a new home for my blog very soon. I&amp;rsquo;m that fed up.&lt;/p&gt;
&lt;p&gt;I get &lt;strong&gt;way&lt;/strong&gt; too much spam in my comments. Do a Google (Bing) search and you&amp;rsquo;ll find that this has been a &lt;strong&gt;very&lt;/strong&gt; long standing complaint, and there&amp;rsquo;s really no excuse for this. The spam I&amp;rsquo;m getting is very obviously spam, and is guaranteed to be caught by event he lamest of spam filters, but Spaces doesn&amp;rsquo;t employ any spam filters! Oh, but it gets worse. For much of the lifetime of Spaces there was no way to report spam. The tried to address this, but the result is a pain to the user, and there seems to be no results obtained from reporting the spam. There should be a big SPAM button on every comment when you&amp;rsquo;re in admin mode. Pressing that button should do numerous things:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;It should automatically notify the site administrators as to the wrongful behavior of the user, so an investigation can begin and the user can be banned.&lt;/li&gt;
&lt;li&gt;It should delete the comment.&lt;/li&gt;
&lt;li&gt;Optionally, it should block the user from ever posting to the blog again (outright banning from all blogs should be done only after investigation by administrators). In this case it should also delete all other comments on the blog left by this user.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Instead, we&amp;rsquo;re left with having to manually locate a form to fill out with information about the spammer that seems to be ignored, and then manually have to delete every spam comment. Manually deleting those comments is a &lt;strong&gt;royal pain&lt;/strong&gt;. You can&amp;rsquo;t multi-select, it has to be done one message at a time, and each deletion requires confirmation. In less than a week I&amp;rsquo;ve received more than 60 spam messages, and deleting all of those is going to waste a lot of my valuable time. What&amp;rsquo;s worse, it&amp;rsquo;s all spam that I never should have gotten in the first place, if they&amp;rsquo;d simply run a spam filter!&lt;/p&gt;
&lt;p&gt;Yeah, I&amp;rsquo;m going to be moving somewhere else. Just got to figure out where.&lt;/p&gt;
&lt;p&gt;Sorry for the rant, but I&amp;rsquo;m in a mood right now!&lt;/p&gt;
&lt;/div&gt;</description><pubDate>Fri, 21 Jan 2011 19:00:33 GMT</pubDate><guid isPermaLink="true">http://www.digitaltapestry.net:80/blog/spaces-rant</guid></item></channel></rss>