<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://community.bartdesmet.net/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>B# .NET Blog</title><link>http://community.bartdesmet.net/blogs/bart/default.aspx</link><description>Bart De Smet&amp;#39;s on-line blog (0x2B | ~0x2B, that&amp;#39;s the question)</description><dc:language>en</dc:language><generator>CommunityServer 2007 (Build: 20423.869)</generator><item><title>Getting Started with Active Directory Lightweight Directory Services</title><link>http://community.bartdesmet.net/blogs/bart/archive/2010/07/12/getting-started-with-active-directory-lightweight-directory-services.aspx</link><pubDate>Tue, 13 Jul 2010 01:52:32 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:21656</guid><dc:creator>bart</dc:creator><slash:comments>7</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://community.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=21656</wfw:commentRss><comments>http://community.bartdesmet.net/blogs/bart/archive/2010/07/12/getting-started-with-active-directory-lightweight-directory-services.aspx#comments</comments><description>&lt;h1&gt;Introduction&lt;/h1&gt;  &lt;p&gt;In preparation for some upcoming posts related to LINQ (what else?), Windows PowerShell and Rx, I had to set up a local LDAP-capable directory service. (Hint: It will pay off to read till the very end of the post if you’re wondering what I’m up to...) In this post I’ll walk the reader through the installation, configuration and use of &lt;a href="http://www.microsoft.com/windowsserver2008/en/us/ad-lds.aspx"&gt;Active Directory Lightweight Directory Services (LDS)&lt;/a&gt;, formerly known as Active Directory Application Mode (ADAM). Having used the technology several years ago, in relation to the &lt;a href="http://linqtoad.codeplex.com/"&gt;LINQ to Active Directory&lt;/a&gt; project (which as an extension to this blog series will receive an update), it was a warm and welcome reencounter.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;What’s Lightweight Directory Services anyway?&lt;/h1&gt;  &lt;p&gt;Use of hierarchical storage and auxiliary services provided by technologies like Active Directory often has advantages over alternative designs, e.g. using a relational database. For example, user accounts may be stored in a directory service for an application to make use of. While Active Directory seems the natural habitat to store (and replicate, secure, etc.) additional user information, IT admins will likely point you – the poor developer – at the door when asking to extend the schema. That’s one of the places where LDS comes in, offering the ability to take advantage of the programming model of directory services while keeping your hands off “the one and only AD schema”.&lt;/p&gt;  &lt;p&gt;The &lt;a href="http://www.microsoft.com/windowsserver2008/en/us/ad-lds.aspx#none"&gt;LDS website&lt;/a&gt; quotes other use cases, which I’ll just copy here verbatim:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;em&gt;Active Directory Lightweight Directory Service (AD LDS), formerly known as Active Directory Application Mode, can be used to provide directory services for directory-enabled applications. Instead of using your organization’s AD DS database to store the directory-enabled application data, AD LDS can be used to store the data. AD LDS can be used in conjunction with AD DS so that you can have a central location for security accounts (AD DS) and another location to support the application configuration and directory data (AD LDS). Using AD LDS, you can reduce the overhead associated with Active Directory replication, you do not have to extend the Active Directory schema to support the application, and you can partition the directory structure so that the AD LDS service is only deployed to the servers that need to support the directory-enabled application. &lt;/em&gt;&lt;/p&gt;    &lt;ul&gt;     &lt;li&gt;       &lt;p&gt;&lt;em&gt;&lt;b&gt;Install from Media Generation.&lt;/b&gt; The ability to create installation media for AD LDS by using Ntdsutil.exe or Dsdbutil.exe.&lt;/em&gt;&lt;/p&gt;     &lt;/li&gt;      &lt;li&gt;       &lt;p&gt;&lt;em&gt;&lt;b&gt;Auditing.&lt;/b&gt; Auditing of changed values within the directory service.&lt;/em&gt;&lt;/p&gt;     &lt;/li&gt;      &lt;li&gt;       &lt;p&gt;&lt;em&gt;&lt;b&gt;Database Mounting Tool.&lt;/b&gt; Gives you the ability to view data within snapshots of the database files.&lt;/em&gt;&lt;/p&gt;     &lt;/li&gt;      &lt;li&gt;       &lt;p&gt;&lt;em&gt;&lt;b&gt;Active Directory Sites and Services Support.&lt;/b&gt; Gives you the ability to use Active Directory Sites and Services to manage the replication of the AD LDS data changes.&lt;/em&gt;&lt;/p&gt;     &lt;/li&gt;      &lt;li&gt;       &lt;p&gt;&lt;em&gt;&lt;b&gt;Dynamic List of LDIF files.&lt;/b&gt; With this feature, you can associate custom LDIF files with the existing default LDIF files used for setup of AD LDS on a server.&lt;/em&gt;&lt;/p&gt;     &lt;/li&gt;      &lt;li&gt;       &lt;p&gt;&lt;em&gt;&lt;b&gt;Recursive Linked-Attribute Queries.&lt;/b&gt; LDAP queries can follow nested attribute links to determine additional attribute properties, such as group memberships.&lt;/em&gt;&lt;/p&gt;     &lt;/li&gt;   &lt;/ul&gt; &lt;/blockquote&gt;  &lt;p&gt;Obviously that last bullet point grabs my attention through I will retain myself from digressing here.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Getting started&lt;/h1&gt;  &lt;p&gt;If you’re running Windows 7, the following explanation is the right one for you. For older versions of the operating system, things are pretty similar though different downloads will have to be used. For Windows Server 2008, a server role exists for LDS. So, assuming you’re on Windows 7, start by &lt;a href="http://www.microsoft.com/downloads/details.aspx?displaylang=en&amp;amp;FamilyID=a45059af-47a8-4c96-afe3-93dab7b5b658"&gt;downloading the installation media over here&lt;/a&gt;. After installing this, you should find an entry “Active Directory Lightweight Directory Services Setup Wizard” under the “Administrative Tools” section in “Control Panel”:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_thumb.png" width="587" height="330" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;LDS allows you to install multiple instances of directory services on the same machine, just like SQL Server allows multiple server instances to co-exist. Each instance has a name and listens on certain ports using the LDP protocol. Starting this wizard – which lives under %SystemRoot%\ADAM\adaminstall.exe, revealing the former product name – brings us here:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_3.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_thumb_3.png" width="513" height="398" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;After clicking Next, we need to decide whether we create a new unique instance that hasn’t any ties with existing instances, or whether we want to create a replicate of an existing instance. For our purposes, the first option is what we need:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_4.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_thumb_4.png" width="513" height="398" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Next, we’re asked for an instance name. The instance name will be used for the creation of a Windows Service, as well as to store some settings. Each instance will get its own Windows Service. In our sample, we’ll create a directory for the Northwind Employees tables, which we’ll use to create accounts further on.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_5.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_thumb_5.png" width="513" height="398" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;We’re almost there with the baseline configuration. The next question is to specify a port number, both for plain TCP and for SSL-encrypted traffic. The default ports, 389 and 636, are fine for us. Later we’ll be able to connect to the instance by connecting to LDP over port 389, e.g. using the System.DirectoryServices namespace functionality in .NET. Notice every instance of LDS should have its own port number, so only one can be using the default port numbers.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_6.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_thumb_6.png" width="513" height="398" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Now that we have completed the “physical administration”, the wizard moves on to a bit of “logical administration”. More specifically, we’re given the option to create a directory partition for the application. Here we choose to create such a partition, though in many concrete deployment scenarios you’ll want the application’s setup to create this at runtime. Our partition’s distinguished name will mimic a “Northwind.local” domain containing a partition called “Employees”:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_7.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_thumb_7.png" width="513" height="398" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;After this bit of logical administration, some more physical configuration has to be carried out, specifying the data files location and the account to run the services under. For both, the default settings are fine. Also the administrative account assigned to manage the LDS instance can be kept as the currently logged in user, unless you feel the need to change this in your scenario:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_8.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_thumb_8.png" width="513" height="398" /&gt;&lt;/a&gt;&amp;#160;&lt;a href="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_9.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_thumb_9.png" width="513" height="398" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Finally, we’ve arrived at an interesting step where we’re given the option to import LDIF files. And LDIF file, with extension .ldf, contains the definition of a class that can be added to a directory service’s schema. Basically those contain things like attributes and their types. Under the %SystemRoot%\ADAM folder, a set of out-of-the-box .ldf files can be found:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_10.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_thumb_10.png" width="669" height="293" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Instead of having to run the ldifde.exe tool, the wizard gives us the option to import LDIF files directly. Those classes are documented in various places, such as &lt;a href="http://www.faqs.org/rfcs/rfc2798.html"&gt;RFC2798 for inetOrgPerson&lt;/a&gt;. On TechNet, information is presented in a more structured manner, e.g revealing that &lt;a href="http://msdn.microsoft.com/en-us/library/ms682282(VS.85).aspx"&gt;inetOrgPerson&lt;/a&gt; is a subclass of &lt;a href="http://msdn.microsoft.com/en-us/library/ms683980(v=VS.85).aspx"&gt;user&lt;/a&gt;. Custom classes can be defined and imported after setup has completed. In this post, we won’t extend the schema ourselves but we will simply be using the built-in User class so let’s tick that one:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_11.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_thumb_11.png" width="513" height="398" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;After clicking Next, we get a last chance to revisit our settings or can confirm the installation. At this point, the wizard will create the instance – setting up the service – and import the LDIF files.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_12.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_thumb_12.png" width="513" height="398" /&gt;&lt;/a&gt;&amp;#160;&lt;a href="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_13.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_thumb_13.png" width="513" height="398" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Congratulations! Your first LDS instance has materialized. If everything went alright, the NorthwindEmployees service should show up:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_14.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_thumb_14.png" width="1091" height="329" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Inspecting the directory&lt;/h1&gt;  &lt;p&gt;To inspect the newly created directory instance, a bunch of tools exist. One is ADSI Edit which you could already see in the Administrative Tools. To set it up, open the MMC-based tool and go to Action, Connect to… In the dialog that appears, specify the server name and choose Schema as the Naming Context.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_15.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_thumb_15.png" width="394" height="392" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;For example, if you want to inspect the User class, simply navigate to the Schema node in the tree and show the properties of the User entry.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_16.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_thumb_16.png" width="866" height="234" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;To visualize the objects in the application partition, connect using the distinguished name specified during the installation:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_17.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_thumb_17.png" width="394" height="392" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Now it’s possible to create a new object in the directory using the context menu in the content pane:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_18.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_thumb_18.png" width="626" height="276" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;After specifying the class, we get to specify the “CN” name (for common name) of the object. In this case, I’ll use my full name:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_19.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_thumb_19.png" width="451" height="384" /&gt;&lt;/a&gt;&amp;#160;&lt;a href="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_20.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_thumb_20.png" width="451" height="384" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;We can also set additional attributes, as shown below (using the “physicalDeliveryOfficeName” to specify the office number of the user):&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_21.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_thumb_21.png" width="451" height="384" /&gt;&lt;/a&gt;&amp;#160;&lt;a href="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_22.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_thumb_22.png" width="414" height="461" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;After clicking Set, closing the Attributes dialog and clicking Finish to create the object, we see it pop up in the items view of the ADSI editor snap-in:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_23.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_thumb_23.png" width="572" height="367" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Programmatic population of the directory&lt;/h1&gt;  &lt;p&gt;Obviously we’re much more interested in a programmatic way to program Directory Services. .NET supports the use of directory services and related protocols (LDAP in particular) through the System.DirectoryServices namespace. In a plain new Console Application, add a reference to the assembly with the same name (don’t both about other assemblies that deal with account management and protocol stuff):&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_24.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_thumb_24.png" width="468" height="208" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;For this sample, I’ll also assume the reader got a Northwind SQL database sitting somewhere and knows how to get data out of its Employees table as rich objects. Below is how things look when using the LINQ to SQL designer:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_25.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_thumb_25.png" width="260" height="495" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;We’ll just import a few details about the users; it’s left to the reader to map other properties onto attributes using the &lt;a href="http://msdn.microsoft.com/en-us/library/ms683980(v=VS.85).aspx"&gt;documentation about the user directory services class&lt;/a&gt;. Just a few lines of code suffice to accomplish the task (assuming the System.DirectoryServices namespace is imported):&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;static void &lt;/span&gt;Main()
{
    &lt;span style="color:blue;"&gt;var &lt;/span&gt;path = &lt;span style="color:#a31515;"&gt;&amp;quot;LDAP://bartde-hp07/CN=Employees,DC=Northwind,DC=local&amp;quot;&lt;/span&gt;;
    &lt;span style="color:blue;"&gt;var &lt;/span&gt;root = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DirectoryEntry&lt;/span&gt;(path);

    &lt;span style="color:blue;"&gt;var &lt;/span&gt;ctx = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;NorthwindDataContext&lt;/span&gt;();
    &lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:blue;"&gt;var &lt;/span&gt;e &lt;span style="color:blue;"&gt;in &lt;/span&gt;ctx.Employees)
    {
        &lt;span style="color:blue;"&gt;var &lt;/span&gt;cn = &lt;span style="color:#a31515;"&gt;&amp;quot;CN=&amp;quot; &lt;/span&gt;+ e.FirstName + e.LastName;

        &lt;span style="color:blue;"&gt;var &lt;/span&gt;u = root.Children.Add(cn, &lt;span style="color:#a31515;"&gt;&amp;quot;user&amp;quot;&lt;/span&gt;);
        u.Properties[&lt;span style="color:#a31515;"&gt;&amp;quot;employeeID&amp;quot;&lt;/span&gt;].Value = e.EmployeeID;
        u.Properties[&lt;span style="color:#a31515;"&gt;&amp;quot;sn&amp;quot;&lt;/span&gt;].Value = e.LastName;
        u.Properties[&lt;span style="color:#a31515;"&gt;&amp;quot;givenName&amp;quot;&lt;/span&gt;].Value = e.FirstName;
        u.Properties[&lt;span style="color:#a31515;"&gt;&amp;quot;comment&amp;quot;&lt;/span&gt;].Value = e.Notes;
        u.Properties[&lt;span style="color:#a31515;"&gt;&amp;quot;homePhone&amp;quot;&lt;/span&gt;].Value = e.HomePhone;
        u.Properties[&lt;span style="color:#a31515;"&gt;&amp;quot;photo&amp;quot;&lt;/span&gt;].Value = e.Photo.ToArray();
        u.CommitChanges();
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;After running this code – obviously changing the LDAP path to reflect your setup – you should see the following in ADSI Edit (after hitting refresh):&lt;/p&gt;

&lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_26.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_thumb_26.png" width="918" height="338" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;Now it’s just plain easy to write an application that visualizes the employees with their data. We’ll leave that to the UI-savvy reader (just to tease that segment of my audience, I’ve also imported the employee’s photo as a byte-array).&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;A small preview of what’s coming up&lt;/h1&gt;

&lt;p&gt;To whet the reader’s appetite about next episodes on this blog, below is a single screenshot illustrating something – IMHO – rather cool (use of &lt;a href="http://linqtoad.codeplex.com/"&gt;LINQ to Active Directory&lt;/a&gt; is just an implementation &lt;em&gt;detail &lt;/em&gt;below):&lt;/p&gt;

&lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_27.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/GettingStartedwithActiveDirectoryLightwe_F193/image_thumb_27.png" width="681" height="205" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; What’s shown here is the result of a &lt;font color="#ff0000"&gt;very early experiment&lt;/font&gt; done as part of my current job on “LINQ to Anything” here in the “Cloud Data Programmability Team”. Please don’t fantasize about it as being a vNext feature of any product involved whatsoever. The core intent of those experiments is to emphasize the omnipresence of LINQ (and more widely, monads) in today’s (and tomorrow’s) world. While we’re not ready to reveal the “LINQ to Anything” mission in all its glory (rather think of it as “LINQ to the unimaginable”), we can drop some hints.&lt;/p&gt;

&lt;p&gt;Stay tuned for more!&lt;/p&gt;&lt;img src="http://community.bartdesmet.net/aggbug.aspx?PostID=21656" width="1" height="1"&gt;</description></item><item><title>The Case of The Failed Demo – StackOverflowException on x64</title><link>http://community.bartdesmet.net/blogs/bart/archive/2010/07/07/the-case-of-the-failed-demo-stackoverflowexception-on-x64.aspx</link><pubDate>Wed, 07 Jul 2010 09:34:57 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:21619</guid><dc:creator>bart</dc:creator><slash:comments>5</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://community.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=21619</wfw:commentRss><comments>http://community.bartdesmet.net/blogs/bart/archive/2010/07/07/the-case-of-the-failed-demo-stackoverflowexception-on-x64.aspx#comments</comments><description>&lt;h1&gt;Introduction&lt;/h1&gt;  &lt;p&gt;A while ago I was explaining runtime mechanisms like the stack and the heap to some folks. (As an aside, I’m writing a debugger course on “Advanced .NET Debugging with WinDbg with SOS”, which is an ongoing project. Time will tell when it’s ready to hit the streets.) Since the context was &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2009/11/08/jumping-the-trampoline-in-c-stack-friendly-recursion.aspx"&gt;functional programming where recursion is a typical substitute (or fuel if you will) for loops&lt;/a&gt;, an obvious topic for discussion is the possibility to hit a stack overflow. Armed with my favorite editor, Notepad.exe, and the C# command-line compiler, I quickly entered the following sample to show “looping with recursion” and how disaster can strike:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;using System; &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;class Program       &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; static void Main()        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Rec(0);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; } &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; static void Rec(int n)       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; if (n % 1024 == 0)        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(n); &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;strong&gt;Rec(n + 1);&lt;/strong&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The module-based condition in there is to avoid excessive slowdowns due to Console.WriteLine use, which is rather slow due to the way the Win32 console output system works. To my initial surprise, the overflow didn’t come anywhere in sight and the application kept running happily:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/TheCaseofTheFailedDemoStackOverflowExcep_BE15/image.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/TheCaseofTheFailedDemoStackOverflowExcep_BE15/image_thumb.png" width="677" height="162" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;I rather expected something along the following lines:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/TheCaseofTheFailedDemoStackOverflowExcep_BE15/image_3.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/TheCaseofTheFailedDemoStackOverflowExcep_BE15/image_thumb_3.png" width="677" height="162" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;So, what’s going on here? Though I realized pretty quickly what the root cause is of this unexpected good behavior, I’ll walk the reader through the thought process used to “debug” the application’s code.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;I made a call, didn’t I?&lt;/h1&gt;  &lt;p&gt;The first thing to check is that we really are making a recursive call in our Rec method. Obviously ildasm is the way to go to inspect that kind of stuff, so here’s the output which we did expect.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/TheCaseofTheFailedDemoStackOverflowExcep_BE15/image_4.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/TheCaseofTheFailedDemoStackOverflowExcep_BE15/image_thumb_4.png" width="603" height="458" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;In fact, the statement made above – “which we did expect” – is debatable. Couldn’t the compiler just turn the call into a jump right to the start of the method after messing around a bit with the local argument slot that holds argument value n? That way we wouldn’t have to make a call and the code would still work as expected. Essentially what we’re saying here is that the compiler could have turned the recursive call into a loop construct. And indeed, some compilers do exactly that. For example, consider the following F# sample:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;#light &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;let &lt;strong&gt;rec&lt;/strong&gt; Rec n =        &lt;br /&gt;&amp;#160;&amp;#160; if n % 1024 = 0 then        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; printfn &amp;quot;%d&amp;quot; n &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160; Rec (n + 1) &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;Rec 0&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Notice the explicit indication of the recursive nature of a function by means of the “rec” keyword. After compiling this piece of code using fsc.exe, the following code is shown in Reflector (decompiling to C# syntax) for the Rec function:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/TheCaseofTheFailedDemoStackOverflowExcep_BE15/image_5.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/TheCaseofTheFailedDemoStackOverflowExcep_BE15/image_thumb_5.png" width="1106" height="373" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;The mechanics of the printf call are irrelevant. What matters is the code that’s executed after the n++ statement, which isn’t a recursive call to Rec itself. Instead, the compiler has figured out a loop can be used. Hence, no StackOverflowException will result.&lt;/p&gt;  &lt;p&gt;Back to the C# sample though. What did protect the code from overflowing the stack? Let’s have some further investigations, but first … some background.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Tail calls&lt;/h1&gt;  &lt;p&gt;One optimization that can be carried out for recursive functions is to spot tail calls and optimize them away into looping – or at a lower level, jumps – constructs. A tail call is basically a call after which the current stack frame is no longer needed upon return from the call. For example, our simple sample can benefit from tail call optimization since the Rec method doesn’t really do anything anymore after returning from the recursive Rec call:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;static void Rec(int n)       &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; if (n % 1024 == 0)        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(n); &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;strong&gt;Rec(n + 1);&lt;/strong&gt;        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;This kind of optimization – as carried out by F# in the sample shown earlier – can’t always take place. For example, consider the following definition of a factorial method:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;static int Fac(int n)       &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; if (n == 0)        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; return 1;        &lt;br /&gt;        &lt;br /&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&lt;strong&gt;&amp;#160;&amp;#160;&amp;#160; return n * Fac(n – 1);         &lt;br /&gt;&lt;/strong&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The above has quite a few issues such as the inability to deal with negative values and obviously the arithmetic overflow disaster that will strike when the supplied “n” parameter is too large for the resulting factorial to fit in an Int32. &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2007/02/24/system-numeric-biginteger.aspx"&gt;The BigInteger type introduced in .NET 4 (and not in .NET 3.5 as originally planned)&lt;/a&gt; would be a better fit for this kind of computation, but let’s ignore this fact for now.&lt;/p&gt;  &lt;p&gt;A more relevant issue in the context of our discussion is the code’s use of recursion where a regular loop would suffice, but now I’m making a value judgment of imperative control flow constructs versus a more functional style of using recursion. That’s true nonetheless is the fact that the code above is not immediately amenable for tail call optimization. To see why this is, rewrite the code as follows:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;static int Fac(int n)       &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; if (n == 0)        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; return 1;        &lt;br /&gt;        &lt;br /&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&lt;strong&gt;&amp;#160;&amp;#160;&amp;#160; int t = Fac(n – 1);         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; return n * t;&lt;/strong&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&lt;strong&gt;         &lt;br /&gt;&lt;/strong&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;See what’s going on? After returning from the recursive call to Fac, we still need to have access to the value of “n” in the current call frame. As a result, we can’t reuse the current stack frame when making the recursive call. Implementing the above in F# (just for the sake of it) and decompiling it, shows the following code:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/TheCaseofTheFailedDemoStackOverflowExcep_BE15/image_6.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/TheCaseofTheFailedDemoStackOverflowExcep_BE15/image_thumb_6.png" width="500" height="322" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;The culprit keeping us from employing tail call optimization is the multiplication instruction needed after the return from the recursive call to Fac. (Note: the second operand to the multiplication was pushed onto the evaluation stack in IL_0005; in fact IL_0006 could also have been a dup instruction.) C# code will be slightly different but achieve the same computation (luckily!).&lt;/p&gt;  &lt;p&gt;Sometimes it’s possible to make a function amenable for tail call optimization by carrying out a manual rewrite. In the case of the factorial method, we can employ the following trick:&lt;/p&gt;  &lt;blockquote&gt;&lt;font face="Courier New"&gt;static int Fac(int n)     &lt;br /&gt;{      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; return Fac_(n, 1);      &lt;br /&gt;}      &lt;br /&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;     &lt;br /&gt;static int Fac_(int n, int res)      &lt;br /&gt;{      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; if (n == 0)      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; return &lt;strong&gt;res&lt;/strong&gt;;      &lt;br /&gt;      &lt;br /&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&lt;strong&gt;&amp;#160;&amp;#160;&amp;#160; return Fac_(n – 1, n * res);&lt;/strong&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&lt;strong&gt;       &lt;br /&gt;&lt;/strong&gt;}&lt;/font&gt;&lt;/blockquote&gt;  &lt;p&gt;Here, we’re not only decrementing n in every recursive call, we’re also keeping the running multiplication at the same time. In my post &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2009/11/08/jumping-the-trampoline-in-c-stack-friendly-recursion.aspx"&gt;Jumping the trampoline in C# – Stack-friendly recursion&lt;/a&gt;, I explained this principle in the “Don’t stand on my tail!” section. The F# equivalent of the code, shown below, results in tail call optimization once more:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;let rec Fac_ n res =       &lt;br /&gt;&amp;#160;&amp;#160; if n = 0 then        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; res        &lt;br /&gt;&amp;#160;&amp;#160; else        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Fac_ (n - 1) (n * res) &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;let Fac n =       &lt;br /&gt;&amp;#160;&amp;#160; Fac_ n 1&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The compilation result is shown below:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/TheCaseofTheFailedDemoStackOverflowExcep_BE15/image_7.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/TheCaseofTheFailedDemoStackOverflowExcep_BE15/image_thumb_7.png" width="506" height="383" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;You can clearly see the reuse of local argument slots.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;A smart JIT&lt;/h1&gt;  &lt;p&gt;All of this doesn’t yet explain why the original C# code is just working fine though our look at the generated IL code in the second section of this post did reveal the call instruction to really be there. One more party is involved in getting our much beloved piece of C# code to run on the bare metal of the machine: the JIT compiler.&lt;/p&gt;  &lt;p&gt;In fact, as soon as I saw the demo not working as intended, the mental click was made to go and check this possibility. Why? Well, the C# compiler doesn’t optimize tail calls into loops, nor does it emit &lt;a href="http://bartdesmet.net/blogs/bart/archive/2006/09/22/4463.aspx"&gt;tail.call instructions&lt;/a&gt;. The one and only remaining party is the JIT compiler. And indeed, since I’m running on x64 and am using the command-line compiler, the JIT compiler is more aggressive about performing tail call optimizations.&lt;/p&gt;  &lt;p&gt;Let’s explain a few things about the previous paragraph. First of all, why does the use of the command-line compiler matter? Won’t the same result pop up if I used a Console Application project in Visual Studio? Not quite, if you’re using Visual Studio 2010 that is. One the decisions made in the last release is to mark executables IL assemblies (managed .exe files) as 32-bit only. That doesn’t mean the image contains 32-bit instructions (in fact, the C# compiler never emits raw assembler); all it does it tell the JIT to only emit 32-bit assembler at runtime, hence resulting in a WOW64 process on 64-bit Windows. The reasons for this are explained in the &lt;a href="http://blogs.msdn.com/b/rmbyers/archive/2009/06/09/anycpu-exes-are-usually-more-trouble-then-they-re-worth.aspx"&gt;Rick Byer’s blog post on the subject&lt;/a&gt;. In our case, we’re running the C# compiler without the /platform:x86 flag – which now is passed by the default settings of a Visual Studio 2010 executable (not library!) project – therefore resulting in an “AnyCPU” assembly. The corflags.exe tool can be used to verify this claim:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/TheCaseofTheFailedDemoStackOverflowExcep_BE15/image_8.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/TheCaseofTheFailedDemoStackOverflowExcep_BE15/image_thumb_8.png" width="614" height="400" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;In Visual Studio 2010, a new Console Application project will have the 32-bit only flag set by default. Again, reasons for this decision are brought up in Rick’s post on the subject.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/TheCaseofTheFailedDemoStackOverflowExcep_BE15/image_9.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/TheCaseofTheFailedDemoStackOverflowExcep_BE15/image_thumb_9.png" width="658" height="295" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Indeed, when running the 32-bit only assembly, a StackOverflowException results. An alternative way to tweak the flags of a managed assembly is by using corflags.exe itself, as shown below:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/TheCaseofTheFailedDemoStackOverflowExcep_BE15/image_10.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/TheCaseofTheFailedDemoStackOverflowExcep_BE15/image_thumb_10.png" width="617" height="399" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;It turns out when the 64-bit JIT is involved, i.e. when the AnyCPU Platform target is set – the default on the csc.exe compiler – tail call optimization is carried out for our piece of code. A whole bunch of conditions under which tail calls can be optimized by the various JIT flavors can be found on &lt;a href="http://blogs.msdn.com/b/davbr/archive/2007/06/20/tail-call-jit-conditions.aspx"&gt;David Broman’s blog&lt;/a&gt;. Grant Richins has been blogging about &lt;a href="http://blogs.msdn.com/b/clrcodegeneration/archive/2009/05/11/tail-call-improvements-in-net-framework-4.aspx"&gt;improvements made in .NET 4&lt;/a&gt; (which don’t really apply to our particular sample). One important change in .NET 4 is the fact the 64-bit JIT now honors the “tail.” prefix on call instructions, which is essential to the success of functional style languages like F# (indeed, F#’s compiler actually has a tailcalls flags, which is on by default due to the language’s nature).&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Seeing the 64-bit JIT’s work in action&lt;/h1&gt;  &lt;p&gt;In order to show the reader the generated x64 code for our recursive Rec method definition, we’ll switch gears and open up WinDbg, leveraging the SOS debugger extension. Obviously this requires one to install the &lt;a href="http://www.microsoft.com/whdc/devtools/debugging/default.mspx"&gt;Debugging Tools for Windows&lt;/a&gt;. Also notice the section’s title to apply to x64. For x86 users, the same experiment can be carried out, revealing the x86 instructions generated &lt;em&gt;without&lt;/em&gt; the tail call optimization, hence explaining the overflow observed on 32-bit executions.&lt;/p&gt;  &lt;p&gt;Loading the ovf.exe sample (making sure the 32-bit only flag is &lt;em&gt;&lt;u&gt;not&lt;/u&gt;&lt;/em&gt; set!) under the WinDbg debugger – using windbg.exe ovf.exe – brings us to the first loader breakpoint as shown below. In order to load the Son Of Strike (SOS) debugger extension, set a module load breakpoint for clrjit.dll (which puts us in a convenient spot where the CLR has been sufficiently loaded to use SOS successfully). When that breakpoint hits, the extension can be loaded using .loadby sos clr:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/TheCaseofTheFailedDemoStackOverflowExcep_BE15/image_11.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/TheCaseofTheFailedDemoStackOverflowExcep_BE15/image_thumb_11.png" width="867" height="407" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Next, we need to set a breakpoint on the Rec method. In my case, the assembly’s file name is ovf.exe, the class is Program and the method is Rec, requiring me to enter the following commands:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/TheCaseofTheFailedDemoStackOverflowExcep_BE15/image_12.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/TheCaseofTheFailedDemoStackOverflowExcep_BE15/image_thumb_12.png" width="368" height="58" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;The !bpmd extension command is used to set a breakpoint based on a MethodDesc – a structure used by the CLR to describe a method. Since the method hasn’t been JIT compiled yet, and hence no physical address for the executable code is available yet, a pending breakpoint is added. Now we let go the debugger and end up hitting the breakpoint which got automatically set when the JIT compiler took care of compiling the method (since it came “in sight” for execution, i.e. because of Main’s call into it). Using the !U – for unassemble – command we can now see the generated code:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/TheCaseofTheFailedDemoStackOverflowExcep_BE15/image_13.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/TheCaseofTheFailedDemoStackOverflowExcep_BE15/image_thumb_13.png" width="957" height="657" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Notice the presence of code like InitializeStdOutError which is the result from inlining of the Console.WriteLine method’s code. What’s going on here with regards to the tail call behavior is the replacement of a call instruction with a jump simply to the beginning of the generated code. The rest of the code can be deciphered with a bit of x86/x64 knowledge. For one thing, you can recognize the 1024 value (used for our modulo arithmetic) in 3FF which is 1023. The module check stretches over a few instructions that basically use a mask over the value to see whether any of the low bits is non-zero. If so, the value is not dividable by 1024; otherwise, it is. Based on this test (whose value gets stored in eax), a jump is made or not, either going through the path of calling Console.WriteLine or not.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Contrasting with the x86 assembler being used&lt;/h1&gt;  &lt;p&gt;In the x86 setting, we’ll see different code. To show this, let’s use a Console Application in Visual Studio 2010, whose default platform target is – as mentioned earlier – 32-bit. In order to load SOS from inside the Immediate Window, enable the native debugger through the project settings:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/TheCaseofTheFailedDemoStackOverflowExcep_BE15/image_14.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/TheCaseofTheFailedDemoStackOverflowExcep_BE15/image_thumb_14.png" width="666" height="417" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Using similar motions as before, we can load the SOS extension upon hitting a breakpoint. Instead of using !bpmd, we can use !name2ee to resolve the JITTED Code Address for the given symbol, in this case the Program.Rec method:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/TheCaseofTheFailedDemoStackOverflowExcep_BE15/image_15.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/TheCaseofTheFailedDemoStackOverflowExcep_BE15/image_thumb_15.png" width="503" height="579" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Inspecting the generated code, one will encounter the following call instruction to the same method. This is the regular recursive call without any tail call optimization carried out. Obviously this will cause a StackOverflowException to occur. Also notice from the output below that the Console.WriteLine method call didn’t get inlined in this particular x86 case.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/TheCaseofTheFailedDemoStackOverflowExcep_BE15/image_16.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/TheCaseofTheFailedDemoStackOverflowExcep_BE15/image_thumb_16.png" width="704" height="282" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Revisiting the tail. instruction prefix&lt;/h1&gt;  &lt;p&gt;As &lt;a href="http://bartdesmet.net/blogs/bart/archive/2006/09/22/4463.aspx"&gt;referred to before&lt;/a&gt;, the IL instruction set has a tail. prefix for call instructions. Before .NET 4, this was merely a hint to the JIT compiler. For x86, it was (and still is) a request of the IL generator to the JIT compiler to perform a tail call. For x64, prior to CLR 4.0, this request was not always granted. For our x86 case, we can have a go at inserting the tail. prefix for the recursive call in the code generated by the C# compiler (which doesn’t emit this instruction by itself as explained before). Using ildasm’s /out parameter, you can export the ovf.exe IL code to a text file. Notice the COR flags have been set to “32-bit required” using either the x86 platform target flag on csc.exe or by using corflags /32bit+:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/TheCaseofTheFailedDemoStackOverflowExcep_BE15/image_17.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/TheCaseofTheFailedDemoStackOverflowExcep_BE15/image_thumb_17.png" width="579" height="424" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Now tweak the code of Rec as shown below. After a tail call instruction, no further code should execute other than a ret. If this rule isn’t obeyed, the CLR will throw an exception signaling an invalid program. Hence we remove the nop instruction that resulted from a non-optimized build (Debug build or csc.exe use without /o+ flag). To turn the call into a tail call one, we add the “tail.” prefix. Don’t forget the space after the dot though:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/TheCaseofTheFailedDemoStackOverflowExcep_BE15/image_18.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/TheCaseofTheFailedDemoStackOverflowExcep_BE15/image_thumb_18.png" width="1152" height="360" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;The session of roundtripping through ILDASM and ILASM with the manual tweak in Notepad shown above is shown here:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/TheCaseofTheFailedDemoStackOverflowExcep_BE15/image_19.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/TheCaseofTheFailedDemoStackOverflowExcep_BE15/image_thumb_19.png" width="625" height="558" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;With this change in place, the ovf.exe will keep on running without overflowing the stack. Looking at the generated code through the debugger, one would see a jmp instruction instead of a call, explaining the fixed behavior.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Conclusion&lt;/h1&gt;  &lt;p&gt;Tail calls are the bread and butter of iterative programs written in a functional style. As such, the CLR has evolved to support tail call optimization in the JIT when the tail. prefix is present, e.g. as emitted by the F# compiler when needed (though the IL code itself may be turned into a loop by the compiler itself). One thing to know is that on x64, the JIT is more aggressive about detecting and carrying out tail recursive calls (since it has a good value proposition with regards to “runtime intelligence cost” versus “speed-up factor”). For more information, I strongly recommend you to have a look at the CLR team’s blog: &lt;a href="http://blogs.msdn.com/b/clrcodegeneration/archive/2009/05/11/tail-call-improvements-in-net-framework-4.aspx"&gt;Tail Call Improvements in .NET Framework 4&lt;/a&gt;.&lt;/p&gt;&lt;img src="http://community.bartdesmet.net/aggbug.aspx?PostID=21619" width="1" height="1"&gt;</description><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/Functional+programming/default.aspx">Functional programming</category><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/.NET+Framework+v4.0/default.aspx">.NET Framework v4.0</category></item><item><title>Hosting Windows PowerShell 2.0 under CLR 4.0</title><link>http://community.bartdesmet.net/blogs/bart/archive/2010/07/06/hosting-windows-powershell-2-0-under-clr-4-0.aspx</link><pubDate>Tue, 06 Jul 2010 19:38:51 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:21616</guid><dc:creator>bart</dc:creator><slash:comments>8</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://community.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=21616</wfw:commentRss><comments>http://community.bartdesmet.net/blogs/bart/archive/2010/07/06/hosting-windows-powershell-2-0-under-clr-4-0.aspx#comments</comments><description>&lt;h1&gt;Introduction&lt;/h1&gt;  &lt;p&gt;Recently I’ve been playing with Windows PowerShell 2.0 again, in the context of my day-to-day activities. One hint should suffice for the reader to get an idea of what’s going on: push-based collections. While I’ll follow up on this subject pretty soon, this precursor post explains one of the things I had to work around.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;PowerShell: a managed application or not?&lt;/h1&gt;  &lt;p&gt;Being designed around the concept of managed object pipelines, one may expect powershell.exe to be a managed executable. However, it turns out this isn’t the case completely. If you try to run ildasm.exe on the PowerShell executable (which lives in %windir%\system32\WindowsPowerShell\v1.0 despite the 2.0 version number, due to setup complications), you get the following message:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/HostingWindowsPowerShell2.0underCLR4.0_A80A/image.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/HostingWindowsPowerShell2.0underCLR4.0_A80A/image_thumb.png" width="496" height="171" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;So much for the managed executable theory. What else can be going on to give PowerShell the power of managed objects. Well, it could be hosting the CLR. To check this theory, we can use the dumpbin.exe tool, using the /imports flag, checking for mscoree.dll functions being called. And indeed, we encounter the &lt;a href="http://msdn.microsoft.com/en-us/library/99sz37yh.aspx"&gt;CorBindToRuntimeEx&lt;/a&gt; function that’s been the way to host the CLR prior to .NET 4’s &lt;a href="http://msdn.microsoft.com/en-us/magazine/ee819091.aspx"&gt;in-process side-by-side&lt;/a&gt; introduction (a feature I should blog about as well since I wrote a CLR host for in-process side-by-side testing on my prior team here at Microsoft).&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/HostingWindowsPowerShell2.0underCLR4.0_A80A/image_3.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/HostingWindowsPowerShell2.0underCLR4.0_A80A/image_thumb_3.png" width="677" height="414" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;One of the parameters passed to CorBindToRuntimeEx is the version of the CLR to be loaded. Geeks can use WinDbg or cdb to set a breakpoint on this function and investigate the version parameter passed to it by the PowerShell code:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/HostingWindowsPowerShell2.0underCLR4.0_A80A/image_4.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/HostingWindowsPowerShell2.0underCLR4.0_A80A/image_thumb_4.png" width="1092" height="200" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Notice the old code name of PowerShell still being revealed in the third stack frame (from the top). In order to hit this breakpoint on a machine that has .NET 4 installed, I’ve used the mscoreei.dll module rather than mscoree.dll. The latter has become a super-shim in the System32 folder, while the former one is where the CLR shim really lives (“i” stands for “implementation”). This refactoring has been done to aid in servicing the CLR on different version of Windows, where the operating system “owns” the files in the System32 folder.&lt;/p&gt;  &lt;p&gt;Based on this experiment, it’s crystal clear the CLR is hosted by Windows PowerShell, with hardcoded affinity to v2.0.50727. This is in fact a good thing since automatic roll-forward to whatever the latest version of the CLR is on the machine could cause incompatibilities. One can expect future versions of Windows PowerShell to be based on more recent versions of the CLR, once all required testing has been carried out. (And in that case, one will likely use the &lt;a href="http://msdn.microsoft.com/en-us/library/dd233134.aspx"&gt;new “metahost” CLR hosting APIs&lt;/a&gt;.)&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Loading .NET v4 code in PowerShell v2.0&lt;/h1&gt;  &lt;p&gt;The obvious question with regards to some of the stuff I’ve been working on was whether or not we can run .NET v4 code in Windows PowerShell v2.0? It shouldn’t be a surprise this won’t work as-is, since the v2.0 CLR is loaded by the PowerShell host. Even if the hosting APIs weren’t involved and the managed executable were compiled against .NET v2.0, that version’s CLR would take precedence. This is in fact the case for ISE:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/HostingWindowsPowerShell2.0underCLR4.0_A80A/image_5.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/HostingWindowsPowerShell2.0underCLR4.0_A80A/image_thumb_5.png" width="579" height="344" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Trying to load a v4.0 assembly in Windows PowerShell v2.0 pathetically fails – as expected – with the following message:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/HostingWindowsPowerShell2.0underCLR4.0_A80A/image_6.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/HostingWindowsPowerShell2.0underCLR4.0_A80A/image_thumb_6.png" width="677" height="174" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;So, what are the options to get this to work? Let’s have a look.&lt;/p&gt;  &lt;p&gt;&lt;font color="#ff0000"&gt;&lt;strong&gt;Warning:&lt;/strong&gt;&amp;#160; None of those hacks are officially supported. At this point, Windows PowerShell is a CLR 2.0 application, capable of loading and executing code targeting .NET 2.0 through .NET 3.5 SP1 (all of which run on the second major version of the CLR).&lt;/font&gt;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h2&gt;Option 1 – Hacking the parameter passed to CorBindToRuntimeEx&lt;/h2&gt;  &lt;p&gt;If we just need an ad-hoc test of Windows PowerShell v2.0 running on CLR v4.0, we can take advantage of WinDbg once more. Simply break on the CorBindToRuntimeEx and replace the v2.0.50727 string in memory by the v4.0 version, i.e. v4.0.30319. The “eu” command used for this purpose stands for “edit memory Unicode”:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/HostingWindowsPowerShell2.0underCLR4.0_A80A/image_7.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/HostingWindowsPowerShell2.0underCLR4.0_A80A/image_thumb_7.png" width="1047" height="413" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;If we let go the debugger after this tweak, we’ll ultimately get to see Windows PowerShell running seemingly fine, this time on CLR 4.0. One proof is the fact we can load the .NET 4 assembly we tried to load before:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/HostingWindowsPowerShell2.0underCLR4.0_A80A/image_8.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/HostingWindowsPowerShell2.0underCLR4.0_A80A/image_thumb_8.png" width="677" height="198" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Another proof can be found by looking at the DLL list for the PowerShell.exe instance in Process Explorer:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/HostingWindowsPowerShell2.0underCLR4.0_A80A/image_9.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/HostingWindowsPowerShell2.0underCLR4.0_A80A/image_thumb_9.png" width="540" height="377" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;No longer we see mscorwks.dll (which is indicative of CLR 2.0 or below), but a clr.dll module appears instead. While this hack works fine for single-shot experiments, we may want to get something more usable for demo and development purposes.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt;&amp;#160; Another option – not illustrated here – would be to use &lt;a href="http://research.microsoft.com/en-us/projects/detours/"&gt;Detours&lt;/a&gt; and intercept the CorBindToRuntimeEx call programmatically, performing the same parameter substitution as the one we’ve shown through the lenses of the debugger. Notice though the use of CorBindToRuntimeEx is deprecated since .NET 4, so this is and stays a bit of a hack either way.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h2&gt;Option 2 – Hosting Windows PowerShell yourself&lt;/h2&gt;  &lt;p&gt;The second option we’ll explore is to host Windows PowerShell ourselves, not by hosting the CLR and mimicking what PowerShell.exe does, but by using the APIs provided for this purpose. In particular, the &lt;a href="http://msdn.microsoft.com/en-us/library/microsoft.powershell.consoleshell(VS.85).aspx"&gt;ConsoleShell&lt;/a&gt; class is of use to achieve this. Moreover, besides simply hosting PowerShell in a CLR v4 process, we can also load snap-ins out of the box. But first things first, starting with a .NET 4 Console Application, add a reference to the System.Management.Automation and Microsoft.PowerShell.ConsoleHost assemblies which can be found under %programfiles%\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/HostingWindowsPowerShell2.0underCLR4.0_A80A/image_10.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/HostingWindowsPowerShell2.0underCLR4.0_A80A/image_thumb_10.png" width="482" height="408" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;The little bit of code required to get basic hosting to work is shown below:&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;using &lt;/span&gt;System;
&lt;span style="color:blue;"&gt;using &lt;/span&gt;System.Management.Automation.Runspaces;
&lt;span style="color:blue;"&gt;using &lt;/span&gt;Microsoft.PowerShell;

&lt;span style="color:blue;"&gt;namespace &lt;/span&gt;PSHostCLRv4
{
&lt;span style="color:blue;"&gt;    class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Program
    &lt;/span&gt;{
&lt;span style="color:blue;"&gt;        static int &lt;/span&gt;Main(&lt;span style="color:blue;"&gt;string&lt;/span&gt;[] args)
        {
            &lt;span style="color:blue;"&gt;var &lt;/span&gt;config = &lt;span style="color:#2b91af;"&gt;RunspaceConfiguration&lt;/span&gt;.Create();
            &lt;span style="color:blue;"&gt;return &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ConsoleShell&lt;/span&gt;.Start(&lt;br /&gt;                config,&lt;br /&gt;                &lt;span style="color:#a31515;"&gt;&amp;quot;Windows PowerShell - Hosted on CLR v4\nCopyright (C) 2010 Microsoft Corporation. All rights reserved.&amp;quot;&lt;/span&gt;,&lt;br /&gt;                &lt;span style="color:#a31515;"&gt;&amp;quot;&amp;quot;&lt;/span&gt;,&lt;br /&gt;                args&lt;br /&gt;            );
        }
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Using the RunspaceConfiguration object, it’s possible to load snap-ins if desired. Since that would reveal the reason I was doing this experiment, I won’t go into detail on that just yet :-). The tip in the introduction should suffice to get an idea of the experiment I’m referring to. Here’s the output of the above:&lt;/p&gt;

&lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/HostingWindowsPowerShell2.0underCLR4.0_A80A/image_11.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/HostingWindowsPowerShell2.0underCLR4.0_A80A/image_thumb_11.png" width="677" height="198" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;While this hosting on .NET 4 is all done using legitimate APIs, it’s better to be conservative when it comes to using this in production since PowerShell hasn’t been blessed to be hosted on .NET 4. While compatibility between CLR versions and for the framework assemblies has been a huge priority for the .NET teams (I was there when it happened), everything should be fine. But the slightest bit of pixy dust (e.g. changes in timing for threading, a classic!) could reveal some issue. &lt;font color="#ff0000"&gt;Till further notice, use this technique only for testing and experimentation.&lt;/font&gt;&lt;/p&gt;

&lt;p&gt;Enjoy and stay tuned for more PowerShell fun (combined with other technologies)!&lt;/p&gt;&lt;img src="http://community.bartdesmet.net/aggbug.aspx?PostID=21616" width="1" height="1"&gt;</description><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/Windows+PowerShell/default.aspx">Windows PowerShell</category></item><item><title>Where’s Bart’s Blog Been?</title><link>http://community.bartdesmet.net/blogs/bart/archive/2010/07/02/where-s-bart-s-blog-been.aspx</link><pubDate>Fri, 02 Jul 2010 07:19:44 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:21608</guid><dc:creator>bart</dc:creator><slash:comments>3</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://community.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=21608</wfw:commentRss><comments>http://community.bartdesmet.net/blogs/bart/archive/2010/07/02/where-s-bart-s-blog-been.aspx#comments</comments><description>&lt;p&gt;A quick update to my readers on a few little subjects. First of all, some people have noticed my blog welcomed readers with &lt;strong&gt;a not-so-sweet 404 error message&lt;/strong&gt; the last few days. Turned out my monthly bandwidth was exceeded which was enough reason for my hosting provider to take the thing offline.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/WheresBartsBlogBeen_49D/image.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/WheresBartsBlogBeen_49D/image_thumb.png" width="550" height="300" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Since this is quite inconvenient I’ve started some migration of image content to another domain, which is work in progress and should (hopefully) prevent the issue from occurring again. Other measures will be taken to limit the download volumes.&lt;/p&gt;  &lt;p&gt;Secondly, many others have noticed &lt;strong&gt;it’s been quite silent on my blog lately&lt;/strong&gt;. As my colleague &lt;a href="http://blogs.msdn.com/wesdyer"&gt;Wes&lt;/a&gt; warned me, once you start enjoying every day of functional programming hacking on Erik’s team, time for blogging steadily decreases. What we call “hacking” has been applied to many projects we’ve been working on over here in the Cloud Programmability Team, some of which are yet undisclosed. The most visible one today is obviously the &lt;a href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx"&gt;Reactive Extensions&lt;/a&gt; both for .NET and for JavaScript, which I’ve been evangelizing both within and outside the company. Another one which I can only give the name for is dubbed “LINQ to Anything” that’s – as you can imagine – keeping me busy and inspired on a daily and nightly basis. On top of all of this, I’ve got some other writing projects going on that are nearing completion (finally).&lt;/p&gt;  &lt;p&gt;Anyway, the big plan is to &lt;strong&gt;&lt;font color="#ff0000"&gt;break the silence&lt;/font&gt;&lt;/strong&gt; and start blogging again about our established technologies, including Rx in all its glory. Subjects will include continuation passing style, duality between IEnumerable&amp;lt;T&amp;gt; and IObservable&amp;lt;T&amp;gt;, parameterization for concurrency, discussion of the plethora of operators available, a good portion of monads for sure, the IQbservable&amp;lt;T&amp;gt; interface (no, I won’t discuss the &lt;a href="http://en.wikipedia.org/wiki/Color_of_the_bikeshed"&gt;color of the bikeshed&lt;/a&gt;) and one of its applications (LINQ to WMI Events), etc. Stay tuned for a series on those subjects starting in the hopefully very near future.&lt;/p&gt;  &lt;p&gt;See you soon!&lt;/p&gt;&lt;img src="http://community.bartdesmet.net/aggbug.aspx?PostID=21608" width="1" height="1"&gt;</description><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/IIgnorable/default.aspx">IIgnorable</category><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/Rx/default.aspx">Rx</category></item><item><title>Some introductory Rx samples</title><link>http://community.bartdesmet.net/blogs/bart/archive/2010/04/19/some-introductory-rx-samples.aspx</link><pubDate>Mon, 19 Apr 2010 07:45:00 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:15110</guid><dc:creator>bart</dc:creator><slash:comments>17</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://community.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=15110</wfw:commentRss><comments>http://community.bartdesmet.net/blogs/bart/archive/2010/04/19/some-introductory-rx-samples.aspx#comments</comments><description>&lt;p&gt;During my last tour I’ve been collecting quite some fundamental and introductory Rx samples as illustrations with my presentations on the topic. As promised, I’m sharing those out through my blog. More Rx content is to follow in the (hopefully near) future, with an exhaustive discussion of various design principles and choices, the underlying theoretical foundation of Rx and coverage of lots of operators.&lt;/p&gt;  &lt;p&gt;In the meantime, &lt;a href="http://www.bartdesmet.net/download/Rx40Samples.zip"&gt;download the sample project here&lt;/a&gt;. While the project targets Visual Studio 2010 RTM, you can simply take the Program.cs file and build a Visual Studio 2008 project around it, referencing the necessary Rx assemblies (which you can download from &lt;a href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx"&gt;DevLabs&lt;/a&gt;).&lt;/p&gt;  &lt;p&gt;Enjoy!&lt;/p&gt;&lt;img src="http://community.bartdesmet.net/aggbug.aspx?PostID=15110" width="1" height="1"&gt;</description><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/Rx/default.aspx">Rx</category></item><item><title>New drop of the Reactive Extensions for .NET (Rx) available</title><link>http://community.bartdesmet.net/blogs/bart/archive/2010/03/05/new-drop-of-the-reactive-extensions-for-net-rx-available.aspx</link><pubDate>Fri, 05 Mar 2010 23:02:00 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:15080</guid><dc:creator>bart</dc:creator><slash:comments>10</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://community.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=15080</wfw:commentRss><comments>http://community.bartdesmet.net/blogs/bart/archive/2010/03/05/new-drop-of-the-reactive-extensions-for-net-rx-available.aspx#comments</comments><description>&lt;p&gt;It&amp;#39;s been a long time I&amp;#39;ve written epic blog posts over here, but for a good reason. We&amp;#39;ve been working very hard on getting a new Rx release out the door and I&amp;#39;m proud to announce it&amp;#39;s available now through &lt;a href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx"&gt;http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx&lt;/a&gt;. Notice we got a .NET 4 RC compatible download available as well, so you can play with the latest and greatest of technologies in one big jar :-). More goodness will follow later, so stay tuned!&lt;/p&gt;
&lt;p&gt;At some point in the foreseeable future, I&amp;#39;ll start a series on how Rx works and what its operators are as well. If you have any particular topics you&amp;#39;d like to see covered, don&amp;#39;t hesitate to let me know through my blog. In the meantime, make sure to evaporate all your feedback on the forums at &lt;a href="http://social.msdn.microsoft.com/Forums/en-US/rx/threads"&gt;http://social.msdn.microsoft.com/Forums/en-US/rx/threads&lt;/a&gt;. We love to hear what you think, what operators you believe are missing, any bugs you find, etc.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Update:&lt;/strong&gt; We also have published a video on the new release at &lt;a href="http://channel9.msdn.com/posts/J.Van.Gogh/Your-RxNET-Prescription-Has-Been-Refilled"&gt;http://channel9.msdn.com/posts/J.Van.Gogh/Your-RxNET-Prescription-Has-Been-Refilled&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Have fun!&lt;br /&gt;Bart @ Rx&lt;/p&gt;&lt;img src="http://community.bartdesmet.net/aggbug.aspx?PostID=15080" width="1" height="1"&gt;</description><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/LINQ/default.aspx">LINQ</category><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/Rx/default.aspx">Rx</category></item><item><title>2010 – A Personal Change: putting my “Head In The Cloud”</title><link>http://community.bartdesmet.net/blogs/bart/archive/2010/01/10/2010-a-personal-change-putting-my-head-in-the-cloud.aspx</link><pubDate>Mon, 11 Jan 2010 01:26:00 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:15042</guid><dc:creator>bart</dc:creator><slash:comments>5</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://community.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=15042</wfw:commentRss><comments>http://community.bartdesmet.net/blogs/bart/archive/2010/01/10/2010-a-personal-change-putting-my-head-in-the-cloud.aspx#comments</comments><description>&lt;p&gt;Slightly over two years after arriving here in Redmond to work on the WPF team, time has come for me to make a switch and pursue other opportunities within the company. Starting January 13th, I’ll be working on the &lt;strong&gt;SQL Cloud Data Programmability Team&lt;/strong&gt; on various projects related to &lt;em&gt;democratizing the cloud&lt;/em&gt;. While we have much more rabbits sitting in our magician hats, &lt;a href="http://blogs.bartdesmet.net/blogs/bart/archive/tags/Rx/default.aspx"&gt;Rx&lt;/a&gt; is the first big deliverable we’re working on.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;a href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx"&gt;&lt;img style="BORDER-BOTTOM:0px;BORDER-LEFT:0px;DISPLAY:inline;MARGIN-LEFT:0px;BORDER-TOP:0px;MARGIN-RIGHT:0px;BORDER-RIGHT:0px;" title="" border="0" alt="" src="http://i.msdn.microsoft.com/ee794896.DevLabs_Rx_Project(en-us).png" /&gt;&lt;/a&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;For my blog, there won’t be much change as I’ve always written on topics related to what I’ll be working on: language innovation, data access, LINQ, type systems, lambda fun, etc. I’m planning to stay committed to blogging and other evangelism activities, including speaking engagements from time to time, so feel free to ping me if I’m in your proximity (or if you’re visiting our campus). Next up and confirmed are TechDays “low lands” in &lt;a href="http://www.techdays.be/"&gt;Belgium&lt;/a&gt; and the &lt;a href="http://www.devdays.nl/"&gt;Netherlands&lt;/a&gt;, end of March.&lt;/p&gt;
&lt;p&gt;Needless to say, I’m thrilled to have this opportunity of working together with a relatively small group of smart and passionate people, on the things I’d spend all my free time on anyway. Having this one-to-one alignment between day-to-day professional activities at work and all sorts of free time hacking projects is like a dream coming true. Thanks &lt;a href="http://blogs.msdn.com/dannyvv"&gt;Danny&lt;/a&gt;, &lt;a href="http://research.microsoft.com/en-us/um/people/emeijer/"&gt;Erik&lt;/a&gt;, &lt;a href="http://blogs.msdn.com/jeffva"&gt;Jeffrey&lt;/a&gt;, &lt;a href="http://www.cartesianclosed.com/"&gt;Mark&lt;/a&gt; and &lt;a href="http://blogs.msdn.com/wesdyer"&gt;Wes&lt;/a&gt; for taking me on board.&lt;/p&gt;
&lt;p&gt;Expect to see more Rx blogging love over here, and watch out for more goodness to come your way in the foreseeable future. In the meantime, check out the following resources on the matter:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx"&gt;MSDN DevLabs Rx homepage&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://channel9.msdn.com/tags/Rx/"&gt;Channel 9 Rx videos&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://blogs.bartdesmet.net/blogs/bart/archive/tags/Rx/default.aspx"&gt;My Rx blog category&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://social.msdn.microsoft.com/Forums/en-US/rx/threads"&gt;Our forums&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;Please keep the feedback on Rx coming: help us, help you!&lt;/p&gt;&lt;img src="http://community.bartdesmet.net/aggbug.aspx?PostID=15042" width="1" height="1"&gt;</description><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/Personal/default.aspx">Personal</category><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/IIgnorable/default.aspx">IIgnorable</category><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/Rx/default.aspx">Rx</category></item><item><title>More LINQ with System.Interactive – Functional fun and taming side-effects</title><link>http://community.bartdesmet.net/blogs/bart/archive/2010/01/07/more-linq-with-system-interactive-functional-fun-and-taming-side-effects.aspx</link><pubDate>Thu, 07 Jan 2010 11:43:42 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:15025</guid><dc:creator>bart</dc:creator><slash:comments>13</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://community.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=15025</wfw:commentRss><comments>http://community.bartdesmet.net/blogs/bart/archive/2010/01/07/more-linq-with-system-interactive-functional-fun-and-taming-side-effects.aspx#comments</comments><description>&lt;p&gt;With the recent release of the &lt;a href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx"&gt;Reactive Extensions for .NET (Rx)&lt;/a&gt; on &lt;a href="http://msdn.microsoft.com/en-us/devlabs/default.aspx"&gt;DevLabs&lt;/a&gt;, you’ll hear quite a bit about reactive programming, based on the IObservable&amp;lt;T&amp;gt; and IObserver&amp;lt;T&amp;gt; interfaces. A great amount of resources is available &lt;a href="http://channel9.msdn.com/tags/Rx/"&gt;on Channel 9&lt;/a&gt;. In this series, I’ll focus on the &lt;a href="http://channel9.msdn.com/shows/Going+Deep/Expert-to-Expert-Brian-Beckman-and-Erik-Meijer-Inside-the-NET-Reactive-Framework-Rx/"&gt;dual&lt;/a&gt; of the System.Reactive assembly, which is System.Interactive, providing a bunch of extensions to the &lt;a href="http://www.codeplex.com/LINQSQO"&gt;LINQ Standard Query Operators&lt;/a&gt; for IEnumerable&amp;lt;T&amp;gt;. In today’s installment we’ll talk about EnumerableEx’s facilities to tame side-effects in a functionally inspired manner:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/Mor.InteractiveFunctionalfunandtamingsid_9DCC/image.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/Mor.InteractiveFunctionalfunandtamingsid_9DCC/image_thumb.png" width="526" height="480" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;To side effect or not to side effect?&lt;/h1&gt;  &lt;p&gt;Being rooted in query comprehensions as seen in various functional programming languages (including (the) pure one(s)), one would expect LINQ to have a very functional basis. Indeed it has, but being hosted in various not functionally pure languages like C# and Visual Basic, odds are off reasoning about side-effects in a meaningful and doable manner. As we’ve seen before, when talking about the Do and Run operators, it’s perfectly possible for a query to exhibit side-effects during iteration. You don’t even have to look that far, since every lambda passed to a query operator is an opportunity of introducing effects. The delayed execution nature of LINQ queries makes that those effects appear at the point of query execution. So far, nothing new.&lt;/p&gt;  &lt;p&gt;So, the philosophical question ought to be whether or not we should embrace side-effects or go for absolute purity. While the latter would be preferable for various reasons, it’s not enforceable through the hosting languages for LINQ, so maybe we should exploit side-effects if we really want to do so. The flip side of this train of thought is that those side-effects could come and get us if we’re not careful, especially when queries get executed multiple times, potentially as part of a bigger query. In such a case, you’d likely not want effects to be duplicated. Below is a sample of such a problematic query expression:&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;xrs = &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Generate(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Random&lt;/span&gt;(), rnd =&amp;gt; &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Return(rnd.Next(100)), &lt;span style="color:green;"&gt;/* iterate */ &lt;/span&gt;_ =&amp;gt; _);
xrs.Zip(xrs, (l, r) =&amp;gt; l + r).Take(10).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Using Generate, we generate a sequence of random numbers. Recall the first argument is the state of the anamorphic Generate operator, which we get passed in the lambdas following it: once to produce an output sequence (just a single random number in our case) and once to iterate (just keeping the same random number generator here). What’s more important is we’re relying on the side-effect of reading the random number generator which, as the name implies, provides random answers to the Next inquiry every time it gets called. In essence, the side-effect can (not) be seen by looking at the signature of Random.Next, which says it returns an int. In .NET this means the method &lt;em&gt;may&lt;/em&gt; return the &lt;em&gt;same&lt;/em&gt; int every time it gets called, but there are no guarantees whatsoever (as there would be in pure functional programming languages).&lt;/p&gt;

&lt;p&gt;This side-effect, innocent and intentional as it may seem, comes and gets us if we perform a Zip on the sequence with itself. Since Zip iterates both sides, we’re really triggering separate enumeration (“GetEnumerator”) over the same sequence two times. Though it’s the same sequence object, each of its iterations will produce different results. As a result, the expected invariant of the Zip’s output being only even numbers (based on the assumption l and r would be the same as they’re produced by the same sequence) doesn’t hold:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;52
    &lt;br /&gt;114

    &lt;br /&gt;112

    &lt;br /&gt;&lt;font color="#ff0000"&gt;103
      &lt;br /&gt;41

      &lt;br /&gt;135&lt;/font&gt;

    &lt;br /&gt;78

    &lt;br /&gt;114

    &lt;br /&gt;&lt;font color="#ff0000"&gt;59
      &lt;br /&gt;137&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;While random number generation is a pretty innocent side-effect, not having it under control properly can lead to unexpected results as shown above. We can visualize this nicely using another side-effect introduced by Do:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;xrs = &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Generate(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Random&lt;/span&gt;(), rnd =&amp;gt; &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Return(rnd.Next(100)), &lt;span style="color:green;"&gt;/* iterate */ &lt;/span&gt;_ =&amp;gt; _)
    .Do(xr =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;! -&amp;gt; &amp;quot; &lt;/span&gt;+ xr));
&lt;font color="#ff0000"&gt;xrs&lt;/font&gt;.Zip(&lt;font color="#ff0000"&gt;xrs&lt;/font&gt;, (l, r) =&amp;gt; l + r).Take(10).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;This will print a message for every number flowing out of the random number generating sequence, as shown below:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;! -&amp;gt; 97
    &lt;br /&gt;! -&amp;gt; 78

    &lt;br /&gt;175

    &lt;br /&gt;! -&amp;gt; 11

    &lt;br /&gt;! -&amp;gt; 6

    &lt;br /&gt;17

    &lt;br /&gt;! -&amp;gt; 40

    &lt;br /&gt;! -&amp;gt; 17

    &lt;br /&gt;57

    &lt;br /&gt;! -&amp;gt; 92

    &lt;br /&gt;! -&amp;gt; 63

    &lt;br /&gt;155

    &lt;br /&gt;! -&amp;gt; 70

    &lt;br /&gt;! -&amp;gt; 13

    &lt;br /&gt;83

    &lt;br /&gt;! -&amp;gt; 41

    &lt;br /&gt;! -&amp;gt; 1

    &lt;br /&gt;42

    &lt;br /&gt;! -&amp;gt; 64

    &lt;br /&gt;! -&amp;gt; 76

    &lt;br /&gt;140

    &lt;br /&gt;! -&amp;gt; 30

    &lt;br /&gt;! -&amp;gt; 71

    &lt;br /&gt;101

    &lt;br /&gt;! -&amp;gt; 1

    &lt;br /&gt;! -&amp;gt; 81

    &lt;br /&gt;82

    &lt;br /&gt;! -&amp;gt; 65

    &lt;br /&gt;! -&amp;gt; 45

    &lt;br /&gt;110&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;If we look a bit further to the original query, we come to the conclusion we can’t apply any form of equational reasoning anymore: it seems that the common subexpression “xrs” is not “equal” (as in exposing the same results) in both use sites. The immediate reason in the case of LINQ is the delayed execution, which is a good thing as our Generate call produces an infinite sequence. More broadly, it’s the side-effect that lies at the heart of the problem as equational reasoning breaks down in such a setting. For that very reason, side-effect permitting languages have a much harder time carrying out optimizations to code and need to be very &lt;em&gt;strict&lt;/em&gt; about specifying the order in which operations are performed (e.g. in C#, arguments to a method call – which is always “call-by-value” – are evaluated in a left-to-right order).&lt;/p&gt;

&lt;p&gt;Moving Take(10) up doesn’t change the delayed characteristic either:&lt;/p&gt;

&lt;blockquote&gt;&lt;/blockquote&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;xrs = &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Generate(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Random&lt;/span&gt;(), rnd =&amp;gt; &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Return(rnd.Next(100)), &lt;span style="color:green;"&gt;/* iterate */ &lt;/span&gt;_ =&amp;gt; _)
&lt;strong&gt;&lt;font color="#ff0000"&gt;    .Take(10)&lt;/font&gt;&lt;/strong&gt;
    .Do(xr =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;! -&amp;gt; &amp;quot; &lt;/span&gt;+ xr));
xrs.Zip(xrs, (l, r) =&amp;gt; l + r).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;What would help is forcing the common subexpression’s query to execute, persisting (= caching) its results in memory, before feeding them in to the expression using it multiple times:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;xrs = &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Generate(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Random&lt;/span&gt;(), rnd =&amp;gt; &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Return(rnd.Next(100)), &lt;span style="color:green;"&gt;/* iterate */ &lt;/span&gt;_ =&amp;gt; _)
    .Take(10)&lt;font color="#00ff00"&gt;.ToArray()&lt;/font&gt;
    .Do(xr =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;! -&amp;gt; &amp;quot; &lt;/span&gt;+ xr));
xrs.Zip(xrs, (l, r) =&amp;gt; l + r).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Don’t forget the Take(10) call though, as calling ToArray (or ToList) on an infinite sequence is not quite advised on today’s machines with finite amounts of memory. It’s clear such hacking is quite brittle and it breaks the delayed execution nature of the query expression. In other words, you can’t really hand out the resulting expression to a caller for it to call when it needs results (if it ever does). We’re too eager about evaluating (part of) the query, just to be able to tame the side-effect:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;xrs = &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Generate(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Random&lt;/span&gt;(), rnd =&amp;gt; &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Return(rnd.Next(100)), &lt;span style="color:green;"&gt;/* iterate */ &lt;/span&gt;_ =&amp;gt; _)
    .Take(10)&lt;font color="#ff0000"&gt;.ToArray()&lt;/font&gt;;

&lt;span style="color:blue;"&gt;var &lt;/span&gt;randomEvens = xrs.Zip(xrs, (l, r) =&amp;gt; l + r);&lt;/pre&gt;

  &lt;pre class="code"&gt;&lt;span style="color:green;"&gt;// What if the consumer of randomEvens &lt;em&gt;expects&lt;/em&gt; different results on each enumeration... Hard cheese! &lt;/span&gt;
randomEvens.Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);
randomEvens.Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;It’s clear that we need some more tools in our toolbox to tame desired side-effects when needed. That’s exactly what this post focuses on.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Option 1: Do nothing with Let&lt;/h1&gt;

&lt;p&gt;A first way to approach side-effects is to embrace them as-is. We just allow multiple enumerations of the same sequence to yield different results (or more generally, replicate side-effects). However, we can provide a bit more syntactical convenience in writing queries that reuse the same common subexpression in multiple places. In the above, we had to introduce an intermediate variable to store the common expression in, ready for reuse further on:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;xrs = &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Generate(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Random&lt;/span&gt;(), rnd =&amp;gt; &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Return(rnd.Next(100)), &lt;span style="color:green;"&gt;/* iterate */ &lt;/span&gt;_ =&amp;gt; _);
xrs.Zip(xrs, (l, r) =&amp;gt; l + r).Take(10).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;Can’t we somehow write this more fluently? The answer is yes, using the Let operator which passes its left-hand side to a lambda expression that can potentially use it multiple times:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Generate(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Random&lt;/span&gt;(), rnd =&amp;gt; &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Return(rnd.Next(100)), &lt;span style="color:green;"&gt;/* iterate */ &lt;/span&gt;_ =&amp;gt; _)
    .Let(xrs =&amp;gt; xrs.Zip(xrs, (l, r) =&amp;gt; l + r)).Take(10).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;You can guess the signature of Let just by looking at the use above, but &lt;em&gt;let&lt;/em&gt;’s include it for completeness:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TResult&amp;gt; Let&amp;lt;TSource, TResult&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; source, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt;, &lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TResult&amp;gt;&amp;gt; function);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Because of the call-by-value nature of the languages we’re talking about, the expression used for the source parameter will be fully evaluated (not the same as enumerated!) before Let gets called, so we can feed it (again in a call-by-value manner) to the function which then can refer to it multiple times by means of its lambda expression parameter (in the sample above this is “xrs”). Let comes from the world of functional languages where it takes the following form:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;let x = y in z&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;means (in C#-ish syntax)&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;(x =&amp;gt; z)(y)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In other words, there’s a hidden function x =&amp;gt; z sitting in a let-expression and the “value” for x (which is y in the sample) gets passed to it, providing the result for the entire let-expression. In EnumerableEx.Let, the function is clear as the second parameter, and the role of “y” is fulfilled by the source parameter. One could create a Let-form for any object as follows (not recommended because of the unrestricted extension method):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;R Let&amp;lt;T, R&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;T t, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;T, R&amp;gt; f)
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;f(t);
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;With this, you can write things like this:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#2b91af;"&gt;DateTime&lt;/span&gt;.Now.Let(x =&amp;gt; x - x).Ticks);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;This will print 0 ticks for sure, since the same DateTime.Now is used for x on both sides of the subtraction. If we were to expand this expression by substituting DateTime.Now for x, we’d get something different due to the duplicate evaluation of DateTime.Now, exposing the side-effect of reading from the system clock:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine((&lt;span style="color:#2b91af;"&gt;DateTime&lt;/span&gt;.Now - &lt;span style="color:#2b91af;"&gt;DateTime&lt;/span&gt;.Now).Ticks);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;(Pop quiz: What sign will the above Ticks result have? Is it possible for the above to return 0 sometimes?)&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Option 2: Cache on demand a.k.a. MemoizeAll&lt;/h1&gt;

&lt;p&gt;As we’ve seen before, on way to get rid of the side-effect replication is by forcing eager evaluation of the sequence through operators like ToArray or ToList. However, those are a bit too eager in various ways:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;They &lt;em&gt;persist &lt;/em&gt;the whole sequence, which won’t work for infinite sequences.&lt;/li&gt;

  &lt;li&gt;They do so &lt;em&gt;on the spot&lt;/em&gt;, i.e. the eagerness can’t be delayed till a later point (‘on demand”).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The last problem can be worked around using the Defer operator, but the first one is still a problem requiring another operator. Both those things are what MemoizeAll provides for, essentially persisting the sequence bit-by-bit upon consumption. This is achieved by exposing the enumerable while only maintaining a single enumerator to its source:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/Mor.InteractiveFunctionalfunandtamingsid_9DCC/image_3.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/Mor.InteractiveFunctionalfunandtamingsid_9DCC/image_thumb_3.png" width="640" height="456" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In the figure above, this is illustrated. Red indicates a fetch operation where the original source’s iterator makes progress as an element is requested that hasn’t been fetched before. Green indicates persisted (cached, memoized) objects. Gray indicates elements in the source that have been fetched and hence belong to the past from the (single) source-iterators point of view: MemoizeAll won’t ever request those again. Applying this operator to our running sample using Zip will produce results with the expected invariant:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;xrs = &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Generate(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Random&lt;/span&gt;(), rnd =&amp;gt; &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Return(rnd.Next(100)), &lt;span style="color:green;"&gt;/* iterate */ &lt;/span&gt;_ =&amp;gt; _)
    .Do(xr =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;! -&amp;gt; &amp;quot; &lt;/span&gt;+ xr))
    .MemoizeAll();
xrs.Do(xr =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;L -&amp;gt; &amp;quot; &lt;/span&gt;+ xr)).Zip(
    xrs.Do(xr =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;R -&amp;gt; &amp;quot; &lt;/span&gt;+ xr)),
    (l, r) =&amp;gt; l + r).Take(10).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Now we’ll see the xrs-triggered Do messages being printed only 10 times since the same element will be consumed by the two uses of xrs within Zip. The result looks as follows, showing how the right consumer of Zip never causes a fetch back to the random number generating source due to the internal caching by MemoizeAll:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;! -&amp;gt; 71
    &lt;br /&gt;L -&amp;gt; 71

    &lt;br /&gt;R -&amp;gt; 71

    &lt;br /&gt;142

    &lt;br /&gt;! -&amp;gt; 18

    &lt;br /&gt;L -&amp;gt; 18

    &lt;br /&gt;R -&amp;gt; 18

    &lt;br /&gt;36

    &lt;br /&gt;! -&amp;gt; 12

    &lt;br /&gt;L -&amp;gt; 12

    &lt;br /&gt;R -&amp;gt; 12

    &lt;br /&gt;24

    &lt;br /&gt;! -&amp;gt; 96

    &lt;br /&gt;L -&amp;gt; 96

    &lt;br /&gt;R -&amp;gt; 96

    &lt;br /&gt;192

    &lt;br /&gt;! -&amp;gt; 1

    &lt;br /&gt;L -&amp;gt; 1

    &lt;br /&gt;R -&amp;gt; 1

    &lt;br /&gt;2

    &lt;br /&gt;! -&amp;gt; 54

    &lt;br /&gt;L -&amp;gt; 54

    &lt;br /&gt;R -&amp;gt; 54

    &lt;br /&gt;108

    &lt;br /&gt;! -&amp;gt; 9

    &lt;br /&gt;L -&amp;gt; 9

    &lt;br /&gt;R -&amp;gt; 9

    &lt;br /&gt;18

    &lt;br /&gt;! -&amp;gt; 87

    &lt;br /&gt;L -&amp;gt; 87

    &lt;br /&gt;R -&amp;gt; 87

    &lt;br /&gt;174

    &lt;br /&gt;! -&amp;gt; 18

    &lt;br /&gt;L -&amp;gt; 18

    &lt;br /&gt;R -&amp;gt; 18

    &lt;br /&gt;36

    &lt;br /&gt;! -&amp;gt; 12

    &lt;br /&gt;L -&amp;gt; 12

    &lt;br /&gt;R -&amp;gt; 12

    &lt;br /&gt;24&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;What about lifetime of the source’s single enumerator? As soon as one of the consumers reaches the end of the underlying sequence, we got all elements cached and are prepared to any possible inquiry for elements on the output side of the MemoizeAll operator, hence it’s possible to dispose of the original enumerator. It should also be noted that memoization operators use materialization internally to capture the behavior of the sequence to expose to all consumers. This means exceptions are captured as Notification&amp;lt;T&amp;gt; so they’re repeatable to all consumers:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;xes = &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Throw&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Exception&lt;/span&gt;()).StartWith(1).MemoizeAll();
xes.Catch((&lt;span style="color:#2b91af;"&gt;Exception &lt;/span&gt;_) =&amp;gt; &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Return(42)).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);
xes.Catch((&lt;span style="color:#2b91af;"&gt;Exception &lt;/span&gt;_) =&amp;gt; &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Return(42)).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;The above will therefore print 1, 42 twice. In other words, the source blowing up during fetching by MemoizeAll doesn’t terminate other consumers that haven’t reached the faulty state yet (but if they iterate long enough, they’ll eventually see it exactly as the original consumer did).&lt;/p&gt;

&lt;p&gt;Finally, what’s All about MemoizeAll? In short: the cache used by the operator can grow infinitely large. The difference compared to ToArray and ToList has been explained before, but it’s worth repeating it: MemoizeAll doesn’t fetch its source’s results on the spot but only makes progress through the source’s enumerator when one of the consumers requests an element that hasn’t been retrieved yet. Call it a piecemeal ToList if you want.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Option 3: Memoize, but less “conservative”&lt;/h1&gt;

&lt;p&gt;While MemoizeAll does the trick to avoid repetition of side-effects, it’s quite conservative in its caching as it never throws away elements it has retrieved. You never know whether someone – like a slow enumerator or a whole new enumerator over the memoized result – will request the data again, so a general-purpose Memoize can’t throw away a thing. However, if you know the behavior of the consumers of the memoized source, you can be more efficient about it and use Memoize specifying a buffer size. In our running sample of Zip we know that both uses of the source for the left and right inputs to Zip will be enumerated at the same pace, so it suffices to keep the last element in the cache in order for the right enumerator to be able to see the element the left enumerator just saw. Memoize with buffer size 1 does exactly that:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;xrs = &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Generate(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Random&lt;/span&gt;(), rnd =&amp;gt; &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Return(rnd.Next(100)), &lt;span style="color:green;"&gt;/* iterate */ &lt;/span&gt;_ =&amp;gt; _)
    .Do(xr =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;! -&amp;gt; &amp;quot; &lt;/span&gt;+ xr))
    .Memoize(1);
xrs.Do(xr =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;L -&amp;gt; &amp;quot; &lt;/span&gt;+ xr)).Zip(
    xrs.Do(xr =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;R -&amp;gt; &amp;quot; &lt;/span&gt;+ xr)),
    (l, r) =&amp;gt; l + r).Take(10).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;In pictures, this looks as follows:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/Mor.InteractiveFunctionalfunandtamingsid_9DCC/image_4.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/Mor.InteractiveFunctionalfunandtamingsid_9DCC/image_thumb_4.png" width="640" height="456" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Another valid buffer size – also the default – is zero. It’s left to the reader, as an exercise, to come up with a plausible theory for what that one’s behavior should be and to depict this case graphically.&lt;/p&gt;

&lt;p&gt;(Question: Would it be possible to provide a “smart” memoization operator that knows exactly when it can abandon items in the front of its cache? Why (not)?)&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Derived forms&lt;/h1&gt;

&lt;p&gt;The difference between Let and the Memoize operators is that the former feeds in a view on an IEnumerable&amp;lt;T&amp;gt; source to a function, allowing that one to refer to the source multiple times in the act of producing a source in return. Let is, as we saw, nothing but fancy function application in a “fluent” left-to-right dataflowy way. Derived forms of Memoize exist that have the same form where a function is fed a memoized data source:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Replay is Memoize on steroids&lt;/li&gt;

  &lt;li&gt;Publish is MemoizeAll on steroids&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The following snippets show just what those operators do (modulo parameter checks):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TResult&amp;gt; Publish&amp;lt;TSource, TResult&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; source,&lt;br /&gt;                                                             Func&amp;lt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt;, &lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TResult&amp;gt;&amp;gt; function)
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;function(source.MemoizeAll());
}

&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TResult&amp;gt; Publish&amp;lt;TSource, TResult&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; source,&lt;br /&gt;                                                             Func&amp;lt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt;, &lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TResult&amp;gt;&amp;gt; function,&lt;br /&gt;                                                             TSource initialValue)
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;function(source.MemoizeAll().StartWith(initialValue));
}

&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TResult&amp;gt; Replay&amp;lt;TSource, TResult&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; source,&lt;br /&gt;                                                            Func&amp;lt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt;, &lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TResult&amp;gt;&amp;gt; function)
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;function(source.Memoize());
}

&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TResult&amp;gt; Replay&amp;lt;TSource, TResult&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; source,&lt;br /&gt;                                                            Func&amp;lt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt;, &lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TResult&amp;gt;&amp;gt; function,&lt;br /&gt;                                                            &lt;span style="color:blue;"&gt;int &lt;/span&gt;bufferSize)
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;function(source.Memoize(bufferSize));
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;So we could rewrite our Zip sample in a variety of ways, the following being the cleanest one-sized buffer variant:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Generate(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Random&lt;/span&gt;(), rnd =&amp;gt; &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Return(rnd.Next(100)), &lt;span style="color:green;"&gt;/* iterate */ &lt;/span&gt;_ =&amp;gt; _)
    .Do(xr =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;! -&amp;gt; &amp;quot; &lt;/span&gt;+ xr))
    .Replay(&lt;font color="#ff0000"&gt;xrs&lt;/font&gt; =&amp;gt; &lt;font color="#ff0000"&gt;xrs&lt;/font&gt;.Do(xr =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;L -&amp;gt; &amp;quot; &lt;/span&gt;+ xr)).Zip(
                   &lt;font color="#ff0000"&gt;xrs&lt;/font&gt;.Do(xr =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;R -&amp;gt; &amp;quot; &lt;/span&gt;+ xr)),
                   (l, r) =&amp;gt; l + r),
            1)
    .Take(10).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Option 4: Fair (?) sharing with Share and Prune&lt;/h1&gt;

&lt;p&gt;The Share operator shares an IEnumerator&amp;lt;T&amp;gt; for any number of consumers of an IEnumerable&amp;lt;T&amp;gt;, hence avoiding duplication of side-effects. In addition, it also guarantees that no two consumers can see the same element, so in effect the Share operator has the potential of distributing elements across different consumers. Looking at it from another angle, one consumer can steal elements from the source, preventing another consumer from seeing it. Prune is derived from Share as follows:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TResult&amp;gt; Prune&amp;lt;TSource, TResult&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; source,&lt;br /&gt;                                                           Func&amp;lt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt;, &lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TResult&amp;gt;&amp;gt; function)
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;function(source.Share());
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;The naming for Prune follows from the effect consumers inside the function have on the sequence being shared: each one consuming data effectively prunes elements from the head of the sequence, so that others cannot see those anymore. An example is shown below, showing another way a Zip could go &lt;em&gt;wrong&lt;/em&gt; (practical scenarios for this operator would involve sharing) since the left and right consumers both advance the cursor of the same shared enumerator under the hood:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Generate(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Random&lt;/span&gt;(), rnd =&amp;gt; &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Return(rnd.Next(100)), &lt;span style="color:green;"&gt;/* iterate */ &lt;/span&gt;_ =&amp;gt; _)
    .Do(xr =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;! -&amp;gt; &amp;quot; &lt;/span&gt;+ xr))
    .Prune(xrs =&amp;gt; xrs.Do(xr =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;L -&amp;gt; &amp;quot; &lt;/span&gt;+ xr)).Zip(
                   xrs.Do(xr =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;R -&amp;gt; &amp;quot; &lt;/span&gt;+ xr)),
                   (l, r) =&amp;gt; l + r))
    .Take(10).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;The result of this is of interest since the logging will reveal the sharing characteristic. Looking at the first Do’s output we’ll see it gets triggered by any consumer on the inside of Prune:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;! -&amp;gt; 37
    &lt;br /&gt;L -&amp;gt; 37

    &lt;br /&gt;! -&amp;gt; 51

    &lt;br /&gt;R -&amp;gt; 51

    &lt;br /&gt;88

    &lt;br /&gt;! -&amp;gt; 98

    &lt;br /&gt;L -&amp;gt; 98

    &lt;br /&gt;! -&amp;gt; 89

    &lt;br /&gt;R -&amp;gt; 89

    &lt;br /&gt;187

    &lt;br /&gt;! -&amp;gt; 4

    &lt;br /&gt;L -&amp;gt; 4

    &lt;br /&gt;! -&amp;gt; 71

    &lt;br /&gt;R -&amp;gt; 71

    &lt;br /&gt;75

    &lt;br /&gt;! -&amp;gt; 43

    &lt;br /&gt;L -&amp;gt; 43

    &lt;br /&gt;! -&amp;gt; 30

    &lt;br /&gt;R -&amp;gt; 30

    &lt;br /&gt;73

    &lt;br /&gt;! -&amp;gt; 18

    &lt;br /&gt;L -&amp;gt; 18

    &lt;br /&gt;! -&amp;gt; 24

    &lt;br /&gt;R -&amp;gt; 24

    &lt;br /&gt;42

    &lt;br /&gt;! -&amp;gt; 17

    &lt;br /&gt;L -&amp;gt; 17

    &lt;br /&gt;! -&amp;gt; 41

    &lt;br /&gt;R -&amp;gt; 41

    &lt;br /&gt;58

    &lt;br /&gt;! -&amp;gt; 45

    &lt;br /&gt;L -&amp;gt; 45

    &lt;br /&gt;! -&amp;gt; 68

    &lt;br /&gt;R -&amp;gt; 68

    &lt;br /&gt;113

    &lt;br /&gt;! -&amp;gt; 83

    &lt;br /&gt;L -&amp;gt; 83

    &lt;br /&gt;! -&amp;gt; 53

    &lt;br /&gt;R -&amp;gt; 53

    &lt;br /&gt;136

    &lt;br /&gt;! -&amp;gt; 64

    &lt;br /&gt;L -&amp;gt; 64

    &lt;br /&gt;! -&amp;gt; 69

    &lt;br /&gt;R -&amp;gt; 69

    &lt;br /&gt;133

    &lt;br /&gt;! -&amp;gt; 0

    &lt;br /&gt;L -&amp;gt; 0

    &lt;br /&gt;! -&amp;gt; 22

    &lt;br /&gt;R -&amp;gt; 22

    &lt;br /&gt;22&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In pictures, this looks as follows:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/Mor.InteractiveFunctionalfunandtamingsid_9DCC/image_5.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/Mor.InteractiveFunctionalfunandtamingsid_9DCC/image_thumb_5.png" width="640" height="456" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Exercise: Can you guess how Memoize(0) differs from Share?&lt;/p&gt;

&lt;p&gt;Quiz: What should be the behavior of the following fragment? (Tip: you got to know what two from clauses result in and how they execute)&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;Enumerable&lt;/span&gt;.Range(0, 10)&lt;font color="#008000"&gt;&lt;br /&gt;&lt;/font&gt;&lt;span style="color:green;"&gt;    &lt;/span&gt;.Prune(xs =&amp;gt; &lt;span style="color:blue;"&gt;from &lt;/span&gt;x &lt;span style="color:blue;"&gt;in &lt;/span&gt;xs.Zip(xs, (l, r) =&amp;gt; l + r)
                 &lt;span style="color:blue;"&gt;from &lt;/span&gt;y &lt;span style="color:blue;"&gt;in &lt;/span&gt;xs
                 &lt;span style="color:blue;"&gt;select &lt;/span&gt;x + y)
    .Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Next on More LINQ&lt;/h1&gt;

&lt;p&gt;A look at the Asynchronous and Remotable operators, dealing with some infrastructure-related concepts, wrapping up this series for now.&lt;/p&gt;&lt;img src="http://community.bartdesmet.net/aggbug.aspx?PostID=15025" width="1" height="1"&gt;</description><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/LINQ/default.aspx">LINQ</category><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/Rx/default.aspx">Rx</category></item><item><title>Top 9 Posts from 2009</title><link>http://community.bartdesmet.net/blogs/bart/archive/2010/01/03/top-9-posts-from-2009.aspx</link><pubDate>Sun, 03 Jan 2010 09:08:39 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:14996</guid><dc:creator>bart</dc:creator><slash:comments>4</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://community.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=14996</wfw:commentRss><comments>http://community.bartdesmet.net/blogs/bart/archive/2010/01/03/top-9-posts-from-2009.aspx#comments</comments><description>&lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;select top &lt;/span&gt;9 [Subject] &lt;span style="color:blue;"&gt;from &lt;/span&gt;dbo&lt;span style="color:gray;"&gt;.&lt;/span&gt;cs_Posts&lt;br /&gt;&lt;span style="color:blue;"&gt;where &lt;/span&gt;postlevel &lt;span style="color:gray;"&gt;= &lt;/span&gt;1 &lt;span style="color:gray;"&gt;and &lt;/span&gt;usertime &lt;span style="color:gray;"&gt;&amp;lt; &lt;/span&gt;&lt;span style="color:red;"&gt;&amp;#39;01/01/2010&amp;#39; &lt;/span&gt;&lt;span style="color:gray;"&gt;and &lt;/span&gt;usertime &lt;span style="color:gray;"&gt;&amp;gt;= &lt;/span&gt;&lt;span style="color:red;"&gt;&amp;#39;01/01/2009&amp;#39;&lt;br /&gt;&lt;/span&gt;&lt;span style="color:blue;"&gt;order by &lt;/span&gt;TotalViews &lt;span style="color:blue;"&gt;desc&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Forgive me for the classic SQL, but here are the results with some short annotations inline:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2009/08/17/mis-using-c-4-0-dynamic-type-free-lambda-calculus-church-numerals-and-more.aspx"&gt;(Mis)using C# 4.0 Dynamic – Type-Free Lambda Calculus, Church Numerals, and more&lt;/a&gt; 

    &lt;br /&gt;

    &lt;br /&gt;Uses the new C# 4.0 dynamic feature to implement the type-free lambda calculus consisting of an abstraction and application operator. Besides talking about the fundamentals of lambda calculus, this post shows how to implement the SKI combinators and Church Booleans, Church numerals and even recursive functions. 

    &lt;br /&gt;&amp;#160; &lt;/li&gt;

  &lt;li&gt;&lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2009/08/17/linq-to-ducks-bringing-back-the-duck-typed-foreach-statement-to-linq.aspx"&gt;LINQ to Ducks – Bringing Back The Duck-Typed foreach Statement To LINQ&lt;/a&gt; 

    &lt;br /&gt;

    &lt;br /&gt;Since LINQ to Objects is layered on top of IEnumerable&amp;lt;T&amp;gt;, it doesn’t work against objects that just happen to implement the enumeration pattern consisting of GetEnumerator, MoveNext and Current. Since the foreach statement actually does work against such data sources, we bring back this duck typing to LINQ using AsDuckEnumerable&amp;lt;T&amp;gt;(). 

    &lt;br /&gt;&amp;#160; &lt;/li&gt;

  &lt;li&gt;&lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2009/08/30/type-free-lambda-calculus-in-c-pre-4-0-defining-the-lambda-language-runtime-llr.aspx"&gt;Type-Free Lambda Calculus in C#, Pre-4.0 – Defining the Lambda Language Runtime (LLR)&lt;/a&gt; 

    &lt;br /&gt;

    &lt;br /&gt;We repeat the exercise of the first blog post but now without C# 4.0 dynamic features., encoding application and abstraction operators using none less that exceptions. Those primitives define what I call the Lambda Language Runtime (LLR), which we use subsequently to implement a bunch of samples similar to the ones in the first post. 

    &lt;br /&gt;&amp;#160; &lt;/li&gt;

  &lt;li&gt;&lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2009/09/12/taming-your-sequence-s-side-effects-through-ienumerable-let.aspx"&gt;Taming Your Sequence’s Side-Effects Through IEnumerable.Let&lt;/a&gt; 

    &lt;br /&gt;

    &lt;br /&gt;Enumerable sequences can exhibit side-effects for various reasons ranging from side-effecting filter predicates to iterators with side-effecting imperative code interwoven in them. The Let operator introduced in this post helps you to keep those side-effects under control when multiple “stable” enumerations over the sequence are needed. 

    &lt;br /&gt;&amp;#160; &lt;/li&gt;

  &lt;li&gt;&lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2009/08/11/statement-trees-with-less-pain-follow-up-on-system-linq-expressions-v4-0.aspx"&gt;Statement Trees With Less Pain – Follow-Up on System.Linq.Expressions v4.0&lt;/a&gt; 

    &lt;br /&gt;

    &lt;br /&gt;The introduction of the DLR in the .NET 4 release brings us not only dynamic typing but also full-fledged statement trees as an upgrade to the existing LINQ expression trees. Here we realize a prime number generator using statement trees and runtime compilation, reusing expression trees emitted by the C# compiler where possible. 

    &lt;br /&gt;&amp;#160; &lt;/li&gt;

  &lt;li&gt;&lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2009/09/27/linq-to-z3-theorem-solving-on-steroids-part-1.aspx"&gt;LINQ to Z3 – Theorem Solving on Steroids – Part 1&lt;/a&gt; 

    &lt;br /&gt;

    &lt;br /&gt;LINQifying Microsoft Research’s Z3 theorem solver has been one of my long-running side-projects. This most recent write-up on the matter illustrates the concept of a LINQ-enabled Theorem&amp;lt;T&amp;gt; and the required visitor implementation to interop with the Z3 libraries. Finally, we show a Sudoku and Kakuro solver expressed in LINQ. 

    &lt;br /&gt;&amp;#160; &lt;/li&gt;

  &lt;li&gt;&lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2009/08/10/expression-trees-take-two-introducing-system-linq-expressions-v4-0.aspx"&gt;Expression Trees, Take Two – Introducing System.Linq.Expressions v4.0&lt;/a&gt; 

    &lt;br /&gt;

    &lt;br /&gt;Just like post 5, we have a look at the .NET 4 expression tree support, now including statement trees. Besides pointing out the new tree node types, we show dynamic compilation and inspect the generated IL code using the SOS debugger’s dumpil command. In post 5, we follow up by showing how to reuse C# 3.0 expression tree support. 

    &lt;br /&gt;&amp;#160; &lt;/li&gt;

  &lt;li&gt;&lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2009/04/27/unlambda-net-with-a-big-dose-of-c-3-0-lambdas.aspx"&gt;Unlambda .NET – With a Big Dose of C# 3.0 Lambdas&lt;/a&gt; 

    &lt;br /&gt;

    &lt;br /&gt;Esoteric programming languages are good topics for &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/tags/Crazy+Sundays/default.aspx"&gt;Crazy Sundays&lt;/a&gt; posts. In this one we had a look at how to implement the Unlambda language – based on SKI combinators and with “little” complications like Call/CC – using C# 3.0 with lots of lambda expressions. To satisfy our curiosity, we run a Fibonacci sample program. 

    &lt;br /&gt;&amp;#160; &lt;/li&gt;

  &lt;li&gt;&lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2009/04/13/c-4-0-feature-focus-part-4-generic-co-and-contra-variance-for-delegate-and-interface-types.aspx"&gt;C# 4.0 Feature Focus – Part 4 – Co- and Contra-Variance for Generic Delegate and Interface Types&lt;/a&gt; 

    &lt;br /&gt;

    &lt;br /&gt;Generic co- and contra-variance is most likely the most obscure C# 4.0 feature, so I decided to give it a bit more attention using samples of the everyday world (like apples and tomatoes). We explain why arrays are unsafe for covariance and how generic variance gets things right, also increasing your expressiveness. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In conclusion, it seems esoteric and foundational posts are quite popular, but then again that’s what I write about most. For 2010, I hope to please my readers’ interests even further with the occasional “stunt coding”, “brain pain” and “mind bending” (based on Twitter quotes in 2009). If there are particular topics you’d like to see covered, feel free to let me know. So, thanks again for reading in 2009 (good for slightly over 1TB – no that’s not a typo – of data transfer from my hoster) and &lt;strong&gt;hope to see you back in 2010&lt;/strong&gt;!&lt;/p&gt;&lt;img src="http://community.bartdesmet.net/aggbug.aspx?PostID=14996" width="1" height="1"&gt;</description><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/Personal/default.aspx">Personal</category></item><item><title>LINQSQO v4.0 and MinLINQ v1.0 Now Available for Download</title><link>http://community.bartdesmet.net/blogs/bart/archive/2010/01/02/linqsqo-v4-0-and-minlinq-v1-0-now-available-for-download.aspx</link><pubDate>Sat, 02 Jan 2010 16:33:31 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:14989</guid><dc:creator>bart</dc:creator><slash:comments>2</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://community.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=14989</wfw:commentRss><comments>http://community.bartdesmet.net/blogs/bart/archive/2010/01/02/linqsqo-v4-0-and-minlinq-v1-0-now-available-for-download.aspx#comments</comments><description>&lt;p&gt;Introduced in my previous blog post on &lt;a href="http://blogs.bartdesmet.net/blogs/bart/archive/2010/01/01/the-essence-of-linq-minlinq.aspx"&gt;The Essence of LINQ – MinLINQ&lt;/a&gt;, the first release of this project is now available for reference at the LINQSQO CodePlex website at &lt;a title="http://linqsqo.codeplex.com/" href="http://linqsqo.codeplex.com"&gt;http://linqsqo.codeplex.com&lt;/a&gt;. Compared to the write-up over here in my previous post, there are a few small differences and caveats:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Only FEnumerable functionality is available currently; the FObservable dual may follow later.&lt;/li&gt;    &lt;li&gt;Option&amp;lt;T&amp;gt; has been renamed to Maybe&amp;lt;T&amp;gt;, to be CLS compliant and avoid clashes with the VB keyword.&lt;/li&gt;    &lt;li&gt;Some operators are not provided, in particular GroupBy, GroupJoin and Join. They’re left as an exercise.&lt;/li&gt;    &lt;li&gt;A few operator implementations are categorized as “cheaters” since they roundtrip through System.Linq.&lt;/li&gt;    &lt;li&gt;Don’t nag about performance. The MinLINQ code base is by no means optimal and so be it.&lt;/li&gt;    &lt;li&gt;Very few System.Interactive operators are included since those often require extra foundations (such as concurrency).&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;A few highlights:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;FEnumerable.Essentials.cs is where the fun starts. Here the three primitives – Ana, Bind and Cata – form the ABC of LINQ.&lt;/li&gt;    &lt;li&gt;There’s a Naturals() constructor function generating an infinite sequence of natural numbers, used in operators that use indexes.&lt;/li&gt;    &lt;li&gt;OrderBy and ThenBy are supported through roundtripping to System.Linq with a handy trick to keep track of IOrderedEnumerable&amp;lt;T&amp;gt;.&lt;/li&gt;    &lt;li&gt;As a sample, I’ve included &lt;a href="http://blogs.msdn.com/lukeh/archive/2007/10/01/taking-linq-to-objects-to-extremes-a-fully-linqified-raytracer.aspx"&gt;Luke Hoban’s LINQified RayTracer&lt;/a&gt; with AsFEnumerable and AsEnumerable roundtripping. It works just fine.&lt;/li&gt;    &lt;li&gt;Creating an architectural diagram in Visual Studio 2010 yields the following result (not meant to zoomed in), where I’ve used the following colors:&lt;/li&gt;    &lt;ul&gt;     &lt;li&gt;Green = Ana&lt;/li&gt;      &lt;li&gt;Blue = Bind&lt;/li&gt;      &lt;li&gt;Red = Cata&lt;/li&gt;   &lt;/ul&gt; &lt;/ul&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/LINQSQOv4.0andM.0NowAvailableforDownload_71CD/image.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/LINQSQOv4.0andM.0NowAvailableforDownload_71CD/image_thumb.png" width="1131" height="274" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Obviously, all sorts of warnings apply. People familiar to my blog adventures will know this already, but just in case:&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="code"&gt;&lt;span style="color:green;"&gt;//
// This project is meant as an illustration of how an academically satifying layering
// of a LINQ to Objects implementation can be realized using monadic concepts and only
// three primitives: anamorphism, bind and catamorphism.
//
// The code in this project is not meant to be used in production and no guarantees are
// made about its functionality. Use it for academic stimulation purposes only. To use
// LINQ for real, use System.Linq in .NET 3.5 or higher.
//
// All of the source code may be used in presentations of LINQ or for other educational
// purposes, but references to http://www.codeplex.com/LINQSQO and the blog post referred
// to above - &amp;quot;The Essence of LINQ - MinLINQ&amp;quot; - are required.
//&lt;/span&gt;&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Either way, if you find LINQ interesting and can stand some “brain pain of the highest quality” (a Twitter quote by dahlbyk), this will likely be something for you.&lt;/p&gt;&lt;img src="http://community.bartdesmet.net/aggbug.aspx?PostID=14989" width="1" height="1"&gt;</description><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/LINQ/default.aspx">LINQ</category><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/Crazy+Sundays/default.aspx">Crazy Sundays</category></item></channel></rss>