<?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 &#187; Scott</title>
	<atom:link href="http://scottbilas.com/blog/author/Scott/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>Sat, 17 Sep 2011 23:47:34 +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>Build Conference 2011: Wednesday</title>
		<link>http://scottbilas.com/blog/build-conference-2011-wednesday/</link>
		<comments>http://scottbilas.com/blog/build-conference-2011-wednesday/#comments</comments>
		<pubDate>Sat, 17 Sep 2011 23:02:29 +0000</pubDate>
		<dc:creator>Scott</dc:creator>
				<category><![CDATA[conference]]></category>
		<category><![CDATA[windows8]]></category>

		<guid isPermaLink="false">http://scottbilas.com/?p=568</guid>
		<description><![CDATA[[This is my notes from Wednesday. See Tuesday's Notes.]
Important: some of these are out of date and superceded by later notes I took after talking with Microsofties. I’ve tried to mark them as such where I remember with a [*].
Visual Studio 11
No release date of course, same as Win8. Feels like “definitely not this year”. [...]]]></description>
			<content:encoded><![CDATA[<p><em>[This is my notes from Wednesday. See </em><a href="http://scottbilas.com/blog/build-conference-2011-tuesday/"><em>Tuesday's Notes.</em></a><em>]</em></p>
<p><em>Important: some of these are out of date and superceded by later notes I took after talking with Microsofties. I’ve tried to mark them as such where I remember with a [*].</em></p>
<h2>Visual Studio 11</h2>
<p>No release date of course, same as Win8. Feels like “definitely not this year”. Did you all download the preview yet? It’s available for everybody. Win8 and the dev tools (VS11, Blend 5, etc.) are online.</p>
<p>Anyway, what’s new…</p>
<ul>
<li>After 10 years they finally updated the image editor. Now it supports transparency and DDS’s. </li>
<li>VS has an FBX viewer w/ property editor. Right in the IDE you can open a 3D model, select meshes, set properties like color and transform. </li>
<li>They put a lot of work into a new thing called DGSL that is your typical shader graph.</li>
<ul>
<li>Preview rendering at different stages of the pipeline, things like pins and wires connecting them to output a final render.</li>
<li>Good for the XNA crowd I guess? Seems like a distraction for the VS team. </li>
</ul>
<li>Pix is integrated into VS.</li>
<ul>
<li>You can debug a 3D app, take a frame grab, then in VS walk the drawprim calls backwards from a pixel. Get call stack per graphic event and all that.</li>
<li>Being integrated into VS means that this this will have a nice, consistent UI, yay.</li>
</ul>
<li>There is this great DOM Explorer (JS/HTML only)</li>
<ul>
<li>Reminds me a lot of the tools built into Firebug or Chrome’s dev mode, except it runs through VS.</li>
<li>Even on a server web app you can hover over a rendered web page and it will point you at the aspx line that generated it. </li>
</ul>
<li>Productivity Power Tools are part of VS now. You probably already know this. Well, perhaps they’ll fix some of its many bugs if it’s an in-box addon. </li>
<li>Nice random improvements to the VS UI like categories for Intellisense (“commonly used by you” vs. “all”) and minor new features in snippets.</li>
<ul>
<li>Maybe now R# will pick up this much-needed feature that VisualAssist has had for a while..</li>
</ul>
<li>Await/async is deeply supported in the debugger.</li>
<ul>
<li>Step through async code (like WinRT’s ShowDialogAsync) procedurally without needing to get confused by all the underlying thread context switches. I like. </li>
</ul>
<li>Tons of new unit testing support. Now is the time when I remind myself to look into unit testing again..</li>
<li>The Kernel Debugger can now run from inside of VS. Sure to come in handy next time you’re developing a device driver (har).</li>
<li>Static code analysis is now a plug-in architecture.</li>
<ul>
<li>He talked about, for example, the kernel mode driver validation static analysis tools that just show up as part of the compile.</li>
<li>Works on C++ or C# or whatever.</li>
<li>I expect we’ll see the same type of integration for FxCop/StyleCop</li>
</ul>
<li>Javascript in VS now has a REPL command pane, just like the browsers have had.</li>
<li>Full support for ECMAScript 5. I’m only familiar with 4, which added (I think) static typing. Well, fake static typing. Anyway, now we have 5! That’s 1.0 better than 4!</li>
<li>No word of improving E&amp;C like supporting altering a function containing a lambda..I’m going to ask them about this. <em>[* answer: no]</em></li>
<li>Ooh a nice new color picker for CSS. Probably for Xaml as well.</li>
<li>VS11 projects are going to be the same format as VS2010.</li>
<ul>
<li>No upgrade required, forward/backward compatible. That will make testing the beta on our stuff easier.</li>
</ul>
</ul>
<h2>WinRT (Windows Runtime – the Metro API)</h2>
<ul>
<li>“Language Projection” is what they’re calling the layer between the language and the kernel services. It maps a language onto the underlying API’s, reflection and type system (the metadata).</li>
<ul>
<li>They are dropping the least-common-denomenator “CLI” system and instead are mapping things as close as possible to the language you’re using.</li>
<li>Example: on an array returned by the core, C# uses “.Add()” to add an item, whereas Javascript uses “.append()”. I like this. Least common denominator probably wasn’t working out for them anyway because nobody really cared about making things VB-compatible when writing libraries in C#.</li>
<li>WinRT types are automatically adapted to the language. For example getting an array back from WinRT will come back to C# as an IList&lt;T&gt;, done through adaptors but not by making a new list (no copying). In C++ they have adaptors to get it into STL iterator form, etc.</li>
</ul>
<li>Async is embedded very deeply.</li>
<ul>
<li>Martyn said that in .NET when they provided a sync and an async version of the same function, people would just use the sync version and then get crap behavior and experience.</li>
<li>New stuff heavily encourages use of async, though not sure if that means the sync functions are unavailable <em>[* they are]</em>.</li>
</ul>
<li>New Windows Metadata format that is used sort of like the Reference Assemblies, sounds like, except this metadata IS the OS. Not libraries on top, but the actual Windows API’s.</li>
<ul>
<li>Format is based on .NET type system but extended to meet the new needs.</li>
<li>Metadata catalog is extensible (again, Metro apps only, for custom WinRT objects) but only privately. No publishing of shared assemblies. Not that they are using the word “assembly” any more…</li>
<li>Sharing across apps is done exclusively through “contracts”, which are part of the OS. If you want to communicate across apps it must be done through a preexisting contract, looks like.</li>
</ul>
<li>YAY! A new string type!!! This one is called HSTRING and is probably the 15th string type I’ll have used.</li>
<ul>
<li>It gets mapped onto whatever the local language thinks of as a string but sounds just like a .NET string – immutable, and so does not copied.</li>
</ul>
<li>WinRT is heavily interface driven, as is now common in the rest of the programming world</li>
<ul>
<li>IUnknown is now IInspectable. They said IUnknown confused people or something. Anyway, IInspectable -&gt; ISpecificInterface -&gt; ConcreteClass (runtime, private).</li>
<li>C++ binds statically as usual.</li>
<li>C#/VB binding is mostly static but also uses some runtime metadata (very cheap though)</li>
<li>JS/HTML binding is dynamic dispatch at runtime, works completely through metadata as you expect a dynamic language to operate</li>
</ul>
<li>Some MC++ changes, like “gcnew” is now “ref new”. <em>[* turns out this is not true. See later notes.]</em></li>
</ul>
<h2>Other</h2>
<ul>
<li>Lots and lots of stuff about Azure, which is pretty neat but I’ve heard is very expensive for large-scale use.</li>
<li>Pithy statement I just made up: “swipe is the new right click”.</li>
<li>TFS marches forward.</li>
<ul>
<li>The new stuff looks really cool, and I’d consider using their hosted TFS if I had a small studio. They even support scrum directly.</li>
</ul>
</ul>
<h2>Expo Floor Queries</h2>
<h3>WPF</h3>
<ul>
<li>What&#8217;s New in WPF Version 4.5 Developer Preview: <a href="http://msdn.microsoft.com/library/bb613588(v=VS.110).aspx">http://msdn.microsoft.com/library/bb613588(v=VS.110).aspx</a></li>
<li>WinRT is definitely Metro only.</li>
<ul>
<li>We cannot embed Metro in WPF, and vice versa (well we can, but they said it would be awful, dirty, and please run away).</li>
<li>Metro really is a completely independent sandbox that has little to do with Windows.</li>
<li><em>[* Some of the above is a lie, as I found out on Friday. WinRT is definitely useable outside of Metro. See later notes I’ll post.]</em></li>
</ul>
<li>Very little work has been done in WPF. It still exists! Visual Studio and the Expression suite are all WPF apps and will remain that way. But for 4.5 they focused exclusively on perf and stability. I suppose that’s ok.</li>
<li>I lost track of how many times I’d ask someone about desktop apps (WPF) and would get asked why we didn’t just “rewrite it all” for Metro. Ah, Microsoft, never change!</li>
</ul>
<h3>Blend/VS</h3>
<ul>
<li>The reason Silverlight has data-binding breakpoints is because the Silverlight team put the hooks in there independently and VS was able to use them.</li>
<ul>
<li>Until someone does that for non-SL Xaml (whether Metro or WPF) we will not have this functionality in VS.</li>
</ul>
<li>The reason JS/HTML has such freaking awesome debugging support (like interactive mode) is completely provided by the hooks already developed independently in IE over many years.</li>
<ul>
<li>Again, work that Blend/VS did not have to do.</li>
<li>So they’re waiting for debug hooks in Xaml frameworks, which may never appear. Complicated problem to solve and limited resources/initiative to do it.</li>
</ul>
<li>We should use DynamicResource and not StaticResource as a general rule.</li>
<li>They know that debugging resources sucks.</li>
<ul>
<li>They want to work on the problem. They aren’t working on the problem. They have no plans to do so.</li>
<li>They recommended using DynamicResource (again) and binary-search style commenting out stuff to narrow down problems. Yeah, so, nothing new here.</li>
</ul>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://scottbilas.com/blog/build-conference-2011-wednesday/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Build Conference 2011: Tuesday</title>
		<link>http://scottbilas.com/blog/build-conference-2011-tuesday/</link>
		<comments>http://scottbilas.com/blog/build-conference-2011-tuesday/#comments</comments>
		<pubDate>Fri, 16 Sep 2011 16:41:58 +0000</pubDate>
		<dc:creator>Scott</dc:creator>
				<category><![CDATA[conference]]></category>
		<category><![CDATA[windows8]]></category>

		<guid isPermaLink="false">http://scottbilas.com/?p=565</guid>
		<description><![CDATA[I’ve been at Microsoft’s Build 2011 conference. Over the years I’ve gone to a handful of Microsoft conferences – Gamefest, Meltdown, Gamestock, Windows World (if you go waaay back). Mostly gaming related. Build is the merger of PDC and WinHEC, neither of which I had attended in the past. Unlike the gaming conferences I’ve been [...]]]></description>
			<content:encoded><![CDATA[<p>I’ve been at Microsoft’s Build 2011 conference. Over the years I’ve gone to a handful of Microsoft conferences – Gamefest, Meltdown, Gamestock, Windows World (if you go waaay back). Mostly gaming related. Build is the merger of PDC and WinHEC, neither of which I had attended in the past. Unlike the gaming conferences I’ve been to, Build has serious money behind it. It’s been incredibly well-managed.</p>
<p>I sent out notes about the conference to my team and figured I’d post them here as well in case it would be useful to anyone. Stripping out any Bungie-specific commentary that wouldn’t be generally applicable of course.</p>
<p><em>Important: some of these are out of date and superceded by later notes I took after talking with Microsofties. I’ve tried to mark them as such where I remember with a [*].</em></p>
<h2>Notes From Tuesday</h2>
<p>I’m writing these up while it’s still fresh in my head..</p>
<p>Two big takeaways for me:</p>
<ol>
<li><strong>Windows 8 will actually be really awesome. Seriously.</strong></li>
<li><strong>It won’t matter to production tools developers. Business as usual.</strong></li>
</ol>
<p>As a consumer, I am really looking forward to Windows 8. They did what needed to be done in order to live in the modern world: new API, breaking of backwards compatibility, heavy integration of touch and gestures, complete guidance provided for new design, large library and protocols for connecting apps together, support for web development on the desktop to bring in all those crazy kids, plus some really forward looking design&#8230;</p>
<p>But only for Metro – “the new stuff”. Windows 8 will run all the apps that 7 did, but there are now two classes: <span style="text-decoration: underline;">desktop apps</span> and <span style="text-decoration: underline;">Metro apps</span>. Desktop apps are 3DS Max, Photoshop, Word, Notepad, etc. Metro apps are 100% new. It is a brand new platform in just about every way. Really don’t even need to call it Windows.</p>
<p>Metro has clearly been the focus of Build and therefore Microsoft. So far today, the only thing I heard about ordinary desktop apps is that “they will still work great”. They all run within a context in Metro called “Desktop”, which is already seeming very antiquated, almost like Windows XP Mode was with Vista. Everything MS is talking about here is geared towards Metro. And it’s <em>seriously cool</em>. I look forward to switching all my home machines over to it, especially my girl’s Dell Duo. Win8 is fast, lean, and cool as hell.</p>
<p>So I don’t have much to report on the future of our platform: Win32/64 + WPF/.NET. I’ll be finding out what I can over the next three days.</p>
<p>I did take some notes, though. Here they are in no particular order:</p>
<p><em>Non-Metro:</em></p>
<ul>
<li>No mention of WPF all day. Not even whispered. Is WPF rolled into Silverlight? Is WPF on life support? What about frogs? No word yet.</li>
<li>New C++ standards compliant compiler is shipping with Visual Studio vNext. I saw the “auto” keyword being used for duck typing.</li>
<li>They kept making a big deal about performance as a top priority, over and over again. This is a pillar of Win8.
<ul>
<li>Perf is even more important than in Windows 7 due to touch support, because people are unwilling to put up with any latency whatsoever when using a touch interface. So look for a lot of async support integrated at all levels.</li>
</ul>
</li>
<li>Cider is <span style="text-decoration: underline;">gone</span>. Blend&#8217;s designer is now integrated into Visual Studio. Big yay. Always annoyed me that something would work in one place and not the other, or vice versa. (Now we can have things not work in both places, but at least it will be consistent.)</li>
<li>There’s a new debug view that lets you view parallel stacks of async/TPL tasks as well as the program flow through the tasks. I’m going to ask them if this can be applied to our own scheduling system (or if we should switch to Task in order to take advantage).</li>
<li>Looks like they upgraded the remote debugging, way easier to set up. Even have remote Javascript breakpoints. Definitely won’t need Firebug in this world.
<ul>
<li>There is even a DOM inspector for JS that works over remote debugging. Not only are the UI elements hot as you hover/touch them (like in Snoop or Chrome dev) but you can modify properties on the fly while debugging. Remotely! OMG!</li>
</ul>
</li>
<li>Blend has a crazyass new interactive mode where you can run the app inside of Blend, fully interactive, then pause it on the screen you want to modify and switch to design mode to update the Xaml. Sort of like play-in-editor. (Think Expanders or other state-dependent stuff..a bit of a pain to do right now.)</li>
</ul>
<p><em>Metro:</em></p>
<ul>
<li>XAML is coming to C++ which compiles down to native x86/ARM. Appears to be Managed C++ due to use of ^ ref modifier <em>[* nope]</em>. Makes sense. Don’t know how they’d make any of this work with pure C++.</li>
<li>Thankfully they’re not just copying Apple but fixing a lot of stupid UI problems on the iphonepodpad. My favorite is how they said that the modal rearranging of the home screen is crap and how folders bury things too far. Couldn’t agree more.
<ul>
<li>They are also expanding the “touch language” beyond existing standards of swipe-to-scroll and pinch-to-zoom/rotate. Selection, context bars, app switching..</li>
<li>Totally eliminating the “mouse-ish” stuff like holding down a touch to bring up the context right-click. All of those old Windows 4 Pen-isms are gone. This is why touch sucked on Win7/Vista and is finally usable on 8.</li>
<li><em>BTW if you have any time at all, be sure to watch Jensen Harris’s “big picture” talk from today (should be posted online sometime on Wednesday). I thought it was superb.</em></li>
</ul>
</li>
<li>Metro apps do not have access to Win32 api&#8217;s (such as MessageBox or anything in GDI)! &#8211; no overlapping windows etc
<ul>
<li>All graphics are done through DirectX only.</li>
<li>Metro apps are totally different. Don&#8217;t even have a message loop. <em>[* not true]</em></li>
</ul>
</li>
<li>I saw examples of the “await” and “async” keywords a lot in the demos. This is a key part of delivering high perf UI. Their expectation is that nothing is synchronous.</li>
<li>WinRT (windows runtime, the new API) appears to be a true new API and not just a forms/.net style wrapper.
<ul>
<li>This one appears designed well from the start! Takes advantage of modern design patterns and not held back by obsession with backwards compat.</li>
<li>They said several times that this is definitely not a “layer on top” (like how winforms wrapped up user32 etc.) but talks straight to the kernel. <em>[* mostly true]</em></li>
<li> Fully object-oriented, has reflection, even in C++.</li>
</ul>
</li>
<li>Async support features are implemented in all languages.
<ul>
<li>For example in Javascript, known as “promises”: mediaCapture.initializeAsync().<span style="background-color: #ffff00;">then</span>(function() {&#8230;}) type stuff.</li>
</ul>
</li>
<li>The javascript integration is pretty damn cool. Has data binding even. Hope this brings web devs in to make things for Win8 (obviously MS does too).</li>
<li>Can write native C++ to reference-in from javascript. They gave a demo of HLSL compute shader-based image processing lib written in C++ and used in Metro javascript app. Neato.</li>
<li>Single file .appx package for distro. Yay finally. No more installers! Turns out this is just a zip file too, like Java did with jars. Yay, no more proprietary package formats!</li>
<li>They have a very cool Metro simulator that runs your app through a fake local RDP session that makes it easy to test different rez / dpi / orientation without needing a VM or separate computer with the correct display.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://scottbilas.com/blog/build-conference-2011-tuesday/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Enable SkyDrive for OneNote 2010</title>
		<link>http://scottbilas.com/blog/enable-skydrive-for-onenote-2010/</link>
		<comments>http://scottbilas.com/blog/enable-skydrive-for-onenote-2010/#comments</comments>
		<pubDate>Fri, 15 Jul 2011 16:22:57 +0000</pubDate>
		<dc:creator>Scott</dc:creator>
				<category><![CDATA[quickie]]></category>

		<guid isPermaLink="false">http://scottbilas.com/?p=562</guid>
		<description><![CDATA[Using OneNote 2010?
Trying to create a new notebook on SkyDrive through OneNote and can&#8217;t choose &#8220;Web&#8221; from File &#124; New? Error is &#8220;This service is disabled by policy. Contact your system administrator to enable it.&#8221;?
Solution:
HKEY_CURRENT_USER\Software\Microsoft\Office\Common\WebIntegration\WebIntegrationEnabled=1

]]></description>
			<content:encoded><![CDATA[<p>Using OneNote 2010?</p>
<p>Trying to create a new notebook on SkyDrive through OneNote and can&#8217;t choose &#8220;Web&#8221; from File | New? Error is &#8220;This service is disabled by policy. Contact your system administrator to enable it.&#8221;?</p>
<p>Solution:</p>
<p><code>HKEY_CURRENT_USER\Software\Microsoft\Office\Common\WebIntegration\WebIntegrationEnabled=1<br />
</code></p>
]]></content:encoded>
			<wfw:commentRss>http://scottbilas.com/blog/enable-skydrive-for-onenote-2010/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Quickie: &#8220;NullOr&#8221; For Fluent Null-Friendly Member Access</title>
		<link>http://scottbilas.com/blog/quickie-nullor-for-fluent-null-friendly-member-access/</link>
		<comments>http://scottbilas.com/blog/quickie-nullor-for-fluent-null-friendly-member-access/#comments</comments>
		<pubDate>Mon, 04 Oct 2010 01:53:49 +0000</pubDate>
		<dc:creator>Scott</dc:creator>
				<category><![CDATA[csharp]]></category>
		<category><![CDATA[quickie]]></category>

		<guid isPermaLink="false">http://scottbilas.com/?p=559</guid>
		<description><![CDATA[Are you a fan of C#’s ?? operator like I am? It’s one of the lesser known features of the language, so don’t feel bad if you don’t. I like it because I’m a fan of special language syntax to shorten super common tasks. For example, it lets you change this:

if (obj == null) { [...]]]></description>
			<content:encoded><![CDATA[<p>Are you a fan of C#’s ?? operator like I am? It’s one of the <a href="http://stackoverflow.com/questions/9033/hidden-features-of-c">lesser known features</a> of the language, so don’t feel bad if you don’t. I like it because I’m a fan of special language syntax to shorten super common tasks. For example, it lets you change this:</p>
<pre class="brush: csharp;">
if (obj == null) { obj = defaultValue; }
Console.WriteLine(obj.Name != null ? obj.Name : &quot;&lt;null&gt;&quot;);
</pre>
<p>…into this:</p>
<pre class="brush: csharp;">
obj = obj ?? defaultValue;
Console.WriteLine(obj.Name ?? &quot;&lt;null&gt;&quot;);
</pre>
<p>Awesome. That covers a lot of simple use cases. Now, there&#8217;s another super common case: accessing members of objects that may or may not be null. Like this:</p>
<pre class="brush: csharp;">
var name = obj != null ? obj.Name : &quot;&lt;null&gt;&quot;;
var lname = obj != null &amp;&amp; obj.Name != null ? obj.Name.ToLower() : &quot;&lt;null&gt;&quot;;
</pre>
<p>Yuck.</p>
<p>It would be great if C# had a ?. operator that lets you tersely express “return the member if the object is not null, otherwise return null”. Then we could do this instead:</p>
<pre class="brush: csharp;">
var name = obj?.Name ?? &quot;&lt;null&gt;&quot;;
var lname = obj?.Name?.ToLower() ?? &quot;&lt;null&gt;&quot;;
</pre>
<p>Well, we <em>can</em> do something like this using one of my favorite tools, the <strong>extension method</strong>.</p>
<pre class="brush: csharp;">
public static class ObjectOperations
{
    [DebuggerStepThrough]
    public static TReturn NullOr&lt;TIn, TReturn&gt;(
        this TIn obj, Func&lt;TIn, TReturn&gt; func,
        TReturn elseValue = default(TReturn))
        where TIn : class
    {
        return obj != null ? func(obj) : elseValue;
    }
}
</pre>
<p>NullOr means “this object can be null or we’ll run the function”. Access to the member can be expressed via a lambda, so the above code can now be expressed like this:</p>
<pre class="brush: csharp;">
var name = obj.NullOr(_=&gt;_.Name) ?? &quot;&lt;null&gt;&quot;;
var lname = obj.NullOr(_=&gt;_.Name).NullOr(_=&gt;_.ToLower()) ?? &quot;&lt;null&gt;&quot;;
</pre>
<p>Not bad. It isn’t as terse as I’d like, but it is <a href="http://en.wikipedia.org/wiki/Fluent_interface">fluent</a> and more readable, at least to me. Also, being a lambda, you really can put whatever you like in there. It’s not limited to just member access.</p>
<h2>Extra</h2>
<p>For fun I threw in an “elseValue” clause that lets you provide a default other than null. I haven’t had cause to use this yet, because I find the ?? more readable. Of these, which do you prefer?</p>
<pre class="brush: csharp;">
var name = obj.NullOr(_=&gt;_.Name) ?? &quot;&lt;null&gt;&quot;;
var name = obj.NullOr(_=&gt;_.Name, &quot;&lt;null&gt;&quot;);
</pre>
<p>I think I prefer the ?? version because it expresses “no matter what, if the result of this entire chain is null, use this instead”, whereas the default gets a little lost when it’s part of the final function call. It also is more work to rearrange the clauses, should the order of lookups be changed for whatever reason.</p>
<p><em>(I also <a href="http://stackoverflow.com/questions/271398/what-are-your-favorite-extension-methods-for-c-codeplex-com-extensionoverflow/3842545#3842545">wrote this up</a> at <a href="http://stackoverflow.com/">StackOverflow</a> and earned myself a nice <a href="http://stackoverflow.com/badges/17/necromancer">Necromancer</a> badge.)</em></p>
]]></content:encoded>
			<wfw:commentRss>http://scottbilas.com/blog/quickie-nullor-for-fluent-null-friendly-member-access/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<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" class="broken_link">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[
[Update: Stefan posted in a comment below a much simpler method. I recommend going with this instead of my considerably more complex method.]
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 [...]]]></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" /></p>
<p><em>[<strong>Update:</strong> Stefan posted in a <a href="http://scottbilas.com/blog/automatically-choose-32-or-64-bit-mixed-mode-dlls/#comment-657">comment</a> below a much simpler method. I recommend going with this instead of my considerably more complex method.]</em></p>
<p>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" class="broken_link">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>20</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>6</slash:comments>
		</item>
	</channel>
</rss>

