<?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>New Fun Blog - Scott Bilas</title>
	<atom:link href="http://scottbilas.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://scottbilas.com</link>
	<description>Take what you want, and leave the rest (just like your salad bar).</description>
	<lastBuildDate>Tue, 31 Aug 2010 15:35:53 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Quickie: Fluent Object Casting</title>
		<link>http://scottbilas.com/blog/quickie-fluent-object-casting/</link>
		<comments>http://scottbilas.com/blog/quickie-fluent-object-casting/#comments</comments>
		<pubDate>Tue, 18 May 2010 04:40:31 +0000</pubDate>
		<dc:creator>Scott</dc:creator>
				<category><![CDATA[csharp]]></category>
		<category><![CDATA[quickie]]></category>

		<guid isPermaLink="false">http://scottbilas.com/?p=523</guid>
		<description><![CDATA[I’m a big fan of fluent interfaces. C# picked this style up in a big way starting with 3.5 and the Enumerable operators class. People are going nuts with it, often for replacing verbose old XML with something a little more readable and compact. Yay. Finally, C# has caught up with languages like Lua or [...]]]></description>
			<content:encoded><![CDATA[<p>I’m a big fan of <a href="http://en.wikipedia.org/wiki/Fluent_interface">fluent interfaces</a>. C# picked this style up in a big way starting with 3.5 and the Enumerable operators class. People are <a href="http://blog.vuscode.com/malovicn/archive/2008/08/31/fluent-nhibernate-nhibernate-without-configuration-files.aspx">going nuts</a> with it, often for replacing verbose old XML with something a little more readable and compact. Yay. Finally, C# has caught up with languages like <a href="http://www.lua.org/">Lua</a> or <a href="http://www.json.org/">Javascript</a> which have had this ability forever.</p>
<p>Aside from a better configuration language, what I really like about coding fluently is that it’s a steady stream of left-to-right operators, like a pipeline. You think of the next operation and just chain it along, never having to back up. Domain specific sublanguages like <a href="http://en.wikipedia.org/wiki/Language_Integrated_Query">LINQ</a> (which I adore, incidentally) can make this even more compact, but I’m talking about the function-based fluent operators.</p>
<p>For enumerables, it’s easy:</p>
<pre class="brush: csharp;">
var names = list.Where(i =&gt; i.Foo &gt; 5).Cast&lt;IBar&gt;().Select(j =&gt; j.Name);
</pre>
<p>Take the list, filter it, cast to the type we want, and pull out an element. Operation by operation, left to right. But what about for a single object? That fluency hits a brick wall when you run into C#’s old C-style casting on an individual object. </p>
<pre class="brush: csharp;">
var name = ((IBar)list.First()).Name;
</pre>
<p>Yuck. Not fluent, and hard to read. As you’re typing, you have to back up, stick the casted type on the front in parens, and, oh yeah, have to also go wrap the whole thing in parens to be able to continue the method chain. I’ve always hated having to do this and in the past would usually pull out the casting into a separate local.</p>
<p>It’s also easy to fix. We just need a little extension method:</p>
<pre class="brush: csharp;">
public static partial class Extensions
{
    [DebuggerStepThrough]
    public static T To&lt;T&gt;(this object o)
        { return (T)o; }
}
</pre>
<p>Now it’s nice and fluent:</p>
<pre class="brush: csharp;">
var name = list.First().To&lt;IBar&gt;().Name;
</pre>
<p>So we now have the system Cast&lt;T&gt; operator for casting elements within an enumerable, and To&lt;T&gt; for casting the overall type. Solid.</p>
]]></content:encoded>
			<wfw:commentRss>http://scottbilas.com/blog/quickie-fluent-object-casting/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Quickie: Case Insensitive WordPress Login</title>
		<link>http://scottbilas.com/blog/quickie-case-insensitive-wordpress-login/</link>
		<comments>http://scottbilas.com/blog/quickie-case-insensitive-wordpress-login/#comments</comments>
		<pubDate>Tue, 11 May 2010 04:30:30 +0000</pubDate>
		<dc:creator>Scott</dc:creator>
				<category><![CDATA[quickie]]></category>
		<category><![CDATA[wordpress]]></category>

		<guid isPermaLink="false">http://scottbilas.com/?p=519</guid>
		<description><![CDATA[Do you have a locked down WordPress site that has a case-sensitive login even though the Googles are telling you that in WordPress 2.8 they went case-insensitive? Most likely you have John Kolbert’s nice Absolute Privacy plugin installed. It just needs a minor fix.
Edit absolute_privacy.php. Easiest way is through the admin interface under Edit Plugins. [...]]]></description>
			<content:encoded><![CDATA[<p>Do you have a locked down WordPress site that has a case-sensitive login even though the Googles are telling you that in WordPress 2.8 they went case-insensitive? Most likely you have John Kolbert’s nice <a href="http://www.johnkolbert.com/portfolio/wp-plugins/absolute-privacy/">Absolute Privacy</a> plugin installed. It just needs a minor fix.</p>
<p>Edit absolute_privacy.php. Easiest way is through the admin interface under Edit Plugins. Change this line:</p>
<pre class="brush: php;">
if ( !$user || ($user-&gt;user_login != $username) ) {
</pre>
<p>To this:</p>
<pre class="brush: php;">
if ( !$user || (strtolower($user-&gt;user_login) != strtolower($username)) ) {
</pre>
<p>Now you can log in with whatever case you like.</p>
]]></content:encoded>
			<wfw:commentRss>http://scottbilas.com/blog/quickie-case-insensitive-wordpress-login/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Quickie: Building P4.Net</title>
		<link>http://scottbilas.com/blog/quickie-building-p4-net/</link>
		<comments>http://scottbilas.com/blog/quickie-building-p4-net/#comments</comments>
		<pubDate>Sun, 25 Apr 2010 23:23:01 +0000</pubDate>
		<dc:creator>Scott</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[p4]]></category>
		<category><![CDATA[quickie]]></category>

		<guid isPermaLink="false">http://scottbilas.com/blog/quickie-building-p4-net/</guid>
		<description><![CDATA[In my last post I wrote about building AnyCPU assemblies that can reference 32 or 64 bit DLL’s automatically based on the environment. Just wanted to make a quick followup for people who are actually following my example, specifically trying to implement it for P4.Net. There are a few little snags if you’re not super [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://scottbilas.com/blog/automatically-choose-32-or-64-bit-mixed-mode-dlls/">last post</a> I wrote about building AnyCPU assemblies that can reference 32 or 64 bit DLL’s automatically based on the environment. Just wanted to make a quick followup for people who are actually following my example, specifically trying to implement it for <a href="http://p4dotnet.sourceforge.net/index.php/P4.Net_Overview">P4.Net</a>. There are a few little snags if you’re not super familiar with native programming.</p>
<p>Make sure you do the following:</p>
<ul>
<li>You must have the 64 bit compilers installed or you won’t be able to add 64-bit configurations to p4dn. Most likely you didn’t check the box for this when originally installing Visual Studio. Just go to add/remove programs, “change”, and check 64-bit under the C++ area.</li>
<li>The p4dn library requires Perforce’s p4api native library, which comes in many flavors. It is included in the distribution for P4.Net, but it is an old version. I recommend getting the latest API from their <a href="ftp://ftp.perforce.com/pub/perforce/r09.2/">FTP site</a>.</li>
<ul>
<li>I used the <em>p4api_vs2008_dyn</em> and <em>p4api_vs2008_dyn_vsdebug</em> configurations from the ntx64 and ntx86 builds.</li>
<li>Why dynamic instead of static? .NET is all about DLL’s – using static just causes problems with the linker with conflicting runtimes.</li>
</ul>
<li>Update the include and lib paths in the p4dn C++ project settings so that the library can find your p4api. If you don’t do this you’ll get #include errors about missing paths.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://scottbilas.com/blog/quickie-building-p4-net/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Automatically Choose 32 or 64 Bit Mixed Mode DLL&#8217;s</title>
		<link>http://scottbilas.com/blog/automatically-choose-32-or-64-bit-mixed-mode-dlls/</link>
		<comments>http://scottbilas.com/blog/automatically-choose-32-or-64-bit-mixed-mode-dlls/#comments</comments>
		<pubDate>Mon, 19 Apr 2010 04:39:23 +0000</pubDate>
		<dc:creator>Scott</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[p4]]></category>

		<guid isPermaLink="false">http://scottbilas.com/?p=513</guid>
		<description><![CDATA[Here’s a problem that was bugging me at my last job that I finally got around to solving last week on the bus: letting your top-level project run as AnyCPU and automatically choose a 32-bit or 64-bit low level  native/managed DLL based on environment bit width.
Say you’re using Shawn Hladky’s great P4.Net project (source) so [...]]]></description>
			<content:encoded><![CDATA[<p><img style="margin: 0px 0px 10px 10px; display: inline; border: 0px;" title="Máncora" src="http://scottbilas.com/wp-content/uploads/2010/04/P1000886.jpg" border="0" alt="Máncora" width="160" height="153" align="right" />Here’s a problem that was bugging me at my last job that I finally got around to solving last week on the bus: letting your top-level project run as AnyCPU and automatically choose a 32-bit or 64-bit low level  native/managed DLL based on environment bit width.</p>
<p>Say you’re using Shawn Hladky’s great <a href="http://p4dotnet.sourceforge.net/index.php/P4.Net_Overview">P4.Net</a> project (<a href="http://public.perforce.com:8080/@md=d&amp;cd=//guest/shawn_hladky/&amp;c=MFz@//guest/shawn_hladky/P4.Net/?ac=83" class="broken_link">source</a>) so your C# can speak <a href="http://www.perforce.com">Perforce</a> – two great tastes that taste great together. P4.Net talks to the server using a native Perforce API. Now, unlike a C# EXE, which is usually AnyCPU (i.e. “let the jitter decide”), the native code that talks to the Perforce server must be compiled as either x86 or x64. This causes two big problems.</p>
<p>The <strong>first problem</strong> is that your app will crash with a confusing error if run on the wrong version of the .Net Framework! Say you’re using the x86 P4.Net and you run your app on Win7-x64. The jitter will compile the app in 64 bit, but on the first reference to P4.Net, it tries and fails to load the x86 DLL, and puts up an unhelpful error about a bad image format.</p>
<p>The easy workaround to this, of course, is to mark your EXE as x86 instead of AnyCPU. Solved. Unfortunately, you have to remember to do this with every single app that references P4.Net. Or references a DLL that indirectly references P4.Net. It’s like a virus in that way, but we can handle it.</p>
<p>Well, no. That leads to the <strong>second problem</strong>. What happens if you reference P4.Net (directly or indirectly) into an app that really <em>does</em> need 64 bit? Like, say, some memory-hoovering game build related tool that runs on the server farm? Well now you need a 64-bit version, not only of P4.Net, and not only of your EXE, but of <em>every single DLL that is referenced on the path down to your new P4.Net_x64.DLL</em>. Now we have a real problem. The pain in the ass to maintain kind of problem. Do we really want to have our tool chain output 32 and 64 bit versions of everything, just in case?</p>
<p>Had Microsoft supported <a href="http://en.wikipedia.org/wiki/Universal_binary">fat binaries</a> like <a href="http://en.wikipedia.org/wiki/NeXTSTEP">NeXTSTEP</a> did back in the early 90’s, we’d just have P4.Net with 32 and 64 bit in the same DLL, and go on with our lives. But no, we have to jump through hoops. This article is the story of how to jump through those hoops to make your bits go.</p>
<p><em>I’m actually a bit shocked that Microsoft hasn’t extended </em><a href="http://en.wikipedia.org/wiki/Portable_Executable"><em>PE</em></a><em> and their OS loaders to support fat binaries. There would be zero perf cost, and it’s been a long time since we had to worry about the size of binaries on disk (content overwhelms executable code size in nearly every app today).</em></p>
<h2>About P4.Net</h2>
<p>If I’m going to continue to use P4.Net for my example, I need to give a little more background. P4.Net is built from three components:</p>
<ol>
<li><strong>p4api.lib</strong>: A native C++ API (headers and libs) provided by Perforce to talk to their server directly through sockets, without running p4.exe or using the COM object.</li>
<li><strong>p4dn.dll</strong>: A bridge assembly that statically links in p4api, and uses Managed C++ to export p4api as a low level set of .Net types.</li>
<li><strong>p4api.dll</strong>: A managed C# API that wraps up the low level p4dn and adds functionality to make it easier to work with. This is what everybody does an “add reference” on to talk to P4 from C#.</li>
</ol>
<p>Note that p4api.dll is not <em>strictly necessary</em> as a separate assembly. The low level types exported by p4dn.dll could instead be kept internal, and all of that C# code from p4api.dll be written in Managed C++ and moved into p4dn.dll, entirely eliminating the need for p4api.dll.</p>
<p>Personally I was a fan of Managed C++, up until C# 3.0 where we started getting all kinds of nice language syntax to write better code more compactly. Today, I suppose I’d keep the extra DLL just for easier maintenance.</p>
<h2>The Solution</h2>
<p>In a nutshell, the solution is to trick the loader! Reference a p4dn.dll that does not exist, and use the <a href="http://msdn.microsoft.com/en-us/library/system.appdomain.assemblyresolve.aspx">AssemblyResolve</a> event to intercept the load and reroute it to the correct bit size assembly.</p>
<p>It’s simple in concept but has a lot of details that took me a whole bus ride to figure out all the way (happily, there was a lot of traffic). Here is what I ended up doing to make it work how I wanted:</p>
<ol>
<li>Rename the x86 output of p4dn.dll to p4dn.proxy.dll.</li>
<li>Update the x86 linker input settings to add __DllMainCRTStartup@12 to Force Symbol References.</li>
<li>Build a new x64 configuration for p4dn, using the x86 configuration (well, ‘Win32’) as a template. Have it output to p4dn.x64.dll.</li>
<li>Update the x64 linker input settings to add _DllMainCRTStartup to Force Symbol References.</li>
<li>Add a post-build event to p4dn’s x86 configuration that deletes p4dn.x86.* and copies the p4dn.proxy.* to p4dn.x86.*.</li>
<li>Update p4api to reference p4dn.proxy.dll. Not the csproj, but the actual DLL.</li>
<li>Update the SLN settings to make p4api dependent on p4dn.</li>
<li>Add a post-build step to p4api to delete p4dn.proxy.dll.</li>
<li>Set all p4api and p4dn configurations to output to the same bin folder.</li>
<li>Add a static constructor to P4API.P4Connection that registers an event handler on AppDomain.CurrentDomain.AssemblyResolve to pick the right DLL when the proxy is requested. I’ve pasted my code at the bottom of this post.</li>
</ol>
<p>Once this is done, you’ll be able to have p4api as well as any assemblies that reference it set to AnyCPU. It will, upon first usage of the P4Connection class, fail to resolve the proxy and reroute to the correct bit width DLL.</p>
<p>A few notes on the above:</p>
<ul>
<li>The _DllMainCRTStartup is required because, without it, I got a crash from uninitialized memory systems in the CRT DLL’s that p4dn was linked to. This happened regardless of static vs. dynamic linking. I didn’t bother to find out the real reason for it. The different symbol names for 32 bit vs. 64 bit are because the convention changed when Microsoft went to 64 bit.</li>
<li>The name of the DLL being referenced must match the original name of the DLL being built. That is, if you were to have p4dn outputting to p4dn.x86.dll then renaming it to proxy, and then referencing that, then it will actually look for the referenced DLL’s “true” name of p4dn.x86.dll and never call your hook.</li>
<li>In projects that reference p4api it’s best to set the references to non-private (clear the “Copy Local” flag) and have a post-build step that just copies whatever is in the p4api bin folder. That makes sure you get the exact files that you need. None of this will work if you accidentally end up with the proxy file existing.</li>
</ul>
<p>Here’s the code for my hook function. Note that it attempts to catch problems with the post-build scripts.</p>
<pre class="brush: csharp;">
static P4Connection()
{
	string assemblyDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
	if (	File.Exists(Path.Combine(assemblyDir, &quot;p4dn.proxy.dll&quot;))
		|| !File.Exists(Path.Combine(assemblyDir, &quot;p4dn.x86.dll&quot;))
		|| !File.Exists(Path.Combine(assemblyDir, &quot;p4dn.x64.dll&quot;)))
	{
		throw new InvalidOperationException(&quot;Found p4dn.proxy.dll which cannot exist. &quot;
			+ &quot;Must instead have p4dn.x86.dll and p4dn.x64.dll. Check your build settings.&quot;);
	}

	AppDomain.CurrentDomain.AssemblyResolve += (_, e) =&gt;
	{
		if (e.Name.StartsWith(&quot;p4dn.proxy,&quot;, StringComparison.OrdinalIgnoreCase))
		{
			string fileName = Path.Combine(assemblyDir,
				string.Format(&quot;p4dn.{0}.dll&quot;, (IntPtr.Size == 4) ? &quot;x86&quot; : &quot;x64&quot;));
			return Assembly.LoadFile(fileName);
		}
		return null;
	};
}
</pre>
<p>Microsoft, if you’re listening: <strong>FAT BINARIES</strong>.</p>
]]></content:encoded>
			<wfw:commentRss>http://scottbilas.com/blog/automatically-choose-32-or-64-bit-mixed-mode-dlls/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Quickie: Adding Utility Functions To Interfaces</title>
		<link>http://scottbilas.com/blog/quickie-adding-utility-functions-to-interfaces/</link>
		<comments>http://scottbilas.com/blog/quickie-adding-utility-functions-to-interfaces/#comments</comments>
		<pubDate>Sun, 21 Mar 2010 19:20:48 +0000</pubDate>
		<dc:creator>Scott</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[quickie]]></category>

		<guid isPermaLink="false">http://scottbilas.com/?p=504</guid>
		<description><![CDATA[In working in C#, one thing I miss from C++ is being able to implement interfaces via a rich base class. C#’s lack of multiple inheritance (a good decision on balance) just about prevents this.
I have two things in mind when I say “rich base class”. First is for mixing in object functionality. I’ve spoken [...]]]></description>
			<content:encoded><![CDATA[<p>In working in C#, one thing I miss from C++ is being able to implement interfaces via a rich base class. C#’s lack of multiple inheritance (a good decision on balance) just about prevents this.</p>
<p>I have two things in mind when I say “rich base class”. First is for mixing in object functionality. I’ve spoken about this <a href="http://scottbilas.com/blog/assertive-finalizers/">before</a>. There really is no way to do this nicely in C#. However, today’s post is about the other thing C++ gives you with multiple inheritance: <em>utility methods</em>.</p>
<p>Consider this interface and implementing class, paying attention to the overloads:</p>
<pre class="brush: csharp;">
interface ILogger
{
	void Log(string message);
	void LogLine(string message);
	void Log(string format, params object[] args);
	void LogLine(string format, params object[] args);
}

class DebugLogger : ILogger
{
	void ILogger.Log(string message)
		{ Debug.Write(message); }
	void ILogger.LogLine(string message)
		{ Debug.WriteLine(message); }
	void ILogger.Log(string format, params object[] args)
		{ Debug.Write(string.Format(format, args)); }
	void ILogger.LogLine(string format, params object[] args)
		{ Debug.WriteLine(string.Format(format, args)); }
}
</pre>
<p>The more versions of the log function you want, the more work you have to do in any class implementing the interfaces. You could create a LoggerBase that does all of this, but that is severely limiting.</p>
<p>In C++ it’s easy of course. Make a mixin class.</p>
<pre class="brush: csharp;">
class Logger
{
public:
	void Log(const char* message)
		{ OnLog(message); }
	void LogLine(const char* message)
		{ OnLog(message); OnLog(&quot;\n&quot;); }

	void LogF(const char* format, ...)
	{
		char buffer[2000];
		va_list args;
		va_start(args, format);
		vsprintf_s(buffer, format, args);
		va_end(args);
		Log(buffer);
	}

	void LogLineF(const char* format, ...)
	{
		char buffer[2000];
		va_list args;
		va_start(args, format);
		vsprintf_s(buffer, format, args);
		va_end(args);
		LogLine(buffer);
	}

protected:
	virtual void OnLog(const char* message) = 0;
};

class DebugLogger : public Logger
{
	virtual void OnLog(const char* message)
	{
		OutputDebugString(message);
	}
};
</pre>
<p>Exactly one virtual method is required in the derived class. To add new overloads, you just add them to the base, and have them call the virtual. All end up with dynamic behavior. With interfaces in C#, you’re forced to implement each overload. This ends up with a lot of duplication everywhere you implement this same interface. Worse, if you want to add more utility functions to the interface, you break every implementing class, which must now implement that function as well.</p>
<p>The other day, it hit me that there’s an easy and perhaps obvious solution to this in C#: <strong>extension methods</strong>.</p>
<pre class="brush: csharp;">
interface ILogger
{
	void Log(string message);
}

static partial class Extensions
{
	public static void LogLine(this ILogger logger, string message)
	{
		logger.Log(message);
		logger.Log(&quot;\n&quot;);
	}

	public static void LogFormat(this ILogger logger, string format, params object[] args)
	{
		logger.Log(string.Format(format, args));
	}

	public static void LogLineFormat(this ILogger logger, string format, params object[] args)
	{
		logger.LogFormat(format, args);
		logger.Log(&quot;\n&quot;);
	}
}

class DebugLogger : ILogger
{
	void ILogger.Log(string message)
	{
		Debug.Write(message);
	}
}
</pre>
<p>This will do what I want. I can implement a minimal interface, and easily add new utility functions. It&#8217;s not quite as good as C++, because I can&#8217;t store any data in my extension methods, and I must work solely through the published interface, but it&#8217;s good enough for 80%.</p>
<p>In one very small way it&#8217;s actually <em>better</em> than C++. In C++, that base class isn&#8217;t always something that can be changed. Perhaps it was provided by a standard library or a third party. Yet in C#, anybody can create an extension class to add functionality to any other class. So you can add all the overloads you like.</p>
]]></content:encoded>
			<wfw:commentRss>http://scottbilas.com/blog/quickie-adding-utility-functions-to-interfaces/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Assertive Finalizers</title>
		<link>http://scottbilas.com/blog/assertive-finalizers/</link>
		<comments>http://scottbilas.com/blog/assertive-finalizers/#comments</comments>
		<pubDate>Tue, 09 Mar 2010 02:04:14 +0000</pubDate>
		<dc:creator>Scott</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://scottbilas.com/?p=485</guid>
		<description><![CDATA[
In my previous post, I talked about why I have stopped using finalizers for unmanaged resource collection. I want this to be done through the disposable pattern instead, forcing the programmer to manage resources manually.
Ironically, finalizers are a great way to verify this.
Sander van Rossen quickly figured out where I was going with this and [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://scottbilas.com/wp-content/uploads/2010/03/MG_3288.jpg"><img style="margin: 0px 0px 10px 10px; display: inline; border-width: 0px;" title="Oruro" src="http://scottbilas.com/wp-content/uploads/2010/03/MG_3288_thumb.jpg" border="0" alt="Oruro" width="120" height="168" align="right" /></a></p>
<p>In my <a href="http://scottbilas.com/blog/finalizers-an-incomplete-pattern">previous post</a>, I talked about why I have stopped using finalizers for unmanaged resource collection. I want this to be done through the disposable pattern instead, forcing the programmer to manage resources manually.</p>
<p><em>Ironically, finalizers are a great way to verify this.</em></p>
<p><a href="http://sandervanrossen.blogspot.com/">Sander van Rossen</a> quickly figured out where I was going with this and proposed in a <a href="http://scottbilas.com/blog/finalizers-an-incomplete-pattern#comment-413">comment</a> that we can just assert in a finalizer. We just need a couple more things:</p>
<ol>
<li>We need to track the source of the object to figure out where the leak is.</li>
<li>We need to ensure that finalizers run on shutdown, or our assert will never get hit.</li>
</ol>
<p>This is familiar territory to C++ programmers. Most of us use memory management libraries that provide <a href="http://msdn.microsoft.com/en-us/library/e5ewb1h3%28VS.80%29.aspx">leak detection and reporting</a>. Let’s do something similar in C#.</p>
<h2>DisposableBase</h2>
<p>If you look around online, you’ll find some full-featured IDisposable <a href="http://www.danrigsby.com/blog/index.php/2008/03/15/disposable-base-class/">base classes</a> intended to deal with the full finalization model. We can eliminate most of that as either too complicated or unnecessary. We just need a few things:</p>
<ul>
<li><em>A stack trace grabbed at construction time<br />
</em>This will be used for the error report. Because this is expensive to gather, we need to control it with an #if that is off by default, only turned on if needed to help an investigation. Most of the time a leaked disposable will be easy to find by inspection, but in the 5% case we will need a lot more context.</li>
<li><em>A finalizer that reports the problem<br />
</em>It could throw an exception, fire an assert, or route to an error reporter. Depends on the application. In my example I just have it output to the debug window for a demo.</li>
<li><em>Disposal helper methods</em><br />
These wrap up disposal a bit, so inheritors only need to implement OnDispose. The most important feature, though, is that Dispose will call <strong>GC.SuppressFinalize</strong> when our object is disposed. This eliminates the performance cost of having a finalizer in the normal case when clients are disposing this class properly. This is why the finalizer has no “if” in it – if it ever gets called, then we have a bug.</li>
</ul>
<p>This is what I am currently using as my base class for handling unmanaged resources:</p>
<pre class="brush: csharp;">
// comment out unless diagnosing a leak
#define DEBUG_DISPOSE

public abstract class DisposableBase : IDisposable
{
    // store stack at point of construction for possible later use
#	if DEBUG_DISPOSE
    StackTrace _trace = new StackTrace(true);
#	endif

    // finalizer will not be called if object was properly disposed
    ~DisposableBase()
    {
        string message = &quot;!! Forgot to dispose a &quot; + GetType().FullName;
#		if DEBUG_DISPOSE
        message += &quot;\n\nStack at construction:\n\n&quot; + _trace + &quot;!!&quot;;
#		endif
        Debug.WriteLine(message);
    }

    public bool IsDisposed { get; private set; }

    public void Dispose()
    {
        ThrowIfDisposed();
        IsDisposed = true;

        try { OnDispose(); }
        finally { GC.SuppressFinalize(this); }
    }

    protected abstract void OnDispose();

    protected void ThrowIfDisposed()
    {
        if (IsDisposed)
            throw new ObjectDisposedException(GetType().FullName);
    }
}
</pre>
<h2>Demonstration</h2>
<p>Here is a simple test app that shows what happens if we forget to dispose an instance.</p>
<pre class="brush: csharp;">
public class DatabaseConnection : DisposableBase
{
    protected override void OnDispose()
        { Debug.WriteLine(&quot;Disposing&quot;); }
}

public class Program
{
    static void Main(string[] args)
    {
        using (var remembered0 = new DatabaseConnection())
        using (var remembered1 = new DatabaseConnection())
        {
        }

        var forgotten = new DatabaseConnection();

        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}
</pre>
<p>The first two instances dispose fine, but the third is leaked and so we get a log to the output window:</p>
<pre class="brush: plain;">
Disposing
Disposing
!! Forgot to dispose a DatabaseConnection

Stack at construction:

   at DisposableBase..ctor() in C:\Users\Scott\Cloud\Proj\tests\BlogSamples\ConsoleApplication1\Finalizers.cs:line 18
   at DatabaseConnection..ctor()
   at Program.Main(String[] args) in C:\Users\Scott\Cloud\Proj\tests\BlogSamples\ConsoleApplication1\Finalizers.cs:line 89
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()
!!
</pre>
<p>We can easily zero in on the exact spot where the leaked resource was allocated and wrap it in a ‘using’ to resolve.</p>
<p>Note the use of <strong>GC.Collect</strong> and <strong>GC.WaitForPendingFinalizers</strong> right before the test application exits. This is necessary in order to force all finalizing objects to be collected and reported before process shutdown, otherwise they are simply dropped by the system when the process’s memory is released.</p>
<p>These two can even be called during normal app run as well for leak testing without needing to wait for shutdown. This would be useful in a live service with a periodic leak for which we want an in-session nonfatal log of leaks.</p>
<h2>What About External Classes?</h2>
<p>This takes care of our own classes, where we have full control. But what about system or third party classes that are using finalizers? With those it’s back to square one.</p>
<p>Well, I suppose would write a helper class..</p>
<pre class="brush: csharp;">
public class SafeDisposer&lt;T&gt; : DisposableBase where T : IDisposable
{
    public SafeDisposer(T disposable) { Obj = disposable; }

    public T Obj { get; private set; }

    protected override void OnDispose()
    {
        Obj.Dispose();
        Obj = default(T);
    }
}

public static class SafeDisposer
{
    public static SafeDisposer&lt;T&gt; Wrap&lt;T&gt;(T disposable) where T : IDisposable
        { return new SafeDisposer&lt;T&gt;(disposable); }
}
</pre>
<p>And equivalent updates in the demo code:</p>
<pre class="brush: csharp;">
public class Program
{
    static void Main(string[] args)
    {
        using (var remembered2 = SafeDisposer.Wrap(new StringReader(&quot;foo&quot;)))
        using (var remembered3 = SafeDisposer.Wrap(new StringReader(&quot;poo&quot;)))
        {
            remembered2.Obj.Peek();
        }

        var forgotten2 = SafeDisposer.Wrap(new StringReader(&quot;boo&quot;));

        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}
</pre>
<p>And output:</p>
<pre class="brush: plain;">
!! Forgot to dispose a SafeDisposer`1[[System.IO.StringReader, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]

Stack at construction:

   at DisposableBase..ctor() in C:\Users\Scott\Cloud\Proj\tests\BlogSamples\ConsoleApplication1\Finalizers.cs:line 18
   at SafeDisposer`1..ctor(T disposable) in C:\Users\Scott\Cloud\Proj\tests\BlogSamples\ConsoleApplication1\Finalizers.cs:line 53
   at SafeDisposer.Wrap[T](T disposable) in C:\Users\Scott\Cloud\Proj\tests\BlogSamples\ConsoleApplication1\Finalizers.cs:line 67
   at Program.Main(String[] args) in C:\Users\Scott\Cloud\Proj\tests\BlogSamples\ConsoleApplication1\Finalizers.cs:line 98
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()
!!
</pre>
<p>So to use, we just wrap a disposable at the point of creation in SafeDisposer.Wrap() and access it through “.Obj”. Not bad, but not great either. I’m ok with the wrapper function, but the required access via the Obj member is a pain, and also means that converting an unsafe disposable into a safe one requires updating a lot of code.</p>
<p>Another option is (maybe) to use a <a href="http://www.castleproject.org/dynamicproxy/index.html">dynamic proxy system</a> to inject the functionality we need, letting client code remain unchanged except at the point of creation. Or perhaps a run-time system that patches system assemblies to do the injection.</p>
<p>I’ll leave this as an exercise for the reader because I think we’re probably getting seriously diminishing returns at this point. Most disposable objects in a large system will be classes that we have full control over. The few objects <em>not</em> under our control will likely be low level primitives that will be wrapped up by our own foundation classes anyway.</p>
]]></content:encoded>
			<wfw:commentRss>http://scottbilas.com/blog/assertive-finalizers/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Finalizers: An Incomplete Pattern</title>
		<link>http://scottbilas.com/blog/finalizers-an-incomplete-pattern/</link>
		<comments>http://scottbilas.com/blog/finalizers-an-incomplete-pattern/#comments</comments>
		<pubDate>Tue, 02 Mar 2010 04:45:38 +0000</pubDate>
		<dc:creator>Scott</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://scottbilas.com/?p=473</guid>
		<description><![CDATA[ When you were first learning about how .NET finalization works, did it just feel wrong to you? It sure did for me. The mechanisms and rules involved with finalizers always felt painfully over-complicated, hard to get right, and hacky. Here we have this clean managed-memory paradigm that feels great to use. And it’s got [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://scottbilas.com/wp-content/uploads/2010/03/DSC04726.jpg"><img style="margin: 0px 0px 10px 10px; display: inline; border-width: 0px;" title="Whistler" src="http://scottbilas.com/wp-content/uploads/2010/03/DSC04726_thumb.jpg" border="0" alt="Whistler" width="150" height="230" align="right" /></a> When you were first learning about how .NET finalization works, did it just feel <em>wrong</em> to you? It sure did for me. The mechanisms and rules involved with finalizers always felt painfully <a href="http://msdn.microsoft.com/en-us/library/fs2xkftw%28VS.80%29.aspx">over-complicated</a>, <a href="http://www.bluebytesoftware.com/blog/PermaLink.aspx?guid=88e62cdf-5919-4ac7-bc33-20c06ae539ae">hard to get right</a>, and hacky. Here we have this clean managed-memory paradigm that feels great to use. And it’s got a big gnarly barnacle named Finalize growing out of its side that we’re supposed to use to deal with unmanaged resources.</p>
<p>I learned .NET when the beta of 1.0 was out, and at the time Microsoft was putting a lot of effort into educating programmers the difference between native and managed programming to make the switch. “In C++ you’d do <em>this</em>, but in .NET you do <em>this</em>” kind of thing. So practically <em>every </em>article on the CLR talked about finalizers. They often made analogies to C++ destructors. C# even added some ill-advised sugar that converts ~Class() to Finalize() to make us grognards feel more at home.</p>
<p>Finalizers were obviously very important, and so we learned about them. We evolved <a href="http://www.danrigsby.com/blog/index.php/2008/03/15/disposable-base-class/">base classes</a> to help us do the boilerplate work and wished that the .NET languages supported <a href="http://www.re-motion.org/blogs/team/archive/2008/02/20/introducing-mixins-finally.aspx">mixins</a>. But it never felt right to me.</p>
<h2>The Problem With Finalizers</h2>
<p>Recently, after a couple conversations at work, I figured out what’s been bothering me about finalizers. The problem is that <em>we’re using a commodity manager to manage non-commodity resources</em>.</p>
<p>In .NET, raw memory can be treated as a commodity, like a gas tank. We can use it fluidly and at any granularity, and treat it all roughly the same. This is a simplification of course, and there are performance considerations, but they closely map onto the underlying OS and are familiar to everyone.</p>
<p>Yet non-memory resources are not commodities and cannot be treated with a one-size-fits-all pattern. They have semantics and effects far beyond incrementally draining and refilling that gas tank. Each situation, each class, is different, and has different implications that we have to remember. Because of this, we can’t treat these resources in a nondeterministic way without potential hazards.</p>
<p>For example, take a file handle managed by a finalizer. Off the top of my head, there are three adverse effects of an unused handle not finalizing in time:</p>
<ol>
<li>If there are pending writes to the file, then they are lost if the app exits without forcing finalizers to be called.</li>
<li>If the file was opened with restrictive sharing, then other applications cannot manipulate it until the GC gets around to finalizing the file object.</li>
<li>The OS isn’t designed to treat file handles as a commodity, and using them that way can negatively affect performance. We could even run out of file handles because the GC has no idea when there’s pressure in this space (all finalizers are equal).</li>
</ol>
<p>Worse yet, in diagnosing any of the above issues, we also must roll our own tools. System tools such as <a href="http://www.lockhunter.com/">LockHunter</a> and <a href="http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx">Process Explorer</a> have no way of distinguishing which handles are actually in use and will just give us a noisy, useless mess.</p>
<p>And that&#8217;s just a simple file handle example. The situation is obviously worse as more limited and complicated resources are involved like DirectX surfaces or database connections.</p>
<h2>Dispose: Only A Partial Solution</h2>
<p>You might wonder why I’m making a fuss. There’s an obvious answer to the non-determinism, right? Microsoft recognized this problem early in in .NET 1.0 and gave us the <a href="http://msdn.microsoft.com/en-us/library/b1yfkh5e%28VS.71%29.aspx">disposable pattern</a>. It is a standard way of managing resources the old-fashioned way: ‘new’ allocates the resource, and Dispose() frees it. We even have some special syntax that helps automate this:</p>
<pre class="brush: csharp;">
using (var textureMgr = new TextureManager())
using (var texture = textureMgr.AllocTexture())
{
    texture.Fill(Color.White);
}
</pre>
<p>The above is roughly equivalent to:</p>
<pre class="brush: csharp;">
var textureMgr = new TextureManager();
try
{
	texture = textureMgr.AllocTexture();
	try
	{
		texture.Fill(Color.White);
	}
	finally
	{
		texture.Dispose();
	}
}
finally
{
	textureMgr.Dispose();
}
</pre>
<p>This gives us a rough, though somewhat tedious approximation of the <a href="http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization">RAII</a> pattern used universally in C++.</p>
<p>In Microsoft’s .NET classes that wrap unmanaged resources, both patterns are typically used. There is a Dispose system that closes the handle, and a safety Finalize that cleans up if not already done already via Dispose.</p>
<p>So what&#8217;s the big deal? Well, the problem is in (a) knowing when it is necessary to call Dispose, (b) remembering to call it, and (c) updating dependent code when an existing type adds a new IDisposable implementation. It’s easy to miss something and let bugs creep in. For every single ‘new’ call, we must check the type to see if it or one of its parent classes implements IDisposable. If it does, then we must manage the instance directly. This means wrapping allocation in the ‘using’ construct for local temporaries, or <a href="http://stackoverflow.com/questions/661815/how-do-you-prevent-idisposable-from-spreading-to-all-your-classes">implementing IDisposable</a> and forwarding Dispose if contained as a member in another class.</p>
<p>Forgetting to dispose an unmanaged resource can lead to some of the most frustrating and difficult to track down bugs. And the nondeterminism in the underlying system pretty much squares that problem. It’s guaranteed to behave differently in the field than on a development machine.</p>
<p>Every new .NET programmer figures this out quickly when they write their first command line app that opens a file, does something to it, and writes out a new file. They find that, apparently randomly, sometimes the end of the new file is cut off. Forgot to call Dispose to flush and close it eh?</p>
<h2>Most Strategies Not 100% Guaranteed</h2>
<p>It’s not hopeless. We’ve come up with strategies to deal with this. First is knowledge base. Over time, we get a sense for what types of objects tend to implement IDisposable. File handles, database connections and so on, those are easy. Though what about systems written by someone else on your team? Does the source control connection have to get disposed when you’re done with it because it wraps a COM object? For those cases, it’s better to be safe and check for IDisposable until the foreign classes become familiar.</p>
<p>There are also tools that help out. <a href="http://msdn.microsoft.com/en-us/library/bb429476%28VS.80%29.aspx">FxCop</a> can find problems <a href="http://stackoverflow.com/questions/2214605/is-there-a-fxcop-rule-for-local-used-idisposables">that are discoverable</a> via static analysis. <a href="http://www.devexpress.com/Products/Visual_Studio_Add-in/Coding_Assistance/">CodeRush</a> will draw graphical markup for types it detects as IDisposable.</p>
<p>But these strategies still aren’t enough for me. I want <em>absolute certainty</em> that Dispose is called on all unmanaged resources, and not left to the nondeterministic finalizer system to cause latent timing problems.</p>
<p>So I want to propose an additional strategy. It’s pretty simple, actually: consider the finalizer to be a last, and <strong>illegal</strong> resort. Microsoft&#8217;s guidelines say that you should not assume Dispose has been called. I propose the reverse: if the finalizer is called, then there is a bug in the code.</p>
<p>More on this in the next post.</p>
]]></content:encoded>
			<wfw:commentRss>http://scottbilas.com/blog/finalizers-an-incomplete-pattern/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Bracketing Operations With IDisposable</title>
		<link>http://scottbilas.com/blog/bracketing-operations-with-idisposable/</link>
		<comments>http://scottbilas.com/blog/bracketing-operations-with-idisposable/#comments</comments>
		<pubDate>Wed, 10 Feb 2010 05:45:27 +0000</pubDate>
		<dc:creator>Scott</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[trick]]></category>

		<guid isPermaLink="false">http://scottbilas.com/?p=459</guid>
		<description><![CDATA[ I learned a fun little .NET trick today at work, figured I’d pass it along. This is probably a well-known pattern, but I don’t know its name.
The Problem
Say you have a pair of functions that bracket other operations you want to do. For example, you must first call BeginRender() before you call RenderModel(), and [...]]]></description>
			<content:encoded><![CDATA[<p><img style="margin: 0px 0px 10px 10px; display: inline; border: 0px;" title="Carnaval Oruro" src="http://scottbilas.com/wp-content/uploads/2010/02/MG_3046.jpg" border="0" alt="Carnaval Oruro" width="160" height="121" align="right" /> I learned a fun little .NET trick today at work, figured I’d pass it along. This is probably a well-known pattern, but I don’t know its name.</p>
<h2>The Problem</h2>
<p>Say you have a pair of functions that bracket other operations you want to do. For example, you must first call BeginRender() before you call RenderModel(), and after you’re all done, you need to call EndRender(). Another example would be a EnterLock() on a critical section, that must be accompanied by a LeaveLock(). I’ll call these bracketing functions simply “BeginX” and “EndX” for the purposes of this article.</p>
<p>The problem is that the caller must not only remember to call EndX, but must do so even in case of an exception, to avoid blocking the system.</p>
<h2>The Solution: IDisposable</h2>
<p>What we’re doing here, really, is acquiring and releasing a resource. The .NET Framework already has a pattern for that, and it’s called <a href="http://msdn.microsoft.com/en-us/library/system.idisposable.aspx">IDisposable</a>. Ok, that’s not much of a trick in itself. What I learned today was a little twist on the concept.</p>
<p>The trick is simple:</p>
<ol>
<li>Create a private inner class that implements IDisposable.</li>
<li>Return a new’d instance of this class in BeginX.</li>
<li>In the instance’s Dispose(), have it call the private EndX.</li>
<li>Callers can simply wrap the &#8216;handle&#8217; in a using declaration for cleanup.</li>
</ol>
<p>It&#8217;s obvious in retrospect, and it’s clean. The &#8216;using&#8217; guarantees calling EndX even in case of an exception. And in leveraging IDisposable we can build on top of the C# programmer’s instinct to wrap usages of IDisposable objects in ‘using’ constructs. As a fallback, we can rely on tools like <a href="http://www.devexpress.com/Coderush">CodeRush</a> to catch it as we type (or <a href="http://msdn.microsoft.com/en-us/library/bb429476%28VS.80%29.aspx">FxCop</a> as a fallback).</p>
<h2>Implementation</h2>
<p>First, we need a fun little helper base class.</p>
<pre class="brush: csharp;">
public abstract class DisposerBase&lt;T&gt; : IDisposable
{
    bool _disposed;
    T _owner;

    public DisposerBase(T owner)
        { _owner = owner; }

    public void Dispose()
    {
        Debug.Assert(!_disposed);
        _disposed = true;
        OnDispose(_owner);
    }

    protected abstract void OnDispose(T owner);
}
</pre>
<p>Here&#8217;s a sample class that demonstrates the IDisposable-bracket pattern. Note the inner class that has access to private methods, which we use to call EndX. This method is private so that the only way to close the bracket is to call Dispose() on the handle. Simple, straightforward, consistent.</p>
<pre class="brush: csharp;">
public class TransactionManager
{
    bool _inTransaction;

    public IDisposable BeginTransaction()
    {
        Debug.Assert(!_inTransaction);
        Console.WriteLine(&quot;Begin Transaction&quot;);

        _inTransaction = true;

        // ... do other transaction setup here ...

        // caller must dispose this when done
        return new TransactionDisposer(this);
    }

    private void EndTransaction(TransactionDisposer state)
    {
        Debug.Assert(_inTransaction);
        Console.WriteLine(&quot;End Transaction&quot;);

        // ... do transaction cleanup here ...
        // (state could provide more context if needed)

        _inTransaction = false;
    }

    #region TransactionDisposer

    class TransactionDisposer : DisposerBase&lt;TransactionManager&gt;
    {
        // obviously some state could go here
        // (say, for more transactions in flight at once)

        public TransactionDisposer(TransactionManager owner)
            : base(owner) { }

        protected override void OnDispose(TransactionManager owner)
            { owner.EndTransaction(this); }
    }

    #endregion

    public void DoSomeAction(string actionName)
    {
        Debug.Assert(_inTransaction);

        // ... do the action ...
        Console.WriteLine(&quot;  Action performed: &quot; + actionName);
    }
}
</pre>
<p><em>Note that this is a very simple example that only permits one transaction in flight at once.</em> If we wanted to do more, we could have a Dictionary that maps outstanding transactions to pending state, or we could just put the state directly into the TransactionDisposer. I&#8217;ve noted this in the comments.</p>
<p>Now, it’s a bit of typing to implement this disposer, but that’s what <a href="http://msdn.microsoft.com/en-us/library/ms165392%28VS.80%29.aspx">snippets</a> are for, right? Bracketed code like this isn&#8217;t overwhelmingly common either, so it shouldn&#8217;t be a big deal. Still, I have to say I miss my old friend <a href="http://en.wikipedia.org/wiki/C_preprocessor#Macro_definition_and_expansion">#define</a> from the C world sometimes. Not often. I&#8217;m looking forward to a future version of the C# compiler that lets us plug into the <a href="http://en.wikipedia.org/wiki/Abstract_syntax_tree">AST</a> directly and codegen as we go.</p>
<p>Anyway, here is an example usage of this pattern:</p>
<pre class="brush: csharp;">
var transactionManager = new TransactionManager();
using (var handle = transactionManager.BeginTransaction())
{
    transactionManager.DoSomeAction(&quot;action 1&quot;);
}
</pre>
<h2>Implicit Chaining</h2>
<p>There is one interesting benefit that comes from this: <strong>implicit chaining</strong>.</p>
<p>Say you have a higher level class that provides additional functionality within its own BeginX. Perhaps it calls BeginRender() and then immediately sets some default states. Rather than having to create a new inner class to manage the bracketing, you can simply return the result of BeginRender, and the caller will not know the difference.</p>
<p>Let&#8217;s extend the above example in this way.</p>
<pre class="brush: csharp;">
public class RequestManager
{
    TransactionManager _transactionManager;

    public RequestManager(TransactionManager transactionManager)
        { _transactionManager = transactionManager; }

    public IDisposable BeginRequest(string initialActionName)
    {
        var handle = _transactionManager.BeginTransaction();
        _transactionManager.DoSomeAction(initialActionName);
        return handle;
    }
}
</pre>
<p>See how it chains the TransactionManager&#8217;s bracketed calls through itself? We could have gone through the trouble of making an inner RequestDisposer class and a private EndRequest and all that, using the IDisposable from TransactionManager as the state, but why bother? Just chain it along. When the caller disposes the handle, it routes straight through to the TransactionManager, which is all we needed.</p>
<p>Some sample usage:</p>
<pre class="brush: csharp;">
var requestManager = new RequestManager(transactionManager);
using (var handle = requestManager.BeginRequest(&quot;action 2&quot;))
{
    transactionManager.DoSomeAction(&quot;action 3&quot;);
}
</pre>
<p>Of course, if RequestManager has to do anything special in its EndX, then we&#8217;ll have to go and add that inner class after all. It&#8217;s a nice shortcut otherwise.</p>
<p>The output from both examples looks like this:</p>
<pre class="brush: plain;">
Begin Transaction
Action performed: action 1
End Transaction
Begin Transaction
Action performed: action 2
Action performed: action 3
End Transaction
</pre>
<p>Easy huh?</p>
<h2>Performance Implications</h2>
<p>It&#8217;s worth asking what the costs of this method are. <em>How does this compare to simply calling BeginX and EndX?</em></p>
<p>Let&#8217;s consider this sample usage again:</p>
<pre class="brush: csharp;">
using (var handle = transactionManager.BeginTransaction())
{
    transactionManager.DoSomeAction(&quot;action 1&quot;);
}
</pre>
<p>This is <a href="http://en.wikipedia.org/wiki/Syntactic_sugar">syntactic sugar</a> (I loathe this term but it is unfortunately apt) that the compiler translates into something like this:</p>
<pre class="brush: csharp;">
IDisposable handle = transactionManager.BeginTransaction();
try
{
    transactionManager.DoSomeAction(&quot;action 1&quot;);
}
finally
{
    if (handle != null)
        handle.Dispose();
}
</pre>
<p>Note that the runtime does not do anything special with IDisposable types. They are created and collected exactly the same as any other type. And as a result, this is almost identical to what we&#8217;d have to do for a manual BeginX/EndX:</p>
<pre class="brush: csharp;">
transactionManager.BeginTransaction();
try
{
    transactionManager.DoSomeAction(&quot;action 1&quot;);
}
finally
{
    transactionmanager.EndTransaction();
}
</pre>
<p>Now, this is assuming no state needs to be maintained in the handle. If it were, then we&#8217;d have to store it in a local and pass it into EndTransaction, and the BeginX/EndX pattern would almost exactly match the disposer pattern.</p>
<p>So: the cost of the disposer pattern over BeginX/EndX is that an extra object gets new&#8217;d up, with a bit of glue logic that runs. Insignificant, not worth worrying about.</p>
<p>Even if it did have a real cost, I&#8217;d <em>still</em> not worry about it. This is intended to be used in bracket patterns where resources are being allocated and freed. The cost of the underlying resource management is going to mask whatever minor cost the disposer adds.</p>
<p>The cleaner, more maintainable, and statically-analyzable code that results is an easy win.</p>
]]></content:encoded>
			<wfw:commentRss>http://scottbilas.com/blog/bracketing-operations-with-idisposable/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Dungeon Siege Page Posted</title>
		<link>http://scottbilas.com/blog/dungeon-siege-page-posted/</link>
		<comments>http://scottbilas.com/blog/dungeon-siege-page-posted/#comments</comments>
		<pubDate>Wed, 03 Feb 2010 04:49:11 +0000</pubDate>
		<dc:creator>Scott</dc:creator>
				<category><![CDATA[blog]]></category>
		<category><![CDATA[dungeon siege]]></category>

		<guid isPermaLink="false">http://scottbilas.com/blog/dungeon-siege-page-posted/</guid>
		<description><![CDATA[By popular request, I just posted a new page that has everything I could find that I’ve done related to Dungeon Siege. It’s got the good, the bad, and the ugly. A large, memorable chapter of my early game development life.
Until now, this stuff has been scattered all over four different defunct websites in a [...]]]></description>
			<content:encoded><![CDATA[<p>By popular request, I just <a href="http://scottbilas.com/games/dungeon-siege">posted a new page</a> that has everything I could find that I’ve done related to Dungeon Siege. It’s got the good, the bad, and the ugly. A large, memorable chapter of my early game development life.</p>
<p>Until now, this stuff has been scattered all over four different defunct websites in a mess of broken links. This new page fixes all of that for good.</p>
<blockquote><p><a href="http://scottbilas.com/games/dungeon-siege"><img style="border-right-width: 0px; margin: 0px 0px 0px 10px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Dungeon Siege" border="0" alt="Dungeon Siege" align="right" src="http://scottbilas.com/wp-content/uploads/2010/01/image7.png" width="120" height="217" /></a>I worked at Gas Powered Games between November 1999 and October 2003, back when it was a fresh startup. In that time, I lectured and wrote about some of the technology we used to build Dungeon Siege and later projects. I also released specifications for some of the internals of the engine to help the mod community.</p>
<p>This page collects all of my published Dungeon Siege work.</p>
<p><em>…continued <a href="http://scottbilas.com/games/dungeon-siege">here</a></em></p>
</blockquote>
]]></content:encoded>
			<wfw:commentRss>http://scottbilas.com/blog/dungeon-siege-page-posted/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Finally Onto WPF</title>
		<link>http://scottbilas.com/blog/finally-onto-wpf/</link>
		<comments>http://scottbilas.com/blog/finally-onto-wpf/#comments</comments>
		<pubDate>Thu, 14 Jan 2010 15:00:00 +0000</pubDate>
		<dc:creator>Scott</dc:creator>
				<category><![CDATA[wpf]]></category>

		<guid isPermaLink="false">http://scottbilas.com/2010/01/14/finally-onto-wpf/</guid>
		<description><![CDATA[ I’ve been learning WPF for some GUI tools I’m building, and it’s a whole new world. I feel like I’m back with .NET 1.0 in the late 90’s trying to inhale a bunch of new technology and patterns all at once.
It’s pretty exciting, even if I am joining this game very late.
As I work [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://scottbilas.com/wp-content/uploads/2010/01/P1000584.jpg"><img style="border-right-width: 0px; margin: 0px 0px 10px 10px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="In Lima" border="0" alt="In Lima" align="right" src="http://scottbilas.com/wp-content/uploads/2010/01/P1000584_thumb.jpg" width="160" height="106" /></a> I’ve been learning <a href="http://en.wikipedia.org/wiki/Windows_Presentation_Foundation">WPF</a> for some GUI tools I’m building, and it’s a <em>whole new world</em>. I feel like I’m back with .NET 1.0 in the late 90’s trying to inhale a bunch of new technology and patterns all at once.</p>
<p>It’s pretty exciting, even if I am joining this game very late.</p>
<p>As I work in the WPF world (and maybe <a href="http://en.wikipedia.org/wiki/Windows_Communication_Foundation">WCF</a> and other techs as I start messing around with them) I’ll be posting odds and ends here about research I do and dead-end paths I go down.</p>
<h2>Not WinForms++</h2>
<p>The first thing I learned is that <strong>WPF isn’t WinForms++</strong> or even “WinForms in XML”. It lives in an entirely different universe. Though, for folks like me that have been stuck in that old world too long, WPF is initially going to <em>feel</em> like a simple upgrade of an old framework. There are a lot of similar-sounding classes and concepts in the new framework. These are merely false cognates.</p>
<p>I’ve been learning that it’s better for me to enter into new WPF concepts like a 101 student: by reading books and MSDN docs. I haven’t done that in a while. Normally I just bang on code and refine, using <a href="http://www.google.com">Google</a> and <a href="http://www.stackoverflow.com">StackOverflow</a> to guide my way (and <a href="https://addons.mozilla.org/en-US/firefox/addon/12305">surfclarity</a> to filter out spam sites like experts-exchange.com). I’m still doing that as I pick up WPF, but adding on top of it some serious reading.</p>
<p><a href="http://my.safaribooksonline.com/9781590599556"><img style="border-bottom: 0px; border-left: 0px; margin: 0px 10px 0px 0px; display: inline; border-top: 0px; border-right: 0px" title="Pro WPF in C# 2008" border="0" alt="Pro WPF in C# 2008" align="left" src="http://scottbilas.com/wp-content/uploads/2010/01/image.png" width="50" height="88" /></a> <a href="http://my.safaribooksonline.com/9781590599556">Pro WPF in C# 2008</a> (available at <a href="http://www.safaribooksonline.com">Safari</a> where I’m reading it) is my current favorite book for learning WPF concepts. Most books I come across are lame reference manuals disguised as tutorials, or sensationalized drooling over new tech with no real experience to back it up. The author does great things like quickly explaining a cool-sounding WPF concept, then telling you not to use it and why. Not all of WPF turned out to be a good idea, after all.</p>
<p>So, here are some of the key benefits I’ve noticed in the short time I’ve worked in WPF:</p>
<h3>Layout and Composition</h3>
<p>The problem of control layout (wrap, dock, table, stretch, fill, and so on) is <em>solved</em>. It’s nice of WPF to catch up with where HTML has been for a while, though in a much cleaner and more internally consistent way. Later versions of WinForms started to get somewhere with <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.tablelayoutpanel.aspx">TableLayoutPanel</a> and friends, but it’s still the same old underlying framework, where you run into limitations very quickly.</p>
<p>WPF lets you easily nest any control within nearly any other, and has a sensible system for guiding layout containers (attached properties rather than Control-derived least-common-denominator properties). It’s simple, for example, to put a pair of icons and a few checkboxes into each element of a <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.listview.aspx">ListView</a>, and make it look good. <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.listview.aspx">Virtualization</a> is automatic as well, given certain constraints. Trying to make any of that work in old WinForms requires a lot of custom code.</p>
<p><img style="border-bottom: 0px; border-left: 0px; margin: 0px 0px 10px 10px; display: inline; border-top: 0px; border-right: 0px" title="Easy to code, hard to follow" border="0" alt="Easy to code, hard to follow" align="right" src="http://scottbilas.com/wp-content/uploads/2010/01/image1.png" width="150" height="165" /> In fact, it was enough work in WinForms that I tended to avoid doing <em>anything </em>complicated. This led to UI’s that were easier to program but harder to use due to the need to break out elements or hide things behind the ubiquitous “more” or “advanced” buttons. Consider your average Tools|Options dialog and the custom toolwork required to make that work in a Form. This is why “field of checkboxes” settings dialogs proliferate in so many apps (see pic at right).</p>
<p>With WPF I’ve found it easy to not only wire up the initial draft of the UI, but also to go back and do a big reorg without any real trouble, and usually without significantly changing any code. I Just did it three times today, in fact!</p>
<p><em>A Special Note on XAML</em></p>
<p>Layout and composition are now typically done in XML, using Microsoft’s <a href="http://en.wikipedia.org/wiki/Extensible_Application_Markup_Language">XAML</a>. At first I was tentative on XAML compared to <a href="http://en.wikipedia.org/wiki/MXML">MXML</a> due to the total lack of support for writing code inline in the attributes. Well, it turns out that <a href="http://en.wikipedia.org/wiki/Model_View_ViewModel">viewmodels</a> eliminate the need for much of that inline code (with the glaring exception of value converters – more on this in a future post). It’s also probably a good idea to keep code out of the XAML if you’re splitting the work with a designer. Having code in those attributes would not only get in the way, but would be brittle and hard to maintain.</p>
<p>The bottom line is that WinForms’ crazy InitializeComponent is gone. Bye bye merge problems and periodic, inexplicable total reorganization of that function by Visual Studio. Instead, we lay things out hierarchically in nice, simple, consistent, and nearly unreadable XML. Well, that’s what the visual designer is for.</p>
<h3>Data Binding</h3>
<p>I’ll admit I didn’t mess around with data binding much in the WinForms world. It just felt like too much work for what was a simple thing to do by hand. And WPF is vastly more complicated and capable than Forms, so it was intimidating at first.</p>
<p>But in WPF you really need to <em>fully embrace</em> data binding. I suppose it’s possible to do old UI-driven Visual Basic style state management in WPF, by putting everything in the codebehind, but you’re not going to get much support for this. All samples and tutorials you’ll find online use data binding. It really is how the entire system was designed to be used. Data binding is about a lot more than simply tying a textbox to a text string member. It’s about separation of concerns.</p>
<p>Thankfully, it’s not difficult to pick up. There’s some crazy complicated <a href="http://benjismith.net/index.php/2005/09/30/hate-frameworks/">20-levels-deep-stack logic</a> that makes it all work under the hood, but the end result is that you just cover your eyes and type {Binding SomeName} on whatever field you want bound to your viewmodel and it magically works. “Except”, as they say, “when it doesn’t”. So far it’s been rare for me when something fails to bind, or binds to the wrong place, and I’m developing a bag of tricks to debug these issues. I’ll try to post some of these in the future.</p>
<p>Now, about that viewmodel thing. It’s <em>also</em> practically required to embrace the <a href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx">MVVM pattern</a> in building up nontrivial WPF-based UI’s. This is the “separation” I mentioned previously. Now, this takes a lot of practice to figure out and to start applying correctly. It took me about two months to really grok WPF+MVVM. So be sure to budget time to learn and practice this. Read the <a href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx">article</a> I just linked for a good introduction.</p>
<h3>Styling</h3>
<p>The problem of styling controls and windows is hugely improved. It simply isn’t possible to modify controls in WinForms without writing a totally custom solution. WPF takes a big step forward in enabling simple as well as complex styling of the standard controls. You can completely alter the look and visual behavior of any WPF control without a lot of work.</p>
<p><a href="http://www.microsoft.com/expression/products/Blend_Overview.aspx"><img style="border-bottom: 0px; border-left: 0px; margin: 0px 10px 0px 0px; display: inline; border-top: 0px; border-right: 0px" title="Expression Blend 3" border="0" alt="Expression Blend 3" align="left" src="http://scottbilas.com/wp-content/uploads/2010/01/image2.png" width="64" height="85" /></a> And then there’s <a href="http://www.microsoft.com/expression/products/Blend_Overview.aspx">Expression Blend</a>, my new love interest. Blend is a tool for the design and styling of WPF UI’s, and permits dividing responsibilities between engineers writing code and designers building the look &amp; feel. We have this exact split at work, in fact. Engineers will poke out a rough UI, and later on one of the game UI designers will take some time to upgrade elements to look cool and be consistent with the rest of the tool.</p>
<p>Blend has a goofy, nerdy interface, but it’s really growing on me as I use it every day. It’s far from intuitive, but is powerful in terms of designing controls and styles, previewing it all live, live live! in its awesome designer. It can even build your full Visual Studio solution from within itself. I do almost all of my design work within Blend, partially because VS2008’s designer is so awful as to be almost useless (haven’t used 2010’s enough yet to comment) but mostly because it’s more familiar to the Flash programmer within me. What can I say, I like arty tools.</p>
<h3>Rendering</h3>
<p>One of the reasons styling can be done so easily is that WPF doesn’t rely on the underlying OS window manager to draw checkboxes and so on. This removes all limitations on what you can change. If you use a tool like <a href="http://blois.us/Snoop/">Snoop</a> or <a href="http://www.codeproject.com/KB/macros/MoleForVisualStudioEdit.aspx">Mole</a> to take apart a UI control, you can see that every little graphical piece and state of it resolves down to primitive WPF objects that you can inspect.</p>
<p><img style="border-right-width: 0px; margin: 0px 0px 0px 15px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="ResizeGrip taken apart in Blend" border="0" alt="ResizeGrip taken apart in Blend" align="right" src="http://scottbilas.com/wp-content/uploads/2010/01/image6.png" width="125" height="128" /><img style="border-right-width: 0px; margin: 0px 0px 0px 10px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="ResizeGrip control" border="0" alt="ResizeGrip control" align="right" src="http://scottbilas.com/wp-content/uploads/2010/01/image3.png" width="61" height="59" />For fun, I edited the template of the <a href="http://joshsmithonwpf.wordpress.com/cracknet/">ResizeGrip</a> control in Blend to see what makes it tick. This is the little triangular dotted thingy that sits in the lower right corner of most sizable windows. Blend showed me that it’s rendered using a simple brush that has a repeated pattern of gradient squares clipped to a little stair-step box. All vector so it scales nicely.</p>
<p>How does this new rendering model affect Remote Desktop, by the way? Custom-rendered windows typically perform poorly through RDP. Try running Chrome or iTunes through RDP, or nearly any app through VNC, on a low bandwidth VPN connection to see what I mean. In earlier versions of .NET, if a DWM existed on both sides, the WPF graphics primitives would get remoted directly. However, it seems that in .NET 3.5SP1 and newer, <a href="http://blogs.msdn.com/jgoldb/archive/2008/05/15/what-s-new-for-performance-in-wpf-in-net-3-5-sp1.aspx">WPF is remoted completely as bitmaps</a>.</p>
<p>Microsoft is saying that this should actually improve performance in many cases. Well, we can only expect a future of more complex, denser GUI construction (I mean complex in the UI tree sense, not in the end user’s perception of complexity). So the 100%-bitmap-remoting solution may be needed in the long term anyway. But I’m not sure I agree with the timing of this decision. Bitmap remoting so far performs an order of magnitude slower for me than graphic primitive remoting, at least in the everyday apps I use through RDP.</p>
<h2>Bye Bye WinForms</h2>
<p>It’s clear to me that anyone working in WinForms should ditch it as soon as possible in favor of WPF. Rewriting old tools is always a cost-benefit analysis, but for new tools, this is clearly the way to go. Especially if you’re in control of your user environment, such as within the enterprise, where you can force install the framework on every machine.</p>
<p>If you’re still hanging out in the WinForms world, or considering buying an expensive Forms-based UI package to pick up the pace on building UI’s, you really ought to take a hard look at WPF.</p>
<p>Don’t expect to be productive immediately, or even within a month. It will take a while to get used to it, learn the framework, and develop patterns to use in building UI. It’s time well spent. This is clearly the future.</p>
]]></content:encoded>
			<wfw:commentRss>http://scottbilas.com/blog/finally-onto-wpf/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
	</channel>
</rss>
