<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://www.lostechies.com/utility/FeedStylesheets/atom.xsl" media="screen"?><feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en"><title type="html">Solutionizing .NET (Keith Dahlby)</title><subtitle type="html" /><id>http://www.lostechies.com/blogs/dahlbyk/atom.aspx</id><link rel="alternate" type="text/html" href="http://www.lostechies.com/blogs/dahlbyk/default.aspx" /><link rel="self" type="application/atom+xml" href="http://www.lostechies.com/blogs/dahlbyk/atom.aspx" /><generator uri="http://communityserver.org" version="4.1.30929.2835">Community Server</generator><updated>2009-08-18T01:25:00Z</updated><entry><title>posh-git: A PowerShell Environment for Git</title><link rel="alternate" type="text/html" href="/blogs/dahlbyk/archive/2010/03/15/posh-git-a-powershell-environment-for-git.aspx" /><id>/blogs/dahlbyk/archive/2010/03/15/posh-git-a-powershell-environment-for-git.aspx</id><published>2010-03-15T14:31:00Z</published><updated>2010-03-15T14:31:00Z</updated><content type="html">&lt;p&gt;I've been meaning to put together a post about this for a few days, but &lt;a href="http://www.markembling.info/"&gt;Mark Embling&lt;/a&gt; &lt;a title="Git &amp;amp; PowerShell Revisited" href="http://www.markembling.info/view/git-powershell-revisited"&gt;beat me to it&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;I'm a big fan of PowerShell and Git, but had never bothered using them together until Jeremy Skinner's &lt;a title="Using Git with Windows PowerShell" href="http://www.jeremyskinner.co.uk/2010/03/07/using-git-with-windows-powershell/"&gt;post about adding tab completion&lt;/a&gt; pushed me over the edge. &lt;a title="Git &amp;amp; PowerShell Revisited" href="http://www.markembling.info/view/git-powershell-revisited"&gt;Mark's post&lt;/a&gt; has more details, but the short version is that there's a &lt;a href="http://groups.google.com/group/posh-git/"&gt;Google Group&lt;/a&gt; and &lt;a title="posh-git on GitHub" href="http://github.com/dahlbyk/posh-git"&gt;GitHub repository&lt;/a&gt; that we will be using going forward in an effort to make Git and PowerShell work better together.&lt;/p&gt;
&lt;p&gt;Over the coming weeks I'll have more to say about what we've been up to, but if you're at all interested in Git on PowerShell or have your own tips or tricks you'd like to share, please leave a comment or join the group.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;a href="http://www.dotnetkicks.com/kick/?title=posh-git%3a+A+PowerShell+Environment+for+Git&amp;url=http%3a%2f%2fwww.lostechies.com%2fblogs%2fdahlbyk%2farchive%2f2010%2f03%2f15%2fposh-git-a-powershell-environment-for-git.aspx"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.lostechies.com%2fblogs%2fdahlbyk%2farchive%2f2010%2f03%2f15%2fposh-git-a-powershell-environment-for-git.aspx" border="0" alt="Kick It on DotNetKicks.com" /&gt;&lt;/a&gt;&lt;img src="http://www.lostechies.com/aggbug.aspx?PostID=75141" width="1" height="1"&gt;</content><author><name>dahlbyk</name><uri>http://www.lostechies.com/members/dahlbyk/default.aspx</uri></author><category term="posh-git" scheme="http://www.lostechies.com/blogs/dahlbyk/archive/tags/posh-git/default.aspx" /><category term="git" scheme="http://www.lostechies.com/blogs/dahlbyk/archive/tags/git/default.aspx" /><category term="powershell" scheme="http://www.lostechies.com/blogs/dahlbyk/archive/tags/powershell/default.aspx" /></entry><entry><title>SPWeb.AssociatedGroups.Contains Lies</title><link rel="alternate" type="text/html" href="/blogs/dahlbyk/archive/2010/01/27/spweb-associatedgroups-contains-lies.aspx" /><id>/blogs/dahlbyk/archive/2010/01/27/spweb-associatedgroups-contains-lies.aspx</id><published>2010-01-27T11:00:00Z</published><updated>2010-01-27T11:00:00Z</updated><content type="html">&lt;p&gt;While working on &lt;a title="SPExLib Release: These Are A Few Of My Favorite Things" href="http://solutionizing.net/2009/06/01/spexlib-release-these-are-a-few-of-my-favorite-things/"&gt;SPExLib&lt;/a&gt; (several months ago), I revisited &lt;a title="More SharePoint Higher-Order Functions" href="http://solutionizing.net/2009/03/19/more-sharepoint-higher-order-functions/"&gt;this post&lt;/a&gt;, which presented a functional approach to a solution Adam describes &lt;a title="Get SPGroup, If Not Available, Create!" href="http://www.sharepointsecurity.com/blog/sharepoint/sharepoint-2007-development/get-spgroup-if-not-available-create/"&gt;here&lt;/a&gt;. Both posts include logic to add an &lt;code&gt;SPWeb&lt;/code&gt; group association, which most simply could look something like this:&lt;/p&gt;
&lt;pre&gt;SPGroup group = web.SiteGroups[groupName];&lt;br /&gt;if (!web.AssociatedGroups.Contains(group))&lt;br /&gt;{&lt;br /&gt;    web.AssociatedGroups.Add(group);&lt;br /&gt;    web.Update();&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;While testing on a few groups, I noticed that the &lt;code&gt;Contains()&lt;/code&gt; call lies, always returning &lt;code&gt;false&lt;/code&gt;. This behavior can also be verified with PowerShell:&lt;/p&gt;
&lt;pre&gt;PS &amp;gt; $w.AssociatedGroups | ?{ $_.Name -eq 'Designers' } | select Name&lt;br /&gt;&lt;br /&gt;Name&lt;br /&gt;----&lt;br /&gt;Designers&lt;br /&gt;&lt;br /&gt;PS &amp;gt; $g = $w.SiteGroups['Designers']&lt;br /&gt;PS &amp;gt; $w.AssociatedGroups.Contains($g)&lt;br /&gt;False&lt;/pre&gt;
&lt;p&gt;Of course, it's not actually lying&amp;mdash;it just doesn't do what we expect. Behind the scenes, &lt;code&gt;AssociatedGroups&amp;nbsp;&lt;/code&gt; is implemented as a simple &lt;code&gt;List&amp;lt;SPGroup&amp;gt;&lt;/code&gt; that is populated with group objects retrieved by IDs stored in the &lt;code&gt;SPWeb&lt;/code&gt;'s &lt;code&gt;vti_associategroups&lt;/code&gt; property. The problem is that &lt;code&gt;List&amp;lt;T&amp;gt;.Contains()&lt;/code&gt; uses &lt;code&gt;EqualityComparer&amp;lt;T&amp;gt;.Default&lt;/code&gt; to find a suitable match, which defaults to reference equality for reference types like &lt;code&gt;SPGroup&lt;/code&gt; that don't implement &lt;code&gt;IEquatable&amp;lt;T&amp;gt;&lt;/code&gt; or override &lt;code&gt;Equals()&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;To get around this, &lt;a href="http://spexlib.codeplex.com/" title="SharePoint Extensions Lib"&gt;SPExLib&lt;/a&gt; provides a few extension methods to make group collections and &lt;code&gt;SPWeb.AssociatedGroups&lt;/code&gt; easier to work with and more closely obey the &lt;a title="Principle of Least Astonishment - Wikipedia" href="http://en.wikipedia.org/wiki/Principle_of_least_astonishment"&gt;Principle of Least Surprise&lt;/a&gt;:&lt;/p&gt;
&lt;pre&gt;public static bool NameEquals(this SPGroup group, string name)&lt;br /&gt;{&lt;br /&gt;    return string.Equals(group.Name, name, StringComparison.OrdinalIgnoreCase);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public static bool Contains(this SPGroupCollection groups, string name)&lt;br /&gt;{&lt;br /&gt;    return groups.Any&amp;lt;SPGroup&amp;gt;(group =&amp;gt; group.NameEquals(name));&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public static bool HasGroupAssociation(this SPWeb web, string name)&lt;br /&gt;{&lt;br /&gt;    return web.AssociatedGroups.Contains(name);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public static bool HasGroupAssociation(this SPWeb web, SPGroup group)&lt;br /&gt;{&lt;br /&gt;    if (group == null)&lt;br /&gt;        throw new ArgumentNullException("group");&lt;br /&gt;    return web.HasGroupAssociation(group.Name);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public static void EnsureGroupAssociation(this SPWeb web, SPGroup group)&lt;br /&gt;{&lt;br /&gt;    if (web.HasGroupAssociation(group))&lt;br /&gt;        web.AssociatedGroups.Add(group);&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;The code should be pretty self-explanatory. The name comparison logic in &lt;code&gt;NameEquals()&lt;/code&gt;
is written to align with how SharePoint compares group names
internally, though they use their own implementation of case
insensitivity because the framework's isn't good enough. Or something
like that.&lt;/p&gt;
&lt;p&gt;There should be two lessons here:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Don't assume methods that have a notion of equality, like &lt;code&gt;Contains()&lt;/code&gt;, will behave like you expect.&lt;/li&gt;
&lt;li&gt;Use &lt;a href="http://spexlib.codeplex.com/" title="SharePoint Extensions Lib"&gt;SPExLib&lt;/a&gt; and contribute other extensions and helpers you find useful. :)&lt;/li&gt;
&lt;/ol&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;a href="http://www.dotnetkicks.com/kick/?title=SPWeb.AssociatedGroups.Contains+Lies&amp;url=http%3a%2f%2fwww.lostechies.com%2fblogs%2fdahlbyk%2farchive%2f2010%2f01%2f27%2fspweb-associatedgroups-contains-lies.aspx"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.lostechies.com%2fblogs%2fdahlbyk%2farchive%2f2010%2f01%2f27%2fspweb-associatedgroups-contains-lies.aspx" border="0" alt="Kick It on DotNetKicks.com" /&gt;&lt;/a&gt;&lt;img src="http://www.lostechies.com/aggbug.aspx?PostID=51645" width="1" height="1"&gt;</content><author><name>dahlbyk</name><uri>http://www.lostechies.com/members/dahlbyk/default.aspx</uri></author><category term="SPExLib" scheme="http://www.lostechies.com/blogs/dahlbyk/archive/tags/SPExLib/default.aspx" /><category term="Extension Methods" scheme="http://www.lostechies.com/blogs/dahlbyk/archive/tags/Extension+Methods/default.aspx" /><category term="SharePoint" scheme="http://www.lostechies.com/blogs/dahlbyk/archive/tags/SharePoint/default.aspx" /></entry><entry><title>Extension Methods on Types You Own?</title><link rel="alternate" type="text/html" href="/blogs/dahlbyk/archive/2010/01/25/extension-methods-on-types-you-own.aspx" /><id>/blogs/dahlbyk/archive/2010/01/25/extension-methods-on-types-you-own.aspx</id><published>2010-01-25T11:00:00Z</published><updated>2010-01-25T11:00:00Z</updated><content type="html">&lt;p&gt;It's no secret that I'm a fan of using extension methods to make
code more concise and expressive. This is particularly handy for
enhancing APIs outside of your control, from the base class library to
ASP.NET MVC and SharePoint. However, there are certain situations where
it might be useful to use extension methods even though you have the
option to add those methods to the class or interface itself. Consider
this simplified caching interface:&lt;/p&gt;
&lt;pre&gt;public interface ICacheProvider&lt;br /&gt;{&lt;br /&gt;    T Get&amp;lt;T&amp;gt;(string key);&lt;br /&gt;    void Insert&amp;lt;T&amp;gt;(string key, T value);&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;And a simple application of the &lt;a title="Decorator pattern - Wikipedia" href="http://en.wikipedia.org/wiki/Decorator_pattern"&gt;decorator pattern&lt;/a&gt; to implement a cached repository:&lt;/p&gt;
&lt;pre&gt;public class CachedAwesomeRepository : IAwesomeRepository&lt;br /&gt;{&lt;br /&gt;    private readonly IAwesomeRepository awesomeRepository;&lt;br /&gt;    private readonly ICacheProvider cacheProvider;&lt;br /&gt;&lt;br /&gt;    public CachedAwesomeRepository(IAwesomeRepository awesomeRepository, ICacheProvider cacheProvider)&lt;br /&gt;    {&lt;br /&gt;        this.awesomeRepository = awesomeRepository;&lt;br /&gt;        this.cacheProvider = cacheProvider;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public Awesome GetAwesome(string id)&lt;br /&gt;    {&lt;br /&gt;        var awesome = cacheProvider.Get&amp;lt;Awesome&amp;gt;(id);&lt;br /&gt;        if(awesome == null)&lt;br /&gt;            cacheProvider.Insert(id, (awesome = awesomeRepository.GetAwesome(id)));&lt;br /&gt;        return awesome;&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;So far, so good. However, as caching is used more often it becomes
clear that there's a common pattern that we might want to extract:&lt;/p&gt;
&lt;pre&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; T ICacheProvider.GetOrInsert&amp;lt;T&amp;gt;(string key, Func&amp;lt;T&amp;gt; valueFactory)&lt;br /&gt;    {&lt;br /&gt;        T value = Get&amp;lt;T&amp;gt;(key);&lt;br /&gt;        if(value == default(T))&lt;br /&gt;            Insert(key, (value = valueFactory()));&lt;br /&gt;        return value;&lt;br /&gt;    }&lt;/pre&gt;
&lt;p&gt;Which would reduce &lt;code&gt;GetAwesome()&lt;/code&gt; to a single, simple expression:&lt;/p&gt;
&lt;pre&gt;    public Awesome GetAwesome(string id)&lt;br /&gt;    {&lt;br /&gt;        return cacheProvider.GetOrInsert(id, () =&amp;gt; awesomeRepository.GetAwesome(id));&lt;br /&gt;    }&lt;/pre&gt;
&lt;p&gt;Now I just need to decide where &lt;code&gt;GetOrInsert()&lt;/code&gt; lives. Since I control &lt;code&gt;ICacheProvider&lt;/code&gt;,
I could just add another method to the interface and update all its
implementers. However, after starting down this path, I concluded this
was not desirable for a number of reasons:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;The implementation of GetOrInsert within each cache provider was essentially identical.&lt;/li&gt;
&lt;li&gt;Tests using a mocked ICacheProvider now needed to know if the code
under test used GetOrInsert() or Get() + Insert(), coupling the test
too tightly to the implementation. Furthermore, natural tests along the
lines of "Should return cached value" and "Should insert value from
repository if not cached" were replaced with a single
implementation-specific test: "Should return value from GetOrInsert".&lt;/li&gt;
&lt;li&gt;Most importantly, I came to realize that GetOrInsert() really just
isn't something that a cache does, so why should it be part of the
interface?&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;So instead I have a handy &lt;code&gt;GetOrInsert()&lt;/code&gt; extension
method (conversion is left as an exercise for the reader) that I can
use to clean up my caching code without needing to change any of my
cache providers or tests for existing consumers.&lt;/p&gt;
&lt;p&gt;The question is really analogous to whether or not &lt;code&gt;Select()&lt;/code&gt; and &lt;code&gt;Where()&lt;/code&gt; should be part of &lt;code&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/code&gt;. They are certainly useful ways to consume the interface, just as &lt;code&gt;GetOrInsert()&lt;/code&gt; is, but they exist outside of what an &lt;code&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/code&gt; really is.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;a href="http://www.dotnetkicks.com/kick/?title=Extension+Methods+on+Types+You+Own%3f&amp;url=http%3a%2f%2fwww.lostechies.com%2fblogs%2fdahlbyk%2farchive%2f2010%2f01%2f25%2fextension-methods-on-types-you-own.aspx"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.lostechies.com%2fblogs%2fdahlbyk%2farchive%2f2010%2f01%2f25%2fextension-methods-on-types-you-own.aspx" border="0" alt="Kick It on DotNetKicks.com" /&gt;&lt;/a&gt;&lt;img src="http://www.lostechies.com/aggbug.aspx?PostID=51496" width="1" height="1"&gt;</content><author><name>dahlbyk</name><uri>http://www.lostechies.com/members/dahlbyk/default.aspx</uri></author></entry><entry><title>Quick Tip: Parse String to Nullable Value</title><link rel="alternate" type="text/html" href="/blogs/dahlbyk/archive/2010/01/23/quick-tip-parse-string-to-nullable-value.aspx" /><id>/blogs/dahlbyk/archive/2010/01/23/quick-tip-parse-string-to-nullable-value.aspx</id><published>2010-01-23T16:39:00Z</published><updated>2010-01-23T16:39:00Z</updated><content type="html">&lt;p&gt;When you're dealing with a system like SharePoint that returns most
data as strings, it's common to want to parse the data back into a
useful numeric format. The .NET framework offers several options to
achieve this, namely the static methods on &lt;code&gt;System.Convert&lt;/code&gt; and the static &lt;code&gt;Parse()&lt;/code&gt; methods on the various value types. However, these are limited in that they turn &lt;code&gt;null&lt;/code&gt;
string values into the default for the given type (0, false, etc) and
they throw exceptions to indicate failure, which might be a performance
concern.&lt;/p&gt;
&lt;p&gt;Often, a better option is to use the static &lt;code&gt;TryParse()&lt;/code&gt;
method provided by most value types (with the notable exception of
enumerations). These follow the common pattern of returning a boolean
to indicate success and using an &lt;code&gt;out&lt;/code&gt; parameter to return the value. While much better suited for what we're trying to achieve, the &lt;code&gt;TryParse&lt;/code&gt;
pattern requires more plumbing than I care to see most of the time&amp;mdash;I
just want the value. To that end, I put together a simple extension
method to encapsulate the pattern:&lt;/p&gt;
&lt;pre&gt;public delegate bool TryParser&amp;lt;T&amp;gt;(string value, out T result) where T : struct;&lt;br /&gt;&lt;br /&gt;public static T? ParseWith&amp;lt;T&amp;gt;(this string value, TryParser&amp;lt;T&amp;gt; parser) where T : struct&lt;br /&gt;{&lt;br /&gt;    T result;&lt;br /&gt;    if (parser(value, out result))&lt;br /&gt;        return result;&lt;br /&gt;    return null;&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;struct&lt;/code&gt; constraint on &lt;code&gt;T&lt;/code&gt; is required to align with the constraint on the &lt;code&gt;Nullable&amp;lt;T&amp;gt;&lt;/code&gt; returned by the method.&lt;/p&gt;
&lt;p&gt;We can now greatly simplify our efforts to parse nullable values:&lt;/p&gt;
&lt;pre&gt;var myIntPropStr = properties.BeforeProperties["MyIntProp"] as string;&lt;br /&gt;var myIntProp = myPropStr.ParseWith&amp;lt;int&amp;gt;(int.TryParse);&lt;br /&gt;if(myIntProp == null)&lt;br /&gt;    throw new Exception("MyIntProp is empty!");&lt;/pre&gt;
&lt;p&gt;One quirk of this technique is that Visual Studio usually cannot infer &lt;code&gt;T&lt;/code&gt; from just the &lt;code&gt;TryParse&lt;/code&gt;
method because of its multiple overloads. One option would be to write
a dedicated method for each value type, but I would view this as
unnecessary cluttering of the &lt;code&gt;string&lt;/code&gt; type. Your mileage may vary.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;a href="http://www.dotnetkicks.com/kick/?title=Quick+Tip%3a+Parse+String+to+Nullable+Value&amp;url=http%3a%2f%2fwww.lostechies.com%2fblogs%2fdahlbyk%2farchive%2f2010%2f01%2f23%2fquick-tip-parse-string-to-nullable-value.aspx"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.lostechies.com%2fblogs%2fdahlbyk%2farchive%2f2010%2f01%2f23%2fquick-tip-parse-string-to-nullable-value.aspx" border="0" alt="Kick It on DotNetKicks.com" /&gt;&lt;/a&gt;&lt;img src="http://www.lostechies.com/aggbug.aspx?PostID=51432" width="1" height="1"&gt;</content><author><name>dahlbyk</name><uri>http://www.lostechies.com/members/dahlbyk/default.aspx</uri></author></entry><entry><title>Selecting Static Results with Dynamic LINQ</title><link rel="alternate" type="text/html" href="/blogs/dahlbyk/archive/2010/01/23/selecting-static-results-with-dynamic-linq.aspx" /><id>/blogs/dahlbyk/archive/2010/01/23/selecting-static-results-with-dynamic-linq.aspx</id><published>2010-01-23T07:05:00Z</published><updated>2010-01-23T07:05:00Z</updated><content type="html">&lt;p&gt;Dynamic LINQ (DLINQ) is a LINQ extension provided in the &lt;a title="Visual Studio 2008 Samples" href="http://msdn.microsoft.com/en-us/bb330936.aspx"&gt;VS 2008 Samples&lt;/a&gt;. Scott Guthrie provides a good overview here: &lt;a href="http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx"&gt;Dynamic LINQ (Part 1: Using the LINQ Dynamic Query Library)&lt;/a&gt;, but the executive summary is that it implements certain query operations on &lt;code&gt;IQueryable&lt;/code&gt;
(the non-generic variety), with filtering, grouping and projection
specified with strings rather than statically-typed expressions.&lt;/p&gt;
&lt;p&gt;I've never had a use for it, but a &lt;a title="System.LINQ.Dynamic: Select(&amp;rdquo; new (&amp;hellip;)&amp;rdquo;) into a List&amp;lt;T&amp;gt; (or any other enumerable collection of &amp;lt;T&amp;gt;)" href="http://stackoverflow.com/questions/1465700/system-linq-dynamic-select-new-into-a-listt-or-any-other-enumerable"&gt;question on Stack Overflow&lt;/a&gt; caused me to take a second look...&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;...the selected groupbyvalue (Group) will always be a
string, and the sum will always be a double, so I want to be able to
cast into something like a List, where Result is an object with
properties Group (string) and TotalValue (double).&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Before we can solve the problem, let's take a closer look at why it is being asked...&lt;/p&gt;
&lt;h2&gt;DynamicExpression.CreateClass&lt;/h2&gt;
&lt;p&gt;We can use the simplest of dynamic queries to explore a bit:&lt;/p&gt;
&lt;pre&gt;[Test]&lt;br /&gt;public void DLINQ_IdentityProjection_ReturnsDynamicClass()&lt;br /&gt;{&lt;br /&gt;    IQueryable nums = Enumerable.Range(1, 5).AsQueryable();&lt;br /&gt;    IQueryable q = nums.Select("new (it as Value)");&lt;br /&gt;    Type elementType = q.ElementType;&lt;br /&gt;&lt;br /&gt;    Assert.AreEqual("DynamicClass1", elementType.Name);&lt;br /&gt;    CollectionAssert.AreEqual(new[] { typeof(int) },&lt;br /&gt;        elementType.GetProperties().Select(p =&amp;gt; p.PropertyType).ToArray());&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;DLINQ defines a special expression syntax for projection that is used to specify what values should be returned and how. &lt;code&gt;it&lt;/code&gt; refers to the current element, which in our case is an &lt;code&gt;int&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The result in question comes from &lt;code&gt;DynamicQueryable.Select()&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;public static IQueryable Select(this IQueryable source, string selector, params object[] values)&lt;br /&gt;{&lt;br /&gt;    LambdaExpression lambda = DynamicExpression.ParseLambda(source.ElementType, null, selector, values);&lt;br /&gt;    return source.Provider.CreateQuery(&lt;br /&gt;        Expression.Call(&lt;br /&gt;            typeof(Queryable), "Select",&lt;br /&gt;            new Type[] { source.ElementType, lambda.Body.Type },&lt;br /&gt;            source.Expression, Expression.Quote(lambda)));&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;The non-generic return type suggest that the type of the values
returned is unknown at compile time. If we check an element's type at
runtime, we'll see something like &lt;code&gt;DynamicClass1&lt;/code&gt;. Tracing down the stack from &lt;code&gt;DynamicExpression.ParseLambda()&lt;/code&gt;, we eventually find that &lt;code&gt;DynamicClass1&lt;/code&gt; is generated by a call to &lt;code&gt;DynamicExpression.CreateClass()&lt;/code&gt; in &lt;code&gt;ExpressionParser.ParseNew()&lt;/code&gt;. &lt;code&gt;CreateClass()&lt;/code&gt; in turn delegates to a static &lt;code&gt;ClassFactory&lt;/code&gt; which manages a dynamic assembly in the current &lt;code&gt;AppDomain&lt;/code&gt; to hold the new classes, each generated by &lt;code&gt;Reflection.Emit&lt;/code&gt;. The resulting type is then used to generate the &lt;code&gt;MemberInit&lt;/code&gt; expression that constructs the object.&lt;/p&gt;
&lt;h2&gt;Dynamic to Static&lt;/h2&gt;
&lt;p&gt;While dynamic objects are useful in some situations (thus support in
C# 4), in this case we want to use static typing. Let's specify our
result type with a generic method:&lt;/p&gt;
&lt;pre&gt;IQueryable&amp;lt;TResult&amp;gt; Select&amp;lt;TResult&amp;gt;(this IQueryable source, string selector, params object[] values);&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;We just need a mechanism to insert our result type into DLINQ to
supersede the dynamic result. This is surprisingly easy to implement,
as &lt;code&gt;ParseLambda()&lt;/code&gt; already accepts a &lt;code&gt;resultType&lt;/code&gt; argument. We just need to capture it...&lt;/p&gt;
&lt;pre&gt;private Type resultType;&lt;br /&gt;public Expression Parse(Type resultType)&lt;br /&gt;{&lt;br /&gt;&amp;nbsp; &amp;nbsp; this.resultType = resultType;&lt;br /&gt;&amp;nbsp; &amp;nbsp; int exprPos = token.pos;&lt;br /&gt;&amp;nbsp; &amp;nbsp; // ...&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;...and then update &lt;code&gt;ParseNew()&lt;/code&gt; to use the specified type:&lt;/p&gt;
&lt;pre&gt;Expression ParseNew()&lt;br /&gt;{&lt;br /&gt;&amp;nbsp; &amp;nbsp; // ...&lt;br /&gt;&amp;nbsp; &amp;nbsp; NextToken();&lt;br /&gt;&amp;nbsp; &amp;nbsp; Type type = this.resultType ?? DynamicExpression.CreateClass(properties);&lt;br /&gt;&amp;nbsp; &amp;nbsp; MemberBinding[] bindings = new MemberBinding[properties.Count];&lt;br /&gt;&amp;nbsp; &amp;nbsp; for (int i = 0; i &amp;lt; bindings.Length; i++)&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; bindings = Expression.Bind(type.GetProperty(properties.Name), expressions);&lt;br /&gt;&amp;nbsp; &amp;nbsp; return Expression.MemberInit(Expression.New(type), bindings);&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;If &lt;code&gt;resultType&lt;/code&gt; is &lt;code&gt;null&lt;/code&gt;, as it is in the existing &lt;code&gt;Select()&lt;/code&gt; implementation, a &lt;code&gt;DynamicClass&lt;/code&gt; is used instead.&lt;/p&gt;
&lt;p&gt;The generic &lt;code&gt;Select&amp;lt;TResult&amp;gt;&lt;/code&gt; is then completed by referencing &lt;code&gt;TResult&lt;/code&gt; as appropriate:&lt;/p&gt;
&lt;pre&gt;public static IQueryable&amp;lt;TResult&amp;gt; Select&amp;lt;TResult&amp;gt;(this IQueryable source, string selector, params object[] values)&lt;br /&gt;{&lt;br /&gt;&amp;nbsp; &amp;nbsp; LambdaExpression lambda = DynamicExpression.ParseLambda(source.ElementType, &lt;b&gt;typeof(TResult)&lt;/b&gt;, selector, values);&lt;br /&gt;&amp;nbsp; &amp;nbsp; return source.Provider.CreateQuery&lt;b&gt;&amp;lt;TResult&amp;gt;&lt;/b&gt;(&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; Expression.Call(&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; typeof(Queryable), "Select",&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; new Type[] { source.ElementType, &lt;b&gt;typeof(TResult)&lt;/b&gt; },&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; source.Expression, Expression.Quote(lambda)));&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;With the following usage:&lt;/p&gt;
&lt;pre&gt;public class ValueClass { public int Value { get; set; } }&lt;br /&gt;&lt;br /&gt;[Test]&lt;br /&gt;public void DLINQ_IdentityProjection_ReturnsStaticClass()&lt;br /&gt;{&lt;br /&gt;    IQueryable nums = Enumerable.Range(1, 5).AsQueryable();&lt;br /&gt;    IQueryable&amp;lt;ValueClass&amp;gt; q = nums.Select&amp;lt;ValueClass&amp;gt;("new (it as Value)");&lt;br /&gt;    Type elementType = q.ElementType;&lt;br /&gt;&lt;br /&gt;    Assert.AreEqual("ValueClass", elementType.Name);&lt;br /&gt;    CollectionAssert.AreEqual(nums.ToArray(), q.Select(v =&amp;gt; v.Value).ToArray());&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;Note that the property names in &lt;code&gt;TResult&lt;/code&gt; must match those in the &lt;code&gt;Select&lt;/code&gt; query exactly. Changing the query to "new (it as value)" results in an unhandled &lt;code&gt;ArgumentNullException&lt;/code&gt; in the &lt;code&gt;Expression.Bind()&lt;/code&gt; call seen in the for loop of &lt;code&gt;ParseNew()&lt;/code&gt; above, as the "value" property cannot be found.&lt;/p&gt;
&lt;h2&gt;Selecting Anonymous Types&lt;/h2&gt;
&lt;p&gt;So we can select dynamic types or existing named types, but what if
we want to have the benefits of static typing without having to declare
a dedicated &lt;code&gt;ValueClass&lt;/code&gt;, as we can with anonymous types
and normal static LINQ? As a variation on techniques used elsewhere,
let's can define an overload of &lt;code&gt;Select()&lt;/code&gt; that accepts an
instance of the anonymous type whose values we will ignore but using
its type to infer the desired return type. The overload is trivial:&lt;/p&gt;
&lt;pre&gt;public static IQueryable&amp;lt;TResult&amp;gt; Select&amp;lt;TResult&amp;gt;(this IQueryable source, TResult template, string selector, params object[] values)&lt;br /&gt;{&lt;br /&gt;    return source.Select&amp;lt;TResult&amp;gt;(selector, values);&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;With usage looking like this (note the required switch to &lt;code&gt;var q&lt;/code&gt;):&lt;/p&gt;
&lt;pre&gt;[Test]&lt;br /&gt;public void DLINQ_IdentityProjection_ReturnsStaticClass()&lt;br /&gt;{&lt;br /&gt;    IQueryable nums = Enumerable.Range(1, 5).AsQueryable();&lt;br /&gt;    var q = nums.Select(new { Value = 0 }, "new (it as Value)");&lt;br /&gt;    Type elementType = q.ElementType;&lt;br /&gt;&lt;br /&gt;    Assert.IsTrue(elementType.Name.Contains("AnonymousType"));&lt;br /&gt;    CollectionAssert.AreEqual(nums.ToArray(), q.Select(v =&amp;gt; v.Value).ToArray());&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;However, if we try the above we encounter an unfortunate error:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;The property 'Int32 Value' has no 'set' accessor&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;As you may or may not know, anonymous types in C# are immutable
(modulo changes to objects they reference), with their values set
through a compiler-generated constructor. (I'm not sure if this is true
in VB.) With this knowledge in hand, we can update &lt;code&gt;ParseNew()&lt;/code&gt; to check if &lt;code&gt;resultType&lt;/code&gt; has such a constructor that we could use instead:&lt;/p&gt;
&lt;pre&gt;    // ...&lt;br /&gt;    Type type = this.resultType ?? DynamicExpression.CreateClass(properties);&lt;br /&gt;&lt;br /&gt;    var propertyTypes = type.GetProperties().Select(p =&amp;gt; p.PropertyType).ToArray();&lt;br /&gt;    var ctor = type.GetConstructor(propertyTypes);&lt;br /&gt;    if (ctor != null)&lt;br /&gt;        return Expression.New(ctor, expressions);&lt;br /&gt;&lt;br /&gt;    MemberBinding[] bindings = new MemberBinding[properties.Count];&lt;br /&gt;    for (int i = 0; i &amp;lt; bindings.Length; i++)&lt;br /&gt;        bindings = Expression.Bind(type.GetProperty(properties.Name), expressions);&lt;br /&gt;    return Expression.MemberInit(Expression.New(type), bindings);&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;And with that we can now project from a dynamic query onto static
types, both named and anonymous, with a reasonably natural interface.&lt;/p&gt;
&lt;p&gt;Due to licensing I can't post the full example, but if you're at all
curious about Reflection.Emit or how DLINQ works I would encourage you
to dive in and let us know what else you come up with. Things will get
even more interesting with the combination of LINQ, the DLR and C# 4's
dynamic in the coming months.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;a href="http://www.dotnetkicks.com/kick/?title=Selecting+Static+Results+with+Dynamic+LINQ&amp;url=http%3a%2f%2fwww.lostechies.com%2fblogs%2fdahlbyk%2farchive%2f2010%2f01%2f23%2fselecting-static-results-with-dynamic-linq.aspx"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.lostechies.com%2fblogs%2fdahlbyk%2farchive%2f2010%2f01%2f23%2fselecting-static-results-with-dynamic-linq.aspx" border="0" alt="Kick It on DotNetKicks.com" /&gt;&lt;/a&gt;&lt;img src="http://www.lostechies.com/aggbug.aspx?PostID=51414" width="1" height="1"&gt;</content><author><name>dahlbyk</name><uri>http://www.lostechies.com/members/dahlbyk/default.aspx</uri></author><category term="LINQ" scheme="http://www.lostechies.com/blogs/dahlbyk/archive/tags/LINQ/default.aspx" /><category term="Expression Trees" scheme="http://www.lostechies.com/blogs/dahlbyk/archive/tags/Expression+Trees/default.aspx" /><category term="DLINQ" scheme="http://www.lostechies.com/blogs/dahlbyk/archive/tags/DLINQ/default.aspx" /><category term="Stack Overflow" scheme="http://www.lostechies.com/blogs/dahlbyk/archive/tags/Stack+Overflow/default.aspx" /></entry><entry><title>HTTP Error Codes in WatiN 1.3</title><link rel="alternate" type="text/html" href="/blogs/dahlbyk/archive/2010/01/12/http-error-codes-in-watin-1-3.aspx" /><id>/blogs/dahlbyk/archive/2010/01/12/http-error-codes-in-watin-1-3.aspx</id><published>2010-01-12T05:11:00Z</published><updated>2010-01-12T05:11:00Z</updated><content type="html">&lt;p&gt;One of the biggest surprises when I started working with WatiN was
the omission of a mechanism to check for error conditions. A partial
solution using a subclass has been &lt;a title="Catching server errors with WatiN: redux" href="http://www.bryancook.net/2008/07/catching-server-errors-with-watin-redux.html"&gt;posted&lt;/a&gt;
before, but it doesn't quite cover all the bases. Specifically, it's
missing a mechanism to attach existing Internet Explorer instances to
objects of the enhanced subtype. Depending on the site under test's use
of pop-ups, this could be a rather severe limitation. So let's see how
we can fix it.&lt;/p&gt;
&lt;p&gt;As &lt;a href="http://watin.sourceforge.net/"&gt;WatiN&lt;/a&gt; is open source, one option is to just patch the existing implementation to include the desired behavior. I've uploaded a &lt;a title="gist: WatiN 1.3.1 - HTTP ErrorCode.patch" href="http://gist.github.com/274920"&gt;patch with tests here&lt;/a&gt;, but the gist of the patch is quite similar to the solution referenced above:&lt;/p&gt;
&lt;pre&gt;protected void AttachEventHandlers()&lt;br /&gt;{&lt;br /&gt;    ie.BeforeNavigate2 += (object pDisp, ref object URL, ref object Flags, ref object TargetFrameName, ref object PostData, ref object Headers, ref bool Cancel) =&amp;gt;&lt;br /&gt;    {&lt;br /&gt;        ErrorCode = null;&lt;br /&gt;    };&lt;br /&gt;    ie.NavigateError += (object pDisp, ref object URL, ref object Frame, ref object StatusCode, ref bool Cancel) =&amp;gt;&lt;br /&gt;    {&lt;br /&gt;        ErrorCode = (HttpStatusCode)StatusCode;&lt;br /&gt;    };&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;/// &amp;lt;summary&amp;gt;&lt;br /&gt;/// HTTP Status Code of last error, or null if the last request was successful&lt;br /&gt;/// &amp;lt;/summary&amp;gt;&lt;br /&gt;public HttpStatusCode? ErrorCode&lt;br /&gt;{&lt;br /&gt;    get;&lt;br /&gt;    private set;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;Before every request we clear out the error code, with errors captured as an enum value borrowed from System.Net.&lt;/p&gt;
&lt;p&gt;We complete the patch by placing calls to our &lt;code&gt;AttachEventHandlers()&lt;/code&gt; method in two places:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;The constructor that accepts an existing SHDocVw.InternetExplorer handle.&lt;/li&gt;
&lt;li&gt;The CreateNewIEAndGoToUri() method used by every other constructor.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;At this point we can now assert success:&lt;/p&gt;
&lt;pre&gt;using (IE ie = new IE("http://solutionizing.net/"))&lt;br /&gt;{&lt;br /&gt;    Assert.That(ie.ErrorCode, Is.Null);&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;Or specific kinds of failure:&lt;/p&gt;
&lt;pre&gt;using (IE ie = new IE("http://solutionizing.net/4040404040404"))&lt;br /&gt;{&lt;br /&gt;    Assert.That(ie.ErrorCode, Is.EqualTo(HttpStatusCode.NotFound));&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;See the patch above for a more complete set of example tests.&lt;/p&gt;
&lt;h2&gt;Private Strikes Again&lt;/h2&gt;
&lt;p&gt;It's wonderful that we have the option to make our own patched build
with the desired behavior, but what if we would rather use the binary
distribution? Well through the magic of inheritance we can get most of
the way there pretty easily:&lt;/p&gt;
&lt;pre&gt;public class MyIE : IE&lt;br /&gt;{&lt;br /&gt;    public MyIE()&lt;br /&gt;    {&lt;br /&gt;        Initialize();&lt;br /&gt;    }&lt;br /&gt;    public MyIE(object shDocVwInternetExplorer)&lt;br /&gt;        : base(shDocVwInternetExplorer)&lt;br /&gt;    {&lt;br /&gt;        Initialize();&lt;br /&gt;    }&lt;br /&gt;    public MyIE(string url)&lt;br /&gt;        : base(url)&lt;br /&gt;    {&lt;br /&gt;        Initialize();&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // Remaining c'tors left as an exercise&lt;br /&gt;&lt;br /&gt;    // Property named ie for consistency with the private field in the parent&lt;br /&gt;    protected InternetExplorer ie&lt;br /&gt;    {&lt;br /&gt;        get { return (InternetExplorer)InternetExplorer; }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    protected void Initialize()&lt;br /&gt;    {&lt;br /&gt;        AttachEventHandlers();&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // AttachEventHandlers() and ErrorCode as defined above&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;But as I suggested before, this is where we run into a bit of a snag. The &lt;code&gt;IE&lt;/code&gt; class also provides a set of static &lt;code&gt;AttachToIE()&lt;/code&gt; methods that, as their name suggests, return an &lt;code&gt;IE&lt;/code&gt;
object for an existing Internet Explorer window. These static methods
have the downside that they are hard-coded to return objects of type &lt;code&gt;IE&lt;/code&gt;, not our enhanced &lt;code&gt;MyIE&lt;/code&gt;
type. And because all the relevant helper methods are private and not
designed for reuse, we have no choice but to pull them into our
subclass in their entirety:&lt;/p&gt;
&lt;pre&gt;    public new static MyIE AttachToIE(BaseConstraint findBy)&lt;br /&gt;    {&lt;br /&gt;        return findIE(findBy, Settings.AttachToIETimeOut, true);&lt;br /&gt;    }&lt;br /&gt;    public new static MyIE AttachToIE(BaseConstraint findBy, int timeout)&lt;br /&gt;    {&lt;br /&gt;        return findIE(findBy, timeout, true);&lt;br /&gt;    }&lt;br /&gt;    public new static MyIE AttachToIENoWait(BaseConstraint findBy)&lt;br /&gt;    {&lt;br /&gt;        return findIE(findBy, Settings.AttachToIETimeOut, false);&lt;br /&gt;    }&lt;br /&gt;    public new static MyIE AttachToIENoWait(BaseConstraint findBy, int timeout)&lt;br /&gt;    {&lt;br /&gt;        return findIE(findBy, timeout, false);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private static MyIE findIE(BaseConstraint findBy, int timeout, bool waitForComplete)&lt;br /&gt;    {&lt;br /&gt;        SHDocVw.InternetExplorer internetExplorer = findInternetExplorer(findBy, timeout);&lt;br /&gt;&lt;br /&gt;        if (internetExplorer != null)&lt;br /&gt;        {&lt;br /&gt;            MyIE ie = new MyIE(internetExplorer);&lt;br /&gt;            if (waitForComplete)&lt;br /&gt;            {&lt;br /&gt;                ie.WaitForComplete();&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            return ie;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        throw new IENotFoundException(findBy.ConstraintToString(), timeout);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    protected static SHDocVw.InternetExplorer findInternetExplorer(BaseConstraint findBy, int timeout)&lt;br /&gt;    {&lt;br /&gt;        Logger.LogAction("Busy finding Internet Explorer matching constriant " + findBy.ConstraintToString());&lt;br /&gt;&lt;br /&gt;        SimpleTimer timeoutTimer = new SimpleTimer(timeout);&lt;br /&gt;&lt;br /&gt;        do&lt;br /&gt;        {&lt;br /&gt;            Thread.Sleep(500);&lt;br /&gt;&lt;br /&gt;            SHDocVw.InternetExplorer internetExplorer = findInternetExplorer(findBy);&lt;br /&gt;&lt;br /&gt;            if (internetExplorer != null)&lt;br /&gt;            {&lt;br /&gt;                return internetExplorer;&lt;br /&gt;            }&lt;br /&gt;        } while (!timeoutTimer.Elapsed);&lt;br /&gt;&lt;br /&gt;        return null;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private static SHDocVw.InternetExplorer findInternetExplorer(BaseConstraint findBy)&lt;br /&gt;    {&lt;br /&gt;        ShellWindows allBrowsers = new ShellWindows();&lt;br /&gt;&lt;br /&gt;        int browserCount = allBrowsers.Count;&lt;br /&gt;        int browserCounter = 0;&lt;br /&gt;&lt;br /&gt;        IEAttributeBag attributeBag = new IEAttributeBag();&lt;br /&gt;&lt;br /&gt;        while (browserCounter &amp;lt; browserCount)&lt;br /&gt;        {&lt;br /&gt;            attributeBag.InternetExplorer = (SHDocVw.InternetExplorer) allBrowsers.Item(browserCounter);&lt;br /&gt;&lt;br /&gt;            if (findBy.Compare(attributeBag))&lt;br /&gt;            {&lt;br /&gt;                return attributeBag.InternetExplorer;&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            browserCounter++;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        return null;&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;The original version of the first &lt;code&gt;findInternetExplorer()&lt;/code&gt; is private. Were it protected instead, we would only have had to implement our own &lt;code&gt;findIE()&lt;/code&gt; to wrap the found &lt;code&gt;InternetExplorer&lt;/code&gt; object in our subtype.&lt;/p&gt;
&lt;p&gt;I won't go so far as to say private methods are a &lt;a title="Private Methods are a Code Smell" href="http://kent.spillner.org/blog/work/2009/11/12/private-methods-stink.html"&gt;code smell&lt;/a&gt;, but they certainly can make the O in &lt;a title="Open/Closed Principle" href="http://en.wikipedia.org/wiki/Open/closed_principle"&gt;OCP&lt;/a&gt; more difficult to achieve.&lt;/p&gt;
&lt;p&gt;So there you have it, two different techniques for accessing HTTP
error codes in WatiN 1.3. At some point I'll look at adding similar
functionality to 2.0, if it's not already there. And if someone on the
project team see this, feel free to run with it.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;a href="http://www.dotnetkicks.com/kick/?title=HTTP+Error+Codes+in+WatiN+1.3&amp;url=http%3a%2f%2fwww.lostechies.com%2fblogs%2fdahlbyk%2farchive%2f2010%2f01%2f12%2fhttp-error-codes-in-watin-1-3.aspx"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.lostechies.com%2fblogs%2fdahlbyk%2farchive%2f2010%2f01%2f12%2fhttp-error-codes-in-watin-1-3.aspx" border="0" alt="Kick It on DotNetKicks.com" /&gt;&lt;/a&gt;&lt;img src="http://www.lostechies.com/aggbug.aspx?PostID=47158" width="1" height="1"&gt;</content><author><name>dahlbyk</name><uri>http://www.lostechies.com/members/dahlbyk/default.aspx</uri></author><category term="testing" scheme="http://www.lostechies.com/blogs/dahlbyk/archive/tags/testing/default.aspx" /><category term="WatiN" scheme="http://www.lostechies.com/blogs/dahlbyk/archive/tags/WatiN/default.aspx" /></entry><entry><title>Script to Enable HTTP Compression (Gzip/Deflate) in IIS 6</title><link rel="alternate" type="text/html" href="/blogs/dahlbyk/archive/2010/01/08/script-to-enable-http-compression-gzip-deflate-in-iis-6.aspx" /><id>/blogs/dahlbyk/archive/2010/01/08/script-to-enable-http-compression-gzip-deflate-in-iis-6.aspx</id><published>2010-01-08T05:09:00Z</published><updated>2010-01-08T05:09:00Z</updated><content type="html">&lt;p&gt;One of the easiest ways to improve web site performance is to enable &lt;a href="http://en.wikipedia.org/wiki/HTTP_compression"&gt;HTTP compression&lt;/a&gt; (often referred to as GZIP compression), which trades CPU time to compress content for a reduced payload delivered over the wire. In the vast majority of cases, the trade-off is a good one.

When implementing HTTP compression, your content will break down into three categories:
&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Content that should not be compressed because it is already compressed: images, PDF files, audio, video, etc.&lt;/li&gt;
&lt;li&gt;Static content that can be compressed once and cached for later.&lt;/li&gt;
&lt;li&gt;Dynamic content that needs to be compressed for every request.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
Excluding already-compressed content will need to be considered regardless of the techniques used to compress categories 2 and 3.

Since &lt;a title="Using HTTP Compression On Your IIS 5.0 Web Site" href="http://technet.microsoft.com/en-us/library/bb742379.aspx"&gt;version 5&lt;/a&gt;, IIS has included support for both kinds of HTTP compression. This can be enabled through the management interface, but you will almost certainly want to tweak the default configuration in the metabase (see script below). While IIS works great for compressing static files, its extension-based configuration is rather limited when serving up dynamic content, especially if you don't use extensions (as with most ASP.NET MVC routes) or you serve dynamic content that should not be compressed. A better solution is provided in &lt;a href="http://blowery.org/httpcompress/"&gt;HttpCompress&lt;/a&gt; by Ben Lowery, a configurable HttpModule that allows content to be excluded from compression by MIME type. A standard configuration might look something like this:
&lt;/p&gt;
&lt;pre&gt;&amp;lt;configuration&amp;gt;&lt;br /&gt;  ...&lt;br /&gt;  &amp;lt;blowery.web&amp;gt;&lt;br /&gt;    &amp;lt;httpCompress preferredAlgorithm="gzip" compressionLevel="normal"&amp;gt;&lt;br /&gt;      &amp;lt;excludedMimeTypes&amp;gt;&lt;br /&gt;        &amp;lt;add type="image/jpeg" /&amp;gt;&lt;br /&gt;        &amp;lt;add type="image/png" /&amp;gt;&lt;br /&gt;        &amp;lt;add type="image/gif" /&amp;gt;&lt;br /&gt;        &amp;lt;add type="application/pdf" /&amp;gt;&lt;br /&gt;      &amp;lt;/excludedMimeTypes&amp;gt;&lt;br /&gt;      &amp;lt;excludedPaths&amp;gt;&amp;lt;/excludedPaths&amp;gt;&lt;br /&gt;    &amp;lt;/httpCompress&amp;gt;&lt;br /&gt;  &amp;lt;/blowery.web&amp;gt;&lt;br /&gt;  ...&lt;br /&gt;&amp;lt;/configuration&amp;gt;&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;
To supplement the compressed dynamic content, you should also enable static compression for the rest of your not-already-compressed content. The script should be pretty self-explanatory, but I'll draw attention to a few things:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The &lt;b&gt;tcfpath&lt;/b&gt; variable at the top is currently set to IIS's default location, which you are free to change.&lt;/li&gt;
&lt;li&gt;The &lt;b&gt;extlist&lt;/b&gt; variable accepts a space-delimited list of file extensions that &lt;i&gt;should&lt;/i&gt; be compressed. Again, only include files types that are not already compressed, as recompressing a file wastes cycles and can actually make some files &lt;i&gt;larger&lt;/i&gt;.&lt;/li&gt;
&lt;li&gt;There are a few other &lt;a title="Metabase Property Reference" href="http://technet.microsoft.com/en-us/library/cc778146%28WS.10%29.aspx"&gt;metabase properties&lt;/a&gt; that can also be set, including compression level, but these are the bare minimum.&lt;/li&gt;
&lt;li&gt;I have been told repeatedly that IISRESET should be sufficient to apply the metabase changes, but I could not get it to work as consistently as manually restarting the IIS Admin Service &amp;mdash; YMMV.&lt;/li&gt;
&lt;li&gt;If all goes well, the nice arrow at the end will point to &lt;b&gt;True&lt;/b&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
If you have anything else to add, or have problems with the script, please let me know.
&lt;/p&gt;
&lt;pre&gt;@echo off&lt;br /&gt;set adsutil=C:\Inetpub\AdminScripts\adsutil.vbs&lt;br /&gt;set tcfpath=%windir%\IIS Temporary Compressed Files&lt;br /&gt;set extlist=css htm html js txt xml&lt;br /&gt;&lt;br /&gt;mkdir "%tcfpath%"&lt;br /&gt;&lt;br /&gt;echo Ensure IIS_WPG has Full Control on %tcfpath%&lt;br /&gt;&lt;br /&gt;explorer "%tcfpath%\.."&lt;br /&gt;pause&lt;br /&gt;&lt;br /&gt;cscript.exe %adsutil% set w3svc/Filters/Compression/Parameters/HcDoStaticCompression true &lt;br /&gt;cscript.exe %adsutil% set w3svc/Filters/Compression/Parameters/HcCompressionDirectory "%tcfpath%"&lt;br /&gt;cscript.exe %adsutil% set w3svc/Filters/Compression/DEFLATE/HcFileExtensions %extlist%&lt;br /&gt;cscript.exe %adsutil% set w3svc/Filters/Compression/GZIP/HcFileExtensions %extlist%&lt;br /&gt;&lt;br /&gt;echo Restart IIS Admin Service - IISRESET does not seem to work&lt;br /&gt;pause&lt;br /&gt;&lt;br /&gt;echo Close Services to continue...&lt;br /&gt;Services.msc&lt;br /&gt;&lt;br /&gt;cscript.exe %adsutil% get w3svc/Filters/Compression/Parameters/HcDoStaticCompression&lt;br /&gt;&lt;br /&gt;echo Should be True -----------------------------^^&lt;br /&gt;&lt;br /&gt;pause&lt;br /&gt;&lt;/pre&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;a href="http://www.dotnetkicks.com/kick/?title=Script+to+Enable+HTTP+Compression+(Gzip%2fDeflate)+in+IIS+6&amp;url=http%3a%2f%2fwww.lostechies.com%2fblogs%2fdahlbyk%2farchive%2f2010%2f01%2f08%2fscript-to-enable-http-compression-gzip-deflate-in-iis-6.aspx"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.lostechies.com%2fblogs%2fdahlbyk%2farchive%2f2010%2f01%2f08%2fscript-to-enable-http-compression-gzip-deflate-in-iis-6.aspx" border="0" alt="Kick It on DotNetKicks.com" /&gt;&lt;/a&gt;&lt;img src="http://www.lostechies.com/aggbug.aspx?PostID=46537" width="1" height="1"&gt;</content><author><name>dahlbyk</name><uri>http://www.lostechies.com/members/dahlbyk/default.aspx</uri></author><category term="Performance" scheme="http://www.lostechies.com/blogs/dahlbyk/archive/tags/Performance/default.aspx" /><category term="HTTP Compression" scheme="http://www.lostechies.com/blogs/dahlbyk/archive/tags/HTTP+Compression/default.aspx" /><category term="IIS" scheme="http://www.lostechies.com/blogs/dahlbyk/archive/tags/IIS/default.aspx" /></entry><entry><title>Is Functional Abstraction Too Clever?</title><link rel="alternate" type="text/html" href="/blogs/dahlbyk/archive/2009/10/17/is-functional-abstraction-too-clever.aspx" /><id>/blogs/dahlbyk/archive/2009/10/17/is-functional-abstraction-too-clever.aspx</id><published>2009-10-17T07:29:00Z</published><updated>2009-10-17T07:29:00Z</updated><content type="html">&lt;p&gt;I received a rather interesting comment on a recent Stack Overflow answer:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;This code seems too clever by half. Is it art? &amp;ndash;&amp;nbsp;&lt;a href="http://stackoverflow.com/users/21365/peterallenwebb"&gt;PeterAllenWebb&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;The &lt;a title="Split value in 24 randomly sized parts using C#" href="http://stackoverflow.com/questions/1581394/split-value-in-24-randomly-sized-parts-using-c/1581464#1581464"&gt;code in question&lt;/a&gt; was a functional solution to an algorithm described approximately as follows:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Draw &lt;i&gt;n&lt;/i&gt;&amp;minus;1 numbers at random, in the range 1 to &lt;i&gt;m&lt;/i&gt;&amp;minus;1. Add 0 and &lt;i&gt;m&lt;/i&gt; to the list and order these numbers. The difference between each two consecutive numbers gives you a return value.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Which I solved like this, with &lt;i&gt;n&lt;/i&gt; = &lt;code&gt;slots&lt;/code&gt; and &lt;i&gt;m&lt;/i&gt; = &lt;code&gt;max&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;static int[] GetSlots(int slots, int max)&lt;br /&gt;{&lt;br /&gt;&amp;nbsp; &amp;nbsp; return new Random().Values(1, max)&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;.Take(slots - 1)&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;.Append(0, max)&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;.OrderBy(i =&amp;gt; i)&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;.Pairwise((x, y) =&amp;gt; y - x)&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;.ToArray();&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;Using a few extension methods:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;Values()&lt;/code&gt; returns an infinite sequence of random values within the specified range.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Append()&lt;/code&gt; takes a &lt;code&gt;params&lt;/code&gt; array and appends its arguments to the original sequence.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Pairwise()&lt;/code&gt; generates a sequence from calculations on pairs of consecutive elements in the original sequence.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;I can see how one would think the code is clever; however, I'm not sure what would qualify it as &lt;i&gt;too&lt;/i&gt; clever. Every method call has a well-defined purpose and maps directly to part of the original algorithm:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;From random numbers in the range 1 to &lt;i&gt;m&lt;/i&gt;&amp;minus;1...&lt;/li&gt;
&lt;li&gt;...draw &lt;i&gt;n&lt;/i&gt;&amp;minus;1.&lt;/li&gt;
&lt;li&gt;Add 0 and &lt;i&gt;m&lt;/i&gt; to the list...&lt;/li&gt;
&lt;li&gt;...and order these numbers.&lt;/li&gt;
&lt;li&gt;The difference between each two consecutive numbers...&lt;/li&gt;
&lt;li&gt;...gives you a return value [in the array].&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;As far as I'm concerned, a solution couldn't get much clearer than
this, but that's easy enough for me to say&amp;mdash;what do you think? Is there
a better way to express the algorithm? Would an imperative solution
with shared state be more readable? How about maintainable?&lt;/p&gt;
&lt;p&gt;For example, one could add the requirement that the random numbers
not be repeated so that the difference between adjacent numbers is
always nonzero. Updating the functional solution is as simple as adding
a Distinct() call:&lt;/p&gt;
&lt;pre&gt;&amp;nbsp; &amp;nbsp; return new Random().Values(1, max)&lt;br /&gt;&lt;b&gt;                       .Distinct()&lt;/b&gt;&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;.Take(slots - 1)&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;...&lt;/pre&gt;
&lt;p&gt;To me, this is the value proposition of functional programming. By
expressing the algorithm in terms of common operations, we're able to
spend more time thinking about the problem than the details of the
solution. A similar change in an imperative implementation would almost
certainly have been more involved and prone to error.&lt;/p&gt;
&lt;p&gt;For completeness, here are the implementations of the extension methods used:&lt;/p&gt;
&lt;pre&gt;public static IEnumerable&amp;lt;int&amp;gt; Values(this Random random, int minValue, int maxValue)&lt;br /&gt;{&lt;br /&gt;&amp;nbsp; &amp;nbsp; while (true)&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; yield return random.Next(minValue, maxValue);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public static IEnumerable&amp;lt;TResult&amp;gt; Pairwise&amp;lt;TSource, TResult&amp;gt;(&lt;br /&gt;    this IEnumerable&amp;lt;TSource&amp;gt; source,&lt;br /&gt;    Func&amp;lt;TSource, TSource, TResult&amp;gt; resultSelector)&lt;br /&gt;{&lt;br /&gt;&amp;nbsp; &amp;nbsp; TSource previous = default(TSource);&lt;br /&gt;&lt;br /&gt;&amp;nbsp; &amp;nbsp; using (var it = source.GetEnumerator())&lt;br /&gt;&amp;nbsp; &amp;nbsp; {&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; if (it.MoveNext())&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; previous = it.Current;&lt;br /&gt;&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; while (it.MoveNext())&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; yield return resultSelector(previous, previous = it.Current);&lt;br /&gt;&amp;nbsp; &amp;nbsp; }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public static IEnumerable&amp;lt;T&amp;gt; Append&amp;lt;T&amp;gt;(this IEnumerable&amp;lt;T&amp;gt; source, params T[] args)&lt;br /&gt;{&lt;br /&gt;&amp;nbsp; &amp;nbsp; return source.Concat(args);&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;This also reminds me that &lt;a title="Jimmy Bogard" href="http://www.lostechies.com/blogs/jimmy_bogard/default.aspx"&gt;Jimmy&lt;/a&gt; posted a similar &lt;code&gt;Append()&lt;/code&gt; method as part of his latest post on &lt;a title="More missing LINQ operators" href="http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/10/15/more-missing-linq-operators.aspx"&gt;missing LINQ operators&lt;/a&gt;. I used to use a version similar to his, but have found the &lt;code&gt;params&lt;/code&gt; version to be more flexible (and easier to implement). Its &lt;code&gt;Prepend()&lt;/code&gt; counterpart is similarly trivial:&lt;/p&gt;
&lt;pre&gt;public static IEnumerable&amp;lt;T&amp;gt; Prepend&amp;lt;T&amp;gt;(this IEnumerable&amp;lt;T&amp;gt; source, params T[] args)&lt;br /&gt;{&lt;br /&gt;&amp;nbsp; &amp;nbsp; return args.Concat(source);&lt;br /&gt;}&lt;/pre&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;a href="http://www.dotnetkicks.com/kick/?title=Is+Functional+Abstraction+Too+Clever%3f&amp;url=http%3a%2f%2fwww.lostechies.com%2fblogs%2fdahlbyk%2farchive%2f2009%2f10%2f17%2fis-functional-abstraction-too-clever.aspx"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.lostechies.com%2fblogs%2fdahlbyk%2farchive%2f2009%2f10%2f17%2fis-functional-abstraction-too-clever.aspx" border="0" alt="Kick It on DotNetKicks.com" /&gt;&lt;/a&gt;&lt;img src="http://www.lostechies.com/aggbug.aspx?PostID=26651" width="1" height="1"&gt;</content><author><name>dahlbyk</name><uri>http://www.lostechies.com/members/dahlbyk/default.aspx</uri></author><category term="Functional Programming" scheme="http://www.lostechies.com/blogs/dahlbyk/archive/tags/Functional+Programming/default.aspx" /></entry><entry><title>Refactoring with Iterators: Prime Factors</title><link rel="alternate" type="text/html" href="/blogs/dahlbyk/archive/2009/09/30/refactoring-with-iterators-prime-factors.aspx" /><id>/blogs/dahlbyk/archive/2009/09/30/refactoring-with-iterators-prime-factors.aspx</id><published>2009-09-30T15:17:00Z</published><updated>2009-09-30T15:17:00Z</updated><content type="html">&lt;p&gt;&lt;a href="http://www.21apps.com/"&gt;Andrew Woodward&lt;/a&gt; recently posted a &lt;a title="Comparing myself to Uncle Bob Martin" href="http://www.21apps.com/development/comparing-myself-to-uncle-bob-martin/"&gt;comparison of his test-driven Prime Factors solution&lt;/a&gt; to &lt;a title="Prime Factors Kata" href="http://www.butunclebob.com/ArticleS.UncleBob.ThePrimeFactorsKata"&gt;one written by&lt;/a&gt; &lt;a title="Robert C. Martin" href="http://butunclebob.com/"&gt;Uncle Bob&lt;/a&gt;. In the comments, someone suggested that Andrew use an iterator instead so I thought I'd give it a try.&lt;/p&gt;
&lt;p&gt;First, let's repost the original code:&lt;/p&gt;
&lt;pre&gt;private const int SMALLEST_PRIME = 2;&lt;br /&gt;&lt;br /&gt;public List&amp;lt;int&amp;gt; Generate(int i)&lt;br /&gt;{&lt;br /&gt;    List&amp;lt;int&amp;gt; primes = new List&amp;lt;int&amp;gt;();&lt;br /&gt;    int divider = SMALLEST_PRIME;&lt;br /&gt;    while (HasPrimes(i))&lt;br /&gt;    {&lt;br /&gt;        while (IsDivisable(i, divider))&lt;br /&gt;        {&lt;br /&gt;            i = AddPrimeToProductsAndReduce(i, primes, divider);&lt;br /&gt;        }&lt;br /&gt;        divider++;&lt;br /&gt;    }&lt;br /&gt;    return primes;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;private bool IsDivisable(int i, int divider)&lt;br /&gt;{&lt;br /&gt;    return i%divider == 0;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;private bool HasPrimes(int i)&lt;br /&gt;{&lt;br /&gt;    return i &amp;gt;= SMALLEST_PRIME;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;private int AddPrimeToProductsAndReduce(int i, List&amp;lt;int&amp;gt; primes, int prime)&lt;br /&gt;{&lt;br /&gt;    primes.Add(prime);&lt;br /&gt;    i /= prime;&lt;br /&gt;    return i;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;By switching our method to return &lt;code&gt;IEnumerable&amp;lt;int&amp;gt;&lt;/code&gt;, we can replace the &lt;code&gt;primes&lt;/code&gt;
list with an iterator. We will also remove the AddPrimeToProducts
functionality from that helper method since we don't have the list any
more:&lt;/p&gt;
&lt;pre&gt;public IEnumerable&amp;lt;int&amp;gt; Generate(int i)&lt;br /&gt;{&lt;br /&gt;    int divider = SMALLEST_PRIME;&lt;br /&gt;    while (HasPrimes(i))&lt;br /&gt;    {&lt;br /&gt;        while (IsDivisable(i, divider))&lt;br /&gt;        {&lt;br /&gt;            yield return divider;&lt;br /&gt;            i = Reduce(i, divider);&lt;br /&gt;        }&lt;br /&gt;        divider++;&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;private int Reduce(int i, int prime)&lt;br /&gt;{&lt;br /&gt;    return i / prime;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;I think this is a good change for three reasons:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;There's nothing about the problem that requires a &lt;code&gt;List&amp;lt;int&amp;gt;&lt;/code&gt; be returned, we just want a sequence of the factors.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;AddPrimeToProductsAndReduce&lt;/code&gt; suggested that it had a side effect, but exactly what wasn't immediately obvious.&lt;/li&gt;
&lt;li&gt;It's much easier to see what values are being included in the result.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;That said, I think we can clean this up even more with a second
iterator. Specifically, I think we should break out the logic for our
candidate factors:&lt;/p&gt;
&lt;pre&gt;private IEnumerable&amp;lt;int&amp;gt; Divisors&lt;br /&gt;{&lt;br /&gt;    get&lt;br /&gt;    {&lt;br /&gt;        int x = SMALLEST_PRIME;&lt;br /&gt;        while (true)&lt;br /&gt;            yield return x++;&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;Which allows us to separate the logic for generating a divider from the code that consumes it:&lt;/p&gt;
&lt;pre&gt;public IEnumerable&amp;lt;int&amp;gt; Generate(int toFactor)&lt;br /&gt;{&lt;br /&gt;    foreach (var divider in Divisors)&lt;br /&gt;    {&lt;br /&gt;        if (!HasPrimes(toFactor))&lt;br /&gt;            break;&lt;br /&gt;&lt;br /&gt;        while (IsDivisable(toFactor, divider))&lt;br /&gt;        {&lt;br /&gt;            yield return divider;&lt;br /&gt;            toFactor = Reduce(toFactor, divider);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;We should also eliminate the negation by flipping &lt;code&gt;HasPrimes&lt;/code&gt; to become &lt;code&gt;IsFactored&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;public IEnumerable&amp;lt;int&amp;gt; Generate(int toFactor)&lt;br /&gt;{&lt;br /&gt;    foreach (var divider in Divisors)&lt;br /&gt;    {&lt;br /&gt;        if (IsFactored(toFactor))&lt;br /&gt;            break;&lt;br /&gt;&lt;br /&gt;        while (IsDivisable(toFactor, divider))&lt;br /&gt;        {&lt;br /&gt;            yield return divider;&lt;br /&gt;            toFactor = Reduce(toFactor, divider);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;private bool IsFactored(int i)&lt;br /&gt;{&lt;br /&gt;    return i &amp;lt;= 1;&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;This does introduce a (very) minor inefficiency in that the &lt;code&gt;Divisors&lt;/code&gt; enumerator will &lt;code&gt;MoveNext()&lt;/code&gt; one extra time before breaking out of the loop, which could be mitigated by checking &lt;code&gt;IsFactored&lt;/code&gt; both before the &lt;code&gt;foreach&lt;/code&gt; and after the &lt;code&gt;while&lt;/code&gt; loop. Less readable, insignificantly more efficient...take your pick.&lt;/p&gt;
&lt;p&gt;The other advantage to breaking out the logic to generate &lt;code&gt;Divisors&lt;/code&gt;
is that we can easily pick smarter candidates. One option is to skip
even numbers greater than 2. An even better optimization takes
advantage of the fact that all primes greater than 3 are of the form
x&amp;plusmn;1 where x is a multiple of 6:&lt;/p&gt;
&lt;pre&gt;private IEnumerable&amp;lt;int&amp;gt; Divisors&lt;br /&gt;{&lt;br /&gt;    get&lt;br /&gt;    {&lt;br /&gt;        yield return 2;&lt;br /&gt;        yield return 3;&lt;br /&gt;        int i = 6;&lt;br /&gt;        while (true)&lt;br /&gt;        {&lt;br /&gt;            yield return i - 1;&lt;br /&gt;            yield return i + 1;&lt;br /&gt;            i += 6;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;Implementing this sort of logic in the original version would have
been much more difficult, both in terms of correctness and readability.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;a href="http://www.dotnetkicks.com/kick/?title=Refactoring+with+Iterators%3a+Prime+Factors&amp;url=http%3a%2f%2fwww.lostechies.com%2fblogs%2fdahlbyk%2farchive%2f2009%2f09%2f30%2frefactoring-with-iterators-prime-factors.aspx"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.lostechies.com%2fblogs%2fdahlbyk%2farchive%2f2009%2f09%2f30%2frefactoring-with-iterators-prime-factors.aspx" border="0" alt="Kick It on DotNetKicks.com" /&gt;&lt;/a&gt;&lt;img src="http://www.lostechies.com/aggbug.aspx?PostID=25671" width="1" height="1"&gt;</content><author><name>dahlbyk</name><uri>http://www.lostechies.com/members/dahlbyk/default.aspx</uri></author><category term="Iterators" scheme="http://www.lostechies.com/blogs/dahlbyk/archive/tags/Iterators/default.aspx" /><category term="Refactoring" scheme="http://www.lostechies.com/blogs/dahlbyk/archive/tags/Refactoring/default.aspx" /></entry><entry><title>Hacking LINQ Expressions: Join With Comparer</title><link rel="alternate" type="text/html" href="/blogs/dahlbyk/archive/2009/09/19/hacking-linq-expressions-join-with-comparer.aspx" /><id>/blogs/dahlbyk/archive/2009/09/19/hacking-linq-expressions-join-with-comparer.aspx</id><published>2009-09-19T18:15:00Z</published><updated>2009-09-19T18:15:00Z</updated><content type="html">&lt;p&gt;In this installment of my &lt;a href="http://solutionizing.net/tag/hacking-linq/"&gt;Hacking LINQ&lt;/a&gt; series we'll take a look at providing an &lt;code&gt;IEqualityComparer&lt;/code&gt; for use in a LINQ &lt;code&gt;join&lt;/code&gt; clause.&lt;/p&gt;
&lt;h2&gt;The Problem&lt;/h2&gt;
&lt;p&gt;Many of the &lt;a title="Standard Query Operators Overview" href="http://msdn.microsoft.com/en-us/library/bb397896.aspx"&gt;Standard Query Operators&lt;/a&gt;
require comparing sequence elements and the default query providers are
kind enough to give us overloads that accept a suitable comparer. Among
these operators, &lt;code&gt;Join&lt;/code&gt; and &lt;code&gt;GroupJoin&lt;/code&gt; have perhaps the most useful query syntax:&lt;/p&gt;
&lt;pre&gt; var res = from s in States&lt;br /&gt;          join a in AreaCodes&lt;br /&gt;            on s.Abbr equals a.StateAbbr&lt;br /&gt;          select new { s.Name, a.AreaCode };&lt;/pre&gt;
&lt;p&gt;While a bit more verbose, I find the intent much easier to read then the method equivalent:&lt;/p&gt;
&lt;pre&gt;var res = States.Join(AreaCodes,&lt;br /&gt;                      s =&amp;gt; s.Abbr, a =&amp;gt; a.StateAbbr,&lt;br /&gt;                      (s, a) =&amp;gt; new { s.Name, a.AreaCode });&lt;/pre&gt;
&lt;p&gt;Or maybe I've just spent too much time in SQL. Either way, I thought it would be useful to support joins by a comparer.&lt;/p&gt;
&lt;h2&gt;The Goal&lt;/h2&gt;
&lt;p&gt;We will use another extension method to specify how the join should be performed:&lt;/p&gt;
&lt;pre&gt;var res = from s in States&lt;br /&gt;          join a in AreaCodes.WithComparer(StringComparer.OrdinalIgnoreCase)&lt;br /&gt;            on s.Abbr equals a.StateAbbr&lt;br /&gt;          select new { s.Name, a.AreaCode };&lt;/pre&gt;
&lt;p&gt;We can also support the same syntax for group joins:&lt;/p&gt;
&lt;pre&gt;var res = from s in States&lt;br /&gt;          join a in AreaCodes.WithComparer(StringComparer.OrdinalIgnoreCase)&lt;br /&gt;            on s.Abbr equals a.StateAbbr into j&lt;br /&gt;          select new { s.Name, Count = j.Count() };&lt;/pre&gt;
&lt;h2&gt;The Hack&lt;/h2&gt;
&lt;p&gt;As with most LINQ hacks, we're going to use the result of &lt;code&gt;WithComparer&lt;/code&gt; to call a specialized version of &lt;code&gt;Join&lt;/code&gt; or &lt;code&gt;GroupJoin&lt;/code&gt;, in this case by providing a replacement for the join's inner sequence:&lt;/p&gt;
&lt;pre&gt;var res = States.Join(AreaCodes.WithComparer(StringComparer.OrdinalIgnoreCase),&lt;br /&gt;                      s =&amp;gt; s.Abbr, a =&amp;gt; a.StateAbbr,&lt;br /&gt;                     &amp;nbsp;(s, a) =&amp;gt; new { s.Name, a.AreaCode });&lt;/pre&gt;
&lt;p&gt;Eventually leading to this method call:&lt;/p&gt;
&lt;pre&gt;var res = States.Join(AreaCodes,&lt;br /&gt;                      s =&amp;gt; s.Abbr, a =&amp;gt; a.StateAbbr,&lt;br /&gt;                     &amp;nbsp;(s, a) =&amp;gt; new { s.Name, a.AreaCode },&lt;br /&gt;                      StringComparer.OrdinalIgnoreCase);&lt;/pre&gt;
&lt;p&gt;Since we need both the inner collection we're extending and the
comparer, we can guess our extension method will be implemented
something like this:&lt;/p&gt;
&lt;pre&gt;public static JoinComparerProvider&amp;lt;T, TKey&amp;gt; WithComparer&amp;lt;T, TKey&amp;gt;(&lt;br /&gt;    this IEnumerable&amp;lt;T&amp;gt; inner, IEqualityComparer&amp;lt;TKey&amp;gt; comparer)&lt;br /&gt;{&lt;br /&gt;    return new JoinComparerProvider&amp;lt;T, TKey&amp;gt;(inner, comparer);&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;With a trivial provider implementation:&lt;/p&gt;
&lt;pre&gt;public sealed class JoinComparerProvider&amp;lt;T, TKey&amp;gt;&lt;br /&gt;{&lt;br /&gt;    internal JoinComparerProvider(IEnumerable&amp;lt;T&amp;gt; inner, IEqualityComparer&amp;lt;TKey&amp;gt; comparer)&lt;br /&gt;    {&lt;br /&gt;        Inner = inner;&lt;br /&gt;        Comparer = comparer;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public IEqualityComparer&amp;lt;TKey&amp;gt; Comparer { get; private set; }&lt;br /&gt;    public IEnumerable&amp;lt;T&amp;gt; Inner { get; private set; }&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;The final piece is our &lt;code&gt;Join&lt;/code&gt; overload:&lt;/p&gt;
&lt;pre&gt;public static IEnumerable&amp;lt;TResult&amp;gt; Join&amp;lt;TOuter, TInner, TKey, TResult&amp;gt;(&lt;br /&gt;    this IEnumerable&amp;lt;TOuter&amp;gt; outer,&lt;br /&gt;    JoinComparerProvider&amp;lt;TInner, TKey&amp;gt; inner,&lt;br /&gt;    Func&amp;lt;TOuter, TKey&amp;gt; outerKeySelector,&lt;br /&gt;    Func&amp;lt;TInner, TKey&amp;gt; innerKeySelector,&lt;br /&gt;    Func&amp;lt;TOuter, TInner, TResult&amp;gt; resultSelector)&lt;br /&gt;{&lt;br /&gt;    return outer.Join(inner.Inner, outerKeySelector, innerKeySelector,&lt;br /&gt;                      resultSelector, inner.Comparer);&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;Implementations of &lt;code&gt;GroupJoin&lt;/code&gt; and their &lt;code&gt;IQueryable&lt;/code&gt; counterparts are similarly trivial.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;a href="http://www.dotnetkicks.com/kick/?title=Hacking+LINQ+Expressions%3a+Join+With+Comparer&amp;url=http%3a%2f%2fwww.lostechies.com%2fblogs%2fdahlbyk%2farchive%2f2009%2f09%2f19%2fhacking-linq-expressions-join-with-comparer.aspx"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.lostechies.com%2fblogs%2fdahlbyk%2farchive%2f2009%2f09%2f19%2fhacking-linq-expressions-join-with-comparer.aspx" border="0" alt="Kick It on DotNetKicks.com" /&gt;&lt;/a&gt;&lt;img src="http://www.lostechies.com/aggbug.aspx?PostID=24993" width="1" height="1"&gt;</content><author><name>dahlbyk</name><uri>http://www.lostechies.com/members/dahlbyk/default.aspx</uri></author><category term="LINQ" scheme="http://www.lostechies.com/blogs/dahlbyk/archive/tags/LINQ/default.aspx" /><category term="Hacking LINQ" scheme="http://www.lostechies.com/blogs/dahlbyk/archive/tags/Hacking+LINQ/default.aspx" /></entry><entry><title>Hacking LINQ Expressions: Select With Index</title><link rel="alternate" type="text/html" href="/blogs/dahlbyk/archive/2009/09/15/hacking-linq-expressions-select-with-index.aspx" /><id>/blogs/dahlbyk/archive/2009/09/15/hacking-linq-expressions-select-with-index.aspx</id><published>2009-09-15T09:04:00Z</published><updated>2009-09-15T09:04:00Z</updated><content type="html">&lt;p&gt;First, a point of clarification: I use LINQ Expressions to mean
(Language-INtegrated) Query Expressions (the language feature) rather
than Expression Trees (the .NET 3.5 library in System.Linq.Expressions).&lt;/p&gt;
&lt;p&gt;So what do I mean by "Hacking LINQ Expressions"? Quite simply, I'm
not content with the rather limited set of operations that query
expressions allow me to represent. By understanding how queries are
translated, we can use various techniques to broaden our expressive
reach. I have already documented one such hack for &lt;a title="Using IDisposables with LINQ" href="http://solutionizing.net/2009/07/23/using-idisposables-with-linq/"&gt;managing IDisposable objects with LINQ&lt;/a&gt;, so I guess we can call this the second in an unbounded series.&lt;/p&gt;
&lt;h2&gt;The Problem&lt;/h2&gt;
&lt;p&gt;In thinking over use cases for &lt;a title="Functional Construction for ASP.NET Web Forms" href="http://solutionizing.net/2009/09/13/functional-construction-for-asp-net-web-forms/"&gt;functional construction of web control trees&lt;/a&gt;, I paused to think through how I would express alternate row styling. My mind immediately jumped to the &lt;a title="Enumerable.Select&amp;lt;TSource, TResult&amp;gt; Method (IEnumerable&amp;lt;TSource&amp;gt;, Func&amp;lt;TSource, Int32, TResult&amp;gt;)" href="http://msdn.microsoft.com/en-us/library/bb534869.aspx"&gt;overload of Select()&lt;/a&gt; that exposes the current element's index:&lt;/p&gt;
&lt;pre&gt;Controls.Add(&lt;br /&gt;    new Table().WithControls(&lt;br /&gt;        data.Select((x, i) =&amp;gt;&lt;br /&gt;            new TableRow() {&lt;br /&gt;                CssClass = i % 2 == 0 ? "" : "alt"&lt;br /&gt;            }.WithControls(&lt;br /&gt;                new TableCell().WithControls(x)&lt;br /&gt;            )&lt;br /&gt;        )&lt;br /&gt;    )&lt;br /&gt;);&lt;/pre&gt;
&lt;p&gt;This works fine for simple cases, but breaks down for more complex queries:&lt;/p&gt;
&lt;pre&gt;Controls.Add(&lt;br /&gt;    new Table().WithControls((&lt;br /&gt;        from x in Xs&lt;br /&gt;        join y in Ys on x.Key equals y.Key&lt;br /&gt;        select new { x, y }&lt;br /&gt;        ).Select((z, i) =&amp;gt;&lt;br /&gt;            new TableRow() {&lt;br /&gt;                CssClass = i % 2 == 0 ? "" : "alt"&lt;br /&gt;            }.WithControls(&lt;br /&gt;                new TableCell().WithControls(z.x.ValueX, z.y.ValueY)&lt;br /&gt;            )&lt;br /&gt;        )&lt;br /&gt;    )&lt;br /&gt;);&lt;/pre&gt;
&lt;h2&gt;The Goal&lt;/h2&gt;
&lt;p&gt;Instead, I propose a simple extension method to retrieve an index at arbitrary points in a query:&lt;/p&gt;
&lt;pre&gt;var res = from x in data&lt;br /&gt;          from i in x.GetIndex()&lt;br /&gt;          select new { x, i };&lt;/pre&gt;
&lt;p&gt;Or our control examples:&lt;/p&gt;
&lt;pre&gt;Controls.Add(&lt;br /&gt;    new Table().WithControls(&lt;br /&gt;        from x in data&lt;br /&gt;        from i in x.GetIndex()&lt;br /&gt;        select new TableRow() {&lt;br /&gt;            CssClass = i % 2 == 0 ? "" : "alt"&lt;br /&gt;        }.WithControls(&lt;br /&gt;            new TableCell().WithControls(x)&lt;br /&gt;        )&lt;br /&gt;    )&lt;br /&gt;);&lt;br /&gt;&lt;br /&gt;Controls.Add(&lt;br /&gt;    new Table().WithControls(&lt;br /&gt;        from x in Xs&lt;br /&gt;        join y in Ys on x.Key equals y.Key&lt;br /&gt;        from i in y.GetIndex()&lt;br /&gt;        select new TableRow() {&lt;br /&gt;            CssClass = i % 2 == 0 ? "" : "alt"&lt;br /&gt;        }.WithControls(&lt;br /&gt;            new TableCell().WithControls(x.ValueX, y.ValueY)&lt;br /&gt;        )&lt;br /&gt;    )&lt;br /&gt;);&lt;/pre&gt;
&lt;p&gt;Much like in the &lt;code&gt;IDisposable&lt;/code&gt; solution, we use a &lt;code&gt;from&lt;/code&gt; clause to act as an intermediate assignment. But in this case our hack is a bit trickier than a simple iterator.&lt;/p&gt;
&lt;h2&gt;The Hack&lt;/h2&gt;
&lt;p&gt;For this solution we're going to take advantage of how multiple &lt;code&gt;from&lt;/code&gt; clauses are translated:&lt;/p&gt;
&lt;pre&gt;var res = data.SelectMany(x =&amp;gt; x.GetIndex(), (x, i) =&amp;gt; new { x, i });&lt;/pre&gt;
&lt;p&gt;Looking at the parameter list, we see that our &lt;code&gt;collectionSelector&lt;/code&gt; should return the result of &lt;code&gt;x.GetIndex()&lt;/code&gt; and our &lt;code&gt;resultSelector&lt;/code&gt;'s second argument needs to be an &lt;code&gt;int&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;public static IEnumerable&amp;lt;TResult&amp;gt; SelectMany&amp;lt;TSource, TResult&amp;gt;(&lt;br /&gt;    this IEnumerable&amp;lt;TSource&amp;gt; source,&lt;br /&gt;    Func&amp;lt;TSource, SelectIndexProvider&amp;gt; collectionSelector,&lt;br /&gt;    Func&amp;lt;TSource, int, TResult&amp;gt; resultSelector)&lt;/pre&gt;
&lt;p&gt;The astute observer will notice that the signature of this &lt;code&gt;resultSelector&lt;/code&gt; exactly matches the &lt;code&gt;selector&lt;/code&gt; used by &lt;code&gt;Select&lt;/code&gt;'s with-index overload, trivializing the method implementation:&lt;/p&gt;
&lt;pre&gt;{&lt;br /&gt;    return source.Select(resultSelector);&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;Note that we're not even using &lt;code&gt;collectionSelector&lt;/code&gt;! We're just using its return type as a flag to force the compiler to use this version of &lt;code&gt;SelectMany()&lt;/code&gt;. The rest of the pieces are incredibly simple now that we know the actual &lt;code&gt;SelectIndexProvider&lt;/code&gt; value is never used:&lt;/p&gt;
&lt;pre&gt;public sealed class SelectIndexProvider&lt;br /&gt;{&lt;br /&gt;    private SelectIndexProvider() { }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public static SelectIndexProvider GetIndex&amp;lt;T&amp;gt;(this T element)&lt;br /&gt;{&lt;br /&gt;    return null;&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;And for good measure, an equivalent version to extend IQueryable&amp;lt;&amp;gt;:&lt;/p&gt;
&lt;pre&gt;public static IQueryable&amp;lt;TResult&amp;gt; SelectMany&amp;lt;TSource, TResult&amp;gt;(&lt;br /&gt;    this IQueryable&amp;lt;TSource&amp;gt; source,&lt;br /&gt;    Expression&amp;lt;Func&amp;lt;TSource, SelectIndexProvider&amp;gt;&amp;gt; collectionSelector,&lt;br /&gt;    Expression&amp;lt;Func&amp;lt;TSource, int, TResult&amp;gt;&amp;gt; resultSelector)&lt;br /&gt;{&lt;br /&gt;    return source.Select(resultSelector);&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;Because we're just calling &lt;code&gt;Select()&lt;/code&gt;, the query expression isn't even aware of the call to &lt;code&gt;GetIndex()&lt;/code&gt;:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;System.Linq.Enumerable+&amp;lt;RangeIterator&amp;gt;d__b1.Select((x, i) =&amp;gt; (x * i))&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;We're essentially providing our own syntactic sugar over the sugar already provided by query expressions. Pretty sweet, eh?&lt;/p&gt;
&lt;p&gt;As a final exercise for the reader, what would this print?&lt;/p&gt;
&lt;pre&gt;var res = from x in Enumerable.Range(1, 5)&lt;br /&gt;          from i in x.GetIndex()&lt;br /&gt;          from y in Enumerable.Repeat(i, x)&lt;br /&gt;          where y % 2 == 1&lt;br /&gt;          from j in 0.GetIndex()&lt;br /&gt;          select i+j;&lt;br /&gt;&lt;br /&gt;foreach (var r in res)&lt;br /&gt;    Console.WriteLine(r);&lt;/pre&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;a href="http://www.dotnetkicks.com/kick/?title=Hacking+LINQ+Expressions%3a+Select+With+Index&amp;url=http%3a%2f%2fwww.lostechies.com%2fblogs%2fdahlbyk%2farchive%2f2009%2f09%2f15%2fhacking-linq-expressions-select-with-index.aspx"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.lostechies.com%2fblogs%2fdahlbyk%2farchive%2f2009%2f09%2f15%2fhacking-linq-expressions-select-with-index.aspx" border="0" alt="Kick It on DotNetKicks.com" /&gt;&lt;/a&gt;&lt;img src="http://www.lostechies.com/aggbug.aspx?PostID=24853" width="1" height="1"&gt;</content><author><name>dahlbyk</name><uri>http://www.lostechies.com/members/dahlbyk/default.aspx</uri></author><category term="LINQ" scheme="http://www.lostechies.com/blogs/dahlbyk/archive/tags/LINQ/default.aspx" /><category term="Hacking LINQ" scheme="http://www.lostechies.com/blogs/dahlbyk/archive/tags/Hacking+LINQ/default.aspx" /></entry><entry><title>Functional Construction for ASP.NET Web Forms</title><link rel="alternate" type="text/html" href="/blogs/dahlbyk/archive/2009/09/13/functional-construction-for-asp-net-web-forms.aspx" /><id>/blogs/dahlbyk/archive/2009/09/13/functional-construction-for-asp-net-web-forms.aspx</id><published>2009-09-13T08:59:00Z</published><updated>2009-09-13T08:59:00Z</updated><content type="html">&lt;p&gt;System.Xml.Linq (a.k.a. LINQ to XML) introduces a nifty approach to creating XML elements called &lt;a title="Functional Construction (LINQ to XML)" href="http://msdn.microsoft.com/en-us/library/bb387019.aspx"&gt;functional construction&lt;/a&gt;.
I'm not entirely sure why they call it functional given that
constructing an object graph is a decidedly non-functional task in the
traditional sense of the word, but I digress.&lt;/p&gt;
&lt;p&gt;Functional construction has three key features:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Constructors accept arguments of various types, handling them appropriately.&lt;/li&gt;
&lt;li&gt;Constructors accept a &lt;code&gt;params&lt;/code&gt; array of type &lt;code&gt;Object&lt;/code&gt; to enable creation of complex objects.&lt;/li&gt;
&lt;li&gt;If an argument implements &lt;code&gt;IEnumerable&lt;/code&gt;, the objects within the sequence are added.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;If you haven't seen it in action, I encourage you to take a look at
the examples on MSDN and elsewhere&amp;mdash;it really is pretty slick. This post
will show how a similar technique can be used to build control trees in
ASP.NET web forms (and probably WinForms with minimal adjustment).&lt;/p&gt;
&lt;p&gt;Basic functional construction can be implemented using two relatively simple extension methods:&lt;/p&gt;
&lt;pre&gt;public static void Add(this ControlCollection @this, object content)&lt;br /&gt;{&lt;br /&gt;    if (content is Control)&lt;br /&gt;        @this.Add((Control)content);&lt;br /&gt;    else if (content is IEnumerable)&lt;br /&gt;        foreach (object c in (IEnumerable)content)&lt;br /&gt;            @this.Add(c);&lt;br /&gt;    else if (content != null)&lt;br /&gt;        @this.Add(new LiteralControl(content.ToString()));&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public static void Add(this ControlCollection @this, params object[] args)&lt;br /&gt;{&lt;br /&gt;    @this.Add((IEnumerable)args);&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;We handle four cases:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Control? Add it.&lt;/li&gt;
&lt;li&gt;Sequence? Add each.&lt;/li&gt;
&lt;li&gt;Other value? Add literal.&lt;/li&gt;
&lt;li&gt;Null? Ignore.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;And our &lt;code&gt;params&lt;/code&gt; overload just calls its arguments a sequence and defers to the other.&lt;/p&gt;
&lt;p&gt;In the time-honored tradition of contrived examples:&lt;/p&gt;
&lt;pre&gt;Controls.Add(&lt;br /&gt;    new Label() { Text = "Nums:" },&lt;br /&gt;    "&amp;amp;nbsp;",&lt;br /&gt;    from i in Enumerable.Range(1, 6)&lt;br /&gt;    group i by i % 2&lt;br /&gt;);&lt;/pre&gt;
&lt;p&gt;This would render "Nums: 135246". Note that the result of that LINQ
expression is a sequence of sequences, which is flattened automatically
and converted into literals. For comparison, here's an equivalent set
of statements:&lt;/p&gt;
&lt;pre&gt;Controls.Add(new Label() { Text = "Nums:" });&lt;br /&gt;Controls.Add(new LiteralControl("&amp;amp;nbsp;"));&lt;br /&gt;foreach (var g in from i in Enumerable.Range(1, 6)&lt;br /&gt;                  group i by i % 2)&lt;br /&gt;    foreach (var i in g)&lt;br /&gt;        Controls.Add(new LiteralControl(i.ToString()));&lt;/pre&gt;
&lt;p&gt;Hopefully seeing them side by side makes it clear why this new method of construction might have merit. But we're not done yet.&lt;/p&gt;
&lt;h2&gt;Expressions, Expressions, Expressions&lt;/h2&gt;
&lt;p&gt;Many language features introduced in C# 3.0 and Visual Basic 9 make
expressions increasingly important. By expressions I mean a single
"line" of code that returns a value. For example, an object initializer
is a single expression...&lt;/p&gt;
&lt;pre&gt;var tb = new TextBox()&lt;br /&gt;{&lt;br /&gt;    ID = "textBox1",&lt;br /&gt;    Text = "Text"&lt;br /&gt;};&lt;/pre&gt;
&lt;p&gt;... that represents several statements ...&lt;/p&gt;
&lt;pre&gt;var tb = new TextBox()&lt;br /&gt;tb.ID = "textBox1";&lt;br /&gt;tb.Text = "Text";&lt;/pre&gt;
&lt;p&gt;That single TextBox expression can then be used in a number of
places that its statement equivalent can't: in another object
initializer, in a collection initializer, as a parameter to a method,
in a .NET 3.5 expression tree, the list goes on. Unfortunately, many
older APIs simply aren't built to work in an expression-based world. In
particular, initializing subcollections is a considerable pain.
However, we can extend the API to handle this nicely:&lt;/p&gt;
&lt;pre&gt;public static T WithControls&amp;lt;T&amp;gt;(this T @this, params object[] content) where T : Control&lt;br /&gt;{&lt;br /&gt;    if(@this != null)&lt;br /&gt;        @this.Controls.Add(content);&lt;br /&gt;    return @this;&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;The key is the return value: Control in, Control out. We can now
construct and populate a container control with a single expression.
For example, we could build a dictionary list (remember those?) from
our groups:&lt;/p&gt;
&lt;pre&gt;Controls.Add(&lt;br /&gt;    new HtmlGenericControl("dl")&lt;br /&gt;    .WithControls(&lt;br /&gt;        from i in Enumerable.Range(1, 6)&lt;br /&gt;        group i by i % 2 into g&lt;br /&gt;        select new [] {&lt;br /&gt;            new HtmlGenericControl("dt")&lt;br /&gt;            { InnerText = g.Key == 0 ? "Even" : "Odd" },&lt;br /&gt;            new HtmlGenericControl("dd")&lt;br /&gt;            .WithControls(g)&lt;br /&gt;        }&lt;br /&gt;    )&lt;br /&gt;);&lt;/pre&gt;
&lt;p&gt;Which would render this:&lt;/p&gt;
&lt;blockquote&gt;&lt;dl&gt;&lt;dt&gt;Odd&lt;/dt&gt;&lt;dd&gt;135&lt;/dd&gt;&lt;dt&gt;Even&lt;/dt&gt;&lt;dd&gt;246&lt;/dd&gt;&lt;/dl&gt;
&lt;/blockquote&gt;
&lt;p&gt;Without the ability to add controls within an expression, this
result would require nested loops with local variables to store
references to the containers. The actual code produced by the compiler
would be nearly identical, but I find the expressions much easier to
work with. Similarly, we can easily populate tables. Let's build a cell
per number:&lt;/p&gt;
&lt;pre&gt;Controls.Add(&lt;br /&gt;    new Table().WithControls(&lt;br /&gt;        from i in Enumerable.Range(1, 6)&lt;br /&gt;        group i by i % 2 into g&lt;br /&gt;        select new TableRow().WithControls(&lt;br /&gt;            new TableCell()&lt;br /&gt;            { Text = g.Key == 0 ? "Even" : "Odd" },&lt;br /&gt;            g.Select(n =&amp;gt; new TableCell().WithControls(n))&lt;br /&gt;        )&lt;br /&gt;    )&lt;br /&gt;);&lt;/pre&gt;
&lt;p&gt;In a future post I'll look at some other extensions we can use to
streamline the construction and initialization of control hierarchies.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;a href="http://www.dotnetkicks.com/kick/?title=Functional+Construction+for+ASP.NET+Web+Forms&amp;url=http%3a%2f%2fwww.lostechies.com%2fblogs%2fdahlbyk%2farchive%2f2009%2f09%2f13%2ffunctional-construction-for-asp-net-web-forms.aspx"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.lostechies.com%2fblogs%2fdahlbyk%2farchive%2f2009%2f09%2f13%2ffunctional-construction-for-asp-net-web-forms.aspx" border="0" alt="Kick It on DotNetKicks.com" /&gt;&lt;/a&gt;&lt;img src="http://www.lostechies.com/aggbug.aspx?PostID=24795" width="1" height="1"&gt;</content><author><name>dahlbyk</name><uri>http://www.lostechies.com/members/dahlbyk/default.aspx</uri></author><category term="Functional Construction" scheme="http://www.lostechies.com/blogs/dahlbyk/archive/tags/Functional+Construction/default.aspx" /><category term="ASP.NET" scheme="http://www.lostechies.com/blogs/dahlbyk/archive/tags/ASP.NET/default.aspx" /></entry><entry><title>Simplifying LazyLinq</title><link rel="alternate" type="text/html" href="/blogs/dahlbyk/archive/2009/09/13/simplifying-lazylinq.aspx" /><id>/blogs/dahlbyk/archive/2009/09/13/simplifying-lazylinq.aspx</id><published>2009-09-13T05:09:00Z</published><updated>2009-09-13T05:09:00Z</updated><content type="html">&lt;p&gt;This is the fourth in a series of posts on &lt;a href="http://lazylinq.codeplex.com/"&gt;LazyLinq&lt;/a&gt;, a wrapper to support lazy initialization and deferred disposal of a LINQ query context:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;a href="http://solutionizing.net/2009/08/06/introducing-lazylinq-overview/"&gt;Introducing LazyLinq: Overview&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://solutionizing.net/2009/08/17/introducing-lazylinq-internals/"&gt;Introducing LazyLinq: Internals&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://solutionizing.net/2009/08/20/introducing-lazylinq-queryability/"&gt;Introducing LazyLinq: Queryability&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Simplifying LazyLinq&lt;br /&gt;
&lt;/b&gt;&lt;/li&gt;
&lt;li&gt;Introducing LazyLinq: Lazy DataContext&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;As I was iterating on the proof of concept for LazyLinq, I always wanted to get rid of the &lt;code&gt;TQuery&lt;/code&gt; type parameter. I thought I needed it to distinguish between ordered and unordered wrapped queries, but it just felt messy. The underlying provider mechanism didn&amp;rsquo;t need it, so why should I?&lt;/p&gt;
&lt;p&gt;Well after taking a closer look at the SQL query provider, I figured out how to eliminate it. The object of inspiration is &lt;code&gt;System.Data.Linq.DataQuery&amp;lt;T&amp;gt;&lt;/code&gt;, defined as follows:&lt;/p&gt;
&lt;pre&gt;internal sealed class DataQuery&amp;lt;T&amp;gt; :
    IOrderedQueryable&amp;lt;T&amp;gt;, IQueryable&amp;lt;T&amp;gt;,
    IOrderedQueryable, IQueryable,
    IEnumerable&amp;lt;T&amp;gt;, IEnumerable,
    IQueryProvider,
    IListSource&lt;/pre&gt;
&lt;p&gt;The key was realizing that &lt;code&gt;IOrderedQueryable&amp;lt;&amp;gt;&lt;/code&gt; and &lt;code&gt;ILazyOrderedQueryable&amp;lt;&amp;gt;&lt;/code&gt; don&amp;rsquo;t actually do anything. Implementation-wise, they&amp;rsquo;re just &lt;code&gt;IQueryable&amp;lt;&amp;gt;&lt;/code&gt; or &lt;code&gt;ILazyQueryable&amp;lt;&amp;gt;&lt;/code&gt; with an extra interface on top. It&amp;rsquo;s only on the design side that it actually matters, essentially providing a hook for additional ordering with &lt;code&gt;ThenBy&lt;/code&gt;. In LINQ to SQL&amp;rsquo;s case, that means supporting orderability is as simple as specifying that the query object is both &lt;code&gt;IQueryable&amp;lt;&amp;gt;&lt;/code&gt; and &lt;code&gt;IOrderedQueryable&amp;lt;&amp;gt;&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;So how does this revelation simplify Lazy LINQ? First, it allows us to remove &lt;code&gt;TQuery&lt;/code&gt; from the interfaces:&lt;/p&gt;
&lt;pre&gt;    public interface ILazyContext&amp;lt;TContext&amp;gt; : IDisposable
    {
        TContext Context { get; }
        ILazyQueryable&amp;lt;TContext, TResult&amp;gt;
            CreateQuery&amp;lt;TResult&amp;gt;(Func&amp;lt;TContext, IQueryable&amp;lt;TResult&amp;gt;&amp;gt; queryBuilder);
        TResult Execute&amp;lt;TResult&amp;gt;(Func&amp;lt;TContext, TResult&amp;gt; action);
    }

    public interface ILazyQueryable&amp;lt;TContext, TSource&amp;gt; : IQueryable&amp;lt;TSource&amp;gt;

    {
        ILazyContext&amp;lt;TContext&amp;gt; Context { get; }
        Func&amp;lt;TContext, IQueryable&amp;lt;TSource&amp;gt;&amp;gt; QueryBuilder { get; }
    }

    public interface ILazyOrderedQueryable&amp;lt;TContext, TSource&amp;gt;
        : ILazyQueryable&amp;lt;TContext, TSource&amp;gt;, IOrderedQueryable&amp;lt;TSource&amp;gt;

    { }&lt;/pre&gt;
&lt;p&gt;Note that we can also eliminate &lt;code&gt;ILazyContext.CreateOrderedQuery()&lt;/code&gt;, instead assuming that &lt;code&gt;CreateQuery()&lt;/code&gt; will return something that can be treated as &lt;code&gt;ILazyOrderedQueryable&amp;lt;&amp;gt;&lt;/code&gt; as necessary.&lt;/p&gt;
&lt;p&gt;For the concrete implementations, we take the cue from &lt;code&gt;DataQuery&amp;lt;T&amp;gt;&lt;/code&gt;, letting &lt;code&gt;LazyQueryableImpl&lt;/code&gt; implement &lt;code&gt;ILazyOrderedQueryable&amp;lt;&amp;gt;&lt;/code&gt; so we can eliminate &lt;code&gt;LazyOrderedQueryableImpl&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;    class LazyQueryableImpl&amp;lt;TContext, TSource&amp;gt;
        : ILazyQueryable&amp;lt;TContext, TSource&amp;gt;, ILazyOrderedQueryable&amp;lt;TContext, TSource&amp;gt;
    {
        // Implementation doesn't change
    }&lt;/pre&gt;
&lt;p&gt;Finally, our sorting query operations will look more like their counterparts in &lt;code&gt;System.Linq.Queryable&lt;/code&gt;, casting the result of &lt;code&gt;CreateQuery()&lt;/code&gt; to &lt;code&gt;ILazyOrderedQueryable&amp;lt;&amp;gt;&lt;/code&gt;. To keep things readable, we&amp;rsquo;ll split our &lt;code&gt;CreateOrderedQuery&amp;lt;&amp;gt;&lt;/code&gt; helper into separate versions for &lt;code&gt;OrderBy&lt;/code&gt; and &lt;code&gt;ThenBy&lt;/code&gt;. Note how the types of &lt;code&gt;queryOperation&lt;/code&gt; map to the usage of &lt;code&gt;OrderBy&lt;/code&gt; (unordered to ordered) and &lt;code&gt;ThenBy&lt;/code&gt; (ordered to ordered):&lt;/p&gt;
&lt;pre&gt;        private static ILazyOrderedQueryable&amp;lt;TContext, TResult&amp;gt;
            CreateOrderByQuery&amp;lt;TSource, TContext, TResult&amp;gt;(
                this ILazyQueryable&amp;lt;TContext, TSource&amp;gt; source,
                Func&amp;lt;IQueryable&amp;lt;TSource&amp;gt;, IOrderedQueryable&amp;lt;TResult&amp;gt;&amp;gt; queryOperation
            )
        {
            return (ILazyOrderedQueryable&amp;lt;TContext, TResult&amp;gt;) source.Context.CreateQuery&amp;lt;TResult&amp;gt;(
               context =&amp;gt; queryOperation(source.QueryBuilder(context)));
        }

        private static ILazyOrderedQueryable&amp;lt;TContext, TResult&amp;gt;

            CreateThenByQuery&amp;lt;TSource, TContext, TResult&amp;gt;(
                this ILazyQueryable&amp;lt;TContext, TSource&amp;gt; source,
                Func&amp;lt;IOrderedQueryable&amp;lt;TSource&amp;gt;, IOrderedQueryable&amp;lt;TResult&amp;gt;&amp;gt; queryOperation
            )
        {
            return (ILazyOrderedQueryable&amp;lt;TContext, TResult&amp;gt;) source.Context.CreateQuery&amp;lt;TResult&amp;gt;(
               context =&amp;gt; queryOperation((IOrderedQueryable&amp;lt;TSource&amp;gt;) source.QueryBuilder(context)));
        }&lt;/pre&gt;
&lt;p&gt;Removing &lt;code&gt;TQuery&lt;/code&gt; from the query operators is left as an exercise for the reader. Or you can just &lt;a title="Lazy LINQ Changeset 26863" href="http://lazylinq.codeplex.com/"&gt;get the source on CodePlex&lt;/a&gt;.&lt;/p&gt;
&lt;h3&gt;A Note on &lt;code&gt;IOrderedEnumerable&amp;lt;&amp;gt;&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;Having taken advantage of how LINQ to IQueryable handles orderability, it&amp;rsquo;s worth pointing out that LINQ to Objects uses a different approach, specifying new behavior in &lt;code&gt;IOrderedEnumerable&amp;lt;&amp;gt;&lt;/code&gt; that is used to support multiple sort criteria:&lt;/p&gt;
&lt;pre&gt;public interface IOrderedEnumerable&amp;lt;TElement&amp;gt; : IEnumerable&amp;lt;TElement&amp;gt;, IEnumerable
{
    IOrderedEnumerable&amp;lt;TElement&amp;gt;

        CreateOrderedEnumerable&amp;lt;TKey&amp;gt;(
            Func&amp;lt;TElement, TKey&amp;gt; keySelector,
            IComparer&amp;lt;TKey&amp;gt; comparer, bool descending);
}&lt;/pre&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;a href="http://www.dotnetkicks.com/kick/?title=Simplifying+LazyLinq&amp;url=http%3a%2f%2fwww.lostechies.com%2fblogs%2fdahlbyk%2farchive%2f2009%2f09%2f13%2fsimplifying-lazylinq.aspx"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.lostechies.com%2fblogs%2fdahlbyk%2farchive%2f2009%2f09%2f13%2fsimplifying-lazylinq.aspx" border="0" alt="Kick It on DotNetKicks.com" /&gt;&lt;/a&gt;&lt;img src="http://www.lostechies.com/aggbug.aspx?PostID=24785" width="1" height="1"&gt;</content><author><name>dahlbyk</name><uri>http://www.lostechies.com/members/dahlbyk/default.aspx</uri></author><category term="LINQ" scheme="http://www.lostechies.com/blogs/dahlbyk/archive/tags/LINQ/default.aspx" /><category term="LINQ to SQL" scheme="http://www.lostechies.com/blogs/dahlbyk/archive/tags/LINQ+to+SQL/default.aspx" /><category term="LazyLinq" scheme="http://www.lostechies.com/blogs/dahlbyk/archive/tags/LazyLinq/default.aspx" /><category term="ILazyQueryable" scheme="http://www.lostechies.com/blogs/dahlbyk/archive/tags/ILazyQueryable/default.aspx" /><category term="ILazyContext" scheme="http://www.lostechies.com/blogs/dahlbyk/archive/tags/ILazyContext/default.aspx" /><category term="Queryable" scheme="http://www.lostechies.com/blogs/dahlbyk/archive/tags/Queryable/default.aspx" /></entry><entry><title>Introducing LazyLinq: Queryability</title><link rel="alternate" type="text/html" href="/blogs/dahlbyk/archive/2009/08/20/introducing-lazylinq-queryability.aspx" /><id>/blogs/dahlbyk/archive/2009/08/20/introducing-lazylinq-queryability.aspx</id><published>2009-08-21T02:31:00Z</published><updated>2009-08-21T02:31:00Z</updated><content type="html">&lt;p&gt;This is the third in a series of posts on LazyLinq, a wrapper to support lazy initialization and deferred disposal of a LINQ query context:
&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;a href="http://solutionizing.net/2009/08/06/introducing-lazylinq-overview/"&gt;Introducing LazyLinq: Overview&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://solutionizing.net/2009/08/17/introducing-lazylinq-internals/"&gt;Introducing LazyLinq: Internals&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Introducing LazyLinq: Queryability&lt;/b&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://solutionizing.net/2009/09/12/simplifying-lazylinq/"&gt;Simplifying LazyLinq&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Introducing LazyLinq: Lazy DataContext&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
Having defined the LazyLinq interfaces and provided concrete implementations, we're left to provide support for the standard query operators.
&lt;/p&gt;
&lt;h2&gt;Learning from Queryable&lt;/h2&gt;
&lt;p&gt;
Before we try to query &lt;code&gt;ILazyQueryable&lt;/code&gt;, it's instructive to look at how &lt;code&gt;System.Linq.Queryable&lt;/code&gt; works. There are essentially three types of operators on &lt;code&gt;IQueryable&amp;lt;&amp;gt;&lt;/code&gt;:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Deferred queries returning &lt;code&gt;IQueryable&amp;lt;&amp;gt;&lt;/code&gt;: Select, Where, etc.&lt;/li&gt;
&lt;li&gt;Deferred query returning &lt;code&gt;IOrderedQueryable&amp;lt;&amp;gt;&lt;/code&gt;: OrderBy, OrderByDescending, ThenBy, ThenByDescending&lt;/li&gt;
&lt;li&gt;Everything else: Aggregate, Count, First, etc.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
Reflecting &lt;code&gt;Queryable.Select&lt;/code&gt;, modulo error checking, we see the following:
&lt;/p&gt;
&lt;pre&gt;public static IQueryable&amp;lt;TResult&amp;gt; Select&amp;lt;TSource, TResult&amp;gt;(&lt;br /&gt;    this IQueryable&amp;lt;TSource&amp;gt; source, Expression&amp;lt;Func&amp;lt;TSource, TResult&amp;gt;&amp;gt; selector)&lt;br /&gt;{&lt;br /&gt;    return source.Provider&lt;br /&gt;        .CreateQuery&amp;lt;TResult&amp;gt;(&lt;br /&gt;            Expression.Call(null,&lt;br /&gt;                ((MethodInfo) MethodBase.GetCurrentMethod())&lt;br /&gt;                    .MakeGenericMethod(new Type[] { typeof(TSource), typeof(TResult) }),&lt;br /&gt;                new Expression[] { source.Expression, Expression.Quote(selector) }));&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;
The &lt;code&gt;source&lt;/code&gt;'s &lt;code&gt;Provider&lt;/code&gt; is used to construct a new query whose expression includes the call to &lt;code&gt;Select&lt;/code&gt; with the given parameters. An ordered query follows a similar pattern, trusting that the query provider will return an &lt;code&gt;IOrderedQueryable&amp;lt;&amp;gt;&lt;/code&gt; as appropriate:
&lt;/p&gt;
&lt;pre&gt;public static IOrderedQueryable&amp;lt;TSource&amp;gt; OrderBy&amp;lt;TSource, TKey&amp;gt;(&lt;br /&gt;    this IQueryable&amp;lt;TSource&amp;gt; source, Expression&amp;lt;Func&amp;lt;TSource, TKey&amp;gt;&amp;gt; keySelector)&lt;br /&gt;{&lt;br /&gt;    return (IOrderedQueryable&amp;lt;TSource&amp;gt;) source.Provider&lt;br /&gt;        .CreateQuery&amp;lt;TSource&amp;gt;(&lt;br /&gt;            Expression.Call(null,&lt;br /&gt;                ((MethodInfo) MethodBase.GetCurrentMethod())&lt;br /&gt;                    .MakeGenericMethod(new Type[] { typeof(TSource), typeof(TKey) }),&lt;br /&gt;                new Expression[] { source.Expression, Expression.Quote(keySelector) }));&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;
And finally, everything that's not a query is handled by the provider's &lt;code&gt;Execute&lt;/code&gt; method:
&lt;/p&gt;
&lt;pre&gt;public static TSource First&amp;lt;TSource&amp;gt;(this IQueryable&amp;lt;TSource&amp;gt; source)&lt;br /&gt;{&lt;br /&gt;    return source.Provider&lt;br /&gt;        .Execute&amp;lt;TSource&amp;gt;(&lt;br /&gt;            Expression.Call(null,&lt;br /&gt;                ((MethodInfo) MethodBase.GetCurrentMethod())&lt;br /&gt;                    .MakeGenericMethod(new Type[] { typeof(TSource) }),&lt;br /&gt;                new Expression[] { source.Expression }));&lt;br /&gt;}&lt;/pre&gt;
&lt;h2&gt;Querying ILazyQueryable&lt;/h2&gt;
&lt;p&gt;
You may have noticed that the above scenarios map rather closely to the methods provided by &lt;code&gt;ILazyContext&lt;/code&gt;:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;pre&gt;ILazyQueryable&amp;lt;TContext, TResult, TQuery&amp;gt;&lt;br /&gt;    CreateQuery&amp;lt;TResult, TQuery&amp;gt;(Func&amp;lt;TContext, TQuery&amp;gt; queryBuilder)&lt;br /&gt;    where TQuery : IQueryable&amp;lt;TResult&amp;gt;;&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;pre&gt;ILazyOrderedQueryable&amp;lt;TContext, TResult, TQuery&amp;gt;&lt;br /&gt;    CreateOrderedQuery&amp;lt;TResult, TQuery&amp;gt;(Func&amp;lt;TContext, TQuery&amp;gt; queryBuilder)&lt;br /&gt;    where TQuery : IOrderedQueryable&amp;lt;TResult&amp;gt;;&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;pre&gt;TResult Execute&amp;lt;TResult&amp;gt;(Func&amp;lt;TContext, TResult&amp;gt; action);&lt;/pre&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
However, rather than expression trees we're pushing around delegates. &lt;code&gt;Execute&lt;/code&gt; seems pretty simple, so let's start there:
&lt;/p&gt;
&lt;pre&gt;public static TSource First&amp;lt;TSource, TContext, TQuery&amp;gt;(&lt;br /&gt;        this ILazyQueryable&amp;lt;TContext, TSource, TQuery&amp;gt; source&lt;br /&gt;    ) where TQuery : IQueryable&amp;lt;TSource&amp;gt;&lt;br /&gt;{&lt;br /&gt;    Func&amp;lt;TContext, TResult&amp;gt; action = context =&amp;gt; ???;&lt;br /&gt;    return source.Context.Execute(action);&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;
So our source has a &lt;code&gt;Context&lt;/code&gt;, which knows how to &lt;code&gt;Execute&lt;/code&gt; an action from &lt;code&gt;context&lt;/code&gt; to some result. To find that result, we need to leverage the other property of source: &lt;code&gt;QueryBuilder&lt;/code&gt;. Recalling that &lt;code&gt;QueryBuilder&lt;/code&gt; is a function from &lt;code&gt;TContext&lt;/code&gt; to &lt;code&gt;TQuery&lt;/code&gt;, and that &lt;code&gt;TQuery&lt;/code&gt; is an &lt;code&gt;IQueryable&amp;lt;TSource&amp;gt;&lt;/code&gt;, we see something on which we can execute &lt;code&gt;Queryable.First&lt;/code&gt;:
&lt;/p&gt;
&lt;pre&gt;public static TSource First&amp;lt;TSource, TContext, TQuery&amp;gt;(&lt;br /&gt;        this ILazyQueryable&amp;lt;TContext, TSource, TQuery&amp;gt; source&lt;br /&gt;    ) where TQuery : IQueryable&amp;lt;TSource&amp;gt;&lt;br /&gt;{&lt;br /&gt;    Func&amp;lt;TContext, TResult&amp;gt; action =&lt;br /&gt;        context =&amp;gt; source.QueryBuilder(context).First();&lt;br /&gt;    return source.Context.Execute(action);&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;
Now seeing as we have dozens of methods to implement like this, it seems an opportune time for a bit of eager refactoring. Recognizing that the only variance is the method call on the &lt;code&gt;IQueryable&lt;/code&gt;, let's extract an extension method that does everything else:
&lt;/p&gt;
&lt;pre&gt;private static TResult Execute&amp;lt;TSource, TContext, TResult, TQuery&amp;gt;(&lt;br /&gt;        this ILazyQueryable&amp;lt;TContext, TSource, TQuery&amp;gt; source,&lt;br /&gt;        Func&amp;lt;TQuery, TResult&amp;gt; queryOperation&lt;br /&gt;    ) where TQuery : IQueryable&amp;lt;TSource&amp;gt;&lt;br /&gt;{&lt;br /&gt;    return source.Context.Execute(&lt;br /&gt;        context =&amp;gt; queryOperation(source.QueryBuilder(context)));&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;
From there, additional lazy operators are just a lambda expression away:
&lt;/p&gt;
&lt;pre&gt;public static TSource First&amp;lt;TSource, TContext, TQuery&amp;gt;(&lt;br /&gt;        this ILazyQueryable&amp;lt;TContext, TSource, TQuery&amp;gt; source&lt;br /&gt;    ) where TQuery : IQueryable&amp;lt;TSource&amp;gt;&lt;br /&gt;{&lt;br /&gt;    return source.Execute(q =&amp;gt; q.First());&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public static TAccumulate Aggregate&amp;lt;TContext, TSource, TQuery, TAccumulate&amp;gt;(&lt;br /&gt;        this ILazyQueryable&amp;lt;TContext, TSource, TQuery&amp;gt; source,&lt;br /&gt;        TAccumulate seed, Expression&amp;lt;Func&amp;lt;TAccumulate, TSource, TAccumulate&amp;gt;&amp;gt; func&lt;br /&gt;    ) where TQuery : IQueryable&amp;lt;TSource&amp;gt;&lt;br /&gt;{&lt;br /&gt;    return source.Execute(q =&amp;gt; q.Aggregate(seed, func));&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;
And now having done the hard part (finding an &lt;code&gt;IQueryable&lt;/code&gt;), we can translate that understanding to make similar helpers for queries:
&lt;/p&gt;
&lt;pre&gt;private static ILazyQueryable&amp;lt;TContext, TResult, IQueryable&amp;lt;TResult&amp;gt;&amp;gt;&lt;br /&gt;    CreateQuery&amp;lt;TSource, TContext, TQuery, TResult&amp;gt;(&lt;br /&gt;        this ILazyQueryable&amp;lt;TContext, TSource, TQuery&amp;gt; source,&lt;br /&gt;        Func&amp;lt;TQuery, IQueryable&amp;lt;TResult&amp;gt;&amp;gt; queryOperation&lt;br /&gt;    ) where TQuery : IQueryable&amp;lt;TSource&amp;gt;&lt;br /&gt;{&lt;br /&gt;    return source.Context.CreateQuery&amp;lt;TResult, IQueryable&amp;lt;TResult&amp;gt;&amp;gt;(&lt;br /&gt;        context =&amp;gt; queryOperation(source.QueryBuilder(context)));&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;private static ILazyOrderedQueryable&amp;lt;TContext, TResult, IOrderedQueryable&amp;lt;TResult&amp;gt;&amp;gt;&lt;br /&gt;    CreateOrderedQuery&amp;lt;TSource, TContext, TQuery, TResult&amp;gt;(&lt;br /&gt;        this ILazyQueryable&amp;lt;TContext, TSource, TQuery&amp;gt; source,&lt;br /&gt;        Func&amp;lt;TQuery, IOrderedQueryable&amp;lt;TResult&amp;gt;&amp;gt; queryOperation&lt;br /&gt;    ) where TQuery : IQueryable&amp;lt;TSource&amp;gt;&lt;br /&gt;{&lt;br /&gt;    return source.Context.CreateOrderedQuery&amp;lt;TResult, IOrderedQueryable&amp;lt;TResult&amp;gt;&amp;gt;(&lt;br /&gt;        context =&amp;gt; queryOperation(source.QueryBuilder(context)));&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;
With similarly trivial query operator implementations:
&lt;/p&gt;
&lt;pre&gt;public static ILazyQueryable&amp;lt;TContext, TResult, IQueryable&amp;lt;TResult&amp;gt;&amp;gt;&lt;br /&gt;    Select&amp;lt;TContext, TSource, TQuery, TResult&amp;gt;(&lt;br /&gt;        this ILazyQueryable&amp;lt;TContext, TSource, TQuery&amp;gt; source,&lt;br /&gt;        Expression&amp;lt;Func&amp;lt;TSource, TResult&amp;gt;&amp;gt; selector&lt;br /&gt;    ) where TQuery : IQueryable&amp;lt;TSource&amp;gt;&lt;br /&gt;{&lt;br /&gt;    return source.CreateQuery(q =&amp;gt; q.Select(selector));&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public static ILazyOrderedQueryable&amp;lt;TContext, TSource, IOrderedQueryable&amp;lt;TSource&amp;gt;&amp;gt;&lt;br /&gt;    OrderBy&amp;lt;TContext, TSource, TQuery, TKey&amp;gt;(&lt;br /&gt;        this ILazyQueryable&amp;lt;TContext, TSource, TQuery&amp;gt; source,&lt;br /&gt;        Expression&amp;lt;Func&amp;lt;TSource, TKey&amp;gt;&amp;gt; keySelector&lt;br /&gt;    ) where TQuery : IQueryable&amp;lt;TSource&amp;gt;&lt;br /&gt;{&lt;br /&gt;    return source.CreateOrderedQuery(q =&amp;gt; q.OrderBy(keySelector));&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;
And the end result:

&lt;img title="LazyLinq.First" src="http://solutionizing.wordpress.com/files/2009/08/lazylinq-first.png" alt="LazyLinq.First" height="226" width="739" /&gt;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;a href="http://www.dotnetkicks.com/kick/?title=Introducing+LazyLinq%3a+Queryability&amp;url=http%3a%2f%2fwww.lostechies.com%2fblogs%2fdahlbyk%2farchive%2f2009%2f08%2f20%2fintroducing-lazylinq-queryability.aspx"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.lostechies.com%2fblogs%2fdahlbyk%2farchive%2f2009%2f08%2f20%2fintroducing-lazylinq-queryability.aspx" border="0" alt="Kick It on DotNetKicks.com" /&gt;&lt;/a&gt;&lt;img src="http://www.lostechies.com/aggbug.aspx?PostID=23921" width="1" height="1"&gt;</content><author><name>dahlbyk</name><uri>http://www.lostechies.com/members/dahlbyk/default.aspx</uri></author><category term="LINQ" scheme="http://www.lostechies.com/blogs/dahlbyk/archive/tags/LINQ/default.aspx" /><category term="LazyLinq" scheme="http://www.lostechies.com/blogs/dahlbyk/archive/tags/LazyLinq/default.aspx" /><category term="ILazyQueryable" scheme="http://www.lostechies.com/blogs/dahlbyk/archive/tags/ILazyQueryable/default.aspx" /><category term="Queryable" scheme="http://www.lostechies.com/blogs/dahlbyk/archive/tags/Queryable/default.aspx" /></entry><entry><title>Introducing LazyLinq: Internals</title><link rel="alternate" type="text/html" href="/blogs/dahlbyk/archive/2009/08/18/introducing-lazylinq-internals.aspx" /><id>/blogs/dahlbyk/archive/2009/08/18/introducing-lazylinq-internals.aspx</id><published>2009-08-18T05:25:00Z</published><updated>2009-08-18T05:25:00Z</updated><content type="html">&lt;p&gt;This is the second in a series of posts on LazyLinq, a wrapper to support lazy initialization and deferred disposal of a LINQ query context:
&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;a href="http://solutionizing.net/2009/08/06/introducing-lazylinq-overview/"&gt;Introducing LazyLinq: Overview&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Introducing LazyLinq: Internals&lt;/b&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://solutionizing.net/2009/08/20/introducing-lazylinq-queryability/"&gt;Introducing LazyLinq: Queryability&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://solutionizing.net/2009/09/12/simplifying-lazylinq/"&gt;Simplifying LazyLinq&lt;/a&gt;&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;Introducing LazyLinq: Lazy DataContext&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
My first post introduced the three interfaces that LazyLinq provides. Next, we get to implement them.
&lt;/p&gt;
&lt;h2&gt;Implementing ILazyQueryable&lt;/h2&gt;
&lt;p&gt;
First, the interface:
&lt;/p&gt;
&lt;pre&gt;    public interface ILazyQueryable&amp;lt;TContext, TSource, TQuery&amp;gt;&lt;br /&gt;        : IQueryable&amp;lt;TSource&amp;gt;&lt;br /&gt;        where TQuery : IQueryable&amp;lt;TSource&amp;gt;&lt;br /&gt;    {&lt;br /&gt;        ILazyContext&amp;lt;TContext&amp;gt; Context { get; }&lt;br /&gt;        Func&amp;lt;TContext, TQuery&amp;gt; QueryBuilder { get; }&lt;br /&gt;    }&lt;/pre&gt;
&lt;p&gt;
We'll start simple with an implicit implementation of the interface and a trivial constructor:
&lt;/p&gt;
&lt;pre&gt;    class LazyQueryableImpl&amp;lt;TContext, TSource, TQuery&amp;gt;&lt;br /&gt;            : ILazyQueryable&amp;lt;TContext, TSource, TQuery&amp;gt;&lt;br /&gt;            where TQuery : IQueryable&amp;lt;TSource&amp;gt;&lt;br /&gt;    {&lt;br /&gt;            public ILazyContext&amp;lt;TContext&amp;gt; Context { get; private set; }&lt;br /&gt;            public Func&amp;lt;TContext, TQuery&amp;gt; QueryBuilder { get; private set; }&lt;br /&gt;&lt;br /&gt;            internal LazyQueryableImpl(ILazyContext&amp;lt;TContext&amp;gt; deferredContext, Func&amp;lt;TContext, TQuery&amp;gt; queryBuilder)&lt;br /&gt;            {&lt;br /&gt;                if (deferredContext == null) throw new ArgumentNullException("deferredContext");&lt;br /&gt;                if (queryBuilder == null) throw new ArgumentNullException("queryBuilder");&lt;br /&gt;&lt;br /&gt;                Context = deferredContext;&lt;br /&gt;                QueryBuilder = queryBuilder;&lt;br /&gt;            }&lt;/pre&gt;
&lt;p&gt;
Next, a lazy-loaded query built from our lazy context:
&lt;/p&gt;
&lt;pre&gt;            protected TQuery Query&lt;br /&gt;            {&lt;br /&gt;                get&lt;br /&gt;                {&lt;br /&gt;                    if (query == null)&lt;br /&gt;                    {&lt;br /&gt;                        query = QueryBuilder(Context.Context);&lt;br /&gt;                        if (query == null)&lt;br /&gt;                            throw new InvalidOperationException("Query built as null.");&lt;br /&gt;                    }&lt;br /&gt;                    return query;&lt;br /&gt;                }&lt;br /&gt;            }&lt;/pre&gt;
&lt;p&gt;
And the internals of managing &lt;code&gt;Context&lt;/code&gt;, which implements &lt;code&gt;IDisposable&lt;/code&gt;:
&lt;/p&gt;
&lt;pre&gt;            private void Dispose()&lt;br /&gt;            {&lt;br /&gt;                Context.Dispose();&lt;br /&gt;                query = default(TQuery);&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            private IEnumerator&amp;lt;TSource&amp;gt; GetEnumerator()&lt;br /&gt;            {&lt;br /&gt;                try&lt;br /&gt;                {&lt;br /&gt;                    foreach (var i in Query)&lt;br /&gt;                        yield return i;&lt;br /&gt;                }&lt;br /&gt;                finally&lt;br /&gt;                {&lt;br /&gt;                    Dispose();&lt;br /&gt;                }&lt;br /&gt;            }&lt;/pre&gt;
&lt;p&gt;
Since &lt;code&gt;Query&lt;/code&gt; depends on &lt;code&gt;Context&lt;/code&gt;, once &lt;code&gt;Context&lt;/code&gt; is disposed we need to reset &lt;code&gt;Query&lt;/code&gt; so a new one can be built (if possible). Note that we use an iterator here to return an &lt;code&gt;IEnumerator&amp;lt;TSource&amp;gt;&lt;/code&gt;, rather than the usual &lt;code&gt;IEnumerable&amp;lt;&amp;gt;&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Finally, we'll close out by explicitly implementing &lt;code&gt;IQueryable&lt;/code&gt;:
&lt;/p&gt;
&lt;pre&gt;            IEnumerator&amp;lt;TSource&amp;gt; IEnumerable&amp;lt;TSource&amp;gt;.GetEnumerator()&lt;br /&gt;            {&lt;br /&gt;                return GetEnumerator();&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            IEnumerator IEnumerable.GetEnumerator()&lt;br /&gt;            {&lt;br /&gt;                return GetEnumerator();&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            Type IQueryable.ElementType&lt;br /&gt;            {&lt;br /&gt;                get { return Query.ElementType; }&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            Expression IQueryable.Expression&lt;br /&gt;            {&lt;br /&gt;                get { return Query.Expression; }&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            IQueryProvider IQueryable.Provider&lt;br /&gt;            {&lt;br /&gt;                get { return Query.Provider; }&lt;br /&gt;            }&lt;br /&gt;        }&lt;/pre&gt;
&lt;p&gt;
If this seemed relatively simple, you're right. We're just building a lazy-loaded &lt;code&gt;Query&lt;/code&gt; proxy, with a bit of plumbing to clean up our &lt;code&gt;Context&lt;/code&gt;.
&lt;/p&gt;
&lt;h2&gt;Implementing ILazyOrderedQueryable&lt;/h2&gt;
&lt;p&gt;
Not very exciting, but for completeness:
&lt;/p&gt;
&lt;pre&gt;        public interface ILazyOrderedQueryable&amp;lt;TContext, TSource, TQuery&amp;gt;&lt;br /&gt;            : ILazyQueryable&amp;lt;TContext, TSource, TQuery&amp;gt;, IOrderedQueryable&amp;lt;TSource&amp;gt;&lt;br /&gt;            where TQuery : IOrderedQueryable&amp;lt;TSource&amp;gt;&lt;br /&gt;        { }&lt;br /&gt;&lt;br /&gt;        class LazyOrderedQueryableImpl&amp;lt;TContext, TSource, TQuery&amp;gt;&lt;br /&gt;                : LazyQueryableImpl&amp;lt;TContext, TSource, TQuery&amp;gt;, ILazyOrderedQueryable&amp;lt;TContext, TSource, TQuery&amp;gt;&lt;br /&gt;                where TQuery : IOrderedQueryable&amp;lt;TSource&amp;gt;&lt;br /&gt;        {&lt;br /&gt;            internal LazyOrderedQueryableImpl(ILazyContext&amp;lt;TContext&amp;gt; lazyContext, Func&amp;lt;TContext, TQuery&amp;gt; queryBuilder)&lt;br /&gt;                : base(lazyContext, queryBuilder)&lt;br /&gt;            {&lt;br /&gt;            }&lt;br /&gt;        }&lt;/pre&gt;
&lt;h2&gt;LazyQueryable Factory&lt;/h2&gt;
&lt;p&gt;
Consumers of this API should never need to know about these implementation details, so we can hide them behind a factory class:
&lt;/p&gt;
&lt;pre&gt;        public static class LazyQueryable&lt;br /&gt;        {&lt;br /&gt;            public static ILazyQueryable&amp;lt;TContext, TResult, TQuery&amp;gt; CreateQuery&amp;lt;TContext, TResult, TQuery&amp;gt;(&lt;br /&gt;                ILazyContext&amp;lt;TContext&amp;gt; context, Func&amp;lt;TContext, TQuery&amp;gt; queryBuilder)&lt;br /&gt;                where TQuery : IQueryable&amp;lt;TResult&amp;gt;&lt;br /&gt;            {&lt;br /&gt;                return new LazyQueryableImpl&amp;lt;TContext, TResult, TQuery&amp;gt;(context, queryBuilder);&lt;br /&gt;            }&lt;br /&gt;            public static ILazyOrderedQueryable&amp;lt;TContext, TResult, TQuery&amp;gt; CreateOrderedQuery&amp;lt;TContext, TResult, TQuery&amp;gt;(&lt;br /&gt;                ILazyContext&amp;lt;TContext&amp;gt; context, Func&amp;lt;TContext, TQuery&amp;gt; queryBuilder)&lt;br /&gt;                where TQuery : IOrderedQueryable&amp;lt;TResult&amp;gt;&lt;br /&gt;            {&lt;br /&gt;                return new LazyOrderedQueryableImpl&amp;lt;TContext, TResult, TQuery&amp;gt;(context, queryBuilder);&lt;br /&gt;            }&lt;br /&gt;        }&lt;/pre&gt;
&lt;h2&gt;Implementing ILazyContext&lt;/h2&gt;
&lt;p&gt;
Again, we'll start with the interface:
&lt;/p&gt;
&lt;pre&gt;        public interface ILazyContext&amp;lt;TContext&amp;gt; : IDisposable&lt;br /&gt;        {&lt;br /&gt;            TContext Context { get; }&lt;br /&gt;&lt;br /&gt;            ILazyQueryable&amp;lt;TContext, TResult, TQuery&amp;gt;&lt;br /&gt;                CreateQuery&amp;lt;TResult, TQuery&amp;gt;(Func&amp;lt;TContext, TQuery&amp;gt; queryBuilder)&lt;br /&gt;                where TQuery : IQueryable&amp;lt;TResult&amp;gt;;&lt;br /&gt;&lt;br /&gt;            ILazyOrderedQueryable&amp;lt;TContext, TResult, TQuery&amp;gt;&lt;br /&gt;                CreateOrderedQuery&amp;lt;TResult, TQuery&amp;gt;(Func&amp;lt;TContext, TQuery&amp;gt; queryBuilder)&lt;br /&gt;                where TQuery : IOrderedQueryable&amp;lt;TResult&amp;gt;;&lt;br /&gt;&lt;br /&gt;            TResult Execute&amp;lt;TResult&amp;gt;(Func&amp;lt;TContext, TResult&amp;gt; action);&lt;br /&gt;        }&lt;/pre&gt;
&lt;p&gt;
Now we can start fulfilling our requirements:
&lt;/p&gt;
&lt;h3&gt;1. Lazily expose the Context.&lt;/h3&gt;
&lt;pre&gt;        class LazyContextImpl&amp;lt;TContext&amp;gt; : ILazyContext&amp;lt;TContext&amp;gt;, IDisposable&lt;br /&gt;        {&lt;br /&gt;            public Func&amp;lt;TContext&amp;gt; ContextBuilder { get; private set; }&lt;br /&gt;&lt;br /&gt;            private TContext context;&lt;br /&gt;            public TContext Context&lt;br /&gt;            {&lt;br /&gt;                get&lt;br /&gt;                {&lt;br /&gt;                    if (context == null)&lt;br /&gt;                    {&lt;br /&gt;                        context = ContextBuilder();&lt;br /&gt;                        if (context == null)&lt;br /&gt;                            throw new InvalidOperationException("Context built as null.");&lt;br /&gt;                    }&lt;br /&gt;                    return context;&lt;br /&gt;                }&lt;br /&gt;            }&lt;/pre&gt;
&lt;h3&gt;2. Produce lazy wrappers to represent queries retrieved from a context by a delegate.&lt;/h3&gt;
&lt;pre&gt;            public ILazyQueryable&amp;lt;TContext, TResult, TQuery&amp;gt; CreateQuery&amp;lt;TResult, TQuery&amp;gt;(&lt;br /&gt;                Func&amp;lt;TContext, TQuery&amp;gt; queryBuilder)&lt;br /&gt;                where TQuery : IQueryable&amp;lt;TResult&amp;gt;&lt;br /&gt;            {&lt;br /&gt;                return LazyQueryable.CreateQuery&amp;lt;TContext, TResult, TQuery&amp;gt;(this, queryBuilder);&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            public ILazyOrderedQueryable&amp;lt;TContext, TResult, TQuery&amp;gt; CreateOrderedQuery&amp;lt;TResult, TQuery&amp;gt;(&lt;br /&gt;                Func&amp;lt;TContext, TQuery&amp;gt; queryBuilder)&lt;br /&gt;                where TQuery : IOrderedQueryable&amp;lt;TResult&amp;gt;&lt;br /&gt;            {&lt;br /&gt;                return LazyQueryable.CreateOrderedQuery&amp;lt;TContext, TResult, TQuery&amp;gt;(this, queryBuilder);&lt;br /&gt;            }&lt;/pre&gt;
&lt;h3&gt;3. Execute an action on the context.&lt;/h3&gt;
&lt;p&gt;
There are two ways to "complete" a query, and we need to clean up context after each. The first was after enumeration, implemented above. The second is on execute, implemented here:
&lt;/p&gt;
&lt;pre&gt;            public TResult Execute&amp;lt;TResult&amp;gt;(Func&amp;lt;TContext, TResult&amp;gt; expression)&lt;br /&gt;            {&lt;br /&gt;                try&lt;br /&gt;                {&lt;br /&gt;                    return expression(Context);&lt;br /&gt;                }&lt;br /&gt;                finally&lt;br /&gt;                {&lt;br /&gt;                    Dispose();&lt;br /&gt;                }&lt;br /&gt;            }&lt;/pre&gt;
&lt;h3&gt;4. Ensure the context is disposed as necessary.&lt;/h3&gt;
&lt;p&gt;
We don't require that &lt;code&gt;TContext&lt;/code&gt; is &lt;code&gt;IDisposable&lt;/code&gt;, but we need to handle if it is. We also clear context to support reuse.
&lt;/p&gt;
&lt;pre&gt;            public void Dispose()&lt;br /&gt;            {&lt;br /&gt;                var disposable = context as IDisposable;&lt;br /&gt;                if (disposable != null)&lt;br /&gt;                    disposable.Dispose();&lt;br /&gt;&lt;br /&gt;                context = default(TContext);&lt;br /&gt;            }&lt;/pre&gt;
&lt;h3&gt;Constructors&lt;/h3&gt;
&lt;p&gt;
With our requirements met, we just need a way to create our context. We provide two options:
&lt;/p&gt;
&lt;pre&gt;            internal LazyContextImpl(TContext context) : this(() =&amp;gt; context) { }&lt;br /&gt;&lt;br /&gt;            internal LazyContextImpl(Func&amp;lt;TContext&amp;gt; contextBuilder)&lt;br /&gt;            {&lt;br /&gt;                if (contextBuilder == null) throw new ArgumentNullException("contextBuilder");&lt;br /&gt;&lt;br /&gt;                ContextBuilder = contextBuilder;&lt;br /&gt;            }&lt;/pre&gt;
&lt;p&gt;
The former wraps an existing &lt;code&gt;TContext&lt;/code&gt; instance in a closure, meaning every time &lt;code&gt;ContextBuilder&lt;/code&gt; is called it returns the same instance. The latter accepts any delegate that returns a &lt;code&gt;TContext&lt;/code&gt;. The most common such delegate would be a simple instantiation: &lt;code&gt;() =&amp;gt; new MyDataContext()&lt;/code&gt;.

&lt;/p&gt;
&lt;p&gt;It should be clear now why we would want to clear our context on dispose. If &lt;code&gt;ContextBuilder&lt;/code&gt; returns a new context instance each time, it's perfectly safe to discard of the old (disposed) context to trigger the creation of a new one. Conversely, if the builder returns a single instance, using the context after disposal would trigger an &lt;code&gt;ObjectDisposedException&lt;/code&gt; or something similar.
&lt;/p&gt;
&lt;h2&gt;LazyContext Factory&lt;/h2&gt;
&lt;p&gt;
For consistency, we should also provide factory methods to hide this specific implementation:
&lt;/p&gt;
&lt;pre&gt;            public static class LazyContext&lt;br /&gt;            {&lt;br /&gt;                public static ILazyContext&amp;lt;T&amp;gt; Create&amp;lt;T&amp;gt;(T context)&lt;br /&gt;                {&lt;br /&gt;                    return new LazyContextImpl&amp;lt;T&amp;gt;(context);&lt;br /&gt;                }&lt;br /&gt;                public static ILazyContext&amp;lt;T&amp;gt; Create&amp;lt;T&amp;gt;(Func&amp;lt;T&amp;gt; contextBuilder)&lt;br /&gt;                {&lt;br /&gt;                    return new LazyContextImpl&amp;lt;T&amp;gt;(contextBuilder);&lt;br /&gt;                }&lt;br /&gt;            }&lt;/pre&gt;
&lt;h2&gt;Lazy Extensions&lt;/h2&gt;
&lt;p&gt;
And last, but certainly not least, we're ready to reimplement our &lt;code&gt;Use()&lt;/code&gt; extension methods:
&lt;/p&gt;
&lt;pre&gt;    public static class Lazy&lt;br /&gt;    {&lt;br /&gt;        public static ILazyContext&amp;lt;TContext&amp;gt; Use&amp;lt;TContext&amp;gt;(this TContext @this)&lt;br /&gt;        {&lt;br /&gt;            return LazyContext.Create&amp;lt;TContext&amp;gt;(@this);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public static ILazyContext&amp;lt;TContext&amp;gt; Use&amp;lt;TContext&amp;gt;(this Func&amp;lt;TContext&amp;gt; @this)&lt;br /&gt;        {&lt;br /&gt;            return LazyContext.Create&amp;lt;TContext&amp;gt;(@this);&lt;br /&gt;        }&lt;br /&gt;    }&lt;/pre&gt;
&lt;p&gt;
With several usage possibilities:
&lt;/p&gt;
&lt;pre&gt;    var r1 = from x in new MyDataContext().Use() ...;&lt;br /&gt;&lt;br /&gt;    Func&amp;lt;MyDataContext&amp;gt; f1 = () =&amp;gt; new MyDataContext();&lt;br /&gt;    var r2 = from x in f1.Use() ...;&lt;br /&gt;&lt;br /&gt;    var r3 = from x in new Func&amp;lt;MyDataContext&amp;gt;(() =&amp;gt; new MyDataContext()).Use() ...;&lt;br /&gt;&lt;br /&gt;    var r4 = from x in Lazy.Use(() =&amp;gt; new MyDataContext()) ...;&lt;/pre&gt;
&lt;p&gt;
Or maybe we can make it even easier. Maybe...&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;a href="http://www.dotnetkicks.com/kick/?title=Introducing+LazyLinq%3a+Internals&amp;url=http%3a%2f%2fwww.lostechies.com%2fblogs%2fdahlbyk%2farchive%2f2009%2f08%2f18%2fintroducing-lazylinq-internals.aspx"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.lostechies.com%2fblogs%2fdahlbyk%2farchive%2f2009%2f08%2f18%2fintroducing-lazylinq-internals.aspx" border="0" alt="Kick It on DotNetKicks.com" /&gt;&lt;/a&gt;&lt;img src="http://www.lostechies.com/aggbug.aspx?PostID=23817" width="1" height="1"&gt;</content><author><name>dahlbyk</name><uri>http://www.lostechies.com/members/dahlbyk/default.aspx</uri></author></entry></feed>