<br />
<b>Warning</b>:  Undefined array key "page" in <b>/var/www/vhosts/grumpydev.com/httpdocs/wp-content/themes/carrington-blog/functions/admin.php</b> on line <b>228</b><br />
<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>GrumpyDev</title>
	<atom:link href="http://www.grumpydev.com/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.grumpydev.com</link>
	<description>The Technical Jibber Jabber of Steven Robbins</description>
	<lastBuildDate>Tue, 17 Sep 2013 15:44:04 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.0</generator>
	<item>
		<title>403.14 Error When Trying to Access a WebAPI Route</title>
		<link>https://www.grumpydev.com/2013/09/17/403-14-error-when-trying-to-access-a-webapi-route/</link>
					<comments>https://www.grumpydev.com/2013/09/17/403-14-error-when-trying-to-access-a-webapi-route/#comments</comments>
		
		<dc:creator><![CDATA[Steven Robbins]]></dc:creator>
		<pubDate>Tue, 17 Sep 2013 15:44:04 +0000</pubDate>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[WebAPI]]></category>
		<category><![CDATA[aspnet]]></category>
		<category><![CDATA[iis]]></category>
		<category><![CDATA[should-have-used-nancy]]></category>
		<category><![CDATA[webapi]]></category>
		<guid isPermaLink="false">http://www.grumpydev.com/?p=451</guid>

					<description><![CDATA[Introduction No, there&#8217;s no flying pigs, and Satan isn&#8217;t wearing a woolly hat, but this is a post about WebAPI (boooo!) I hit an &#8220;interesting&#8221; issue today, and felt a blog post was in order in case anyone else is bitten by this rather annoying &#8220;feature&#8221;. I added a very simple route definition: config.Routes.MapHttpRoute( name: [&#8230;]]]></description>
										<content:encoded><![CDATA[<h2>Introduction</h2>
<p>No, there&#8217;s no flying pigs, and Satan isn&#8217;t wearing a woolly hat, but this is a post about WebAPI (boooo!) I hit an &#8220;interesting&#8221; issue today, and felt a blog post was in order in case anyone else is bitten by this rather annoying &#8220;feature&#8221;.</p>
<p>I added a very simple route definition:</p>
<pre class="brush: csharp; toolbar: false;">config.Routes.MapHttpRoute(
  name: "foo",
  routeTemplate: "{controller}/{name}",
  defaults: new { name = RouteParameter.Optional },
  constraints: new { controller = "foos" });</pre>
<p>And a very simple controller:</p>
<pre class="brush: csharp; toolbar: false;">namespace Bar
{
    using System.Web.Http;

    using Bar.Hypermedia;

    public class FoosController : ApiController
    {
        private readonly IFooService fooService;

        public FoosController(IFooService fooService)
        {
            this.fooService = fooService;
        }

        [HttpGet]
        public IEnumerable Root()
        {
            return this.fooService.GetFoos();
        }

        [HttpGet]
        public Foo Root(string name)
        {
            return this.fooService.GetFoo(name);
        }
    }
}</pre>
<p>It couldn&#8217;t get much more simple &#8211; just a controller that returns a collection of Foos, or a single Foo, depending on whether the name of the Foo was specified. I fired up curl and getting a single Foo was fine, but browsing to /foos/ came back with:</p>
<blockquote><p>HTTP Error 403.14 &#8211; Forbidden<br />
The Web server is configured to not list the contents of this directory.</p></blockquote>
<p>Err.. what?!</p>
<h2>The Solution</h2>
<p>The solution was easy &#8211; just ask a friendly neighbourhood ASP.Net WebAPI MVP to fix it for me <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <a href="https://twitter.com/filip_woj" target="_blank">Filip</a> stepped up and confirmed all my code was fine, but after some head scratching noticed that I had my FoosController.cs inside a folder called Foos, and renaming that folder made the route work fine. It seems that if IIS/Asp.Net sees a folder that exactly matches the URL you&#8217;re asking for (/foos in this case) then it takes over and ignores any routes you have setup. Renaming folders would be a major pain in the backside, but luckily you can disable this behaviour by adding one line to the global.asax:</p>
<pre class="brush: csharp; toolbar: false;">public class WebApiApplication : HttpApplication
{
    protected void Application_Start()
    {
        // Stop IIS/Asp.Net breaking our routes
        RouteTable.Routes.RouteExistingFiles = true;

        WebApiConfig.Register(GlobalConfiguration.Configuration);
    }
}</pre>
<p>So many thanks to Filip for helping me solve this one &#8211; I&#8217;m sure I&#8217;d have lost time, and hair, trying to figure it out on my own. I&#8217;d consider this behaviour to be a bug, but I&#8217;m sure it&#8217;s actually a feature in someone&#8217;s mind. If only there was a <a title="Nancy" href="http://nancyfx.org/" target="_blank">better way to write HTTP APIs in .net</a>&#8230;. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grumpydev.com/2013/09/17/403-14-error-when-trying-to-access-a-webapi-route/feed/</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
		<item>
		<title>Lowering The Barrier To Entry For Testing On Linux / Mono With Vagrant</title>
		<link>https://www.grumpydev.com/2013/06/22/lowering-the-barrier-to-entry-for-testing-on-linux-mono-with-vagrant/</link>
					<comments>https://www.grumpydev.com/2013/06/22/lowering-the-barrier-to-entry-for-testing-on-linux-mono-with-vagrant/#respond</comments>
		
		<dc:creator><![CDATA[Steven Robbins]]></dc:creator>
		<pubDate>Sat, 22 Jun 2013 12:47:42 +0000</pubDate>
				<category><![CDATA[Mono]]></category>
		<category><![CDATA[Nancy]]></category>
		<category><![CDATA[Vagrant]]></category>
		<category><![CDATA[VirtualBox]]></category>
		<category><![CDATA[mono]]></category>
		<category><![CDATA[nancy]]></category>
		<category><![CDATA[vagrant]]></category>
		<category><![CDATA[virtualbox]]></category>
		<guid isPermaLink="false">http://www.grumpydev.com/?p=446</guid>

					<description><![CDATA[Introduction We are big fans of Mono on the Nancy project &#8211; we have Continuous Integration builds that run on both Mono 2.x, and Mono 3.x (in addition to Microsoft&#8217;s .net), and we have TravisCI also performing Mono builds of all pull requests as they come in. As good as Mono is though, there are [&#8230;]]]></description>
										<content:encoded><![CDATA[<h2>Introduction</h2>
<p>We are big fans of Mono on the Nancy project &#8211; we have Continuous Integration builds that run on both Mono 2.x, and Mono 3.x (in addition to Microsoft&#8217;s .net), and we have TravisCI also performing Mono builds of all pull requests as they come in.</p>
<p>As good as Mono is though, there are still times where we have issues with compatibility. Sometimes these are down to Mono itself, other times it&#8217;s a casing issue when running on Linux (which generally has a case sensitive file system, so /Images isn&#8217;t the same as /images). Plenty of our contributors are au fait with Mono and Linux, so fixing issues on pull requests isn&#8217;t an issue, but for those that aren&#8217;t, getting Mono and Linux set, even in a virtual environment can be daunting &#8211; and that&#8217;s before you even attempt to edit any files!</p>
<h2>Introducing Nancy.Vagrant</h2>
<p>I&#8217;ve discussed Vagrant in a previous post &#8211; it&#8217;s an excellent tool for automatically spinning up and configuring virtual machines, and we&#8217;ve used it to create two scripts that make creating a Linux/Mono test environment for Nancy as simple as typing:</p>
<blockquote><p>vagrant up<br />
vagrant ssh</p></blockquote>
<p>And because Vagrant is capable of sharing folders between the host machine and the virtual machine, you can continue to edit the files in Visual Studio (or whatever editor of choice you use locally), and run the build in the Linux / Mono environment. Once you&#8217;re all done you can either stop the virtual machine, or delete it completely, using another single command.</p>
<h2>Trying It Out</h2>
<p>The scripts themselves, as well as instructions on getting up and running and some simple Linux help, can be found over on the Github repository:</p>
<p><a href="https://github.com/NancyFx/Nancy.Vagrant">https://github.com/NancyFx/Nancy.Vagrant</a></p>
<p>We hope this helps people get up and running easily with Linux and Mono, whether they&#8217;re contributing to Nancy or not.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grumpydev.com/2013/06/22/lowering-the-barrier-to-entry-for-testing-on-linux-mono-with-vagrant/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Windows 8, Hyper-V, VirtualBox, Vagrant and Hanging on Boot</title>
		<link>https://www.grumpydev.com/2013/06/19/windows-8-hyper-v-virtualbox-vagrant-and-hanging-on-boot/</link>
					<comments>https://www.grumpydev.com/2013/06/19/windows-8-hyper-v-virtualbox-vagrant-and-hanging-on-boot/#comments</comments>
		
		<dc:creator><![CDATA[Steven Robbins]]></dc:creator>
		<pubDate>Wed, 19 Jun 2013 15:45:40 +0000</pubDate>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Misc]]></category>
		<category><![CDATA[Nancy]]></category>
		<category><![CDATA[Vagrant]]></category>
		<category><![CDATA[VirtualBox]]></category>
		<category><![CDATA[hyper-v]]></category>
		<category><![CDATA[vagrant]]></category>
		<category><![CDATA[virtualbox]]></category>
		<category><![CDATA[virtualisation]]></category>
		<category><![CDATA[win8]]></category>
		<guid isPermaLink="false">http://www.grumpydev.com/?p=425</guid>

					<description><![CDATA[ Introduction I&#8217;ve recently been playing around with Vagrant to allow Nancy contributors to easily test their changes on Mono, even if they don&#8217;t have much (or any) experience with Linux or Mono itself (more on this soon). Vagrant allows scripts to be created to quickly and easily spin up virtuals with a certain configuration, and just [&#8230;]]]></description>
										<content:encoded><![CDATA[<h2><span style="color: #000000;"> Introduction</span></h2>
<p><span style="color: #000000;">I&#8217;ve recently been playing around with <a style="color: #888888;" title="Vagrant" href="http://www.vagrantup.com/" target="_blank"><span style="color: #000000;">Vagrant</span></a> to allow <a style="color: #888888;" title="Nancy" href="http://nancyfx.org/" target="_blank"><span style="color: #000000;">Nancy </span></a>contributors to easily test their changes on Mono, even if they don&#8217;t have much (or any) experience with Linux or Mono itself (more on this soon). Vagrant allows scripts to be created to quickly and easily spin up virtuals with a certain configuration, and just as easily tear them down and destroy them when you&#8217;re done (which is just as important if you&#8217;re using a machine with limited SSD space). </span></p>
<p><span style="color: #000000;">Vagrant sits on top of actual Virtualisation software such as <a title="VirtualBox" href="https://www.virtualbox.org/" target="_blank"><span style="color: #000000;">VirtualBox </span></a>or <a title="VMWare" href="http://www.vmware.com/"><span style="color: #000000;">VMWare</span></a> (but no Hyper-V support), but it defaults to VirtualBox, and that&#8217;s the only provider out there that doesn&#8217;t involve spending money as both VMWare, and the Vagrant plugin for it, are commercial.</span></p>
<h2><span style="color: #000000;">The Problem</span></h2>
<p><span style="color: #000000;">Vagrant installed fine, VirtualBox installed fine, everything appeared to be working and could spin up VMs just dandy, but when I rebooted the machine I was stuck with the &#8220;spinning dots of doom&#8221;, and the only way to get the computer back was restoring from system restore and ditching VirtualBox <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f641.png" alt="🙁" class="wp-smiley" style="height: 1em; max-height: 1em;" /></span></p>
<p><span style="color: #000000;">I tried 3 different machines, two failed the same way and the third worked fine; the only difference being the working machine didn&#8217;t have Hyper-V enabled in Win8, but I couldn&#8217;t remove it from the other two as it&#8217;s required for Windows Phone 8 development, and I use it for several other virtuals as the performance is excellent. Stuck between a rock and a hard place <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f641.png" alt="🙁" class="wp-smiley" style="height: 1em; max-height: 1em;" /></span></p>
<h2><span style="color: #000000;">The Solution</span></h2>
<p><span style="color: #000000;">After trying multiple old versions of VirtualBox, and blind alleys that suggested disabling the hypervisor on startup would fix it (it didn&#8217;t), I finally tracked down the problem to be the networking drivers it installs. VirtualBox has three networking modes: NAT (the default), Bridged and HostOnly &#8211; with the latter two requiring separate drivers. Unchecking both sets of drivers in the installer and everything works fine:</span></p>
<p><span style="color: #000000;"><a href="https://www.grumpydev.com/wp-content/uploads/2013/06/VirtualBox.jpg"><span style="color: #000000;"><img fetchpriority="high" decoding="async" class="aligncenter size-medium wp-image-426" alt="VirtualBox" src="https://www.grumpydev.com/wp-content/uploads/2013/06/VirtualBox-300x239.jpg" width="300" height="239" srcset="https://www.grumpydev.com/wp-content/uploads/2013/06/VirtualBox-300x239.jpg 300w, https://www.grumpydev.com/wp-content/uploads/2013/06/VirtualBox.jpg 537w" sizes="(max-width: 300px) 100vw, 300px" /></span></a></span></p>
<p><span style="color: #000000;"> </span></p>
<p><span style="color: #000000;">Vagrant uses NAT by default anyway, and that gives you internet access from the VMs, so there shouldn&#8217;t be too many situations where you need to use the other two options anyway. It even works side-by-side with Hyper-V too, so I can have my normal Hyper-V virtuals running while firing up Vagrant scripts on VirtualBox. It&#8217;s obviously a bit slower this way, as it can&#8217;t use it&#8217;s own HyperVisor, but it seems fast enough, and less hassle than having to disable Hyper-V and reboot every time I wanted to use Vagrant (or vice versa when I wanted to use Hyper-V).</span></p>
<p>Now, back to those Nancy scripts..</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grumpydev.com/2013/06/19/windows-8-hyper-v-virtualbox-vagrant-and-hanging-on-boot/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Could not load file or assembly FSharp.Core with .net 4.5 / NDjango / Win8</title>
		<link>https://www.grumpydev.com/2012/08/16/could-not-load-file-or-assembly-fsharp-core-with-net-4-5-ndjango-win8/</link>
					<comments>https://www.grumpydev.com/2012/08/16/could-not-load-file-or-assembly-fsharp-core-with-net-4-5-ndjango-win8/#respond</comments>
		
		<dc:creator><![CDATA[Steven Robbins]]></dc:creator>
		<pubDate>Thu, 16 Aug 2012 18:18:02 +0000</pubDate>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[fsharp]]></category>
		<category><![CDATA[Nancy]]></category>
		<category><![CDATA[nancy]]></category>
		<category><![CDATA[workaround]]></category>
		<guid isPermaLink="false">http://www.grumpydev.com/?p=410</guid>

					<description><![CDATA[The Problem With today&#8217;s release of the RTM versions of Win8 and Visual Studio 2012 I, like many others no doubt, have formatted one of my machines, thrown the new bits on, and kicked the tyres with some code. Unfortunately, when I tried Nancy, everything build just fine, but running any tests involving NDjango (F# [&#8230;]]]></description>
										<content:encoded><![CDATA[<h2>The Problem</h2>
<p>With today&#8217;s release of the RTM versions of Win8 and Visual Studio 2012 I, like many others no doubt, have formatted one of my machines, thrown the new bits on, and kicked the tyres with some code. Unfortunately, when I tried Nancy, everything build just fine, but running any tests involving NDjango (F# based) blew up with:</p>
<blockquote><p><em>Could not load file or assembly &#8216;FSharp.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a&#8217; or one of its dependencies. The system cannot find the file specified.</em></p></blockquote>
<p>Or:</p>
<blockquote><p><em>Could not load file or assembly &#8216;FSharp.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a&#8217; or one of its dependencies. The system cannot find the file specified.</em></p></blockquote>
<p>All this works perfectly fine with .net 4, and .net 4.5 is supposed to be backwards compatible, but in this case it seems not. I haven&#8217;t done much digging, but if a strongly named assembly changes version between .net 4 and .net 4.5 I would expect an assembly binding to be in place to stop this kind of thing from happening &#8211; it&#8217;s possible that NDjango is doing something odd, but still, if it works in 4, it should work in 4.5.</p>
<p>This may or may not be an issue on Win7 if you&#8217;ve had .net 4 installed previously.</p>
<h2>The Solution</h2>
<p>Luckily, it&#8217;s very simple to add your own binding redirects to get things up and running again. These can either go in the app.config/web.config of your application, or you can put it in the machine.config &#8211; I wouldn&#8217;t recommend the latter though, as you may end up with an &#8220;it works on my machine&#8221; situation a few months down the line.</p>
<p>Either way, this is the section you need to add, it maps both 2.0.0.0 and 4.0.0.0 to the version that ships with .net 4.5/Win8 :</p>
<pre class="brush: xml; toolbar: false;">&lt;assemblyBinding  xmlns="urn:schemas-microsoft-com:asm.v1"&gt;
    &lt;dependentAssembly&gt;
        &lt;assemblyIdentity name="FSharp.Core" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/&gt;
        &lt;bindingRedirect oldVersion="2.0.0.0" newVersion="4.3.0.0"/&gt;
        &lt;bindingRedirect oldVersion="4.0.0.0" newVersion="4.3.0.0"/&gt;
    &lt;/dependentAssembly&gt;
&lt;/assemblyBinding&gt;</pre>
<p>A simple solution, and maybe this will just affect me, but this blog post will at least stop me from pulling my own hair out if this happens again <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grumpydev.com/2012/08/16/could-not-load-file-or-assembly-fsharp-core-with-net-4-5-ndjango-win8/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Nancy v0.8.0 &#8211; Best Laid Plans..</title>
		<link>https://www.grumpydev.com/2011/10/03/nancy-v0-8-0-best-laid-plans/</link>
					<comments>https://www.grumpydev.com/2011/10/03/nancy-v0-8-0-best-laid-plans/#comments</comments>
		
		<dc:creator><![CDATA[Steven Robbins]]></dc:creator>
		<pubDate>Mon, 03 Oct 2011 20:59:01 +0000</pubDate>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Nancy]]></category>
		<category><![CDATA[aspnet]]></category>
		<category><![CDATA[nancy]]></category>
		<category><![CDATA[nancyfx]]></category>
		<guid isPermaLink="false">http://www.grumpydev.com/?p=386</guid>

					<description><![CDATA[TL;DR Nancy v0.8.0 is out, loads of cool new features such as static content (so you *finally* don&#8217;t have to do it yourself :-P), basic authentication support, and CSRF protection, and enhancements to things like error handling (with fancy pants error pages) and the test framework. We also have a fantastic new logo by Nicolas Garfinkiel [&#8230;]]]></description>
										<content:encoded><![CDATA[<h2 align="left">TL;DR</h2>
<p>Nancy v0.8.0 is out, loads of cool new features such as static content (so you *finally* don&#8217;t have to do it yourself :-P), basic authentication support, and CSRF protection, and enhancements to things like error handling (with fancy pants error pages) and the test framework. We also have a fantastic new logo by Nicolas Garfinkiel (<a href="http://codetothepeople.blogspot.com/" target="_blank">codetothepeople.blogspot.com</a>), and a new website &#8211; so go check out the <a title="Nancy" href="http://nancyfx.org/" target="_blank">Nancy</a> site now <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h2>The plan..</h2>
<p>Once v0.7.1 was out of the way the plan was simple &#8211; work on diagnostics, hopefully interfacing with the guys from Glimpse, and get v0.8.0 &#8211; the &#8220;diagnostics release&#8221; out within 6 weeks or so. But things didn&#8217;t go entirely to plan&#8230;</p>
<h2>A very nice problem to have..</h2>
<p>We knew Nancy was getting a bit of a following, but we didn&#8217;t anticipate the level, and the quality, of the community contributions. We received lots of feedback, lots of great suggestions, and lots and lots of pull requests &#8211; before we knew it v0.8.0 was already looking pretty feature rich, without the diagnostics work we intended to be the core part of it, and time was tick tick ticking by. So, after a certain <a title="Mark Rendle's Twitter stream" href="http://twitter.com/#!/markrendle" target="_blank">Mark Rendle</a> started referring to this release as our &#8220;Duke Nukem Forever&#8221; release, we decided people had waiting long enough for an update and we &#8220;re-scoped&#8221; v0.8.0 so we could release the growing list of improvements sooner rather than later.</p>
<p>Taking a look at a <a title="v0.7.1 to v0.8.0 comparison" href="https://github.com/NancyFx/Nancy/compare/v0.7.1...v0.8.0" target="_blank">GitHub comparison</a> it shows v0.8.0 consisting of:</p>
<ul>
<li>186 commits</li>
<li>226 files changed / updated</li>
<li>19 different contributors</li>
</ul>
<div>So 19 different people have contributed code to this release which, to me, is an amazing figure for an OSS project that&#8217;s not only relatively young, but also built using .net, which is frequently &#8220;bashed&#8221; by certain people for its alleged lack of community and its apparent &#8220;do what MS says to do&#8221;, sheep like mentality.</div>
<h2></h2>
<h2>So, what *is* in v0.8.0?</h2>
<p>You can see the commits that went into v0.8.0 in the <a title="v0.7.1 to v0.8.0 comparison" href="https://github.com/NancyFx/Nancy/compare/v0.7.1...v0.8.0" target="_blank">GitHub comparison</a>, or take a look at the <a title="v0.8.0 Issues" href="https://github.com/NancyFx/Nancy/issues?milestone=4&amp;sort=created&amp;direction=desc&amp;state=closed" target="_blank">issue list</a> for a list of features / bug fixes, but some of the highlights are:</p>
<ul>
<li> Static content conventions &#8211; now static content is supported out of the box with pluggable conventions for which files are server from where.</li>
<li>CSRF protection &#8211; currently only supported in Razor, Spark and SSVE, but it&#8217;s now possible to validate  &#8220;tokens&#8221; (with or without a timeout) to protect your site against CSRF vulnerabilities. There&#8217;s a sample of this in the main ASPNet demo project.</li>
<li>The view cache should now be disabled in debug mode properly (yay!)</li>
<li>A new exception handling pipeline and built in error pages.</li>
<li>Basic authentication (as a new Nuget)</li>
<li>Protocol Buffers de/serialization support (as a new Nuget)</li>
<li>An awesome new logo (see below)</li>
</ul>
<div>Plus plenty of other bug fixes, tweaks and behind the scenes changes.</div>
<h2></h2>
<h2>Logo and website</h2>
<p>Thanks to the efforts of Nicolas Garfinkiel (<a href="http://codetothepeople.blogspot.com/" target="_blank">codetothepeople.blogspot.com</a>) Nancy now has an awesome new logo &#8211; many thanks to Nicolas for the speed he put this together, and for putting up with Andreas and myself nitpicking so much <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> You can see the new logo in &#8220;action&#8221; in the updated favicon, and on our newly launched <a title="Nancy" href="http://nancyfx.org/" target="_blank">Nancy</a> site &#8211; go check it out!</p>
<p>Please note that we did have a redirect on that site, so if you get redirected to github you might have to press ctrl+enter (seems to work in Chrome) or clear your cache or restart your browser or something .. sorry <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h2></h2>
<h2>Thanks</h2>
<p>So, a big thank you to everyone who contributed to this release &#8211; comments/suggestions, bug reports, fixes, features and even just giving kudos on Twitter &#8211; it&#8217;s all very much appreciated.</p>
<p>Now.. onwards and upwards to v0.9.0!</p>
<p>P.S. Andreas and I have recently recorded a <a title="Herding Code" href="http://herdingcode.com/" target="_blank">Herding Code</a> episode &#8211; so keep an eye (or ear) out for that.</p>
<p><a href="https://www.grumpydev.com/wp-content/uploads/2011/10/nancy-logo-horizontal.png"><img decoding="async" class="aligncenter size-full wp-image-400" title="Nancy Logo" src="https://www.grumpydev.com/wp-content/uploads/2011/10/nancy-logo-horizontal.png" alt="" width="500" height="164" srcset="https://www.grumpydev.com/wp-content/uploads/2011/10/nancy-logo-horizontal.png 500w, https://www.grumpydev.com/wp-content/uploads/2011/10/nancy-logo-horizontal-300x98.png 300w" sizes="(max-width: 500px) 100vw, 500px" /></a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grumpydev.com/2011/10/03/nancy-v0-8-0-best-laid-plans/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
			</item>
		<item>
		<title>Debugging xUnit Tests Using MonoDevelop</title>
		<link>https://www.grumpydev.com/2011/06/30/debugging-xunit-tests-using-monodevelop/</link>
					<comments>https://www.grumpydev.com/2011/06/30/debugging-xunit-tests-using-monodevelop/#respond</comments>
		
		<dc:creator><![CDATA[Steven Robbins]]></dc:creator>
		<pubDate>Thu, 30 Jun 2011 11:45:25 +0000</pubDate>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[Nancy]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[csharp]]></category>
		<category><![CDATA[mono]]></category>
		<category><![CDATA[monodevelop]]></category>
		<category><![CDATA[nancy]]></category>
		<category><![CDATA[nancyfx]]></category>
		<category><![CDATA[xunit]]></category>
		<guid isPermaLink="false">http://www.grumpydev.com/?p=371</guid>

					<description><![CDATA[Introduction After several months of neglect, we are currently working on getting the Nancy project ship shape on Mono. We&#8217;ve gotten to the point now where everything builds and runs just fine, but we have a few tests that fail when running on Linux/Mono. The failures we are seeing are obviously bugs in the tests/stubs/mocks [&#8230;]]]></description>
										<content:encoded><![CDATA[<h2>Introduction</h2>
<p>After several months of neglect, we are currently working on getting the <a title="Nancy" href="http://nancyfx.org" target="_blank">Nancy</a> project ship shape on Mono. We&#8217;ve gotten to the point now where everything builds and runs just fine, but we have a few tests that fail when running on Linux/Mono. The failures we are seeing are obviously bugs in the tests/stubs/mocks themselves, and we need to debug them to see exactly what&#8217;s going on. MonoDevelop has some decent test runner features, but they appear to be heavily tied to NUnit which is a problem if you happen to use xUnit <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h2>Debugging With xUnit</h2>
<p>Luckily the solution is relatively simple, if a little clunky:</p>
<ol>
<li>Download the latest <a title="xUnit" href="http://xunit.codeplex.com/" target="_blank">xUnit</a> release and unzip it somewhere.</li>
<li>Set whatever breakpoint you need in MonoDevelop and build the test project (in debug mode, obviously).</li>
<li>In MonoDevelop, go to Run, Debug Application, browse to where you extracted the ZIP from step 1 and choose the appropriate xunit.gui.*.exe depending on your target framework/architecture (xunit.gui.clr4.exe in our case).</li>
<li>The gui xUnit runner will popup &#8211; click Assembly, Open, browse to the output of your test project, select the assembly and press OK.</li>
<li>Click Run All in the bottom left.</li>
</ol>
<p>The runner will run the tests and you should break out into MonoDevelop whenever you hit a breakpoint.</p>
<p>Pretty simple, if a bit of a ballache &#8211; but hey, you shouldn&#8217;t need to debug your tests very often anyway <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grumpydev.com/2011/06/30/debugging-xunit-tests-using-monodevelop/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Switching from Cygwin to MSysGit &#8211; Git Thinks Everything Has Been Modified :-(</title>
		<link>https://www.grumpydev.com/2011/01/19/switching-from-cygwin-to-msysgit-git-thinks-everything-has-been-modified/</link>
					<comments>https://www.grumpydev.com/2011/01/19/switching-from-cygwin-to-msysgit-git-thinks-everything-has-been-modified/#comments</comments>
		
		<dc:creator><![CDATA[Steven Robbins]]></dc:creator>
		<pubDate>Wed, 19 Jan 2011 07:37:52 +0000</pubDate>
				<category><![CDATA[Misc]]></category>
		<category><![CDATA[Rambling]]></category>
		<category><![CDATA[cygwin]]></category>
		<category><![CDATA[git]]></category>
		<category><![CDATA[msysgit]]></category>
		<guid isPermaLink="false">http://www.grumpydev.com/?p=365</guid>

					<description><![CDATA[Introduction I’ve been dabbling with git lately, contributing to the Nancy project, and I’ve been happily working away using Cygwin, which I already had installed, and all was fine and dandy. Things went slightly awry, however, when I decided to give MSysGit a whirl. Typing “git status” on my (unmodified) repository, that I’d previously used [&#8230;]]]></description>
										<content:encoded><![CDATA[<h2>Introduction</h2>
<p>I’ve been dabbling with git lately, contributing to the <a href="https://github.com/thecodejunkie/Nancy" target="_blank">Nancy project</a>, and I’ve been happily working away using <a href="http://www.cygwin.com/" target="_blank">Cygwin</a>, which I already had installed, and all was fine and dandy. Things went slightly awry, however, when I decided to give <a href="http://code.google.com/p/msysgit/" target="_blank">MSysGit</a> a whirl. Typing “git status” on my (unmodified) repository, that I’d previously used with Cygwin, showed every single file as modified.. argh!</p>
<h2>Faking FileModes</h2>
<p>A quick “git diff” showed this output for every file:</p>
<pre>
old mode 100755
new mode 100644</pre>
<p>A brief Google later and it turns out that MSysGit “fakes” filemodes (unix permissions – the 755/644 part of the log above), whereas Cygwin, which is a more “complete” Linux implementation on Windows, does them “properly”. Now, by default, git tracks the filemode and considers it a change whenever it’s modified, so the “fake” modes coming back from MSysGit were making everything appear modified.</p>
<h2>Solution</h2>
<p>Luckily, the solution is very simple – tell git to stop tracking filemodes! I set this as a global option, but also had to set it on the repository too as it has a default value set in there. The following two commands sorted it out:</p>
<pre>
git config --global core.filemode false
git config core.filemode false</pre>
<h2>Conclusion</h2>
<p>A simple fix to a, potentially, obscure problem; but I think if you’re using msysgit to work on non-Windows projects, that may have filemodes set for executable scripts, then this workaround may be required too. Apparently MSysGit does attempt to fake the filemode based on file extension, so things that *look* like they should be executable are faked to have +x, but it’s not going to be perfect.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grumpydev.com/2011/01/19/switching-from-cygwin-to-msysgit-git-thinks-everything-has-been-modified/feed/</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
		<item>
		<title>Quick Add Reference Extension for Visual Studio 2010</title>
		<link>https://www.grumpydev.com/2010/10/13/quick-add-reference-extension-for-visual-studio-2010/</link>
					<comments>https://www.grumpydev.com/2010/10/13/quick-add-reference-extension-for-visual-studio-2010/#respond</comments>
		
		<dc:creator><![CDATA[Steven Robbins]]></dc:creator>
		<pubDate>Wed, 13 Oct 2010 19:19:51 +0000</pubDate>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Misc]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[add reference dialog]]></category>
		<category><![CDATA[extensions]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[vs2010]]></category>
		<guid isPermaLink="false">http://www.grumpydev.com/?p=361</guid>

					<description><![CDATA[Introduction I mentioned this on Twitter last week, but completely failed to find it again today, so thought it was worth blogging for future reference &#160; As I have blogged about in the past, the Add Reference dialog in Visual Studio is still pretty terrible in VS2010. Various extensions have made it more bearable by [&#8230;]]]></description>
										<content:encoded><![CDATA[<h2>Introduction</h2>
<p>I mentioned this on Twitter last week, but completely failed to find it again today, so thought it was worth blogging for future reference <img decoding="async" style="border-bottom-style: none; border-right-style: none; border-top-style: none; border-left-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="https://www.grumpydev.com/wp-content/uploads/2010/10/wlEmoticon-smile.png" />&#160;</p>
<p>As I have <a href="https://www.grumpydev.com/?p=306" target="_blank">blogged about in the past</a>, the Add Reference dialog in Visual Studio is still pretty terrible in VS2010. Various extensions have made it more bearable by providing search support and other enhancements, but now you can avoid it completely (most of the time) with an excellent extension from Clarius Consulting:</p>
<p><a href="http://visualstudiogallery.msdn.microsoft.com/en-us/dc06b54c-b6c4-4cf5-8203-a09c6979e881">http://visualstudiogallery.msdn.microsoft.com/en-us/dc06b54c-b6c4-4cf5-8203-a09c6979e881</a></p>
<p>Anyone that’s used ReSharper will instantly recognise the approach – just hit Ctrl+. for the VS2010 Smart Tag on something you don’t currently have referenced, and voila – an option to automatically add the reference and the corresponding using statement:</p>
<p><a href="https://www.grumpydev.com/wp-content/uploads/2010/10/quickaddreference.png"><img decoding="async" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="quickaddreference" border="0" alt="quickaddreference" src="https://www.grumpydev.com/wp-content/uploads/2010/10/quickaddreference_thumb.png" width="454" height="226" /></a></p>
<p>Simple and effective – I haven’t had any problems with it since I installed it last week – go and give it a whirl <img decoding="async" style="border-bottom-style: none; border-right-style: none; border-top-style: none; border-left-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="https://www.grumpydev.com/wp-content/uploads/2010/10/wlEmoticon-smile.png" /></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grumpydev.com/2010/10/13/quick-add-reference-extension-for-visual-studio-2010/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Silverlight Masterclass &#8211; Discounts for NxtGenUG Members</title>
		<link>https://www.grumpydev.com/2010/04/28/silverlight-masterclass-discounts-for-nxtgenug-members/</link>
					<comments>https://www.grumpydev.com/2010/04/28/silverlight-masterclass-discounts-for-nxtgenug-members/#respond</comments>
		
		<dc:creator><![CDATA[Steven Robbins]]></dc:creator>
		<pubDate>Wed, 28 Apr 2010 05:44:22 +0000</pubDate>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[competition]]></category>
		<category><![CDATA[masterclass]]></category>
		<category><![CDATA[NxtGenUG]]></category>
		<category><![CDATA[silverlight tour]]></category>
		<category><![CDATA[training]]></category>
		<guid isPermaLink="false">http://www.grumpydev.com/?p=354</guid>

					<description><![CDATA[Introduction Shawn Wildermuth’s “Silverlight Tour” is coming to the UK, in the guise of the Silverlight Masterclass, and NxtGenUG members can receive £50 off the course price (in addition to the current “early bird” offer if you qualify for that). The 3 day developer course looks quite comprehensive, starting with Silverlight, XAML and Blend basics [&#8230;]]]></description>
										<content:encoded><![CDATA[<h2></h2>
<h2>Introduction</h2>
<p><a href="http://wildermuth.com/" target="_blank">Shawn Wildermuth</a>’s “Silverlight Tour” is coming to the UK, in the guise of the <a href="http://silverlightmasterclass.net/" target="_blank">Silverlight Masterclass</a>, and <a href="http://nxtgenug.net/Region.aspx?RegionID=11" target="_blank">NxtGenUG</a> members can receive £50 off the course price (in addition to the current “early bird” offer if you qualify for that). </p>
<p>The <a href="http://silverlightmasterclass.net/Home/Developers" target="_blank">3 day developer course</a> looks quite comprehensive, starting with Silverlight, XAML and Blend basics on day one, working with data on day two, and finishing off with more advanced topics like MVVM, MEF and PRISM on day three. It’s great to see some patterns and practices coverage in a Silverlight course, especially given my recent experience trying to recruit Silverlight developers!</p>
<p>In addition to the discounts you can also win a free ticket to one of the courses by blogging about it yourself using the text from the “pitch” below. For more details on the competition take a look at <a href="http://silverlightforbusiness.net/2010/04/27/bloggers-win-a-free-place-to-the-silverlight-masterclass-worth/" target="_blank">Ian Blackburn’s blog entry</a>.</p>
<h2>The Pitch</h2>
<p>The Silverlight Tour comes to the UK – and it’s called the Masterclass!</p>
<p>This 3 day hands-on training with both designer and developer tracks looks awesome and (uniquely) has <strong>two </strong>expert trainers per course. </p>
<p>Currently scheduled in London, Manchester, and the Midlands for June, all courses also come with the chance to win an xbox 360, and Silverlight Spy licences!</p>
<p>Early bird discount of £100 if you book in May, and if you are a member of #SLUGUK or #<a href="http://www.nxtgenug.net/">nxtgenug</a> there are additional discounts to be had.</p>
<p>Full Details are here: <a href="http://silverlightmasterclass.net">http://silverlightmasterclass.net</a></p>
<p>In addition bbits are holding a raffle for a free ticket for the masterclass. To be eligible to win the ticket (worth £1095!) you MUST paste this text, including all links, into your blog and email <a href="mailto:Ian@bbits.co.uk">Ian@bbits.co.uk</a> with the url to the blog entry.&#160; The draw will be made on June 1st and the winner informed by email and on <a href="http://silverlightmasterclass.net">http://silverlightmasterclass.net</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grumpydev.com/2010/04/28/silverlight-masterclass-discounts-for-nxtgenug-members/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Optional Parameters in C#4, C#3 and VB.Net, With a Side Order of IL Quirks</title>
		<link>https://www.grumpydev.com/2010/04/19/optional-parameters-in-c4-c3-and-vb-net-with-a-side-order-of-il-quirks/</link>
					<comments>https://www.grumpydev.com/2010/04/19/optional-parameters-in-c4-c3-and-vb-net-with-a-side-order-of-il-quirks/#comments</comments>
		
		<dc:creator><![CDATA[Steven Robbins]]></dc:creator>
		<pubDate>Mon, 19 Apr 2010 07:30:57 +0000</pubDate>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[c#4]]></category>
		<category><![CDATA[csharp]]></category>
		<category><![CDATA[csharp4]]></category>
		<category><![CDATA[il]]></category>
		<category><![CDATA[ildasm]]></category>
		<category><![CDATA[named parameters]]></category>
		<category><![CDATA[optional parameters]]></category>
		<category><![CDATA[quirks]]></category>
		<category><![CDATA[vs2010]]></category>
		<guid isPermaLink="false">http://www.grumpydev.com/?p=338</guid>

					<description><![CDATA[Introduction One of the features C# has gained in it’s latest V4 incarnation is the ability to work with optional parameters. Now VB.Net (and the underlying IL) has had this ability for sometime, but as it’s new to C# folks, and causing a little confusion; I’m going to attempt to explain how it works, when [&#8230;]]]></description>
										<content:encoded><![CDATA[<h2>Introduction</h2>
<p>One of the features C# has gained in it’s latest V4 incarnation is the ability to work with optional parameters. Now VB.Net (and the underlying IL) has had this ability for sometime, but as it’s new to C# folks, and causing a little confusion; I’m going to attempt to explain how it works, when it works and the potential gotchas. I’ll also cover a strange inconsistency between the the VB and C# compilers when it comes to named parameters.</p>
<p><strong>Warning:</strong> This post contains <a href="http://en.wikipedia.org/wiki/Common_Intermediate_Language" target="_blank">IL</a>, but don’t let that put you off – you don’t actually need to understand it to get the point of the post!</p>
<h2></h2>
<h2>So It’s C#4 Only, Right?</h2>
<p>Sort of <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Just to confuse things, optional parameters, from both a definition and consumption perspective, are really the concern of the compiler. As <a href="http://www.humblecoder.co.uk/?p=137" target="_blank">other posts</a> have correctly pointed out, as long as you’re using Visual Studio 2010 you can define and consume optional parameters while targeting an older framework version:</p>
<pre class="brush: csharp; toolbar: false;">public void DoThings(int intParameter = 22, string stringParameter = &quot;Default&quot;)
{
    // Do things
}

// ...

DoThings(); // Uses the default values</pre>
<p>This will work whether you’re in the same assembly, or consuming a library that already exposes methods with optional parameters.</p>
<p>You can also happily consume C# libraries containing optional parameters with VB.Net; even if the VB.Net project is still running under VS2008. The reason this works it that the IL that the new C# compiler is emitting is nothing new, and VB.Net has been able to define and consume optional parameters for some time. You can see the IL that is generated for the above method in the ILDASM output below (interesting parts highlighted in yellow):</p>
<p><a href="https://www.grumpydev.com/wp-content/uploads/2010/04/OptionalParamsIL.png"><img loading="lazy" decoding="async" style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="OptionalParamsIL" border="0" alt="OptionalParamsIL" src="https://www.grumpydev.com/wp-content/uploads/2010/04/OptionalParamsIL_thumb.png" width="454" height="176" /></a></p>
<p>The one thing you <strong>*cannot*</strong> do is consume optional parameters using C# in Visual Studio 2008; even if you’ve built the library in VS2010 and targeted the older framework. The C#3 compiler just doesn’t understand (or more to the point doesn’t care about) optional parameters. If you try and build the code above using Visual Studio 2008 you will get the following error:</p>
<p><a href="https://www.grumpydev.com/wp-content/uploads/2010/04/OptionalParameters2008.png"><img loading="lazy" decoding="async" style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="OptionalParameters2008" border="0" alt="OptionalParameters2008" src="https://www.grumpydev.com/wp-content/uploads/2010/04/OptionalParameters2008_thumb.png" width="454" height="147" /></a></p>
<p>Definitely something for library authors to consider – we’re not quite out of “overload hell” yet unfortunately.</p>
<h2>Gotchas?</h2>
<p>Now you may well think that when you consume an optional parameter, the compiler is emitting code that pulls the default value from the method information at runtime &#8211; but that isn’t the case. In a similar fashion to the way the compiler handles consuming consts, the default values are “baked into” the calling code. This is true whether the calling code is in the same assembly as the definition, or a separate assembly . The following ILDASM screenshot shows the IL generated for the DoThings() call above (interesting parts highlighted in yellow again):</p>
<p><a href="https://www.grumpydev.com/wp-content/uploads/2010/04/CallingOptionalIL.png"><img loading="lazy" decoding="async" style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="CallingOptionalIL" border="0" alt="CallingOptionalIL" src="https://www.grumpydev.com/wp-content/uploads/2010/04/CallingOptionalIL_thumb.png" width="454" height="116" /></a></p>
<p>Even if you don’t fully understand the IL you can clearly see the constant values in the code are “baked into” the TestStuff() method.</p>
<p>The issue this can cause is the same for exposing public consts – if you change the default values in a library, but don’t recompile the calling code,<strong><em> then the calling code will still call your method(s) with the old default values</em></strong>. This is definitely something you need to consider when designing APIs using optional parameters. </p>
<p>One potential way to “work around” this issue and avoid “locking yourself in” to a particular set of defaults would be to follow the following pattern:</p>
<pre class="brush: csharp; toolbar: false;">public void DoThings(int? intParameter = null, string stringParameter = null)
{
    if (intParameter == null)
        intParameter = 22;

    if (stringParameter == null)
        stringParameter = &quot;Default&quot;;

    // Do Stuff
}</pre>
<p>In the code above we still get the benefits of having optional parameters; but because we use “marker” values for defaults (nulls in this case), and set the *real* defaults inside the method, we are free to change the real defaults at a later date. This technique does require more code, and doesn’t look quite as elegant as the previous example, but in my opinion the benefits outweigh the drawbacks, especially for public APIs.</p>
<h2>A VB/C# Named Parameters Quirk</h2>
<p>As I was pulling together the IL for this post I discovered a small “quirk” when comparing the IL output by the VB.Net compiler to the output of the C&#8217;# compiler when dealing with named parameters. If we call the DoThings() method above and specify just the stringParameter the IL produced by the VB.Net compiler looks as I would expect:</p>
<p><a href="https://www.grumpydev.com/wp-content/uploads/2010/04/vbnamed.png"><img loading="lazy" decoding="async" style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="vb-named" border="0" alt="vb-named" src="https://www.grumpydev.com/wp-content/uploads/2010/04/vbnamed_thumb.png" width="454" height="49" /></a></p>
<p>The default value for the intParameter is pushed onto the stack, followed by our “Nondefault” string value and the method is called. The IL produced by the C# compiler is slightly different though, as shown by the highlighted sections below:</p>
<p><a href="https://www.grumpydev.com/wp-content/uploads/2010/04/csnamed.png"><img loading="lazy" decoding="async" style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="cs-named" border="0" alt="cs-named" src="https://www.grumpydev.com/wp-content/uploads/2010/04/csnamed_thumb.png" width="454" height="62" /></a></p>
<p>In the C# version the “Nondefault” string is pushed onto the stack *first*, then pops it off into a local variable (stloc.3), the default value for intParameter is then pushed, followed by the contents of the local variable (ldloc.3).</p>
<p>Not a massive difference, and I’m sure there’s a good reason for it, but the C# version does look decidedly “odd” to me. I’m no expert in IL performance, but this may be conclusive proof that VB is faster than C# <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>*</strong></p>
<p><strong>Update: </strong><a href="http://marcgravell.blogspot.com/" target="_blank">Marc Gravell</a> was kind enough to review this post for me and correctly pointed out that I should really be comparing IL for *optimised* builds, not debug builds (which have optimisation turned off). Marc has done this for himself and confirmed the stloc and ldloc are still present, so my point is still valid (*phew*)</p>
<p><strong><em>* Note: This is a joke.. I got some abuse on Twitter for “VB bashing” recently, hopefully this will appease the VB heads! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></em></strong></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grumpydev.com/2010/04/19/optional-parameters-in-c4-c3-and-vb-net-with-a-side-order-of-il-quirks/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Locating Network Services on the iPhone/iPad with MonoTouch</title>
		<link>https://www.grumpydev.com/2010/03/27/locating-network-services-on-the-iphoneipad-with-monotouch/</link>
					<comments>https://www.grumpydev.com/2010/03/27/locating-network-services-on-the-iphoneipad-with-monotouch/#comments</comments>
		
		<dc:creator><![CDATA[Steven Robbins]]></dc:creator>
		<pubDate>Sat, 27 Mar 2010 12:14:18 +0000</pubDate>
				<category><![CDATA[iPhone]]></category>
		<category><![CDATA[MonoTouch]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[service location]]></category>
		<category><![CDATA[sockets]]></category>
		<category><![CDATA[udp]]></category>
		<guid isPermaLink="false">http://www.grumpydev.com/?p=322</guid>

					<description><![CDATA[Introduction For one of the little iPhone projects I’m working I need to communicate with with a server on the local network. That all sounds very simple, but what I *really* want to be able to do is detect all instances of this service on the local network, and give the user the option of [&#8230;]]]></description>
										<content:encoded><![CDATA[<h2>Introduction</h2>
<p>For one of the little iPhone projects I’m working I need to communicate with with a server on the local network. That all sounds very simple, but what I *really* want to be able to do is detect all instances of this service on the local network, and give the user the option of which one to connect to at runtime.</p>
<p>In WCF land we could leverage <a href="http://msdn.microsoft.com/en-us/library/dd456782(VS.100).aspx" target="_blank">WCF Discovery</a>, but in the world of MonoTouch, and even in .NET 3.5, we don’t have that luxury, so it’s time to roll our own service discovery!</p>
<h2>Ping! Pong!</h2>
<p>To build our service discovery system we will be dropping down to the socket level; but don’t worry! We’re only using sockets to discover the services – after that you are free to use your normal HttpClient to actually access them <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>The basic idea is our client will send out a “ping” containing the IP and port to respond back on. Each server that picks up the ping will send a response back containing some metadata (in this instance a “service name” and a “service endpoint address”). The two classes we will use as “payload” are as follows:</p>
<pre class="brush: csharp; toolbar: false;">[Serializable]
/// &lt;summary&gt;
/// Our initial ping &quot;payload&quot; 
/// &lt;/summary&gt;
public class ServiceClientInfo
{
    /// &lt;summary&gt;
    /// IP address of the client that sent the ping 
    /// &lt;/summary&gt;
    public string IPAddress { get; private set; }
    
    /// &lt;summary&gt;
    /// UDP port to send a response to 
    /// &lt;/summary&gt;
    public int Port { get; private set; }

    public ServiceClientInfo(string iPAddress, int port)
    {
        IPAddress = iPAddress;
        Port = port;
    }
}

[Serializable]
/// &lt;summary&gt;
/// Server response &quot;payload&quot; - could be anything
/// &lt;/summary&gt;
public class ServiceInfo
{
    /// &lt;summary&gt;
    /// Standard port servers listen on 
    /// &lt;/summary&gt;
    public static readonly int UDPPort = 3512;

    /// &lt;summary&gt;
    /// Name of the service 
    /// &lt;/summary&gt;
    public string ServiceName { get; private set; }
    
    /// &lt;summary&gt;
    /// Endpoint address 
    /// &lt;/summary&gt;
    public string EndpointAddress { get; private set; }

    public ServiceInfo(string serviceName, string endpointAddress)
    {
        ServiceName = serviceName;
        EndpointAddress = endpointAddress;
    }
}</pre>
<p>For our test app we will have a simple UITableView to display server responses, and a single button for sending our out ping. It looks a little something like this:</p>
<p><a href="https://www.grumpydev.com/wp-content/uploads/2010/03/iPhoneServiceLocatorSS.png"><img loading="lazy" decoding="async" style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="iPhoneServiceLocatorSS" border="0" alt="iPhoneServiceLocatorSS" src="https://www.grumpydev.com/wp-content/uploads/2010/03/iPhoneServiceLocatorSS_thumb.png" width="190" height="362" /></a> </p>
<p>We will also verify that we have a working WiFi connection before we do anything. We do this using <a href="http://github.com/migueldeicaza/monotouch-samples/blob/master/reachability/reachability.cs" target="_blank">Miguel’s MonoTouch “reachability” sample code</a>. </p>
<h2>Step 1 – Firing the Ping from the iPhone</h2>
<p>First things first, we need to fire off the initial ping from our phone by sending a <a href="http://en.wikipedia.org/wiki/User_Datagram_Protocol" target="_blank">UDP</a> <a href="http://en.wikipedia.org/wiki/Broadcasting_(networks)" target="_blank">broadcast</a> containing our “payload”. UDP is ideal for our application as it gives us a lightweight, connectionless transmission model which allows us to send a single message to every machine on the network using a broadcast. UDP is considered an “unreliable” protocol (i.e. it has no guarantees of delivery), but for our purposes that isn’t a problem. For more information on TCP/UDP and broadcasting you can take a look at the wikipedia pages: <a href="http://en.wikipedia.org/wiki/Transmission_Control_Protocol" target="_blank">TCP</a>, <a href="http://en.wikipedia.org/wiki/User_Datagram_Protocol" target="_blank">UDP</a>, <a href="http://en.wikipedia.org/wiki/Broadcasting_(networks)" target="_blank">Broadcasting</a>.</p>
<p>From a .NET code point of view this is pretty straightforward. We create an IPv4 UDP <a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.aspx" target="_blank">Socket</a>, a UDP broadcast <a href="http://msdn.microsoft.com/en-us/library/system.net.ipendpoint.aspx" target="_blank">IPEndPoint</a>, set some options and then use our Socket to send a serialised version of our “payload” to the network. </p>
<p>In this instance we are using the <a href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatters.binary.binaryformatter.aspx" target="_blank">BinaryFormatter</a> to serialise our payload (using a generic helper class in Helpers.cs), but you could serialise using any mechanism you like. </p>
<p>The code for this is as follows:</p>
<pre class="brush: csharp; toolbar: false;">/// &lt;summary&gt;
/// Send our our server ping
/// &lt;/summary&gt;
private void SendServerPing ()
{
    // Create a socket udp ipv4 socket
    using (Socket sock = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) {
        // Create our endpoint using the IP broadcast address and our port
        IPEndPoint endPoint = new IPEndPoint (IPAddress.Broadcast, Discovery.Core.ServiceInfo.UDPPort);
        
        // Serialize our ping &quot;payload&quot;
        byte[] data = Discovery.Core.Helpers.SerializeObject&lt;ServiceClientInfo&gt; (new ServiceClientInfo (GetCurrentIPAddress ().ToString (), 8762));
        
        // Tell our socket to reuse the address so we can send and
        // receive on the same port.
        sock.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        
        // Tell the socket we want to broadcast - if we don't do this it
        // won't let us send.
        sock.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
        
        // Send the ping and close the socket.
        sock.SendTo (data, endPoint);
        sock.Close ();
    }
}</pre>
<h2>Step 2 – Listening for Responses</h2>
<p>Next up we need to listen for server responses. We actually start listening *before* we send the ping (to make sure we don’t miss anything), but it makes more sense to think of it as a second step. </p>
<p>There are two ways to listen to responses: synchronously, where we sit there and wait for a response to come back, or asynchronously, where we provide a callback method that will respond to data as it comes in. We obviously don’t want our UI to stop responding while we’re waiting, and we certainly don’t want the iPhone to kill our application for being unresponsive, so we will opt for the asynchronous model.</p>
<p>The steps for setting up a listener are, again, very simple. We first create an <a href="http://msdn.microsoft.com/en-us/library/system.net.ipendpoint.aspx" target="_blank">IPEndpoint</a>, this time using the IP address and port we included in our initial ping, and create a <a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.udpclient.aspx" target="_blank">UDPClient</a> bound to it. Finally we call <a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.udpclient.beginreceive.aspx" target="_blank">BeginReceive</a> to tell the client we want to receive data asynchronously, providing our callback method, and start a timer to stop listening after 2 seconds. We pass in a simple “state” object to our callback, so it has access to our endpoint and client, but you could also store those as fields if you prefer.</p>
<p>While we are listening for responses we also disable our Ping button and re-enable it again, making sure to do so on the UI thread, once the timer has elapsed:</p>
<pre class="brush: csharp; toolbar: false;">private void StartListeningForServerPingBacks ()
{
    // Disable our ping button
    PingButton.Enabled = false;
    
    // Listen on our IP addresses on our port
    // In a real scenario you'd probably want to make sure the port
    // was available and fallback to an alternative if not.
    var endPoint = new IPEndPoint (GetCurrentIPAddress(), 8762);
    
    // Make sure we don't grab exclusive &quot;rights&quot; to our address
    // so we can use the same port for send and receive.
    var udpClient = new UdpClient ();
    udpClient.Client.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
    udpClient.ExclusiveAddressUse = false;
    udpClient.Client.Bind (endPoint);
    
    // Setup our &quot;state&quot; object so the callback has access to the client and endpoint
    UdpState state = new UdpState (endPoint, udpClient);
    
    // Setup our async receive
    // Our callback will be called if and when data comes in
    udpClient.BeginReceive (new AsyncCallback (this.ReceiveServerPingCallback), state);
    
    // Setup a timeout timer.
    // When the timer elapses we enable our ping button again and
    // close our udpclient.
    var enableTimer = new Timer (2000);
    enableTimer.AutoReset = false;
    enableTimer.Elapsed += delegate(object sender, ElapsedEventArgs e) {
        InvokeOnMainThread (delegate { PingButton.Enabled = true; });
        udpClient.Close ();
    };
    enableTimer.Enabled = true;
}</pre>
<h2>Step 3 – The Callback</h2>
<p>Our callback method is rather simple (are you seeing a trend? :-)). We first grab the state object, call <a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.udpclient.endreceive.aspx" target="_blank">EndReceive</a> to grab the data, deserialise it to our ServiceInfo object, add it to the UITableView, and then call <a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.udpclient.beginreceive.aspx" target="_blank">BeginReceive</a> again. That last part is the most important &#8211; every call to BeginReceive, which starts an asynchronous receive, must match a call to EndReceive, which ends the asynchronous receive. If we didn’t call BeginReceive at the end of our callback we would only ever get one server response – which obviously isn’t what we want!</p>
<p>As our timer may close the connection, and because we may get bad data sent to our listening port, we wrap the whole callback in a try/catch to make sure we don’t crash the app:</p>
<pre class="brush: csharp; toolbar: false;">/// &lt;summary&gt;
/// Our callback that receives the pings back from the server(s)
/// &lt;/summary&gt;
private void ReceiveServerPingCallback (IAsyncResult ar)
{
    try {
        // Grab the state object and split it up
        UdpState state = (UdpState)(ar.AsyncState);
        UdpClient client = state.client;
        IPEndPoint endPoint = state.endPoint;
        
        // Grab all the data we received
        Byte[] receiveBytes = client.EndReceive (ar, ref endPoint);
        
        // Deserialize it to our ServiceInfo object
        var data = Discovery.Core.Helpers.DeserializeObject&lt;ServiceInfo&gt; (receiveBytes);
        
        // Using the UI thread, update the server list
        InvokeOnMainThread (delegate { AddItemToList (String.Format (&quot;Name: {0} Endpoint: {1}&quot;, data.ServiceName, data.EndpointAddress)); });
        
        // Start listening again
        client.BeginReceive (new AsyncCallback (this.ReceiveServerPingCallback), state);
    } catch (Exception) {
        // Just in case we have any network issues, or we've closed the socket, we catch everything.
        // Rather a horrible catch all than an app crash in this instance.
    }
}</pre>
<h2>The Code</h2>
<p>And that’s that. The full application source is available below. The solution contains the iPhone app, a WinForms “server” that you can run multiple times on your Mac/PC, and a shared library with the common data types in.</p>
<p>I’ve successfully tested this code with 10 servers, spread across multiple machines, without any issues but if your app needs responses from a large amount of servers then your mileage may vary <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p><a href="/wp-content/uploads/2010/03/ServiceLocation.zip">ServiceLocation.zip</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grumpydev.com/2010/03/27/locating-network-services-on-the-iphoneipad-with-monotouch/feed/</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>Announcing: TinyMessenger</title>
		<link>https://www.grumpydev.com/2010/03/22/announcing-tinymessenger/</link>
					<comments>https://www.grumpydev.com/2010/03/22/announcing-tinymessenger/#comments</comments>
		
		<dc:creator><![CDATA[Steven Robbins]]></dc:creator>
		<pubDate>Mon, 22 Mar 2010 08:35:29 +0000</pubDate>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[TinyIoC]]></category>
		<category><![CDATA[TinyMessenger]]></category>
		<category><![CDATA[csharp]]></category>
		<category><![CDATA[event aggregator]]></category>
		<guid isPermaLink="false">http://www.grumpydev.com/?p=315</guid>

					<description><![CDATA[Introduction Just a small post to announce I have added, and finally documented, TinyMessenger to the TinyIoC project. Tiny What-Now? TinyMessenger provides an event aggregator/messenger for loosely coupled communication. Some scenarios where this may prove useful : Communication between Controllers/ViewModels. Service classes raising “events”. Removing responsibilities from classes that receive external events (such as the [&#8230;]]]></description>
										<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Just a small post to announce I have added, and finally documented, TinyMessenger to the TinyIoC project.</p>
<h2>Tiny What-Now?</h2>
<p>TinyMessenger provides an event aggregator/messenger for loosely coupled communication. Some scenarios where this may prove useful :</p>
<ul>
<li>Communication between Controllers/ViewModels. </li>
<li>Service classes raising “events”. </li>
<li>Removing responsibilities from classes that receive external events (such as the AppDelegate in an iPhone application). </li>
<li>Decoupling communication between classes. </li>
</ul>
<p>TinyMessenger uses a Publish/Subscribe model and is orderless, so you can subscribe to a message even if there&#8217;s nobody publishing, and you can publish one even if nobody is subscribed. It is also loosely coupled in that the publisher and subscriber know nothing of each other, all they both care about is the message itself. Some of the key features are:</p>
<ul>
<li>Simple and orderless Publish/Subscribe API. </li>
<li>Messages either need to implement a simple “marker” interface, or they can build on the “base” classes that are in the box (TinyMessageBase and GenericTinyMessage&lt;TContent&gt;. </li>
<li>Subscriptions can supply an optional filter – only message that “pass” the filter are delivered. </li>
<li>Subscriptions can supply an optional “proxy”. A proxy can be used for marshalling to the ui thread, logging or many other purposes. </li>
<li>Subscriptions use weak references by default, but strong references can be specified if required. </li>
</ul>
<p><a href="http://hg.grumpydev.com/tinyioc/wiki/TinyMessenger" target="_blank">TinyMessenger</a> is part of the <a href="http://hg.grumpydev.com/tinyioc" target="_blank">TinyIoC</a> project, but it can be used completely independently – for more information take a look at the <a href="http://hg.grumpydev.com/tinyioc/wiki/TinyMessenger" target="_blank">TinyMessenger Wiki page</a> on the main <a href="http://hg.grumpydev.com/tinyioc" target="_blank">TinyIoC site</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grumpydev.com/2010/03/22/announcing-tinymessenger/feed/</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>Why is Add Reference Still Horribly Broken in VS2010?</title>
		<link>https://www.grumpydev.com/2010/03/19/why-is-add-reference-still-horribly-broken-in-vs2010/</link>
					<comments>https://www.grumpydev.com/2010/03/19/why-is-add-reference-still-horribly-broken-in-vs2010/#comments</comments>
		
		<dc:creator><![CDATA[Steven Robbins]]></dc:creator>
		<pubDate>Fri, 19 Mar 2010 13:49:10 +0000</pubDate>
				<category><![CDATA[Rambling]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[add reference dialog]]></category>
		<category><![CDATA[rant]]></category>
		<category><![CDATA[vs2010]]></category>
		<guid isPermaLink="false">http://www.grumpydev.com/?p=306</guid>

					<description><![CDATA[Introduction We all know Add Reference is horribly broken in VS2008. We’ve all clicked it and had our hearts sink as we realised it was time to make a brew, grab lunch or take a weekend mini-break before even attempting to use Visual Studio again. Now VS2010 is in Release Candidate it’s obviously been fixed.. [&#8230;]]]></description>
										<content:encoded><![CDATA[<h2>Introduction</h2>
<p>We all know Add Reference is horribly broken in VS2008. We’ve all clicked it and had our hearts sink as we realised it was time to make a brew, grab lunch or take a weekend mini-break before even attempting to use Visual Studio again. Now VS2010 is in <a href="http://msdn.microsoft.com/en-us/vstudio/dd582936.aspx" target="_blank">Release Candidate</a> it’s obviously been fixed.. hasn’t it?!</p>
<h2>Not All Change Is For the Better</h2>
<p>The main issue with the VS2008 Add Reference dialog was that it took an age to load, mostly due to it enumerating all of the assemblies available to populate the .NET tab. If all  you wanted to do was add a project or file reference you still had to wait for it to finish building the .NET tab. Not good. In an attempt to fix the problem Microsoft has made two major changes to the dialog for VS2010:</p>
<ul>
<li>The dialog now defaults to the Projects tab.</li>
<li>The .NET tab is now multi-threaded i.e. it loads types in the background.</li>
</ul>
<p>The first of the two fixes is an excellent idea. If you want to use the Projects, Browse or Recent tabs then you don’t even need to look at that snail-paced .NET tab.</p>
<p>The second of the two fixes is horrible. Truly horrible. I’d even go as far as to say that if you actually want to use the .NET tab to add a reference then it’s actually <strong>*more broken than Visual Studio 2008*</strong>. Yes, I did say that. And I&#8217;ll say it again:</p>
<blockquote><p>“If you actually want to use the .NET tab to add a reference then it’s actually <strong>more broken than Visual Studio 2008</strong>.”</p></blockquote>
<p>To illustrate the point, lets say we want to add MEF, which sits in System.ComponentModel.Composition to our application, we’d probably do something similar to the following:</p>
<ol>
<li>Click Add Reference.</li>
<li>Marvel at how quickly Add Reference Loaded.</li>
<li>Click the .NET tab.</li>
<li>Watch the first few items start to load up.</li>
<li>Type “Sys” to jump down to System in the list.</li>
<li>Go to select System.ComponentModel.Compo..oh no.. it’s moved.</li>
<li>Scroll down, go to select Sys.. nope.. it’s moved again.</li>
<li>Scroll down a bit more, click on.. nope, gone again.</li>
<li>Swear.</li>
<li>Wait until the thing has fully finished loading and then select what we want.</li>
</ol>
<p>So what we have there is the same delay as it would have taken with VS2008, but with the added “fun” of playing a game of “chase the reference down the listbox” in a vain attempt to save yourself a few seconds.</p>
<h2>Could It Be Done Better?</h2>
<p>Now I’m no User Experience expert, or an Interface Designer with a fancy job title, but couldn’t this be improved immeasurably with a simple filter box?</p>
<p>Perhaps I work in a strange way, but I never start searching for a reference using the mouse &#8211; I *always* type the first few letters to skip to roughly where I want to go. If we had a simple filter box at the top of the dialog then the “chase the reference” game would be massively reduced, and probably eliminated all together if you’d typed in enough of the namespace name:</p>
<p><a href="https://www.grumpydev.com/wp-content/uploads/2010/03/AddReference.png"><img loading="lazy" decoding="async" style="display: inline; border-width: 0px;" title="AddReference" src="https://www.grumpydev.com/wp-content/uploads/2010/03/AddReference_thumb.png" border="0" alt="AddReference" width="473" height="353" /></a></p>
<p>Now we could get super fancy and support CamelCaseSearching like the <a href="http://www.devexpress.com/Products/Visual_Studio_Add-in/Coding_Assistance/Navigation.xml" target="_blank">QuickNav</a> dialog in <a href="http://www.devexpress.com/Coderush" target="_blank">CodeRush</a>, but I’d be quite happy with a basic filter.</p>
<p>Maybe I’m just picky.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grumpydev.com/2010/03/19/why-is-add-reference-still-horribly-broken-in-vs2010/feed/</wfw:commentRss>
			<slash:comments>10</slash:comments>
		
		
			</item>
		<item>
		<title>Automated &#8220;Unit&#8221; Testing &#8211; It&#8217;s Not Just for TDD, It&#8217;s for Bug Fixing Too!</title>
		<link>https://www.grumpydev.com/2010/03/09/automated-unit-testing-its-not-just-for-tdd-its-for-bug-fixing-too/</link>
					<comments>https://www.grumpydev.com/2010/03/09/automated-unit-testing-its-not-just-for-tdd-its-for-bug-fixing-too/#comments</comments>
		
		<dc:creator><![CDATA[Steven Robbins]]></dc:creator>
		<pubDate>Tue, 09 Mar 2010 13:00:32 +0000</pubDate>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[MonoTouch]]></category>
		<category><![CDATA[Rambling]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[TinyIoC]]></category>
		<category><![CDATA[csharp]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[unit testing]]></category>
		<guid isPermaLink="false">http://www.grumpydev.com/?p=293</guid>

					<description><![CDATA[Disclaimer – What I’m discussing here isn’t unit testing (hence the quotes), it’s more functional or integration testing; but as the term “Unit Testing” is often “abused” to mean “anything that uses a (unit) testing framework” so I’ve included it in the title to avoid confusion. Introduction I’m currently using TinyIoC in my first forays [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><strong><em>Disclaimer – What I’m discussing here isn’t unit testing (hence the quotes), it’s more functional or integration testing; but as the term “Unit Testing” is often “abused” to mean “anything that uses a (unit) testing framework” so I’ve included it in the title to avoid confusion.</em></strong></p>
<h2>Introduction</h2>
<p>I’m currently using <a href="http://hg.grumpydev.com/tinyioc" target="_blank">TinyIoC</a> in my first forays into <a href="http://monotouch.net/" target="_blank">MonoTouch</a> development, and my initialisation code was throwing a resolution error on starup:</p>
<pre class="brush: csharp; toolbar: false;">var container = TinyIoCContainer.Current();
var mainView = new MainView();
container.Register&lt;IViewManager&gt;(mainView);
container.Register&lt;IView, MainView&gt;(mainView, "MainView");
container.Register&lt;IView, SplashView&gt;("SplashView").UsingConstructor(() =&gt; new SplashView());
container.Resolve&lt;IView&gt;("MainView");
container.Register&lt;IStateManager, StateManager&gt;();
// Code was blowing up here..
var stateManager = container.Resolve&lt;IStateManager&gt;();
stateManager.Init();</pre>
<p>The Exception that was given was that IStateManager could not be resolved, which was odd given that the StateManager was registered against IStateManager, and everything in its constructor was also registered:</p>
<pre class="brush: csharp; toolbar: false;">public StateManager(IViewManager viewManager, Func&lt;string, IView&gt; viewFactory)</pre>
<h2>To The Debugger.. Right?!</h2>
<p>So at this point your immediate reaction may be to fire up the debugger, trace into the code and start hacking around, debugging and hacking around some more until it works. Sure, that’s an approach, and one I’m sure we’ve all used in the past; but as I was pretty sure the issue was in TinyIoC itself I took a slightly different tack.</p>
<h2>To The Test Runner!</h2>
<p>With the approach above I would have to build and run my app every time I wanted to check if my “fix” had actually worked – and even if it had, how would I know it hadn’t broken something else? The solution is quite simple – recreate the conditions of the bug in a unit test, using stubs/mocks to replace your real classes, and make sure it fails in the same way:</p>
<pre class="brush: csharp; toolbar: false;">[TestMethod]
public void Dependency_Hierarchy_With_Named_Factories_Resolves_All_Correctly()
{
    var container = UtilityMethods.GetContainer();
    var mainView = new MainView();
    container.Register&lt;IViewManager&gt;(mainView);
    container.Register&lt;IView, MainView&gt;(mainView, "MainView");
    container.Register&lt;IView, SplashView&gt;("SplashView").UsingConstructor(() =&gt; new SplashView());
    container.Resolve&lt;IView&gt;("MainView");
    container.Register&lt;IStateManager, StateManager&gt;();
    var stateManager = container.Resolve&lt;IStateManager&gt;();
    stateManager.Init();

    Assert.IsInstanceOfType(mainView.LoadedView, typeof(SplashView));
}</pre>
<p>I&#8217;ve added an Assert to show what behaviour I think it *should* have. It’s a pretty horrible looking test, but it accurately represents what my failing code was doing, and the test fails as I expected it to. Now I can attach the debugger and find out what’s going on, safe in the knowledge I have a fast executing test available to verify my fix, and the rest of my test suite there to ensure I haven’t broken anything else.</p>
<p>After a very brief investigation it turned out that there was a bug in registration when *just* an Interface type was registered with an concrete instance (the IViewManager registration above). The “InstanceFactory” it was using hadn’t set the “AssumeResolves” flag, so TinyIoC was actually trying to find a valid constructor for IViewManager – which obviously wasn’t going to succeed. It&#8217;s a scenario I probably should have factored into my Unit Tests, but hey, nobody is perfect <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h2>Conclusion</h2>
<p>This post is aimed at covering two points:</p>
<ol>
<li>Test aren’t just for TDD. If you find a bug, isolate it with a test and you have a quick and easy way to verify a fix, and verify you haven’t broken anything else.</li>
<li>Code Coverage isn’t everything. Apart from a few “defensive coding” null checks, the core of TinyIoC has pretty much 100% code coverage with its tests, but it didn’t help me with this issue. Although the code path was covered, the exact input (Interface type, concrete instance) wasn’t in my unit tests, so don’t assume 100% code coverage means 0 bugs in the code, there may well be a scenario you missed!</li>
</ol>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grumpydev.com/2010/03/09/automated-unit-testing-its-not-just-for-tdd-its-for-bug-fixing-too/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Announcing: TinyIoC &#8211; An Easy to Use, Hassle Free, Inversion of Control Container</title>
		<link>https://www.grumpydev.com/2010/03/02/announcing-tinyioc-an-easy-to-use-hassle-free-inversion-of-control-container/</link>
					<comments>https://www.grumpydev.com/2010/03/02/announcing-tinyioc-an-easy-to-use-hassle-free-inversion-of-control-container/#comments</comments>
		
		<dc:creator><![CDATA[Steven Robbins]]></dc:creator>
		<pubDate>Tue, 02 Mar 2010 06:56:15 +0000</pubDate>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[TinyIoC]]></category>
		<category><![CDATA[csharp]]></category>
		<category><![CDATA[dependency injection]]></category>
		<category><![CDATA[di]]></category>
		<category><![CDATA[inversion of control]]></category>
		<category><![CDATA[ioc]]></category>
		<guid isPermaLink="false">http://www.grumpydev.com/?p=288</guid>

					<description><![CDATA[Introduction Whenever I start a new “pet” project I usually *want* to use IoC, but I don’t really want the hassle of taking a dependency on a container, or adding another binary to my project. Usually this leaves me using “poor man’s IoC”, whereby I define dependencies in my constructors, but I pass them in [&#8230;]]]></description>
										<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Whenever I start a new “pet” project I usually *want* to use IoC, but I don’t really want the hassle of taking a dependency on a container, or adding another binary to my project. Usually this leaves me using “poor man’s IoC”, whereby I define dependencies in my constructors, but I pass them in manually or construct them using <a href="http://www.csharp411.com/constructor-chaining/" target="_blank">constructor chaining</a>.</p>
<p>I’ve thought for some time that it would be useful to put together a container that fits the bill for that scenario, but also attempts to “lower the barrier of entry” for developers that are new to IoC, and may be scared off by the “big boys”. A couple of weeks ago <a href="http://twitter.com/dotnetwill" target="_blank">@DotNetWill</a> posted his <a href="http://www.humblecoder.co.uk/?p=102" target="_blank">simplified container</a>, and that gave me the kick up the backside I needed to create my own <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h2>Introducing TinyIoC</h2>
<p>Now you might ask “do we really need *another* IoC container?” – and it’s a reasonable question. We already have <a href="http://www.codeplex.com/unity" target="_blank">Unity</a>, <a href="http://ninject.org/" target="_blank">Ninject</a>, <a href="http://structuremap.sourceforge.net/" target="_blank">StructureMap</a>, <a href="http://code.google.com/p/autofac/" target="_blank">AutoFac</a>.. the list goes on. <a href="http://hg.grumpydev.com/tinyioc" target="_blank">TinyIoC</a> makes no attempt to go “head to head” with any of these other containers, instead <a href="http://hg.grumpydev.com/tinyioc" target="_blank">TinyIoC</a> has been designed to fulfil a single key requirement:</p>
<blockquote><p><strong>To lower the &#8220;level of entry&#8221; for using an IoC container; both for small projects, and developers who are new to IoC.</strong></p></blockquote>
<p>To that end, <a href="http://hg.grumpydev.com/tinyioc" target="_blank">TinyIoC</a> attempts to stick the following core principals:</p>
<ul>
<li><strong>Simplified Inclusion.</strong> No assembly to reference, no binary to worry about, just a single cs file you can include in your project and you&#8217;re good to go. It also works on <a href="http://www.mono-project.com/" target="_blank">Mono</a>, and on <a href="http://monotouch.net/" target="_blank">MonoTouch</a> for the iPhone / iPad.</li>
<li><strong>Simplified Setup. </strong>With auto-resolving of concrete types and an &#8220;auto registration&#8221; option for interfaces, setup is a piece of cake. It can be reduced to 0 lines for concrete types, or 1 line if you have any interface dependencies.</li>
<li><strong>Simple, &#8220;Fluent&#8221; API. </strong>Just because it&#8217;s Tiny, doesn&#8217;t mean it has no features. A simple &#8220;fluent&#8221; API gives you access to the more advanced features, like specifying singleton/multi-instance, strong or weak references or forcing a particular constructor.</li>
</ul>
<p>The following snippet gives an example of the simplified setup:</p>
<pre class="brush: csharp; toolbar: false;">// TinyIoC provides a lazyily constructed singleton
// version of itself if you want to use it.
var container = TinyIoCContainer.Current;

// By default we can resolve concrete types without
// registration
var instance = container.Resolve&lt;MyConcreteType&gt;();

// We can automatically register all concrete types
// and interfaces with a single call.
container.AutoRegister();
var implementation = container.Resolve&lt;IMyInterface&gt;();</pre>
<h2>So Where Now?</h2>
<p>If you want to grab the source, read the tests, or take a look at some more complex examples of the API, wander on over to the <a href="http://hg.grumpydev.com/tinyioc" target="_blank">homepage</a> on <a href="http://hg.grumpydev.com/tinyioc" target="_blank">bitbucket</a>. I’m happy to take comments and suggestions – just grab me on <a href="http://twitter.com/grumpydev" target="_blank">Twitter</a> or ping me an email from the <a href="https://www.grumpydev.com/contact/" target="_blank">contact form</a>.</p>
<p>Over the next few weeks I will be posting a series of “beginners” articles on the hows and whys of IoC. I will be using <a href="http://hg.grumpydev.com/tinyioc" target="_blank">TinyIoC</a> specifically, but the majority of concepts and content can equally apply to other containers. I may even do a “File, New” screencast to show how “un-scary” this stuff is, and how it doesn’t really add any extra development effort,</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grumpydev.com/2010/03/02/announcing-tinyioc-an-easy-to-use-hassle-free-inversion-of-control-container/feed/</wfw:commentRss>
			<slash:comments>27</slash:comments>
		
		
			</item>
		<item>
		<title>Moving a Repository from SVN to Mercurial With Full History</title>
		<link>https://www.grumpydev.com/2010/03/01/moving-a-repository-from-svn-to-mercurial-with-full-history/</link>
					<comments>https://www.grumpydev.com/2010/03/01/moving-a-repository-from-svn-to-mercurial-with-full-history/#comments</comments>
		
		<dc:creator><![CDATA[Steven Robbins]]></dc:creator>
		<pubDate>Mon, 01 Mar 2010 13:58:30 +0000</pubDate>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Mercurial]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[convert]]></category>
		<category><![CDATA[hg]]></category>
		<category><![CDATA[history]]></category>
		<category><![CDATA[subversion]]></category>
		<category><![CDATA[svn]]></category>
		<guid isPermaLink="false">http://www.grumpydev.com/?p=284</guid>

					<description><![CDATA[Disclaimer Let me start with a disclaimer. I’ve only been using Mercurial for 2 days so my nomenclature may be completely wide of the mark. Hopefully this post will help other hgnewbies with what is probably a common requirement. Introduction I keep all of my pet projects in my own Subversion repository but I’ve recently [&#8230;]]]></description>
										<content:encoded><![CDATA[<h2>Disclaimer</h2>
<p>Let me start with a disclaimer. I’ve only been using Mercurial for 2 days so my nomenclature may be completely wide of the mark. Hopefully this post will help other hgnewbies with what is probably a common requirement.</p>
<h2>Introduction</h2>
<p>I keep all of my pet projects in my own Subversion repository but I’ve recently decided to give this distributed version control shenanigans a whirl. I ummed and arred about Git or Mercurial, but in the end I plumped for Mercurial, with a <a href="http://bitbucket.org/" target="_blank">bitbucket</a> account, as it seems to have more ubiquitous support. I’m about to release a project I’ve been working on for the last week or so and thought it would be nice to release it via bitbucket – complete with the version history I’d build up in Subversion.</p>
<p>Turns out, it’s really rather easy!</p>
<h2>I’m Converted!</h2>
<p>I’m assuming at this point you have the commandline version of Mercurial (hg) installed and working. If you don’t then you should probably go and do that first <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> I’ve also assumed you’ve already created a mercurial repository (bitbucket or elsewhere) called “<strong>myproject</strong>”.</p>
<p><em>In my scenario I was converting a single project with no trunk, branch or tag directories. The convert command is capable of handling much more advanced scenarios – take a look at the </em><a href="http://mercurial.selenic.com/wiki/ConvertExtension" target="_blank"><em>documentation</em></a><em> for more infomation.</em></p>
<p>First things first you need to edit your Mercurial settings (.hgrc for *nix, Mercurial.ini in your user dir for Windows) and add the following lines:</p>
<blockquote><p>[extensions]<br />
hgext.convert=</p></blockquote>
<p>This will add the “convert” command extension to our client. Next up we clone our repository and use the new convert command to add the SVN changesets into it:</p>
<blockquote><p>hg clone <a href="https://bitbucket.org/myuser/myproject">https://bitbucket.org/myuser/myproject</a></p>
<p>hg convert <a href="http://mysvn.server.com/svn/myproject/">http://mysvn.server.com/svn/myproject/</a> myproject</p></blockquote>
<p>The convert command will now start counting down the revisions and adding each one to our local hg repository. This may well take some time <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p><strong>Potential gotcha: it <a href="http://mercurial.selenic.com/bts/issue1783" target="_blank">appears</a> that the convert extension <a href="http://mercurial.selenic.com/bts/issue1783" target="_blank">doesn’t work properly with Subversion repositories over http that require authentication</a>. If you get multiple “http authorization required” messages and prompts for your username/password then you have a problem. The only solution I found was to temporarily disable authentication while I did the conversion <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f641.png" alt="🙁" class="wp-smiley" style="height: 1em; max-height: 1em;" /></strong></p>
<p>Once the conversion had finished we push our changes back:</p>
<blockquote><p>cd myproject</p>
<p>hg push</p></blockquote>
<p>Now at this point for me the push worked fine but my local repository had no files in it – despite insisting it was up to date. This may be my lack of knowledge on Mercurial, or it might be a bug, but deleting the myproject directory locally and cloning the remote repo again sorted things out.</p>
<h2>Conclusion</h2>
<p>All in all a pretty trivial task, albeit one that takes a while with a large repository. The only big issue is the authentication one I mention above – this may well be a showstopper for you if you can’t control the ACL on your Subversion repository.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grumpydev.com/2010/03/01/moving-a-repository-from-svn-to-mercurial-with-full-history/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
			</item>
		<item>
		<title>So What Is This &#8220;Thread Safe&#8221; Thing Anyway?</title>
		<link>https://www.grumpydev.com/2010/02/26/so-what-is-this-thread-safe-thing-anyway/</link>
					<comments>https://www.grumpydev.com/2010/02/26/so-what-is-this-thread-safe-thing-anyway/#comments</comments>
		
		<dc:creator><![CDATA[Steven Robbins]]></dc:creator>
		<pubDate>Fri, 26 Feb 2010 10:10:18 +0000</pubDate>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[concurrentdictionary]]></category>
		<category><![CDATA[csharp]]></category>
		<category><![CDATA[dictionary]]></category>
		<category><![CDATA[locks]]></category>
		<guid isPermaLink="false">http://www.grumpydev.com/?p=273</guid>

					<description><![CDATA[Introduction Following on from my previous post about a “Thread Safe” Dictionary, and the subsequent comment from Rajeesh, made me think that perhaps a general post on “thread safety” was in order. Stop With the Quotes Already! The astute amongst you may notice I always try and put the phrase “thread safe” in quotes; and [&#8230;]]]></description>
										<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Following on from my previous post about a <a href="https://www.grumpydev.com/?p=264" target="_blank">“Thread Safe” Dictionary</a>, and the subsequent comment from Rajeesh, made me think that perhaps a general post on “thread safety” was in order.</p>
<h2>Stop With the Quotes Already!</h2>
<p>The astute amongst you may notice I always try and put the phrase “thread safe” in quotes; and there is a good reason for that! “Thread safe” is a pretty horrible term (although I can&#8217;t think of a better one) that doesn’t really give enough detail for what exactly we mean when we express that a class is “thread safe”. As far as I’m concerned, my “library” classes are thread safe if:</p>
<blockquote><p>“All public static and instance methods and properties on the class are safe to be called concurrently from multiple threads.”</p></blockquote>
<p>What this certainly does <strong>*not*</strong> mean is:</p>
<blockquote><p>“You do not have to consider thread safety or concurrency issues in your own code that uses this class.”</p></blockquote>
<p>So in the instance of our dictionary if you get/set a value and then in subsequent lines of code you <strong>*assume that the value you got or set hasn’t changed*</strong> then you have a concurrency issue in <strong>*your*</strong> code and you will <strong>*need to address it, likely using the same </strong><a href="http://msdn.microsoft.com/en-us/library/ms228964(VS.95).aspx" target="_blank"><strong>synchronisation primitives</strong></a><strong> we used internally in our SafeDictionary class.*</strong></p>
<h2>Some Examples</h2>
<p>As an example we can take similar code to the snippet that Rajeesh posted:</p>
<pre class="brush: csharp; toolbar: false;">// Check the item exists and process
// if it does
if (mySafeDictionary["Testing"] != null)
{
    // Process element
    ProcessElement(mySafeDictionary["Testing"]);
}</pre>
<p>Although each of those calls to the SafeDictionary are themselves threadsafe, we are making an assumption in *our code* that those value won’t change between the “if” statement and our call to ProcessElement. This particular scenario is one reason why we should always try to use TryGetValue, rather than the “if it exists do this with it” approach above. To this end we should probably alter our SafeDictionary to explicitly deny gets:</p>
<pre class="brush: csharp; toolbar: false;">public class SafeDictionary&lt;TKey, TValue&gt;
{
    private readonly object _Padlock = new object();
    private readonly Dictionary&lt;TKey, TValue&gt; _Dictionary = new Dictionary&lt;TKey, TValue&gt;();

    public TValue this[TKey key]
    {
        set
        {
            lock (_Padlock)
            {
                _Dictionary[key] = value;
            }
        }
    }

    public bool TryGetValue(TKey key, out TValue value)
    {
        lock (_Padlock)
        {
            return _Dictionary.TryGetValue(key, out value);
        }
    }
}</pre>
<p>If you now try and access a member using the array syntax, rather than through TryGetValue you will get a compile time error like:</p>
<blockquote><p>The property or indexer &#8216;Variabler.this[string]&#8217; cannot be used in this context because it lacks the get accessor.</p></blockquote>
<p>From that simple example you may think that TryGetValue solves all our problems; but unfortunately it still isn’t able to save your from yourself! To reiterate what I said earlier, you need to consider concurrency yourself if you <strong>*assume that the value you got or set hasn’t changed*</strong>. Assuming we expand our SafeDictionary to include all of the options that the normal Dictionary supports, take the following horribly contrived example:</p>
<pre class="brush: csharp; toolbar: false;">public List&lt;String&gt; GetKeysToProcess()
{
    object myObject;
    List&lt;String&gt; keysToProcess = new List&lt;String&gt;();

    // Check to see if the type is valid for
    // processing
    foreach (var currentKey in myDictionary.Keys)
    {
        if (myDictionary.TryGetValue(currentKey, out myObject))
        {
            if (myObject.GetType() == typeof(ProcessorClass))
                keysToProcess.Add(currentKey);
        }
    }

    return keysToProcess;
}</pre>
<p>Now there’s a chance that a key might have been removed between the start of the foreach and us actually using it; but as we use TryGetValue that doesn’t matter – the value just won’t resolve. The key here (pardon the pun) is that we are building and returning a list that <strong>*makes assumptions about the contents of the dictionary*</strong>. Even if in our consuming code we stick to TryGetValue to handle items being deleted, there’s nothing in this example preventing another thread changing any of the items to be a different type – effectively rendering our List of “Keys to process” completely invalid.</p>
<h2>Conclusion</h2>
<p>The examples above are very contrived, and I’d hope nobody would ever write those exact pieces of code; but hopefully it illustrates the point that <strong>*just because you are working with a “Thread safe” object doesn’t mean you can ignore thread safety concerns in your own code*.</strong></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grumpydev.com/2010/02/26/so-what-is-this-thread-safe-thing-anyway/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
			</item>
		<item>
		<title>“Thread safe” Dictionary(TKey,TValue)</title>
		<link>https://www.grumpydev.com/2010/02/25/thread-safe-dictionarytkeytvalue/</link>
					<comments>https://www.grumpydev.com/2010/02/25/thread-safe-dictionarytkeytvalue/#comments</comments>
		
		<dc:creator><![CDATA[Steven Robbins]]></dc:creator>
		<pubDate>Thu, 25 Feb 2010 18:56:58 +0000</pubDate>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[concurrentdictionary]]></category>
		<category><![CDATA[csharp]]></category>
		<category><![CDATA[dictionary]]></category>
		<category><![CDATA[locks]]></category>
		<guid isPermaLink="false">http://www.grumpydev.com/?p=264</guid>

					<description><![CDATA[Update : Based on a comment on this post I&#8217;ve added a follow up post that covers the question: What is This &#8220;Thread Safe&#8221; Thing Anyway? Introduction A pet project I’m currently working on requires the use of an internal Dictionary to store “registered” data, which is a pretty common requirement. For this particular project [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><strong>Update : Based on a comment on this post I&#8217;ve added a follow up post that covers the question: <a href="https://www.grumpydev.com/2010/02/26/so-what-is-this-thread-safe-thing-anyway/" target="_blank">What is This &#8220;Thread Safe&#8221; Thing Anyway?</a></strong></p>
<h2>Introduction</h2>
<p>A pet project I’m currently working on requires the use of an internal Dictionary to store “registered” data, which is a pretty common requirement. For this particular project I’d like to at least *attempt* to make it “thread safe” on .NET 3.5, with an eye to moving it to the <a href="http://msdn.microsoft.com/en-us/library/dd287191(VS.100).aspx" target="_blank">ConcurrentDictionary</a> in .NET 4 which promises not only thread safety, but more granular locking to increase multi-threaded performance.</p>
<p>A simple enough task, but one that I’ve seen many people make mistakes implementing.</p>
<h2>Just Locking Writes?</h2>
<p>It’s obvious we need to do some kind of <a href="http://msdn.microsoft.com/en-us/library/ms228964(VS.95).aspx" target="_blank">syncronisation primitive</a> around our writes, but first impressions might make you think that read should be ok &#8211; especially if we stick to the preferred <a href="http://msdn.microsoft.com/en-us/library/zkw5c9ak(VS.85,classic).aspx" target="_blank">TryGetValue</a> pattern instead of “if it exists then get the value”:</p>
<pre class="brush: csharp; toolbar: false;">object myValue;

// This is obviously not thread safe.
// Something else can alter the collection
// between ContainsKey and reading the
// value.
if (dictionary.ContainsKey("Testing"))
{     myValue = dictionary["Testing"];
}

// Using TryGetValue looks safe though?
// Doesn't it?!
if (!dictionary.TryGetValue("Testing", out myValue))     throw new KeyNotFoundException();</pre>
<p>Unfortunately if we fire up <a href="http://www.red-gate.com/products/reflector/" target="_blank">Reflector</a>, and take a look at how TryGetValue is implemented, it’s pretty obvious it has exactly the same concurrency problem as the first method above:</p>
<pre class="brush: csharp; toolbar: false;">public bool TryGetValue(TKey key, out TValue value)
{
    int index = this.FindEntry(key);
    if (index &gt;= 0)
    {
        value = this.entries[index].value;
        return true;
    }
    value = default(TValue);
    return false;
}</pre>
<h2>Ok, So I Will Lock Reads and Writes?</h2>
<p>The next obvious approach would be to find everywhere in our code where we access the Dictionary, for either reading or writing, and use a <a href="http://msdn.microsoft.com/en-us/library/ms228964(VS.95).aspx" target="_blank">syncronisation primitive</a>, such as <a href="http://msdn.microsoft.com/en-us/library/c5kehkcz(VS.71).aspx" target="_blank">lock</a>, to ensure we’re only accessing it from a single thread at any one time:</p>
<pre class="brush: csharp; toolbar: false;">private readonly object padlock = new object();
private readonly Dictionary&lt;string, object&gt; dictionary = new Dictionary&lt;string, object&gt;();

private void Test()
{
    object myValue;

    // Now we lock before we do anything
    lock (padlock)
    {
        if (dictionary.ContainsKey("Testing"))
        {
            myValue = dictionary["Testing"];
        }
    }

    lock (padlock)
    {
        if (!dictionary.TryGetValue("Testing", out myValue))
            throw new KeyNotFoundException();
    }
}</pre>
<p>Simple enough, but you’re relying on locking around every access, which is not only ugly, but also potentially prone to errors if you miss one. Also, once we move our code to .NET 4, and the new ConcurrentDictionary, we will have to go through the code and remove each lock in turn – pretty laborious!</p>
<h2>Composition, Composition, Composition!</h2>
<p>In this approach we wrap our nasty non-thread safe dictionary in our own class, expose the methods we want to use, and take any locks accordingly. This class only implements “array” access and TryGetValue, but is sufficient to show the approach:</p>
<pre class="brush: csharp; toolbar: false;">public class SafeDictionary&lt;TKey, TValue&gt;
{
    private readonly object _Padlock = new object();
    private readonly Dictionary&lt;TKey, TValue&gt; _Dictionary = new Dictionary&lt;TKey, TValue&gt;();

    public TValue this[TKey key]
    {
        get
        {
            lock (_Padlock)
            {
                return _Dictionary[key];
            }
        }
        set
        {
            lock (_Padlock)
            {
                _Dictionary[key] = value;
            }
        }
    }

    public bool TryGetValue(TKey key, out TValue value)
    {
        lock (_Padlock)
        {
            return _Dictionary.TryGetValue(key, out value);
        }
    }
}</pre>
<p>As we prevent any direct access to the Dictionary, and use our lock internally whenever we need to access it, we can now use our SafeDictionary in code without worrying about concurrency issues – both for reading and for writing!</p>
<h2>To .Net 4 ?</h2>
<p>As I mentioned earlier .Net 4 will be shipping with several “thread safe” collections, including a dictionary, in the new <a href="http://msdn.microsoft.com/en-us/library/system.collections.concurrent(VS.100).aspx" target="_blank">System.Collections.Concurrent namespace</a>. As we have our own SafeDictionary implementation we have a few options here:</p>
<ul>
<li>We could go through our code and replace all references to SafeDictionary with ConcurrentDictionary. We don’t have any locks in our main code so we could do this with a direct replacement.</li>
<li>We could alter our SafeDictionary to use a ConcurrentDictionary internally, and remove all of our internal locks.</li>
<li>If we don’t mind exposing extra methods we can remove all of the implementation from SafeDictionary and just derive it from ConcurrentDictionary:</li>
</ul>
<pre class="brush: csharp; toolbar: false;">public class SafeDictionary&lt;Tkey, TValue&gt; : ConcurrentDictionary&lt;Tkey, TValue&gt;
{
}</pre>
<h2>Conclusion</h2>
<p>Quite a long blog post for quite a simple issue, but even simple concurrency can be the source of mistakes and headaches. Once .NET 4 arrives with its <a href="http://msdn.microsoft.com/en-us/library/system.collections.concurrent(VS.100).aspx" target="_blank">concurrent collections</a>, <a href="http://www.microsoft.com/uk/msdn/nuggets/nugget/290/Intro-to-Parallel-Extensions-to-the-NET-Framework.aspx" target="_blank">parallel extensions</a> and <a href="http://www.danielmoth.com/Blog/2009/05/parallel-tasks-new-visual-studio-2010.html" target="_blank">parallel debugging options</a> hopefully at least *some* of this headache will go away.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grumpydev.com/2010/02/25/thread-safe-dictionarytkeytvalue/feed/</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>Hotwire &#8211; A Remote Control Quick Launch Utility for LogMeIn</title>
		<link>https://www.grumpydev.com/2009/12/27/hotwire-a-remote-control-quick-launch-utility-for-logmein/</link>
					<comments>https://www.grumpydev.com/2009/12/27/hotwire-a-remote-control-quick-launch-utility-for-logmein/#respond</comments>
		
		<dc:creator><![CDATA[Steven Robbins]]></dc:creator>
		<pubDate>Sun, 27 Dec 2009 08:05:20 +0000</pubDate>
				<category><![CDATA[Hotwire]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[googlecode]]></category>
		<category><![CDATA[logmein]]></category>
		<guid isPermaLink="false">http://www.grumpydev.com/?p=258</guid>

					<description><![CDATA[Introduction Hotwire is a project I started some time ago but never completed. It was designed to be a “quick launch” utility for remote controlling machines using the excellent LogMeIn service. While the better half was “enjoying” the Boxing Day sales I took it upon myself to finish the project. And by finish, I obviously [&#8230;]]]></description>
										<content:encoded><![CDATA[<h1><a href="https://www.grumpydev.com/wp-content/uploads/2009/12/hotwiresmall.png"><img loading="lazy" decoding="async" style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="hotwire-small" border="0" alt="hotwire-small" src="https://www.grumpydev.com/wp-content/uploads/2009/12/hotwiresmall_thumb.png" width="240" height="72" /></a> </h1>
<h2>Introduction</h2>
<p>Hotwire is a project I started <a href="https://www.grumpydev.com/2009/03/08/wpf-bootstrapping-notifyicon-shutdownmode-and-the-mysterious-vanishing-application/" target="_blank">some time ago</a> but never completed. It was designed to be a “quick launch” utility for remote controlling machines using the excellent <a href="http://www.logmein.com/" target="_blank">LogMeIn</a> service. While the better half was “enjoying” the Boxing Day sales I took it upon myself to finish the project. And by finish, I obviously mean a complete rewrite <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h2>What does it do?</h2>
<p>I’ve used LogMeIn for quite a while now, and it’s an excellent service, but 99% of the time I just want to get straight to the desktop of the machine I’m connecting to and Hotwire is designed to let me do just that.</p>
<p>The application itself is written using WPF and consists of two parts; the launcher, which sits in the task tray, and the main application. The launcher provides machine configuration and quick launch options for connecting to remote machines. The main application is just a single window (containing a WPF <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.webbrowser.aspx" target="_blank">WebBrowser</a> control) that connects to LogMeIn and does some jiggery pokery to get you directly to your machine desktop.</p>
<h2>More Information</h2>
<p>The project is up on Google Code at <a href="http://code.google.com/p/hotwire/">http://code.google.com/p/hotwire/</a> – I normally prefer to use CodePlex, but the Hotwire name was already taken <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f641.png" alt="🙁" class="wp-smiley" style="height: 1em; max-height: 1em;" /> The Google code site contains a downloadable installer, and the source code should anyone be interested.</p>
<h2>Screenshots</h2>
<p><a href="https://www.grumpydev.com/wp-content/uploads/2009/12/Tray.png"><img loading="lazy" decoding="async" style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Tray" border="0" alt="Tray" src="https://www.grumpydev.com/wp-content/uploads/2009/12/Tray_thumb.png" width="244" height="133" /></a> </p>
<p><a href="https://www.grumpydev.com/wp-content/uploads/2009/12/Configuration.png"><img loading="lazy" decoding="async" style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Configuration" border="0" alt="Configuration" src="https://www.grumpydev.com/wp-content/uploads/2009/12/Configuration_thumb.png" width="404" height="404" /></a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grumpydev.com/2009/12/27/hotwire-a-remote-control-quick-launch-utility-for-logmein/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>WPF RichTextBox Subscript and Superscript Without Font Restrictions</title>
		<link>https://www.grumpydev.com/2009/11/05/wpf-richtextbox-subscript-and-superscript-without-font-restrictions/</link>
					<comments>https://www.grumpydev.com/2009/11/05/wpf-richtextbox-subscript-and-superscript-without-font-restrictions/#respond</comments>
		
		<dc:creator><![CDATA[Steven Robbins]]></dc:creator>
		<pubDate>Thu, 05 Nov 2009 21:30:39 +0000</pubDate>
				<category><![CDATA[WPF]]></category>
		<category><![CDATA[opentype]]></category>
		<category><![CDATA[richtextbox]]></category>
		<category><![CDATA[workaround]]></category>
		<guid isPermaLink="false">http://www.grumpydev.com/?p=248</guid>

					<description><![CDATA[Introduction One of the most bizarre limitation of the WPF RichTextBox is its hit and miss support for subscript and superscript in text. Although you can set the style quite easily using appropriate command, in order for this property to actually alter the appearance of the text the font needs to be OpenType, and come [&#8230;]]]></description>
										<content:encoded><![CDATA[<h2>Introduction</h2>
<p>One of the most bizarre limitation of the WPF <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.richtextbox.aspx" target="_blank">RichTextBox</a> is its hit and miss support for subscript and superscript in text. Although you can set the style quite easily using <a href="http://msdn.microsoft.com/en-us/library/system.windows.documents.editingcommands.togglesuperscript.aspx" target="_blank">appropriate command</a>, in order for this property to actually alter the appearance of the text the font needs to be OpenType, and <a href="http://msdn.microsoft.com/en-us/library/ms745109.aspx#variants" target="_blank">come with a Subscript/Superscript variant</a>, which the vast majority of fonts do not. Obviously in a control that’s designed for user input, restricting what fonts can be used in this way is far from ideal.</p>
<h2>An Alternative Approach</h2>
<p>Having spent some time poking around inside <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.richtextbox.aspx" target="_blank">RichTextBox</a> I would strongly recommend that you don’t. Seriously. The code may well make you physically sick. In the past I have tried to use <a href="http://msdn.microsoft.com/en-us/library/system.windows.documents.textrange.applypropertyvalue.aspx" target="_blank">TextRange.ApplyPropertyValue</a>, which takes a normal DependencyProperty, to attach my own property to a piece of text. You’d imagine this would be pretty straightforward, especially as attaching properties to other types is a fairly fundamental part of WPF, but unfortunately there’s a particularly <em>lovely</em> piece of code that checks to see if the DependencyProperty is on a predefined “allowed” list, and thows an exception if it isn’t. While this chunk of code scuppered my ideas in the past, it did provide a useful place to look for an alternative way to create Subscript and Superscript text.</p>
<p>One of the properties that we are “allowed” to apply to text is <a href="http://msdn.microsoft.com/en-us/library/system.windows.documents.inline.baselinealignment.aspx" target="_blank">Inline.BaselineAlignmentProperty</a> which takes its values from the <a href="http://msdn.microsoft.com/en-us/library/system.windows.baselinealignment.aspx" target="_blank">BaselineAlignment enumeration</a> which includes the following values:</p>
<ul>
<li><strong>Top</strong>       <br />A baseline that is aligned to the upper edge of the containing box. </li>
<li><strong>Center</strong>       <br />A baseline that is aligned to the center of the containing box. </li>
<li><strong>Bottom</strong>       <br />A baseline that is aligned at the lower edge of the containing box. </li>
<li><strong>Baseline</strong>       <br />A baseline that is aligned at the actual baseline of the containing box. </li>
<li><strong>TextTop</strong>       <br />A baseline that is aligned at the upper edge of the text baseline. </li>
<li><strong>TextBottom</strong>       <br />A baseline that is aligned at the lower edge of the text baseline. </li>
<li><strong>Subscript</strong>       <br />A baseline that is aligned at the subscript position of the containing box. </li>
<li><strong>Superscript</strong>       <br />A baseline that is aligned at the superscript position of the containing box. </li>
</ul>
<p>Subscript and Superscript look exactly like what we want, and amazingly, they actually work <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> To demonstrate the technique I’ve created two simple extension methods that toggle either Sub or Superscript on the selected text:</p>
<pre class="c#:nocontrols" name="code">/// &lt;summary&gt;
/// Toggle Superscript for the currently selected text in a RichTextBox. Does not require the font to be OpenType or have a Superscript font style.
/// 
/// Doesn't attempt to change/restore the size of the font, just moves the baseline.
/// &lt;/summary&gt;
/// &lt;param name=&quot;richTextBox&quot;&gt;RichTextBox with selected text&lt;/param&gt;
public static void ToggleSelectionSuperscript(this RichTextBox richTextBox)
{
    var currentAlignment = richTextBox.Selection.GetPropertyValue(Inline.BaselineAlignmentProperty);

    BaselineAlignment newAlignment = ((BaselineAlignment)currentAlignment == BaselineAlignment.Superscript) ? BaselineAlignment.Baseline : BaselineAlignment.Superscript;
    richTextBox.Selection.ApplyPropertyValue(Inline.BaselineAlignmentProperty, newAlignment);
}</pre>
<p>The code checks the current value of the BaselineAlignmentProperty and toggles the value as appropriate. I’ve made no attempt to adjust font size, or do anything clever, so it does look a <em>little</em> goofy, but it proves the concept. The demo application also includes the XAML content of the RichTextBox document so you can see exactly what content it’s producing:</p>
<p><a href="https://www.grumpydev.com/wp-content/uploads/2009/11/RichTextBoxSubSuperscriptScreenshot.png"><img loading="lazy" decoding="async" style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="RichTextBoxSubSuperscriptScreenshot" border="0" alt="RichTextBoxSubSuperscriptScreenshot" src="https://www.grumpydev.com/wp-content/uploads/2009/11/RichTextBoxSubSuperscriptScreenshot_thumb.png" width="244" height="173" /></a> </p>
<p>And that’s that, hope it helps someone out <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> You can grab the sample demo from the link below:</p>
<p><a href="https://www.grumpydev.com/wp-content/uploads/2009/11/RichTextBoxSubSuperscript.zip" target="_blank">RichTextBoxSubSuperscript.zip</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grumpydev.com/2009/11/05/wpf-richtextbox-subscript-and-superscript-without-font-restrictions/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Localising WPF Applications Using RESX Files and Standard Data Binding (Without a MarkupExtension)</title>
		<link>https://www.grumpydev.com/2009/09/08/localising-wpf-applications-using-resx-files-and-standard-data-binding-without-a-markupextension/</link>
					<comments>https://www.grumpydev.com/2009/09/08/localising-wpf-applications-using-resx-files-and-standard-data-binding-without-a-markupextension/#comments</comments>
		
		<dc:creator><![CDATA[Steven Robbins]]></dc:creator>
		<pubDate>Tue, 08 Sep 2009 20:04:01 +0000</pubDate>
				<category><![CDATA[WPF]]></category>
		<category><![CDATA[localisation]]></category>
		<category><![CDATA[localization]]></category>
		<category><![CDATA[resourcemanager]]></category>
		<category><![CDATA[resx]]></category>
		<guid isPermaLink="false">http://www.grumpydev.com/?p=239</guid>

					<description><![CDATA[Introduction Localisation is something everyone should really care about. Creating your applications, or websites, in a manner that can be easily localised for different languages and cultures is not only “good practice”, but it may also provide additional opportunities. Luckily the .NET framework, and WPF, has rich support for localisation, with WPF even having “baked [&#8230;]]]></description>
										<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Localisation is something everyone should really care about. Creating your applications, or websites, in a manner that can be easily localised for different languages and cultures is not only “good practice”, but it may also provide additional opportunities.</p>
<p>Luckily the .NET framework, and WPF, has rich support for localisation, with WPF even having “baked in” support for switching flow direction for <a href="http://en.wikipedia.org/wiki/Bi-directional_text" target="_blank">right to left languages</a>. On top of that <a href="http://www.west-wind.com/weblog/" target="_blank">Rick Strahl</a> and <a href="http://www.dasblonde.net/" target="_blank">Michele Leroux Bustamante</a> compiled an excellent guidance document detailing several technique for localising WPF applications. The documentation, along with sample code, can be found in the <a href="http://wpflocalization.codeplex.com/" target="_blank">WPF Localisation Guidance</a> project on CodePlex.</p>
<p>The document discusses several techniques for localising applications using RESX (resource) files, which is my preferred approach; but each of the techniques has its drawbacks:</p>
<ul>
<li><strong>Static Binding</strong>. Simple and easy, but lacks support for dynamically switching culture. </li>
<li><strong>Attached Properties</strong>. Look powerful, but lacks support for value convertors and it’s a bit inefficient. </li>
<li><strong>Markup Extension</strong>. A new instance of the helper (complete with event wireup for locale switching) is created for every control, which doesn’t sound ideal and may lead to memory leaks. </li>
</ul>
<p>All of the techniques are perfectly workable solutions, but with Binding and INotifyPropertyChanged WPF already contains a powerful mechanism for mapping and automatically updating UI elements with data; surely there’s some way we can leverage those? My goal was to attempt to find a way to localise an application with the following criteria:</p>
<ul>
<li>Use the standard Binding syntax so we can support value convertors. </li>
<li>No complicated markup extensions. </li>
<li>Provide a mechanism for code to “register” resources that can be consumed anywhere in the application, even from other PRISM modules. </li>
<li>Be able to cleanly switch locales, without restarting the application or closing/reopening screens. </li>
<li>Support the design experience with a minimum of fall back values when in design mode. </li>
</ul>
<h2>The Result – Localisation Using Binding</h2>
<p>If you just want to see the code, there’s a basic implementation, and a <a href="http://msdn.microsoft.com/en-us/library/dd458809.aspx" target="_blank">PRISM</a> demonstration, at the end of the article. Both implementations use the same basic “moving parts”:</p>
<h3></h3>
<h3>LocalisationHelper</h3>
<p>In essence this is our ViewModel. There are two key pieces of code here, first being:</p>
<pre class="c#:nocontrols" name="code">public string this[string Key]
{
    get
    {
        if (!validKey(Key))
            throw new ArgumentException(@&quot;Key is not in the valid [ManagerName].[ResourceKey] format&quot;);

        if (DesignHelpers.IsInDesignModeStatic)
            throw new Exception(&quot;Design mode is not supported&quot;);

        return _resourceManager.GetResourceString(GetManagerKey(Key), GetResourceKey(Key));
    }
}</pre>
<p>This allows us to bind elements to the LocalisationHelper and provide a “key” which will be used to lookup the correct resource manager and resource string. Our binding uses a little known syntax that looks like this (take note of the initial “.”):</p>
<pre>{Binding Path=.[MyResourceManager.MyResourceString]}</pre>
<p>To provide design support we throw an exception if we detect design mode (using code from Laurent Bugnion’s <a href="http://www.galasoft.ch/mvvm/getstarted/" target="_blank">MVVM Light Toolkit</a>) so the FallbackValue can be used instead. I’m not too keep on throwing an exception, but I couldn’t see a cleaner way to “fail” the binding.</p>
<p>The other important code hooks an event that fires when the locale changes, and fires a NotifyPropertyChangedEvent with an empty property string. This triggers a refresh for all controls that have bindings to the LocalisationHelper.</p>
<h3>ResourceManagerService</h3>
<p>The ResourceManagerService provides several functions:</p>
<ul>
<li>The ability to register <a href="http://msdn.microsoft.com/en-us/library/system.resources.resourcemanager.aspx" target="_blank">ResourceManagers</a> – these are automatically generated by Visual Studio when you create RESX files and are used to load the locale specific strings. </li>
<li>Retrieve a resource string from a given <a href="http://msdn.microsoft.com/en-us/library/system.resources.resourcemanager.aspx" target="_blank">ResourceManager</a>. </li>
<li>Get and set the current locale. A locale consists of an IETF language tag (such as en-GB) and a boolean to indicate whether the locale uses a <a href="http://en.wikipedia.org/wiki/Bi-directional_text" target="_blank">right to left flow direction</a>. </li>
<li>A event that is fired when the locale changes. This is hooked by the LocalisationHelper, for firing <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.propertychanged.aspx" target="_blank">PropertyChanged</a> events, and also by the main Window which uses the right to left flag to set the flow direction. </li>
</ul>
<h2>Give Me The Code Already!</h2>
<p>There are two samples attached. The first is a simple application that uses a static ResourceManagerService that shows the basic implementation. The second is a <a href="http://msdn.microsoft.com/en-us/library/dd458809.aspx" target="_blank">PRISM</a> based application that uses the container/service locator, EventAggregator, weak references, and several different modules to give a more “advanced” example.</p>
<p><a href="https://www.grumpydev.com/wp-content/uploads/2009/09/ResourceTest.zip" target="_blank">ResourceTest.zip</a></p>
<p><a href="https://www.grumpydev.com/wp-content/uploads/2009/09/PRISMResourceTest.zip" target="_blank">PRISMResourceTest.zip</a></p>
<h2>Conclusion</h2>
<p>I haven’t yet used this solution in anger, but it certainly seems to “tick all the boxes” from my initial requirements. Comments, suggestions, criticisms and flames are welcomed <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grumpydev.com/2009/09/08/localising-wpf-applications-using-resx-files-and-standard-data-binding-without-a-markupextension/feed/</wfw:commentRss>
			<slash:comments>12</slash:comments>
		
		
			</item>
		<item>
		<title>System.OutOfMemoryException Gotcha Using Clipboard.GetData in WPF</title>
		<link>https://www.grumpydev.com/2009/09/05/system-outofmemoryexception-gotcha-using-clipboard-getdata-in-wpf/</link>
					<comments>https://www.grumpydev.com/2009/09/05/system-outofmemoryexception-gotcha-using-clipboard-getdata-in-wpf/#comments</comments>
		
		<dc:creator><![CDATA[Steven Robbins]]></dc:creator>
		<pubDate>Sat, 05 Sep 2009 16:07:08 +0000</pubDate>
				<category><![CDATA[Rambling]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[clipboard]]></category>
		<category><![CDATA[OutOfMemoryException]]></category>
		<category><![CDATA[System.OutOfMemoryException]]></category>
		<guid isPermaLink="false">http://www.grumpydev.com/?p=229</guid>

					<description><![CDATA[Introduction Consider the following simple class for managing storage and retrieval of custom classes in the Windows Clipboard using WPF: using System; using System.Windows; namespace ClipboardTest.Services { public class ClipboardService : IClipboardService { public bool ContainsData&#60;T&#62;() where T:class { return Clipboard.ContainsData(typeof(T).ToString()); } public void SetData&#60;T&#62;(T data) where T:class { Clipboard.SetData(typeof(T).ToString(), data); } public T GetData&#60;T&#62;() [&#8230;]]]></description>
										<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Consider the following simple class for managing storage and retrieval of custom classes in the Windows Clipboard using WPF:</p>
<pre class="c#:nocontrols" name="code">using System;
using System.Windows;

namespace ClipboardTest.Services
{
    public class ClipboardService : IClipboardService
    {
        public bool ContainsData&lt;T&gt;() where T:class
        {
            return Clipboard.ContainsData(typeof(T).ToString());
        }

        public void SetData&lt;T&gt;(T data) where T:class
        {
            Clipboard.SetData(typeof(T).ToString(), data);
        }

        public T GetData&lt;T&gt;() where T : class
        {
            return Clipboard.GetData(typeof(T).ToString()) as T;
        }
    }
}</pre>
<p>Simple stuff, but it lets me abstract the clipboard away and remove the usual “magic string” approach for clipboard types.</p>
<p>Now consider the following basic tests:</p>
<pre class="c#:nocontrols" name="code">using ClipboardTest.Services;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ClipboardTest.Test.Services
{
    public class TestPayload
    {
        public string Data { get; set; }
    }

    [TestClass]
    public class ClipboardServiceTests
    {
        [TestMethod]
        public void SetData_CustomClass_ClipboardContainsInstanceOfClass()
        {
            string data = @&quot;More Cowbell&quot;;
            var clipboardService = new ClipboardService();

            clipboardService.SetData&lt;TestPayload&gt;(new TestPayload() { Data = data });

            Assert.IsTrue(clipboardService.ContainsData&lt;TestPayload&gt;());
        }

        [TestMethod]
        public void SetDataGetData_CustomClass_ReturnsEquivilantClass()
        {
            string data = @&quot;More Cowbell&quot;;
            var clipboardService = new ClipboardService();

            clipboardService.SetData&lt;TestPayload&gt;(new TestPayload() { Data = data });
            var output = clipboardService.GetData&lt;TestPayload&gt;();

            Assert.IsNotNull(output);
            Assert.AreEqual(data, output.Data);
        }
    }
}</pre>
<p>Again, all very simple. The first test checks to make sure that the class gets stored onto the clipboard, and the second checks to see if the class we get back off the clipboard is the same as the one we put in.</p>
<p>The more astute among you have probably spotted the problem in the test code already, but the resultant symptoms are a little confusing.</p>
<h2>System.OutOfMemoryException?</h2>
<p>When we run the tests the first test runs absolutely fine, but the second test crashes out with a <a href="http://msdn.microsoft.com/en-us/library/system.outofmemoryexception.aspx" target="_blank">System.OutOfMemoryException</a>. A bit more digging showed that storing and retrieving standard types such as strings, ints etc all worked fine, but my own class was throwing an exception.</p>
<p>Checking good old MSDN threw up the following statement:</p>
<blockquote>
<p>An object must be serializable for it to be put on the Clipboard.</p>
</blockquote>
<p>Seeing as I had stupidly forgotten to add the <a href="http://msdn.microsoft.com/en-us/library/system.serializableattribute.aspx" target="_blank">SerializableAttribute</a> to the TestPayload class that definitely explained why things weren’t working as I expected; but it didn’t really explain the actual behaviour I was seeing. Another quote from MSDN, but from the WinForms documentation, stated:</p>
<blockquote>
<p>If you pass a non-serializable object to a Clipboard method, the method will fail without throwing an exception.</p>
</blockquote>
<p>So from that I would expect SetData to silently fail, and for nothing to be on the clipboard. However the first test above clearly shows that the clipboard at least <em>thinks</em> that <strong>something</strong> of our specified type has been added to the clipboard – it just throws an exception when we try and retrieve it again. Marking the payload class as serializable did fix the issue, but the behaviour I was seeing certainly didn’t make that obvious!</p>
<p>Just out of interest I tested the same code using the WinForms Clipboard class, which looks to all intents and purposes exactly the same as the WPF one, and that did fail silently and returned <em>null</em> from GetData.</p>
<h2>Conclusion</h2>
<p>So, after all that rambling, the conclusion is that if you are working with the Clipboard in WPF and you are getting <a href="http://msdn.microsoft.com/en-us/library/system.outofmemoryexception.aspx" target="_blank">System.OutOfMemoryException</a>s that don’t seem to make any sense, then you’ve probably forgotten to add the <a href="http://msdn.microsoft.com/en-us/library/system.serializableattribute.aspx" target="_blank">SerializableAttribute</a> to whatever class you placed on the Clipboard.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grumpydev.com/2009/09/05/system-outofmemoryexception-gotcha-using-clipboard-getdata-in-wpf/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Bindings Not Updating in WPF / Silverlight? Common Mistakes</title>
		<link>https://www.grumpydev.com/2009/08/26/bindings-not-updating-in-wpf-silverlight-common-mistakes/</link>
					<comments>https://www.grumpydev.com/2009/08/26/bindings-not-updating-in-wpf-silverlight-common-mistakes/#comments</comments>
		
		<dc:creator><![CDATA[Steven Robbins]]></dc:creator>
		<pubDate>Wed, 26 Aug 2009 07:07:39 +0000</pubDate>
				<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[binding]]></category>
		<category><![CDATA[inotifypropertychanged]]></category>
		<guid isPermaLink="false">http://www.grumpydev.com/?p=225</guid>

					<description><![CDATA[Introduction Yesterday I was working on a small prototype, which I will be blogging about shortly, and ran across the common problem of my bindings not updating. A very common problem, and one that’s usually a very simple fix once you’ve tracked it down. Yes, I’m an Idiot! Normally my ViewModels inherit from my ViewModelBase [&#8230;]]]></description>
										<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Yesterday I was working on a small prototype, which I will be blogging about shortly, and ran across the common problem of my bindings not updating. A very common problem, and one that’s usually a very simple fix once you’ve tracked it down.</p>
<h2>Yes, I’m an Idiot!</h2>
<p>Normally my ViewModels inherit from my ViewModelBase base class, which provides a RaisePropertyChanged method and, when in debug mode, uses reflection to check if the property name is valid. Now I’d recently refactored the code so this particular ViewModel wasn’t using the base class, so my first instinct was that I’d simply mistyped the property name magic string in the event – but that was all fine.</p>
<p>I threw in a few breakpoints and I could see my ViewModel was changing, I could see the OnPropertyChanged method being hit, but there didn’t seem to be any listeners and as a result my UI was just ignoring the changes.</p>
<p>After a few minutes of head scratching I noticed that although my class was firing the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.propertychanged.aspx" target="_blank">PropertyChanged</a> event correctly, I hadn’t added <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx" target="_blank">INotifyPropertyChanged</a> to my class declaration when I removed the base class! So although I was firing an event that <strong>looked</strong> like <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.propertychanged.aspx" target="_blank">INotifyPropertyChanged.PropertyChanged</a>, I was actually just firing my own event with the same name <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h2>Conclusion</h2>
<p>So there you have it, I’m an idiot <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> The moral of the story is, when your bindings aren’t working check the obvious:</p>
<ol>
<li>The property name is correct. A base class that checks this in debug mode can be useful, or failing that, watch the Output window.</li>
<li>Check you are actually implementing <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx" target="_blank">INotifyPropertyChanged</a> and not just firing events that happen to have the same name <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></li>
</ol>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grumpydev.com/2009/08/26/bindings-not-updating-in-wpf-silverlight-common-mistakes/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
			</item>
		<item>
		<title>Stack Overflow &#8211; Share Your Flair &#8211; Now in PNG!</title>
		<link>https://www.grumpydev.com/2009/07/11/stack-overflow-share-your-flair-now-in-png/</link>
					<comments>https://www.grumpydev.com/2009/07/11/stack-overflow-share-your-flair-now-in-png/#comments</comments>
		
		<dc:creator><![CDATA[Steven Robbins]]></dc:creator>
		<pubDate>Sat, 11 Jul 2009 21:01:09 +0000</pubDate>
				<category><![CDATA[Misc]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[flair]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[stack overflow]]></category>
		<guid isPermaLink="false">http://www.grumpydev.com/?p=210</guid>

					<description><![CDATA[Introduction This morning I was taking a look at the new (ish) meta stackoverflow site, and noticed a thread asking “Can we get flare as an image?”. It seemed like a good idea, especially for forum signatures and the like, so I thought that seeing as I’d recently updated the WordPress widget, that I’d try [&#8230;]]]></description>
										<content:encoded><![CDATA[<h2>Introduction</h2>
<p>This morning I was taking a look at the new (ish) <a href="http://meta.stackoverflow.com" target="_blank">meta stackoverflow</a> site, and noticed a thread asking “<a href="http://meta.stackoverflow.com/questions/1475/can-we-get-flair-as-an-image" target="_blank">Can we get flare as an image?”</a>. It seemed like a good idea, especially for forum signatures and the like, so I thought that seeing as I’d recently <a href="https://www.grumpydev.com/2009/07/09/updated-stack-overflow-wordpress-widget/" target="_blank">updated the WordPress widget</a>, that I’d try and put something together.</p>
<h2></h2>
<h2>Pretty as a Picture (or not)</h2>
<p>As C# is generally my weapon of choice these days, I was originally going to knock something together in ASP.Net. I was thinking something along the lines of rending a WPF control to a bitmap, and emitting that as an image. I decided against that approach because:</p>
<ol>
<li>ASP.Net hosting is <em>generally</em> more expensive – most people I know seem to stick to *nix hosting. </li>
<li>Rendering WPF to a bitmap doesn’t work in partial trust scenarios; so it might not even work on ASP.Net hosting anyway. </li>
</ol>
<p>So, feeling in a masochistic mood, I thought I’d knock something together in lovely old PHP; the results of which look something like this:</p>
<p><img decoding="async" border="0" alt="Steve Robbins&#39; StackOverflow Profile" src="https://www.grumpydev.com/imageFlair/imageFlair.php" /></p>
<p>Or, by passing in a userid on the querystring:</p>
<p><img decoding="async" border="0" alt="Marc Gravell&#39;s StackOverflow Profile" src="https://www.grumpydev.com/imageFlair/imageFlair.php?userid=23354" /></p>
<p>You can test&#160; it with your own details by changing the userid on the following url:</p>
<p><a href="https://www.grumpydev.com/imageFlair/imageFlair.php?userid=1">https://www.grumpydev.com/imageFlair/imageFlair.php?userid=1</a></p>
<p>Images are cached (for 30minutes by default) and all of the StackOverflow data is taken from the JSON feed, so the strain on SO should be fairly minimal.</p>
<h2>The Code</h2>
<p>You can use the script hosted on here if you want (although I might have to change my mind on that if the load gets too high), or you can download the code and run it on your own box:</p>
<p><a title="https://www.grumpydev.com/imageFlair.zip" href="https://www.grumpydev.com/imageFlair.zip">https://www.grumpydev.com/imageFlair.zip</a></p>
<p>Although it will run just fine “out of the box”, the code is pretty flexible; with plenty of configurable options for fonts, colours, positioning, background images, caching time etc. Take a look in config.php and you’ll hopefully find you can change everything you want to without having to delve into the main code.</p>
<p>Bear in mind that I am far from a PHP expert, and this was put together in a few hours, so please don’t laugh too much if you do take a peek at the source <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h2></h2>
<h2>Font Support / Licensing</h2>
<p>The text is rendered to the bitmap using a TrueType font of your choosing, which gives us some nice flexibility. Unfortunately though, none of the fonts that we generally take for granted, such as Arial, Verdana etc. come with any distribution rights; so I can’t include any in the source archive. This might not be a problem if you already have your favourite TrueType fonts installed; but if you don’t you can get a “free” version of several core fonts from <a title="http://sourceforge.net/projects/corefonts" href="http://sourceforge.net/projects/corefonts">http://sourceforge.net/projects/corefonts</a>. You just need to extract the archives using <a href="http://www.rarlab.com/" target="_blank">WinRAR</a>, or <a href="http://www.7-zip.org/" target="_blank">7zip</a>, or something of that ilk; then just drop the TTF file into the source code directory.</p>
<p>That&#8217;s it &#8211; hope someone finds it useful <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h2>Update – Bug Fixes and Pretty URLs</h2>
<p>After some feedback from the meta question I’ve fixed a stupid bug in the gravatar code, so now it should work for people who have a 1 in their gravatar hash (don’t ask! :-)).</p>
<p>I’ve also enabled “pretty urls” on the hosted version, so now you can go to a url like:</p>
<p><a title="https://www.grumpydev.com/imageFlair/658.png" href="https://www.grumpydev.com/imageFlair/658.png">https://www.grumpydev.com/imageFlair/658.png</a></p>
<p>And you’ll get the PNG for the corresponding userid. I do intend to expand it to include Flair for the other sites in the “Stack Overflow” family, but I haven’t had chance yet.</p>
<p>For those that are interested, this is the .htaccess file that enables the pretty urls, and also reduces the cache time on pngs to 1 second:</p>
<pre class="xml:nocontrols" name="code">&lt;IfModule mod_rewrite.c&gt;
RewriteEngine On
RewriteRule ^(.*)\.png$ imageFlair.php?userid=$1 [L]
&lt;/IfModule&gt;

&lt;IfModule mod_expires.c&gt;
ExpiresActive On
ExpiresByType image/png &quot;access plus 1 seconds&quot;
&lt;/IfModule&gt;</pre>
<h2>Update 2 – Supporting the Whole Family</h2>
<p>I’ve added an optional parameter to specify which site’s information to display. The “pretty” url format now looks like this:</p>
<p>http://[ur]/[mode]/[id].png</p>
<p>Where [mode] is one of:</p>
<ul>
<ul>
<li>so &#8211; <a href="http://www.stackoverflow.com/" target="_blank">Stack Overflow</a> </li>
<li>meta &#8211; <a href="http://meta.stackoverflow.com/" target="_blank">Meta Stack Overflow</a> </li>
<li>sf &#8211; <a href="http://serverfault.com" target="_blank">Server Fault</a> </li>
<li>su &#8211; <a href="http://superuser.com/" target="_blank">Super User</a> (although this isn&#8217;t live yet) </li>
</ul>
</ul>
<p>So for Jeff (id number 1 everywhere is easy :-)) we end up with:</p>
<p><img decoding="async" alt="Stack Overflow" src="https://www.grumpydev.com/imageFlair/so/1.png" /> <img decoding="async" alt="Meta" src="https://www.grumpydev.com/imageFlair/meta/1.png" /> <img decoding="async" alt="Server Fault" src="https://www.grumpydev.com/imageFlair/sf/1.png" /></p>
<p>The htaccess file now looks like this:</p>
<pre class="xml:nocontrols" name="code">&lt;IfModule mod_rewrite.c&gt;
RewriteEngine On
RewriteRule ^(.*)/(.*)\.png imageFlair.php?mode=$1&amp;userid=$2 [L]
RewriteRule ^(.*)\.png$ imageFlair.php?userid=$1 [L]
&lt;/IfModule&gt;

&lt;IfModule mod_expires.c&gt;
ExpiresActive On
ExpiresByType image/png &quot;access plus 1 seconds&quot;
&lt;/IfModule&gt;</pre>
<p>Source ZIP is updated with all the latest changes. Hopefully that will be it for the time being! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grumpydev.com/2009/07/11/stack-overflow-share-your-flair-now-in-png/feed/</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
		<item>
		<title>Updated: Stack Overflow WordPress Widget</title>
		<link>https://www.grumpydev.com/2009/07/09/updated-stack-overflow-wordpress-widget/</link>
					<comments>https://www.grumpydev.com/2009/07/09/updated-stack-overflow-wordpress-widget/#comments</comments>
		
		<dc:creator><![CDATA[Steven Robbins]]></dc:creator>
		<pubDate>Thu, 09 Jul 2009 19:19:14 +0000</pubDate>
				<category><![CDATA[Misc]]></category>
		<category><![CDATA[stack overflow]]></category>
		<category><![CDATA[widget]]></category>
		<category><![CDATA[wordpress]]></category>
		<guid isPermaLink="false">http://www.grumpydev.com/2009/07/09/updated-stack-overflow-wordpress-widget/</guid>

					<description><![CDATA[Introduction Just a quick post to say I’ve updated my Stack Overflow WordPress Widget to implement some basic caching. I’m still in the process of converting it to the new JSON service that SO have provided; but in the meantime this should cut down on the amount of traffic it uses. You should be able [&#8230;]]]></description>
										<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Just a quick post to say I’ve updated my <a href="http://www.stackoverflow.com/" target="_blank">Stack Overflow</a> WordPress Widget to implement some basic caching. I’m still in the process of converting it to the new JSON service that SO have provided; but in the meantime this should cut down on the amount of traffic it uses.</p>
<p>You should be able to upgrade straight from the admin section of your blog; but you can also grab it from the <a href="http://wordpress.org/extend/plugins/stack-overflow-gamertag-widget/" target="_blank">WordPress Plugin Directory</a>.</p>
<p>The cache time is configurable in the widget settings, and defaults to 30minutes. It attempts to locate your temp directory, then creates a unique filename cache in there; so there’s no need to chmod a cache file to get it to work.</p>
<p>I’ll hopefully get a JSON version working in the next few days, but if anyone has any problems feel free to give me a shout from the <a href="https://www.grumpydev.com/contact/" target="_blank">contact page</a>.</p>
<p><strong>Update:</strong> It seems the JSON version was easier than I thought <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> I’ve uploaded v2.0.0 that still includes the caching changes, but also uses the “official” JSON feed. If you have already used the cached version you might might need to delete the cache file to make it re-download the raw data.</p>
<p>The only “downside” to the JSON version is it requires <a href="http://uk.php.net/json_decode" target="_blank">json_decode</a>, so you must have PHP 5.2.0 or above. If you can’t satisfy this requirement then you’ll be better off with the previous version.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grumpydev.com/2009/07/09/updated-stack-overflow-wordpress-widget/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
	</channel>
</rss>
