<?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 Technical Community Homepage</title><link>http://community.bartdesmet.net/blogs/</link><description>Bart De Smet's online technical community</description><dc:language>en-US</dc:language><generator>CommunityServer 2007 (Build: 20423.869)</generator><item><title>Windows PowerShell through IronRuby - Writing a custom PSHost</title><link>http://community.bartdesmet.net/blogs/bart/archive/2008/07/06/windows-powershell-through-ironruby-writing-a-custom-pshost.aspx</link><pubDate>Sun, 06 Jul 2008 08:00:00 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:13745</guid><dc:creator>bart</dc:creator><slash:comments>1</slash:comments><description>&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;Lately I&amp;#39;ve been playing quite a bit with DLR technologies, including &lt;a href="http://www.ironruby.com/"&gt;IronRuby&lt;/a&gt;. During some experiments I came to the conclusion that the Kernel.` method isn&amp;#39;t implemented yet in the current version. This `backtick` method allows executing OS commands from inside a Ruby program. It&amp;#39;s a bit like Process.Start, redirecting the standard output as a string to the Ruby program for further use (actually the Kernel.exec method is precisely implemented like this).&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;img style="BORDER-TOP-WIDTH:0px;BORDER-LEFT-WIDTH:0px;BORDER-BOTTOM-WIDTH:0px;BORDER-RIGHT-WIDTH:0px;" height="340" alt="image" src="http://bartdesmet.info/images_wlw/WindowsPowerShellthroughIronRuby_12D6E/image_thumb.png" width="677" border="0" /&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;One thing I like about the NotImplementedException is the fact it points unambiguously to the source that&amp;#39;s missing :-). Indeed, if you browse the IronRuby source, you&amp;#39;ll find this:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;[&lt;font color="#008080"&gt;RubyMethod&lt;/font&gt;(&lt;font color="#800000"&gt;&amp;quot;`&amp;quot;&lt;/font&gt;, &lt;font color="#008080"&gt;RubyMethodAttributes&lt;/font&gt;.PrivateInstance)] &lt;br /&gt;[&lt;font color="#008080"&gt;RubyMethod&lt;/font&gt;(&lt;font color="#800000"&gt;&amp;quot;`&amp;quot;&lt;/font&gt;, &lt;font color="#008080"&gt;RubyMethodAttributes&lt;/font&gt;.PublicSingleton)] &lt;br /&gt;&lt;font color="#0000ff"&gt;public static &lt;/font&gt;&lt;font color="#008080"&gt;MutableString &lt;/font&gt;ExecuteCommand(&lt;font color="#008080"&gt;CodeContext&lt;/font&gt;&lt;font color="#008000"&gt;/*!*/ &lt;/font&gt;context, &lt;font color="#0000ff"&gt;object &lt;/font&gt;self, [&lt;font color="#008080"&gt;NotNull&lt;/font&gt;]&lt;font color="#008080"&gt;MutableString&lt;/font&gt;&lt;font color="#008000"&gt;/*!*/&lt;/font&gt; command) { &lt;br /&gt;&lt;font color="#008000"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; // TODO:&lt;/font&gt; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;throw new &lt;/font&gt;&lt;font color="#008080"&gt;NotImplementedException&lt;/font&gt;(); &lt;br /&gt;}&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;Actually there are a couple of things here that are worth to discuss besides the current void of the method body:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Strings in Ruby are mutable as opposed to strings in the CLR/BCL. Therefore they are wrapped in a MutableString class. &lt;/li&gt;
&lt;li&gt;The weird /*!*/ notation indicates not-nullness, mirrored after the equivalent uncommented form in Spec# (e.g. MutableString! means a null-nullable string). To work with regular C#, the NotNullAttribute is used. &lt;/li&gt;
&lt;li&gt;Methods like this one are not invoked by Ruby directly, instead the RubyMethodAttribute declaration carries the metadata that provides the entry-point to the method (as well as other metadata). &lt;/li&gt;&lt;/ul&gt;
&lt;h1&gt;Kernel.`&lt;/h1&gt;
&lt;p&gt;I won&amp;#39;t cover the differences between Kernel.`, Kernel.system and Kernel.exec; more information can be found &lt;a href="http://www.ruby-doc.org/core/classes/Kernel.html"&gt;here&lt;/a&gt;. The backtick one is our target for the scope of this post:&lt;/p&gt;
&lt;p&gt;&lt;a class="" title="M001111" name="M001111"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;a href="http://www.ruby-doc.org/Kernel.src/M001111.html"&gt;&lt;em&gt;`cmd` =&amp;gt; string &lt;br /&gt;&lt;/em&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Returns the standard output of running cmd in a subshell. The built-in syntax %x{…} uses this method. Sets $? to the process status. &lt;/em&gt;&lt;/p&gt;&lt;pre&gt;&lt;em&gt;   `date`                   #=&amp;gt; &amp;quot;Wed Apr  9 08:56:30 CDT 2003\n&amp;quot;
   `ls testdir`.split[1]    #=&amp;gt; &amp;quot;main.rb&amp;quot;
   `echo oops &amp;amp;&amp;amp; exit 99`   #=&amp;gt; &amp;quot;oops\n&amp;quot;
   $?.exitstatus            #=&amp;gt; 99&lt;/em&gt;&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;Actually I want to focus on (yet another) powerful feature in PowerShell, namely the ability to create &lt;strong&gt;custom hosts&lt;/strong&gt;. What we want to achieve here is that the backtick syntax (or the equivalent %x syntax) runs the specified command as a PowerShell command (or pipeline of multiple cmdlets), emitting the string output as the `&amp;#39;s methods return value. Notice though this actually downgrades ones of the core principles of PowerShell concerning the use of objects through the pipeline rather than falling back to strings. One could easily think of a more powerful way to expose the results of a PowerShell invocation as PSObjects in Ruby but we&amp;#39;ll keep that for later.&lt;/p&gt;
&lt;p&gt;&lt;font color="#ff0000"&gt;&lt;u&gt;Important:&lt;/u&gt; This post outlines no more than the capability to hook up PowerShell in IronRuby through Kernel.`. Obviously no promises are made about the way Kernel.` will eventually be implemented in IronRuby as we move forward.&lt;/font&gt;&lt;/p&gt;
&lt;h1&gt;Building a custom PS host&lt;/h1&gt;
&lt;p&gt;Creating custom PS hosts isn&amp;#39;t that hard, depending on how much functionality you want to take over. We&amp;#39;ll stick with the basics of console I/O, actually just the O in this. What we want to get done is this:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Build up a runspace containing the command passed to Kernel.` (in addition to some more pipeline commands to produce the right output, see further). &lt;/li&gt;
&lt;li&gt;Invoke the built-up pipeline. &lt;/li&gt;
&lt;li&gt;Retrieve the string output from the host, concatenate it into one big string and return that one to the caller of Kernel.`. &lt;/li&gt;&lt;/ol&gt;
&lt;h2&gt;&amp;nbsp;&lt;/h2&gt;
&lt;h2&gt;Preparing for PowerShell programming&lt;/h2&gt;
&lt;p&gt;In order to extend PowerShell, you&amp;#39;ll need to add a reference to System.Management.Automation.dll which can be found in the Reference Assemblies folder (click to enlarge):&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/WindowsPowerShellthroughIronRuby_12D6E/image.png"&gt;&lt;img style="BORDER-TOP-WIDTH:0px;BORDER-LEFT-WIDTH:0px;BORDER-BOTTOM-WIDTH:0px;BORDER-RIGHT-WIDTH:0px;" height="128" alt="image" src="http://bartdesmet.info/images_wlw/WindowsPowerShellthroughIronRuby_12D6E/image_thumb_3.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;&lt;/blockquote&gt;
&lt;h2&gt;Runspaces&lt;/h2&gt;
&lt;p&gt;Let&amp;#39;s start at the very top by implementing a method called &amp;quot;InvokePS&amp;quot; that sets up the infrastructure to call PowerShell:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;font color="#0000ff"&gt;public static class&lt;/font&gt; RubyToPS &lt;br /&gt;{ &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public static string &lt;/font&gt;InvokePS(&lt;font color="#0000ff"&gt;string &lt;/font&gt;command) &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#008080"&gt;RubyPSHost &lt;/font&gt;host = &lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;RubyPSHost&lt;/font&gt;(); &lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;using &lt;/font&gt;(&lt;font color="#008080"&gt;Runspace &lt;/font&gt;runspace = &lt;font color="#008080"&gt;RunspaceFactory&lt;/font&gt;.CreateRunspace(host)) &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; runspace.Open(); &lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;using &lt;/font&gt;(&lt;font color="#008080"&gt;Pipeline &lt;/font&gt;pipeline = runspace.CreatePipeline()) &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; pipeline.Commands.AddScript(command); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; pipeline.Commands[0].MergeMyResults(&lt;font color="#008080"&gt;PipelineResultTypes&lt;/font&gt;.Error, &lt;font color="#008080"&gt;PipelineResultTypes&lt;/font&gt;.Output);&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; pipeline.Commands.Add(&lt;font color="#800000"&gt;&amp;quot;out-default&amp;quot;&lt;/font&gt;); &lt;br /&gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; pipeline.Invoke(); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;return&lt;/font&gt; ((&lt;font color="#008080"&gt;RubyPSHostUserInterface&lt;/font&gt;)host.UI).Output; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;br /&gt;}&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;The RubyPSHost class will be shown next, let&amp;#39;s focus on the Runspace stuff for now. A runspace serves as the entry-point to the PowerShell engine and encapsulates all the state needed to execute pipelines. Once we&amp;#39;ve opened the runspace, a pipeline is created to which we add the passed-in command as a script. This allows more than just one cmdlet invocation to be executed (e.g. &amp;quot;gps | where { $_.WorkingSet64 -gt 50MB }&amp;quot;). To send output to the host we append Out-Default to the pipeline:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;NAME &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; Out-Default &lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;SYNOPSIS &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; Send the output to the default formatter and the default output cmdlet. Thi &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; s cmdlet has no effect on the formatting or output. It is a placeholder tha &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; t lets you write your own Out-Default function or cmdlet. &lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;SYNTAX &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; Out-Default [-inputObject &amp;lt;psobject&amp;gt;] [&amp;lt;CommonParameters&amp;gt;] &lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;DETAILED DESCRIPTION &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; The Out-Default cmdlet send the output to the default formatter and the def &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; ault output cmdlet. This cmdlet has no effect on the formatting or output. &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; It is a placeholder that lets you write your own Out-Default function or cm &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; dlet.&lt;/em&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;The &lt;a href="http://msdn.microsoft.com/en-us/library/system.management.automation.runspaces.command.mergemyresults(VS.85).aspx"&gt;MergeMyResults&lt;/a&gt; call is used to ensure that error objects produced by the first command are merged into the output (otherwise you&amp;#39;ll get an exception instead). Finally the output is retrieved from the host after invoking the pipeline. How this works will be covered in a minute.&lt;/p&gt;
&lt;p&gt;To read more about PowerShell runspaces, check out &lt;a href="http://community.bartdesmet.net/blogs/bart/search.aspx?q=powershell+runspace"&gt;my other posts on the topic&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;Deriving from PSHost&lt;/h2&gt;
&lt;p&gt;Custom PowerShell hosts derive from the abstract PSHost base class. There&amp;#39;s quite some stuff that can be done here but we&amp;#39;ll stick with the absolute minimum functionality required to reach our goals:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;font color="#0000ff"&gt;internal class&lt;/font&gt; &lt;font color="#008080"&gt;RubyPSHost &lt;/font&gt;: &lt;font color="#008080"&gt;PSHost&lt;/font&gt; &lt;br /&gt;{ &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;private&lt;/font&gt; &lt;font color="#008080"&gt;Guid &lt;/font&gt;_hostId = &lt;font color="#008080"&gt;Guid&lt;/font&gt;.NewGuid(); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;strong&gt;&lt;font color="#0000ff"&gt;private&lt;/font&gt; &lt;font color="#008080"&gt;RubyPSHostUserInterface &lt;/font&gt;_ui = &lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;RubyPSHostUserInterface&lt;/font&gt;(); &lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public override&lt;/font&gt; &lt;font color="#008080"&gt;Guid&lt;/font&gt; InstanceId &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;get&lt;/font&gt; { &lt;font color="#0000ff"&gt;return &lt;/font&gt;_hostId; } &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public override string &lt;/font&gt;Name &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;get&lt;/font&gt; { &lt;font color="#0000ff"&gt;return &lt;/font&gt;&lt;font color="#800000"&gt;&amp;quot;RubyPSHost&amp;quot;&lt;/font&gt;; } &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public override &lt;/font&gt;&lt;font color="#008080"&gt;Version&lt;/font&gt; Version &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;get&lt;/font&gt; { &lt;font color="#0000ff"&gt;return new &lt;/font&gt;&lt;font color="#008080"&gt;Version&lt;/font&gt;(1, 0); } &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public override &lt;/font&gt;&lt;font color="#008080"&gt;PSHostUserInterface&lt;/font&gt; UI &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;get&lt;/font&gt; { &lt;font color="#0000ff"&gt;return &lt;/font&gt;_ui; } &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/strong&gt; &lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public override &lt;/font&gt;&lt;font color="#008080"&gt;CultureInfo &lt;/font&gt;CurrentCulture &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;get&lt;/font&gt; { &lt;font color="#0000ff"&gt;return &lt;/font&gt;&lt;font color="#008080"&gt;Thread&lt;/font&gt;.CurrentThread.CurrentCulture; } &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public override &lt;/font&gt;&lt;font color="#008080"&gt;CultureInfo &lt;/font&gt;CurrentUICulture &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;get&lt;/font&gt; { &lt;font color="#0000ff"&gt;return &lt;/font&gt;&lt;font color="#008080"&gt;Thread&lt;/font&gt;.CurrentThread.CurrentUICulture; } &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public override void&lt;/font&gt; EnterNestedPrompt() &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;throw new &lt;/font&gt;&lt;font color="#008080"&gt;NotImplementedException&lt;/font&gt;(); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public override void&lt;/font&gt; ExitNestedPrompt() &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;throw new &lt;/font&gt;&lt;font color="#008080"&gt;NotImplementedException&lt;/font&gt;(); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public override void&lt;/font&gt; NotifyBeginApplication() &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;return&lt;/font&gt;; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public override void&lt;/font&gt; NotifyEndApplication() &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;return&lt;/font&gt;; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public override void&lt;/font&gt; SetShouldExit(&lt;font color="#0000ff"&gt;int&lt;/font&gt; exitCode) &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;return&lt;/font&gt;; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;br /&gt;}&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;More information about all of those methods and properties can be found on &lt;a href="http://msdn.microsoft.com/en-us/library/system.management.automation.host.pshost(VS.85).aspx"&gt;MSDN&lt;/a&gt;. The most important one to us the the UI property that points at our PSHostUserInterface implementation called &lt;strong&gt;RubyPSHostUserInterface&lt;/strong&gt;.&lt;/p&gt;
&lt;h2&gt;Implementing PSHostUserInterface&lt;/h2&gt;
&lt;p&gt;Where the PSHost class provides basic information concerning the metadata of the host (name, version, id)m lifetime of the host (nested prompt, execit commands) and general settings (cultures), the &lt;a href="http://msdn.microsoft.com/en-us/library/system.management.automation.host.pshostuserinterface(VS.85).aspx"&gt;PSHostUserInterface&lt;/a&gt; class deals with &lt;em&gt;&amp;quot;dialog-oriented and line-oriented interaction between the cmdlet and the user, such as writing to, prompting for, and reading from user input&amp;quot;&lt;/em&gt; (from MSDN). The part we&amp;#39;re interested in the &lt;em&gt;writing to&lt;/em&gt; part. We won&amp;#39;t deal with prompts or user interaction - if one wants to do this, the Kernel.` command is no longer non-interactive (a possible alternative way to implement this would be to spawn PowerShell.exe and just get the shell&amp;#39;s output here - the default host would take care of all user interaction if required; the only problem is that prompts would appear in the Kernel.` output as well). Implementation of this class isn&amp;#39;t that hard either:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;font color="#0000ff"&gt;internal class&lt;/font&gt; &lt;font color="#008080"&gt;RubyPSHostUserInterface &lt;/font&gt;: &lt;font color="#008080"&gt;PSHostUserInterface&lt;/font&gt; &lt;br /&gt;{ &lt;br /&gt;&lt;strong&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;private&lt;/font&gt; &lt;font color="#008080"&gt;StringBuilder&lt;/font&gt; _sb; &lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public&lt;/font&gt; RubyPSHostUserInterface() &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; _sb = &lt;font color="#0000ff"&gt;new&lt;/font&gt; &lt;font color="#008080"&gt;StringBuilder&lt;/font&gt;(); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public override void&lt;/font&gt; Write(&lt;font color="#008080"&gt;ConsoleColor &lt;/font&gt;foregroundColor, &lt;font color="#008080"&gt;ConsoleColor&lt;/font&gt; backgroundColor, &lt;font color="#0000ff"&gt;string&lt;/font&gt; value) &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; _sb.Append(value); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public override void&lt;/font&gt; Write(&lt;font color="#0000ff"&gt;string&lt;/font&gt; value) &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; _sb.Append(value); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public override void&lt;/font&gt; WriteDebugLine(&lt;font color="#0000ff"&gt;string &lt;/font&gt;message) &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; _sb.AppendLine(&lt;font color="#800000"&gt;&amp;quot;DEBUG: &amp;quot;&lt;/font&gt; + message); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public override void&lt;/font&gt; WriteErrorLine(&lt;font color="#0000ff"&gt;string&lt;/font&gt; value) &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; _sb.AppendLine&lt;font color="#800000"&gt;(&amp;quot;ERROR: &amp;quot;&lt;/font&gt; + value); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public override void&lt;/font&gt; WriteLine(&lt;font color="#0000ff"&gt;string&lt;/font&gt; value) &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; _sb.AppendLine(value); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public override void&lt;/font&gt; WriteVerboseLine(&lt;font color="#0000ff"&gt;string &lt;/font&gt;message) &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; _sb.AppendLine(&lt;font color="#800000"&gt;&amp;quot;VERBOSE: &amp;quot;&lt;/font&gt; + message); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public override void&lt;/font&gt; WriteWarningLine(&lt;font color="#0000ff"&gt;string &lt;/font&gt;message) &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; _sb.AppendLine(&lt;font color="#800000"&gt;&amp;quot;WARNING: &amp;quot;&lt;/font&gt; + message); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public override void&lt;/font&gt; WriteProgress(&lt;font color="#0000ff"&gt;long&lt;/font&gt; sourceId, &lt;font color="#008080"&gt;ProgressRecord&lt;/font&gt; record) &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;return&lt;/font&gt;; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public string&lt;/font&gt; Output &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;get&lt;/font&gt; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;return&lt;/font&gt; _sb.ToString(); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/strong&gt; &lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public override&lt;/font&gt; &lt;font color="#008080"&gt;Dictionary&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;string&lt;/font&gt;, &lt;font color="#008080"&gt;PSObject&lt;/font&gt;&amp;gt; Prompt(&lt;font color="#0000ff"&gt;string&lt;/font&gt; caption, &lt;font color="#0000ff"&gt;string &lt;/font&gt;message, System.Collections.ObjectModel.&lt;font color="#008080"&gt;Collection&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;FieldDescription&lt;/font&gt;&amp;gt; descriptions) &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;throw new&lt;/font&gt; &lt;font color="#008080"&gt;NotImplementedException&lt;/font&gt;(); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public override&lt;/font&gt; &lt;font color="#0000ff"&gt;int&lt;/font&gt; PromptForChoice(&lt;font color="#0000ff"&gt;string&lt;/font&gt; caption, &lt;font color="#0000ff"&gt;string&lt;/font&gt; message, System.Collections.ObjectModel.&lt;font color="#008080"&gt;Collection&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;ChoiceDescription&lt;/font&gt;&amp;gt; choices, &lt;font color="#0000ff"&gt;int&lt;/font&gt; defaultChoice) &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;throw new&lt;/font&gt; &lt;font color="#008080"&gt;NotImplementedException&lt;/font&gt;(); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public override&lt;/font&gt; &lt;font color="#008080"&gt;PSCredential&lt;/font&gt; PromptForCredential(&lt;font color="#0000ff"&gt;string&lt;/font&gt; caption, &lt;font color="#0000ff"&gt;string&lt;/font&gt; message, &lt;font color="#0000ff"&gt;string&lt;/font&gt; userName, &lt;font color="#0000ff"&gt;string&lt;/font&gt; targetName, &lt;font color="#008080"&gt;PSCredentialTypes&lt;/font&gt; allowedCredentialTypes, &lt;font color="#008080"&gt;PSCredentialUIOptions&lt;/font&gt; options) &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;throw new&lt;/font&gt; &lt;font color="#008080"&gt;NotImplementedException&lt;/font&gt;(); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public override&lt;/font&gt; &lt;font color="#008080"&gt;PSCredential&lt;/font&gt; PromptForCredential(&lt;font color="#0000ff"&gt;string&lt;/font&gt; caption, &lt;font color="#0000ff"&gt;string&lt;/font&gt; message, &lt;font color="#0000ff"&gt;string&lt;/font&gt; userName, &lt;font color="#0000ff"&gt;string&lt;/font&gt; targetName) &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;throw new&lt;/font&gt; &lt;font color="#008080"&gt;NotImplementedException&lt;/font&gt;(); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public override&lt;/font&gt; &lt;font color="#008080"&gt;PSHostRawUserInterface&lt;/font&gt; RawUI &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;get&lt;/font&gt; { &lt;font color="#0000ff"&gt;return null&lt;/font&gt;; } &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public override string&lt;/font&gt; ReadLine() &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;throw new&lt;/font&gt; &lt;font color="#008080"&gt;NotImplementedException&lt;/font&gt;(); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public override &lt;/font&gt;System.Security.&lt;font color="#008080"&gt;SecureString &lt;/font&gt;ReadLineAsSecureString() &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;throw new&lt;/font&gt; &lt;font color="#008080"&gt;NotImplementedException&lt;/font&gt;(); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;br /&gt;}&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;The core of our implementation lies in the fact that all Write* methods emit their data to a StringBuilder instance that aggregates all output sent to the host. This is the data that gets retrieved by our &lt;strong&gt;InvokePS &lt;/strong&gt;method on the last line:&lt;/p&gt;
&lt;blockquote&gt;&lt;font color="#0000ff"&gt;return&lt;/font&gt; ((&lt;font color="#008080"&gt;RubyPSHostUserInterface&lt;/font&gt;)host.UI).&lt;strong&gt;Output&lt;/strong&gt;; &lt;br /&gt;&lt;/blockquote&gt;
&lt;p&gt;Notice this isn&amp;#39;t the absolute end of host-level extensibility in PowerShell. A PSHostUserInterface class can point at a PSHost&lt;strong&gt;Raw&lt;/strong&gt;UserInterface object that controls host window characteristics (such as the size, position and title of the window). Actually it would be interesting to implement this one as well in order to provide an accurate BufferSize that will be used by PowerShell to control the maximum length of individual lines before wrapping to the next line. The reason this would be a good idea is that screen-scraping Ruby programs should be able to ignore different wrapping behavior depending on the hosting command window (which would cause programs to behave differently depending where they run). Ideally there would be no wrapping at all (letting the DLR IronRuby command-line host dealing with wrapping when printing data to the screen). I&amp;#39;ll leave this exercise to the reader.&lt;/p&gt;
&lt;h2&gt;Hooking it up&lt;/h2&gt;
&lt;p&gt;All of the above has been implemented in a separate &lt;u&gt;strong-named&lt;/u&gt; Class Library which I&amp;#39;m just referencing in the IronRuby.Libraries project. This is actually very &lt;u&gt;quick-and-dirty&lt;/u&gt;, making IronRuby directly dependent on our assembly and by extension Windows PowerShell. A way around this would be to load the assembly dynamically possibly based on an environment variable. There are lots of possibilities here which we consider just an implementation detail for now. The only thing left to do is to call our InvokePS method which requires some conversions between System.String and MutableString:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;[&lt;font color="#008080"&gt;RubyMethod&lt;/font&gt;(&lt;font color="#800000"&gt;&amp;quot;`&amp;quot;&lt;/font&gt;, &lt;font color="#008080"&gt;RubyMethodAttributes&lt;/font&gt;.PrivateInstance)] &lt;br /&gt;[&lt;font color="#008080"&gt;RubyMethod&lt;/font&gt;(&lt;font color="#800000"&gt;&amp;quot;`&amp;quot;&lt;/font&gt;, &lt;font color="#008080"&gt;RubyMethodAttributes&lt;/font&gt;.PublicSingleton)] &lt;br /&gt;&lt;font color="#0000ff"&gt;public static &lt;/font&gt;&lt;font color="#008080"&gt;MutableString &lt;/font&gt;ExecuteCommand(&lt;font color="#008080"&gt;CodeContext&lt;/font&gt;&lt;font color="#008000"&gt;/*!*/ &lt;/font&gt;context, &lt;font color="#0000ff"&gt;object &lt;/font&gt;self, [&lt;font color="#008080"&gt;NotNull&lt;/font&gt;]&lt;font color="#008080"&gt;MutableString&lt;/font&gt;&lt;font color="#008000"&gt;/*!*/&lt;/font&gt; command) {&amp;nbsp; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;return &lt;/font&gt;&lt;font color="#008080"&gt;MutableString&lt;/font&gt;.Create(&lt;font color="#008080"&gt;RubyToPS&lt;/font&gt;.InvokePS(command.ConvertToString())); &lt;br /&gt;}&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;That&amp;#39;s it! Here&amp;#39;s the result:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/WindowsPowerShellthroughIronRuby_12D6E/image_3.png"&gt;&lt;img style="BORDER-TOP-WIDTH:0px;BORDER-LEFT-WIDTH:0px;BORDER-BOTTOM-WIDTH:0px;BORDER-RIGHT-WIDTH:0px;" height="328" alt="image" src="http://bartdesmet.info/images_wlw/WindowsPowerShellthroughIronRuby_12D6E/image_thumb_4.png" width="701" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;&lt;u&gt;Note: &lt;/u&gt;The \r\n insertions in the output for display by Ruby&amp;#39;s console cause things to wrap a bit nasty given the default of 80 characters buffer width. I&amp;#39;ve adjusted to 83 characters to make this render correctly. With some smart &amp;quot;Raw UI host&amp;quot; one could eliminate some issues here - however the internal contents of the string is more important since the app will likely rely on that (otherwise you&amp;#39;d simply run a PowerShell interactive shell, wouldn&amp;#39;t you?). Just as one sample, here&amp;#39;s the output of the each_line iterator:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/WindowsPowerShellthroughIronRuby_12D6E/image_4.png"&gt;&lt;img style="BORDER-TOP-WIDTH:0px;BORDER-LEFT-WIDTH:0px;BORDER-BOTTOM-WIDTH:0px;BORDER-RIGHT-WIDTH:0px;" height="256" alt="image" src="http://bartdesmet.info/images_wlw/WindowsPowerShellthroughIronRuby_12D6E/image_thumb_5.png" width="701" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;Does look an awful lot like PowerShell, doesn&amp;#39;t it?&lt;/p&gt;
&lt;p&gt;Cheers!&lt;/p&gt;&lt;img src="http://community.bartdesmet.net/aggbug.aspx?PostID=13745" width="1" height="1"&gt;</description><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/Windows+PowerShell/default.aspx">Windows PowerShell</category><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/IronRuby/default.aspx">IronRuby</category></item><item><title>1.To(3) - Ruby-style Internal Iterators in C#</title><link>http://community.bartdesmet.net/blogs/bart/archive/2008/07/05/1-to-3-ruby-style-internal-iterators-in-c.aspx</link><pubDate>Sat, 05 Jul 2008 08:35:44 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:13740</guid><dc:creator>bart</dc:creator><slash:comments>4</slash:comments><description>&lt;h1&gt;External or internal?&lt;/h1&gt;  &lt;p&gt;C# introduced the concept of iterators in C# 2.0 but it&amp;#39;s a less-known fact that there are two sorts of iterators. The ones provided in C# are so-called &lt;strong&gt;external iterators&lt;/strong&gt;. The distinction lies in the party that controls the enumeration of the iteration, e.g.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;public&lt;/font&gt; &lt;font color="#008080"&gt;IEnumerator&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&amp;gt; FromTo(&lt;font color="#0000ff"&gt;int &lt;/font&gt;from, &lt;font color="#0000ff"&gt;int &lt;/font&gt;to)      &lt;br /&gt;{      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;for &lt;/font&gt;(&lt;font color="#0000ff"&gt;int &lt;/font&gt;i = from; i &amp;lt;= to; i++)      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;yield return &lt;/font&gt;i;      &lt;br /&gt;}&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;does by itself not perform any iteration; it&amp;#39;s only when the consumer starts to suck data out of the enumerator object (typically using a foreach loop) that the data is fetched:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;foreach &lt;/font&gt;(&lt;font color="#0000ff"&gt;int &lt;/font&gt;i &lt;font color="#0000ff"&gt;in &lt;/font&gt;FromTo(1, 3))      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(i);&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;In other words, the object returned by FromTo (which is a little state machine implementing IEnumerator&amp;lt;T&amp;gt; or IEnumerable&amp;lt;T&amp;gt;) just captures the capability of iterating over the produced results in an on-request basis. Notice using C# 3.0 syntax, we can make the use of it &amp;#39;different&amp;#39;, obtaining a more Ruby-like style:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;public static&lt;/font&gt;&amp;#160;&lt;font color="#008080"&gt;IEnumerator&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&amp;gt; To(&lt;font color="#0000ff"&gt;this int &lt;/font&gt;from, &lt;font color="#0000ff"&gt;int &lt;/font&gt;to)      &lt;br /&gt;{      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;for &lt;/font&gt;(&lt;font color="#0000ff"&gt;int &lt;/font&gt;i = from; i &amp;lt;= to; i++)      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;yield return &lt;/font&gt;i;      &lt;br /&gt;}&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;using an extension method so it can be called like this:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;foreach &lt;/font&gt;(&lt;font color="#0000ff"&gt;int &lt;/font&gt;i &lt;font color="#0000ff"&gt;in &lt;/font&gt;1.To(3))      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(i);&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Still no different than what we started with but as you can guess: besides external iterators we have &lt;strong&gt;internal iterators&lt;/strong&gt;. Internal iterators perform the iteration themselves (they push the generated values into the code body associated with them) and are therefore very similar to built-in loop control structures in the language. A possible implementation looks like this:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;public static&lt;/font&gt;&amp;#160;&lt;font color="#008080"&gt;IEnumerator&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&amp;gt; To(&lt;font color="#0000ff"&gt;this int &lt;/font&gt;from, &lt;font color="#0000ff"&gt;int &lt;/font&gt;to, &lt;font color="#008080"&gt;Action&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&amp;gt; a)      &lt;br /&gt;{      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;for &lt;/font&gt;(&lt;font color="#0000ff"&gt;int &lt;/font&gt;i = from; i &amp;lt;= to; i++)      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; a(i);      &lt;br /&gt;}&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;which can be called like this:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;1.To(3, i =&amp;gt; { &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(i); });&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;using a C# 3.0 lambda expression. Notice there is no blue (syntax coloring) left, we have defined our own control structure. Nothing fancy but one thing we&amp;#39;ve actually given up here is our ability to define an object that captures the &amp;quot;iterator&amp;#39;s potential&amp;quot; to iterate from 1 to 3 and that can be invoked multiple times. (Whether or not this is a cosmetic detail is left for judgement by the reader.) In other words, we&amp;#39;d like to be able to define a control structure like this:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;myLoop = 1.To(3);      &lt;br /&gt;myLoop(i =&amp;gt; { &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(i); });      &lt;br /&gt;myLoop(i =&amp;gt; { &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(i + &lt;font color="#800000"&gt;&amp;quot; again!&amp;quot;&lt;/font&gt;); });&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;What we&amp;#39;re doing here is making use of &lt;em&gt;partial function application&lt;/em&gt;. It looks like we&amp;#39;re calling the To method with just one parameter, allowing the other parameters to be filled in later, realizing higher-order functions. I deliberately obfuscated the type of 1.To(3) in the fragment above to elaborate on it a bit more now. What does the type of 1.To(3) need to look like? Well, we should be able to &lt;em&gt;call it&lt;/em&gt; with one parameter of type Action&amp;lt;int&amp;gt;. The result of &lt;em&gt;calling through&lt;/em&gt; the 1.To(3) object is purely side-effect based, i.e. the call doesn&amp;#39;t return anything by itself, so the return type of the type we&amp;#39;re looking for is &lt;em&gt;void&lt;/em&gt;. To wrap up, a &lt;em&gt;void&lt;/em&gt;-returning&lt;em&gt; callable&lt;/em&gt; thing is nothing less than an Action&amp;lt;T&amp;gt; where T is our parameter, an Action&amp;lt;int&amp;gt;, so the resulting type is Action&amp;lt;Action&amp;lt;int&amp;gt;&amp;gt;. This level of &amp;quot;action-indirection&amp;quot; signifies the possible delayed characteristic of the iterator invocation. The reason the delayed execution is optional is obvious since one can call it like this:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;1.To(3)(i =&amp;gt; { &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(i); });&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;In Ruby one would write:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;1.upto(3) { |i| &lt;font color="#0000ff"&gt;print &lt;/font&gt;i }&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Implementing internal iterators&lt;/h1&gt;  &lt;p&gt;So how to implement this? Not that difficult at all:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;public static &lt;/font&gt;&lt;font color="#008080"&gt;Action&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Action&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&amp;gt;&amp;gt; To(&lt;font color="#0000ff"&gt;this int &lt;/font&gt;from, &lt;font color="#0000ff"&gt;int &lt;/font&gt;to)      &lt;br /&gt;{      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return &lt;/font&gt;a =&amp;gt; { &lt;font color="#0000ff"&gt;for &lt;/font&gt;(&lt;font color="#0000ff"&gt;int &lt;/font&gt;i = from; i &amp;lt;= to; i++) a(i); };      &lt;br /&gt;}&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Notice how the iteration moved inside the &amp;quot;iterator&amp;quot;, how it&amp;#39;s indirected through one level of lambda-abstraction and now yield keywords have been used (making it no longer an iterator in C# lingo). In fact, there&amp;#39;s lots of magic going on in this fragment. First of all, the type inference carried out by the compiler. Since the signature of the To method indicates we&amp;#39;re returning an Action&amp;lt;Action&amp;lt;int&amp;gt;&amp;gt; - which is fancy speak for &lt;em&gt;delegate void _(delegate void_(int))&lt;/em&gt; - the compiler can infer that the lambda&amp;#39;s parameter a has type Action&amp;lt;int&amp;gt;:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;return &lt;/font&gt;(&lt;strong&gt;&lt;font color="#008080"&gt;Action&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&amp;gt;&lt;/strong&gt; a) =&amp;gt; { &lt;font color="#0000ff"&gt;for &lt;/font&gt;(&lt;font color="#0000ff"&gt;int &lt;/font&gt;i = from; i &amp;lt;= to; i++) a(i); };&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Furthermore, lambda&amp;#39;s are pure syntactical sugar for anonymous methods (at least in this case where no expression trees are involved):&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;return delegate &lt;/font&gt;(&lt;strong&gt;&lt;font color="#008080"&gt;Action&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&amp;gt;&lt;/strong&gt; a) { &lt;font color="#0000ff"&gt;for &lt;/font&gt;(&lt;font color="#0000ff"&gt;int &lt;/font&gt;i = from; i &amp;lt;= to; i++) a(i); };&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The end result with sample looks like this:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/1.To3RubystyleInternalIteratorsinC_CBC/image.png"&gt;&lt;img style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="346" alt="image" src="http://bartdesmet.info/images_wlw/1.To3RubystyleInternalIteratorsinC_CBC/image_thumb.png" width="700" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;We could stop here but if you&amp;#39;re curious for the technical details that make this work, read on.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Behind the compiler curtains&lt;/h1&gt;  &lt;p&gt;The real question though is what gets returned. This is where closures kick in:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/1.To3RubystyleInternalIteratorsinC_CBC/image_3.png"&gt;&lt;img style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="498" alt="image" src="http://bartdesmet.info/images_wlw/1.To3RubystyleInternalIteratorsinC_CBC/image_thumb_3.png" width="1074" border="0" /&gt;&lt;/a&gt;&amp;#160;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The &amp;lt;&amp;gt;c__DisplayClass1 captures the from and to arguments to the iterator &amp;quot;constructor&amp;quot; call (since that&amp;#39;s ultimately what our To call does) and has a method called &amp;lt;To&amp;gt;b__0 that contains our iteration logic:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/1.To3RubystyleInternalIteratorsinC_CBC/image_4.png"&gt;&lt;img style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="560" alt="image" src="http://bartdesmet.info/images_wlw/1.To3RubystyleInternalIteratorsinC_CBC/image_thumb_4.png" width="864" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Notice the call through the supplied Action&amp;lt;int&amp;gt; delegate on line IL_000c. An obvious question is whether or not a closure in this case is useful. What we&amp;#39;re capturing here are the parameters from and to that are supplied to the To method (that lot&amp;#39;s of to&amp;#39;s too...). Since closures in C# capture lvals (mimicking copy by ref semantics) there&amp;#39;s a code-window where the variables can change and where that change is propagated into the closure. Assume our To-implementation would look like this:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;public static &lt;/font&gt;&lt;font color="#008080"&gt;Action&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Action&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&amp;gt;&amp;gt; To(&lt;font color="#0000ff"&gt;this int &lt;/font&gt;from, &lt;font color="#0000ff"&gt;int &lt;/font&gt;to)      &lt;br /&gt;{      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;&lt;font color="#008080"&gt;Action&lt;/font&gt;&lt;font color="#000000"&gt;&amp;lt;&lt;/font&gt;&lt;font color="#008080"&gt;Action&lt;/font&gt;&lt;font color="#000000"&gt;&amp;lt;&lt;/font&gt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&lt;/font&gt;&lt;font color="#000000"&gt;&amp;gt;&amp;gt; res = &lt;/font&gt;a =&amp;gt; { &lt;font color="#0000ff"&gt;for &lt;/font&gt;(&lt;font color="#0000ff"&gt;int &lt;/font&gt;i = from; i &amp;lt;= to; i++) a(i); };      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; from++; to--;      &lt;br /&gt;&lt;font color="#0000ff"&gt;&amp;#160;&amp;#160;&amp;#160; return &lt;/font&gt;res;      &lt;br /&gt;}&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;when calling To(1,3)(i =&amp;gt; { &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(i); }); you&amp;#39;d now see only 2 getting printed on the screen. Why? The locals from and to are getting captured by the closure (also known as captured outer variables, see C# specification &amp;#167;14.5.15.3.1), so wherever one refers to &lt;em&gt;from &lt;/em&gt;and &lt;em&gt;to &lt;/em&gt;in the local scope the captured variables are getting referenced instead. So by the time a call is made &lt;em&gt;through&lt;/em&gt; To(1,3) the captured values have both changed to 2 (from++, to--). However, this closure doesn&amp;#39;t propagate outside the scope of the To method, in other words - and again assuming the original implementation of To - you won&amp;#39;t see the effects of it when writing code like this:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;int &lt;/font&gt;f = 1;      &lt;br /&gt;&lt;font color="#0000ff"&gt;int &lt;/font&gt;t = 3;      &lt;br /&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;loop = f.To(t);      &lt;br /&gt;f++;      &lt;br /&gt;t--;      &lt;br /&gt;loop(i =&amp;gt; { &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(i); });      &lt;br /&gt;loop(i =&amp;gt; { &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(i + &lt;font color="#800000"&gt;&amp;quot; again!&amp;quot;&lt;/font&gt;); });&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;This will still print all 6 expected lines. Let&amp;#39;s eliminate our To method for a moment and try to write everything compacted in one place, like this:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;, &lt;font color="#0000ff"&gt;int&lt;/font&gt;, &lt;font color="#008080"&gt;Action&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Action&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&amp;gt;&amp;gt;&amp;gt; To = (from, to) =&amp;gt; a =&amp;gt; { &lt;font color="#0000ff"&gt;for &lt;/font&gt;(&lt;font color="#0000ff"&gt;int &lt;/font&gt;i = from; i &amp;lt;= to; i++) a(i); };      &lt;br /&gt;To(1, 3)(i =&amp;gt; { &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(i); });      &lt;br /&gt;To(1, 3)(i =&amp;gt; { &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(i + &lt;font color="#800000"&gt;&amp;quot; again!&amp;quot;&lt;/font&gt;); });&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Again 6 lines will be printed to the screen. Notice how the (inline) To &amp;quot;method&amp;quot; above has the same signature as our previous extension method To: we take in two ints and return an Action&amp;lt;Action&amp;lt;int&amp;gt;&amp;gt;. Also notice how lambda arrows are right associative, you should read it as:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;(from, to) =&amp;gt; &lt;strong&gt;(&lt;/strong&gt;a =&amp;gt; { &lt;font color="#0000ff"&gt;for &lt;/font&gt;(&lt;font color="#0000ff"&gt;int &lt;/font&gt;i = from; i &amp;lt;= to; i++) a(i); }&lt;strong&gt;)&lt;/strong&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;What now with closures? Actually, nothing changes. I did say closures capture the outer scope; however, from and to used in the body of the inner lambda refer to the locals from and to defined in the outer lambda, so when calling To(f, t) below:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;int &lt;/font&gt;f = 1;      &lt;br /&gt;&lt;font color="#0000ff"&gt;int &lt;/font&gt;t = 3;      &lt;br /&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;loop = To(f, t);      &lt;br /&gt;f++;      &lt;br /&gt;t--;      &lt;br /&gt;loop(i =&amp;gt; { &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(i); });      &lt;br /&gt;loop(i =&amp;gt; { &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(i + &lt;font color="#800000"&gt;&amp;quot; again!&amp;quot;&lt;/font&gt;); });&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;the values f and t are copied into the anonymous method of the outer lambda; where they get captured in a closure used in the inner lambda&amp;#39;s body. When you&amp;#39;d loosen the abstraction of the To method like this:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;int&lt;/font&gt; from = 1;      &lt;br /&gt;&lt;font color="#0000ff"&gt;int &lt;/font&gt;to = 3; &lt;/p&gt;    &lt;p&gt;&lt;font color="#008080"&gt;Action&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Action&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&amp;gt;&amp;gt; To = a =&amp;gt; { &lt;font color="#0000ff"&gt;for &lt;/font&gt;(&lt;font color="#0000ff"&gt;int &lt;/font&gt;i = from; i &amp;lt;= to; i++) a(i); }; &lt;/p&gt;    &lt;p&gt;from++;     &lt;br /&gt;to--; &lt;/p&gt;    &lt;p&gt;To(i =&amp;gt; { &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(i); });      &lt;br /&gt;To(i =&amp;gt; { &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(i + &lt;font color="#800000"&gt;&amp;quot; again!&amp;quot;&lt;/font&gt;); });&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;there&amp;#39;s just one lambda left for which the outer scope is the directly surrounding method, so from and to are captured by a closure and changing them will affect the operation of To.&lt;/p&gt;  &lt;p&gt;The closure inside the To method doesn&amp;#39;t really gain us anything. Obviously the question is which behavior one wants to realize: one where the loop&amp;#39;s boundaries can be changed afterwards (much like closures would allow us to do) or one where the loop object is immutable. To realize the former - if you&amp;#39;d really insist - some creativity is required. 1.To(3) could return an object with properties From and To while also exposing a method called Invoke to invoke the loop with the specified Action&amp;lt;int&amp;gt;. An object with an Invoke method looks pretty much like a delegate, so geeks could hack up IL to create a delegate with From and To properties. Not worth the effort IMO (apart from being a very interesting experiment), immutability is great and this definitely applies to this particular case. However (:-)) if you still insist, there&amp;#39;s another escape valve: perform one level of indirection to the arguments to the iterator itself:&lt;/p&gt;  &lt;blockquote&gt;&lt;font color="#0000ff"&gt;public static &lt;/font&gt;&lt;font color="#008080"&gt;Action&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Action&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&amp;gt;&amp;gt; To(&lt;font color="#0000ff"&gt;this &lt;/font&gt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&amp;gt; from, &lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&amp;gt; to)    &lt;br /&gt;{    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return &lt;/font&gt;a =&amp;gt; { &lt;font color="#0000ff"&gt;for &lt;/font&gt;(&lt;font color="#0000ff"&gt;int &lt;/font&gt;i = from&lt;strong&gt;()&lt;/strong&gt;; i &amp;lt;= to&lt;strong&gt;()&lt;/strong&gt;; i++) a(i); };    &lt;br /&gt;}&lt;/blockquote&gt;  &lt;p&gt;Notice the orthogonal structure between functions/classes (code versus data) and lifted functions/pointers (=&amp;gt; versus * and - the reverse - () versus *). Calling it doesn&amp;#39;t look pretty anymore though (partially because the left-hand side used in an extension method doesn&amp;#39;t work with a lambda expression since a lambda has no type by itself, it could either be a Func&amp;lt;...&amp;gt; or an Expression&amp;lt;Func&amp;lt;...&amp;gt;&amp;gt; depending on its - in this case non-existent - assignment):&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;int &lt;/font&gt;b = 3;      &lt;br /&gt;&lt;font color="#0000ff"&gt;var&lt;/font&gt; loop = &lt;strong&gt;(&lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&amp;gt;(() =&amp;gt; &lt;/strong&gt;1&lt;strong&gt;))&lt;/strong&gt;.To(&lt;strong&gt;() =&amp;gt; &lt;/strong&gt;b);      &lt;br /&gt;b = 2;      &lt;br /&gt;loop(i =&amp;gt; { &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(i); });      &lt;br /&gt;loop(i =&amp;gt; { &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(i + &lt;font color="#800000"&gt;&amp;quot; again!&amp;quot;&lt;/font&gt;); });&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;but here b is caught by a closure, so changing it after obtaining the loop variable will change it&amp;#39;s semantics. Brrrr...&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;A dynamic approach&lt;/h1&gt;  &lt;p&gt;Sticking with immutable internal iterators, we could eliminate the closure and produce the delegate at runtime using Reflection.Emit. This would look as follows:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;public static &lt;/font&gt;&lt;font color="#008080"&gt;Action&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Action&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&amp;gt;&amp;gt; To(&lt;font color="#0000ff"&gt;this int &lt;/font&gt;from, &lt;font color="#0000ff"&gt;int &lt;/font&gt;to)        &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;DynamicMethod&lt;/font&gt; m = &lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;DynamicMethod&lt;/font&gt;(&lt;font color="#800000"&gt;&amp;quot;&amp;quot;&lt;/font&gt;, &lt;font color="#0000ff"&gt;null&lt;/font&gt;, &lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;Type&lt;/font&gt;[] { &lt;font color="#0000ff"&gt;typeof&lt;/font&gt;(&lt;font color="#008080"&gt;Action&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&amp;gt;) });        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;ILGenerator &lt;/font&gt;ilgen = m.GetILGenerator(); &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;Label &lt;/font&gt;loop = ilgen.DefineLabel();        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;Label &lt;/font&gt;ret&amp;#160; = ilgen.DefineLabel(); &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;/font&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;//         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // for (int i = from; i &amp;lt;= to; i++) { a(i); } return;          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; ^^^^^^^^^^^^          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;var&lt;/font&gt; var_i = ilgen.DeclareLocal(&lt;font color="#0000ff"&gt;typeof&lt;/font&gt;(&lt;font color="#0000ff"&gt;int&lt;/font&gt;));        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ilgen.Emit(&lt;font color="#008080"&gt;OpCodes&lt;/font&gt;.Ldc_I4, from);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ilgen.Emit(&lt;font color="#008080"&gt;OpCodes&lt;/font&gt;.Stloc, var_i); &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; //         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // for (int i = from; i &amp;lt;= to; i++) { a(i); } return;          &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; ^^          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;var&lt;/font&gt; var_to = ilgen.DeclareLocal(&lt;font color="#0000ff"&gt;typeof&lt;/font&gt;(&lt;font color="#0000ff"&gt;int&lt;/font&gt;));        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ilgen.Emit(&lt;font color="#008080"&gt;OpCodes&lt;/font&gt;.Ldc_I4, to);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ilgen.Emit(&lt;font color="#008080"&gt;OpCodes&lt;/font&gt;.Stloc, var_to);        &lt;br /&gt;        &lt;br /&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; //         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // for (int i = from; i &amp;lt;= to; i++) { a(i); } return;          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // ^^^^          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160; ilgen.MarkLabel(loop); &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; //         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // for (int i = from; i &amp;lt;= to; i++) { a(i); } return;          &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; ^^^^^^^          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160; ilgen.Emit(&lt;font color="#008080"&gt;OpCodes&lt;/font&gt;.Ldloc, var_i);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ilgen.Emit(&lt;font color="#008080"&gt;OpCodes&lt;/font&gt;.Ldloc, var_to);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ilgen.Emit(&lt;font color="#008080"&gt;OpCodes&lt;/font&gt;.Cgt);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ilgen.Emit(&lt;font color="#008080"&gt;OpCodes&lt;/font&gt;.Brtrue, ret); &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; //         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // for (int i = from; i &amp;lt;= to; i++) { a(i); } return;          &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; ^ ^^^^^          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160; ilgen.Emit(&lt;font color="#008080"&gt;OpCodes&lt;/font&gt;.Ldarg_0);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ilgen.Emit(&lt;font color="#008080"&gt;OpCodes&lt;/font&gt;.Ldloc, var_i);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ilgen.Emit(&lt;font color="#008080"&gt;OpCodes&lt;/font&gt;.Callvirt, &lt;font color="#0000ff"&gt;typeof&lt;/font&gt;(&lt;font color="#008080"&gt;Action&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&amp;gt;).GetMethod(&lt;font color="#800000"&gt;&amp;quot;Invoke&amp;quot;&lt;/font&gt;)); &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; //         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // for (int i = from; i &amp;lt;= to; i++) { a(i); } return;          &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; ^^^          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160; ilgen.Emit(&lt;font color="#008080"&gt;OpCodes&lt;/font&gt;.Ldloc, var_i);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ilgen.Emit(&lt;font color="#008080"&gt;OpCodes&lt;/font&gt;.Ldc_I4_1);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ilgen.Emit(&lt;font color="#008080"&gt;OpCodes&lt;/font&gt;.Add);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ilgen.Emit(&lt;font color="#008080"&gt;OpCodes&lt;/font&gt;.Stloc, var_i); &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; //         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // for (int i = from; i &amp;lt;= to; i++) { a(i); } return;          &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; ^          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160; ilgen.Emit(&lt;font color="#008080"&gt;OpCodes&lt;/font&gt;.Br, loop); &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; //         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // for (int i = from; i &amp;lt;= to; i++) { a(i); } return;          &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; ^^^^^^^          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160; ilgen.MarkLabel(ret);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ilgen.Emit(&lt;font color="#008080"&gt;OpCodes&lt;/font&gt;.Ret); &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return &lt;/font&gt;(&lt;font color="#008080"&gt;Action&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Action&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&amp;gt;&amp;gt;)m.CreateDelegate(&lt;font color="#0000ff"&gt;typeof&lt;/font&gt;(&lt;font color="#008080"&gt;Action&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Action&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&amp;gt;&amp;gt;));        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Performance-wise you&amp;#39;ll see that the latter obviously is slower (and actually on the functional level you don&amp;#39;t gain anything since the redundant closure is harmless as we have proven higher up - also concerning memory allocation we&amp;#39;re trading closure objects for DynamicMethod &lt;em&gt;and other&lt;/em&gt; Reflection.Emit object instances). It shows however how a 3rd party compiler (or interpreter) could emit IL code that realizes an internal iterator with very little code involved (only 17 IL instructions).&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Other iterators&lt;/h1&gt;  &lt;p&gt;Of course the &amp;quot;To&amp;quot; &lt;em&gt;operator iterator&lt;/em&gt; is just one of the many possibilities. Here&amp;#39;s just one of the many:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;public static &lt;/font&gt;&lt;font color="#008080"&gt;Action&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Action&lt;/font&gt;&amp;lt;T&amp;gt;&amp;gt; ForEach&amp;lt;T&amp;gt;(&lt;font color="#0000ff"&gt;this &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;T&amp;gt; source)      &lt;br /&gt;{      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return &lt;/font&gt;a =&amp;gt; { &lt;font color="#0000ff"&gt;foreach &lt;/font&gt;(T item &lt;font color="#0000ff"&gt;in &lt;/font&gt;source) a(item); };      &lt;br /&gt;}&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;where the indirection of actions is a little artificial, agreed:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;new int &lt;/font&gt;[] { 1, 2, 3 }.ForEach&lt;strong&gt;()&lt;/strong&gt;(i =&amp;gt; { &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(i); });&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;This is a place where extension properties would come in handy, or obviously we could just write the following instead:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;public static void &lt;/font&gt;ForEach&amp;lt;T&amp;gt;(&lt;font color="#0000ff"&gt;this &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;T&amp;gt; source, &lt;font color="#008080"&gt;Action&lt;/font&gt;&amp;lt;T&amp;gt; action)      &lt;br /&gt;{      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;foreach &lt;/font&gt;(T item &lt;font color="#0000ff"&gt;in &lt;/font&gt;source) action(item);      &lt;br /&gt;}&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Enjoy!&lt;/p&gt;&lt;img src="http://community.bartdesmet.net/aggbug.aspx?PostID=13740" width="1" height="1"&gt;</description><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/C_2300_+3.0/default.aspx">C# 3.0</category><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/Functional+programming/default.aspx">Functional programming</category></item><item><title>Parallel Extensions - Using Futures to Calculate Pi in Hexadecimal</title><link>http://community.bartdesmet.net/blogs/bart/archive/2008/07/03/parallel-extensions-using-futures-to-calculate-pi-in-hexadecimal.aspx</link><pubDate>Thu, 03 Jul 2008 18:25:25 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:13730</guid><dc:creator>bart</dc:creator><slash:comments>7</slash:comments><description>&lt;h1&gt;Introduction&lt;/h1&gt;  &lt;p&gt;Last month we released the June 08 CTP of the Parallel Extensions to the .NET Framework. For more information and to get the latest updates, see &lt;a href="http://msdn.microsoft.com/concurrency"&gt;http://msdn.microsoft.com/concurrency&lt;/a&gt; and the team blog at &lt;a href="http://blogs.msdn.com/pfxteam"&gt;http://blogs.msdn.com/pfxteam&lt;/a&gt;. In this post (of a longer series) I want to highlight one particular feature called &lt;strong&gt;futures&lt;/strong&gt;. But first, to get started: download the CTP, install it, open VS 2008 and create a new Console Application (I&amp;#39;ll be using C#) and add a reference to the System.Threading.dll assembly that gets installed by the Parallel Extensions:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/ParallelExtensionsUsingFuturestoCalculat_2AF4/image.png"&gt;&lt;img style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="406" alt="image" src="http://bartdesmet.info/images_wlw/ParallelExtensionsUsingFuturestoCalculat_2AF4/image_thumb.png" width="730" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;There&amp;#39;s a bunch of stuff in this CTP, as you can see from the Object Browser:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/ParallelExtensionsUsingFuturestoCalculat_2AF4/image_3.png"&gt;&lt;img style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="651" alt="image" src="http://bartdesmet.info/images_wlw/ParallelExtensionsUsingFuturestoCalculat_2AF4/image_thumb_3.png" width="251" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;I&amp;#39;ll be covering quite some of this in subsequent posts, but for now we simply stick with &lt;strong&gt;System.Threading.Tasks.Future&amp;lt;T&amp;gt;&lt;/strong&gt;. So, what&amp;#39;s a future? In short, a future is a task that&amp;#39;s supposed to produce a value some time in the &lt;em&gt;future&lt;/em&gt;. Question becomes: what&amp;#39;s a task? One can think of a task as a modern thread, maintained by a task manager which implements a (work-stealing) scheduler. Without going in details for now, it suffices to think of tasks as the parallel version of procedures while futures play the role of parallel equivalents to functions. Actually, a future is a task with just something more: a value.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;The Future&amp;lt;T&amp;gt; 101&lt;/h1&gt;  &lt;p&gt;Using a future is simple. To create one, use the Future.Create factory method:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/ParallelExtensionsUsingFuturestoCalculat_2AF4/image_4.png"&gt;&lt;img style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="68" alt="image" src="http://bartdesmet.info/images_wlw/ParallelExtensionsUsingFuturestoCalculat_2AF4/image_thumb_4.png" width="458" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;All you have to supply is a function that returns a value of type T. That function can take all the time it wants to calculate that particular value without blocking other &amp;quot;work&amp;quot; in the application. This obviously only holds till someone needs the value being produced by the future. Let&amp;#39;s make an easy sample:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/ParallelExtensionsUsingFuturestoCalculat_2AF4/image_5.png"&gt;&lt;img style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="206" alt="image" src="http://bartdesmet.info/images_wlw/ParallelExtensionsUsingFuturestoCalculat_2AF4/image_thumb_5.png" width="488" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Here we have a lottery mechanism that picks a ball with numbers from 1-42 which takes between 1 and 10 seconds to complete. To specify the future&amp;#39;s code, we&amp;#39;re using a C# 3.0 lambda expression although the 2.0 style &amp;quot;delegate&amp;quot; keyword would be appropriate here too. The important thing here is the fact the &amp;quot;Lottery in progress...&amp;quot; message will be shown while the future is calculating its value. In other words, the main thread isn&amp;#39;t blocked by the background calculation, till we call the Value property on the future which waits for the value to be calculated in order to obtain it. Obviously, a lottery would be more complicated since the system has to wait for more balls to get picked (let&amp;#39;s not discuss whether or not the numbers need to be unique; uniqueness gives some interesting concurrent collection access worries depending on how you implement it). A possible refinement is this:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/ParallelExtensionsUsingFuturestoCalculat_2AF4/image_6.png"&gt;&lt;img style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="324" alt="image" src="http://bartdesmet.info/images_wlw/ParallelExtensionsUsingFuturestoCalculat_2AF4/image_thumb_6.png" width="764" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Here we use 6 futures to represent the 6 balls in the lottery and we wait for all balls to get picked using the (new in the last CTP) &lt;strong&gt;WaitAll&lt;/strong&gt; method. I&amp;#39;ll leave it as an exercise to figure out what it would take to print the selection of balls to the screen immediately as soon as they arrive (tip: &lt;strong&gt;WaitAny&lt;/strong&gt; goes in the right direction but the array might not be appropriate).&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;An ancient passion: calculating PI&lt;/h1&gt;  &lt;p&gt;It has been done before but it&amp;#39;s still an attractive business for math freaks: calculating PI. There are lots of algorithms that do this based on the development of series (e.g. by rewriting PI in terms of arctan functions which can be represented using infinite McLaurin series). One more recent algorithm is the &lt;strong&gt;Bailey-Borwein-Plouffe&lt;/strong&gt; (shorthand BBP - &lt;a href="http://crd.lbl.gov/~dhbailey/dhbpapers/digits.pdf"&gt;On the Rapid Computation of Various Polylogarithmic Constants&lt;/a&gt;) algorithm which has some interesting characteristics:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;strong&gt;Non-decimal: &lt;/strong&gt;calculates PI in base 16 hexadecimal.&lt;/li&gt;    &lt;li&gt;&lt;strong&gt;Random access: &lt;/strong&gt;allows to calculate an individual digit without having to calculate the digits that precede it.&lt;/li&gt;    &lt;li&gt;&lt;strong&gt;Distribution friendly:&lt;/strong&gt; can be used to calculate portions of PI in parallel.&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;The formula looks like this and is based on infinite series:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/ParallelExtensionsUsingFuturestoCalculat_2AF4/image_7.png"&gt;&lt;img style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="58" alt="image" src="http://bartdesmet.info/images_wlw/ParallelExtensionsUsingFuturestoCalculat_2AF4/image_thumb_7.png" width="327" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The crux - due to Plouffe - is the 16^k in the denominator which is precisely what base 16 fractionals look like, e.g.:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/ParallelExtensionsUsingFuturestoCalculat_2AF4/image_8.png"&gt;&lt;img style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="42" alt="image" src="http://bartdesmet.info/images_wlw/ParallelExtensionsUsingFuturestoCalculat_2AF4/image_thumb_8.png" width="373" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;In other words, to calculate the digit at a given position it suffices to calculate the following:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/ParallelExtensionsUsingFuturestoCalculat_2AF4/image_9.png"&gt;&lt;img style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="60" alt="image" src="http://bartdesmet.info/images_wlw/ParallelExtensionsUsingFuturestoCalculat_2AF4/image_thumb_9.png" width="439" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;with the overbar notation standing for &amp;quot;fraction of&amp;quot;. Obviously the left-hand side stands for the digit at position &lt;em&gt;pos&lt;/em&gt; in the (hexadecimally represented) value of PI. The right-hand side is a simple rewrite of the original formula multiplied by 16^pos, allowing for the following refactoring:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/ParallelExtensionsUsingFuturestoCalculat_2AF4/image_10.png"&gt;&lt;img style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="28" alt="image" src="http://bartdesmet.info/images_wlw/ParallelExtensionsUsingFuturestoCalculat_2AF4/image_thumb_10.png" width="199" border="0" /&gt;&lt;/a&gt;&amp;#160;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;where&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/ParallelExtensionsUsingFuturestoCalculat_2AF4/image_11.png"&gt;&lt;img style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="54" alt="image" src="http://bartdesmet.info/images_wlw/ParallelExtensionsUsingFuturestoCalculat_2AF4/image_thumb_11.png" width="112" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;This allows for efficient implementation using some binary exponentiation techniques for the power evaluations and with some modulo calculus. I tried to document the code as much as possible to illustrate how it works:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#008000"&gt;&lt;font face="Courier New"&gt;/// &lt;/font&gt;&lt;font face="Courier New"&gt;&lt;font color="#808080"&gt;&amp;lt;summary&amp;gt;           &lt;br /&gt;&lt;/font&gt;/// Calculation of PI using the BBP (Bailey-Borwein-Plouffe) formula.          &lt;br /&gt;/// &lt;font color="#808080"&gt;&amp;lt;/summary&amp;gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;      &lt;br /&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;static class &lt;/font&gt;&lt;font color="#008080"&gt;Pi&lt;/font&gt;        &lt;br /&gt;{        &lt;br /&gt;&lt;/font&gt;&lt;font color="#008000"&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; /// &lt;font color="#808080"&gt;&amp;lt;summary&amp;gt;&lt;/font&gt;          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// Powers of two. Used in the binary exponentiation algorithm (Knuth Vol II - 4.6.3).          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// &lt;/font&gt;&lt;font face="Courier New" color="#808080"&gt;&amp;lt;/summary&amp;gt;         &lt;br /&gt;&lt;/font&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;static int&lt;/font&gt;[] s_powsOf2; &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; /// &lt;font color="#808080"&gt;&amp;lt;summary&amp;gt;&lt;/font&gt;          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// Hexadecimal characters.          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// &lt;font color="#808080"&gt;&amp;lt;/summary&amp;gt;&lt;/font&gt;          &lt;br /&gt;&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;static string &lt;/font&gt;HEX = &lt;font color="#800000"&gt;&amp;quot;0123456789ABCDEF&amp;quot;&lt;/font&gt;; &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; /// &lt;font color="#808080"&gt;&amp;lt;summary&amp;gt;&lt;/font&gt;          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// Static constructor.          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// &lt;font color="#808080"&gt;&amp;lt;/summary&amp;gt;&lt;/font&gt;          &lt;br /&gt;&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;static &lt;/font&gt;Pi()        &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; s_powsOf2 = &lt;font color="#0000ff"&gt;new int&lt;/font&gt;[25]; &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; //         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; // Set powers of two for use in binary exponentiation algorithm.          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; s_powsOf2[0] = 1;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;for &lt;/font&gt;(&lt;font color="#0000ff"&gt;int &lt;/font&gt;i = 1; i &amp;lt; s_powsOf2.Length; i++)        &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; s_powsOf2[i] = s_powsOf2[i - 1] * 2;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;        &lt;br /&gt;&amp;#160;&lt;/font&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160; /// &lt;font color="#808080"&gt;&amp;lt;summary&amp;gt;&lt;/font&gt;          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// Calculates a given number of hexadecimal digits of PI from the given start position.          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// &lt;font color="#808080"&gt;&amp;lt;/summary&amp;gt;&lt;/font&gt;          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// &lt;font color="#808080"&gt;&amp;lt;param name=&amp;quot;start&amp;quot;&amp;gt;&lt;/font&gt;Hexadecimal position to start calculating hexadecimal digits from.&lt;font color="#808080"&gt;&amp;lt;/param&amp;gt;&lt;/font&gt;          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// &lt;font color="#808080"&gt;&amp;lt;param name=&amp;quot;length&amp;quot;&amp;gt;&lt;/font&gt;Number of hexadecimal digits to calculate. Needs to be multiple of 10.&lt;font color="#808080"&gt;&amp;lt;/param&amp;gt;&lt;/font&gt;          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// &lt;font color="#808080"&gt;&amp;lt;returns&amp;gt;&lt;/font&gt;Requested hexadecimal digits of PI.&lt;font color="#808080"&gt;&amp;lt;/returns&amp;gt;&lt;/font&gt;          &lt;br /&gt;&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public static string &lt;/font&gt;Calculate(&lt;font color="#0000ff"&gt;int &lt;/font&gt;start, &lt;font color="#0000ff"&gt;int &lt;/font&gt;length)        &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; &lt;font color="#0000ff"&gt;if &lt;/font&gt;(start &amp;lt; 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; &lt;font color="#0000ff"&gt;throw new &lt;/font&gt;&lt;font color="#008080"&gt;ArgumentException&lt;/font&gt;(&lt;font color="#800000"&gt;&amp;quot;start&amp;quot;&lt;/font&gt;); &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;font color="#0000ff"&gt;if &lt;/font&gt;(length &amp;lt; 0 || length % 10 != 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; &lt;font color="#0000ff"&gt;throw new &lt;/font&gt;&lt;font color="#008080"&gt;ArgumentException&lt;/font&gt;(&lt;font color="#800000"&gt;&amp;quot;length&amp;quot;&lt;/font&gt;); &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;font color="#008080"&gt;StringBuilder &lt;/font&gt;sb = &lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;StringBuilder&lt;/font&gt;(); &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; //         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; // Calculate in chunks of 10 given our precision.          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;for &lt;/font&gt;(&lt;font color="#0000ff"&gt;int &lt;/font&gt;pos = start; pos &amp;lt; start + length; pos += 10)        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {        &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; &lt;font color="#0000ff"&gt;double &lt;/font&gt;val = 4 * Sum(1, pos) - 2 * Sum(4, pos) - Sum(5, pos) - Sum(6, pos);        &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; val = val - (&lt;font color="#0000ff"&gt;int&lt;/font&gt;)val + 1;        &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; sb.Append(ToHex(val));        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return &lt;/font&gt;sb.ToString();        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }&lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; /// &lt;font color="#808080"&gt;&amp;lt;summary&amp;gt;&lt;/font&gt;          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// This method calculates the fractional part of SUM[i = 0..+INF](1 / (16^i * (8 * i + j))).          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// &lt;font color="#808080"&gt;&amp;lt;/summary&amp;gt;&lt;/font&gt;          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// &lt;font color="#808080"&gt;&amp;lt;param name=&amp;quot;j&amp;quot;&amp;gt;&lt;/font&gt;See formula.&lt;font color="#808080"&gt;&amp;lt;/param&amp;gt;&lt;/font&gt;          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// &lt;font color="#808080"&gt;&amp;lt;param name=&amp;quot;pos&amp;quot;&amp;gt;&lt;/font&gt;Starting position for requested hexadecimal part of PI&amp;#39;s fraction.&lt;font color="#808080"&gt;&amp;lt;/param&amp;gt;&lt;/font&gt;          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// &lt;font color="#808080"&gt;&amp;lt;returns&amp;gt;&lt;/font&gt;See formula.&lt;font color="#808080"&gt;&amp;lt;/returns&amp;gt;&lt;/font&gt;          &lt;br /&gt;&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;static double &lt;/font&gt;Sum(&lt;font color="#0000ff"&gt;int &lt;/font&gt;j, &lt;font color="#0000ff"&gt;int &lt;/font&gt;pos)        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {        &lt;br /&gt;&lt;/font&gt;&lt;font face="Courier New" color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; /*       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; * Implementation based on the following observation:        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; *         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; *&amp;#160;&amp;#160; SUM[i = 0..+INF](1 / (16^i * (8 * i + j)))        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; *         &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;&amp;#160; SUM[k = 0..d]((16^(d - k) mod (8 * k + j)) / (8 * k + j)))        &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;&amp;#160; + SUM[k = d + 1..+INF](16^(d - k) / (8 * k + j)))        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;double &lt;/font&gt;res = 0.0; &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;font color="#0000ff"&gt;int &lt;/font&gt;k = 0; &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; //         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; // First part of the sum using binary exponentiation with modulo operation.          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;for &lt;/font&gt;(; k &amp;lt; pos; k++)        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {        &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; &lt;font color="#0000ff"&gt;double &lt;/font&gt;n = 8 * k + j;        &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; res += PowMod(16.0, pos - k, n) / n;        &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; res -= (int)res;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; } &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; //         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; // For the remainder terms, go till we reach the precision of 10^-17,          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; // which allows to reach the required precision in hexadecimals.          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;for &lt;/font&gt;(; ; k++)        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {        &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; &lt;font color="#0000ff"&gt;double &lt;/font&gt;t = &lt;font color="#008080"&gt;Math&lt;/font&gt;.Pow(16.0, pos - k) / (8 * k + j);        &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; &lt;font color="#0000ff"&gt;if &lt;/font&gt;(t &amp;lt; 1e-17)        &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; break;        &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; res += t;        &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; res -= (&lt;font color="#0000ff"&gt;int&lt;/font&gt;)res;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return &lt;/font&gt;res;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; } &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; /// &lt;font color="#808080"&gt;&amp;lt;summary&amp;gt;&lt;/font&gt;          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// Returns a specified number raised to the specified power, module the given modulus.          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// &lt;font color="#808080"&gt;&amp;lt;/summary&amp;gt;&lt;/font&gt;          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// &lt;font color="#808080"&gt;&amp;lt;param name=&amp;quot;x&amp;quot;&amp;gt;&lt;/font&gt;A double-precision floating-point number to be raised to a power.&lt;font color="#808080"&gt;&amp;lt;/param&amp;gt;&lt;/font&gt;          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// &lt;font color="#808080"&gt;&amp;lt;param name=&amp;quot;y&amp;quot;&amp;gt;&lt;/font&gt;A double-precision floating-point number that specifies a power.&lt;font color="#808080"&gt;&amp;lt;/param&amp;gt;&lt;/font&gt;          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// &lt;font color="#808080"&gt;&amp;lt;param name=&amp;quot;m&amp;quot;&amp;gt;&lt;/font&gt;A double-precision floating-point number that specified the modulus.&lt;font color="#808080"&gt;&amp;lt;/param&amp;gt;&lt;/font&gt;          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// &lt;font color="#808080"&gt;&amp;lt;returns&amp;gt;&lt;/font&gt;x^y mod m&lt;font color="#808080"&gt;&amp;lt;/returns&amp;gt;&lt;/font&gt;          &lt;br /&gt;&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;static double &lt;/font&gt;PowMod(&lt;font color="#0000ff"&gt;double &lt;/font&gt;x, &lt;font color="#0000ff"&gt;double &lt;/font&gt;y, &lt;font color="#0000ff"&gt;double &lt;/font&gt;m)        &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; &lt;font color="#0000ff"&gt;if &lt;/font&gt;(m == 1.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; &lt;font color="#0000ff"&gt;return &lt;/font&gt;0.0; &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; //         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; // We look for the largest bit position used by the exponent.          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; // E.g. 16^9 mod 9 = (16 * 16^(2^3)) mod 9          &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; ^          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;int &lt;/font&gt;i;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;for &lt;/font&gt;(i = 0; i &amp;lt; s_powsOf2.Length; i++)        &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; &lt;font color="#0000ff"&gt;if&lt;/font&gt; (s_powsOf2[i] &amp;gt; y)        &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;break&lt;/font&gt;; &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;font color="#0000ff"&gt;double &lt;/font&gt;pow2 = s_powsOf2[i - 1]; &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; //         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; // Set remaining number of exponentiations and result to initial values.          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;double &lt;/font&gt;rem = y;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;double &lt;/font&gt;res = 1.0; &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;font color="#0000ff"&gt;for &lt;/font&gt;(&lt;font color="#0000ff"&gt;int &lt;/font&gt;j = 0; j &amp;lt; i; j++)        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {        &lt;br /&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; //         &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; // &amp;quot;Remainder&amp;quot; steps that do not fit in binary exponentiation.          &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; //          &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; // j&amp;#160;&amp;#160; res&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; res&amp;#39;          &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; // --&amp;#160; --------------&amp;#160; ----          &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; // 0&amp;#160;&amp;#160; 16^0 mod 9 = 1&amp;#160; 16^1 mod 9 = (1 * 16) mod 9 = 7          &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; // 3&amp;#160;&amp;#160; 16^8 mod 9 = 4&amp;#160; 16^9 mod P = (4 * 16) mod 9 = 1          &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; //          &lt;br /&gt;&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;if &lt;/font&gt;(rem &amp;gt;= pow2)        &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; {        &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; res = (res * x) % m;        &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; rem -= pow2;        &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; } &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; pow2 /= 2; &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; //         &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; // Binary exponentation step.          &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; //           &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; // j&amp;#160;&amp;#160; res&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; res&amp;#39;          &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; // --&amp;#160; --------------&amp;#160; ------------------------------          &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; // 0&amp;#160;&amp;#160; 16^1 mod 9 = 7&amp;#160; 16^2 mod 9 = (7 * 7) mod 9 = 4          &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; // 1&amp;#160;&amp;#160; 16^2 mod 9 = 4&amp;#160; 16^4 mod 9 = (4 * 4) mod 9 = 7          &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; // 2&amp;#160;&amp;#160; 16^4 mod 9 = 7&amp;#160; 16^8 mod 9 = (7 * 7) mod 9 = 4          &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; //          &lt;br /&gt;&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;if &lt;/font&gt;(pow2 &amp;gt;= 1.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; {        &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; res = (res * res) % m;        &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; }        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return &lt;/font&gt;res;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; } &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font color="#008000"&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; /// &lt;font color="#808080"&gt;&amp;lt;summary&amp;gt;&lt;/font&gt;          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// Converts the fractional part of the specified double-precision floating-point number          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// to hexadecimal representation.          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// &lt;font color="#808080"&gt;&amp;lt;/summary&amp;gt;&lt;/font&gt;          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// &lt;font color="#808080"&gt;&amp;lt;param name=&amp;quot;d&amp;quot;&amp;gt;&lt;/font&gt;Double-precision floating-point number in base 10.&lt;font color="#808080"&gt;&amp;lt;/param&amp;gt;&lt;/font&gt;          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// &lt;font color="#808080"&gt;&amp;lt;returns&amp;gt;&lt;/font&gt;String representation of the number&amp;#39;s fractional part in base 16.&lt;/font&gt;&lt;font face="Courier New"&gt;&lt;font color="#808080"&gt;&amp;lt;/returns&amp;gt;           &lt;br /&gt;&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160; /// &lt;font color="#808080"&gt;&amp;lt;example&amp;gt;&lt;/font&gt;          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// Sample: d := 0.14159265358979334          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ///           &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ///&amp;#160;&amp;#160;&amp;#160; f := (d - (int)d )&amp;#160;&amp;#160; 16 * f&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Hex((int)(16 * f))          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ///&amp;#160;&amp;#160;&amp;#160; -------------------&amp;#160; -------------------&amp;#160; ------------------          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// 0. 0.14159265358979334&amp;#160;&amp;#160; 2.2654824574366934&amp;#160; 2          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// 1. 0.26548245743669340&amp;#160;&amp;#160; 4.2477193189870945&amp;#160; 4          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// 2. 0.24771931898709450&amp;#160;&amp;#160; 3.9635091037935126&amp;#160; 3          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// 3. 0.96350910379351260&amp;#160; 15.4161456606962020&amp;#160; F          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// 4. 0.41614566069620200&amp;#160;&amp;#160; 6.6583305711392313&amp;#160; 6          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// 5. 0.65833057113923130&amp;#160; 10.5332891382277010&amp;#160; A          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// 6. 0.53328913822770100&amp;#160;&amp;#160; 8.5326262116432190&amp;#160; 8          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// 7. 0.53262621164321900&amp;#160;&amp;#160; 8.5220193862915039&amp;#160; 8          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// 8. 0.52201938629150390&amp;#160;&amp;#160; 8.3523101806640625&amp;#160; 8          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// 9. 0.35231018066406250&amp;#160;&amp;#160; 5.6369628906250000&amp;#160; 5          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ///           &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// Reverse: h := 0.243F6A8885          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ///           &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ///&amp;#160;&amp;#160;&amp;#160; Weight&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Value          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ///&amp;#160;&amp;#160;&amp;#160; -----------&amp;#160; -----------&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// 0. 2 * 16^-1&amp;#160;&amp;#160;&amp;#160; 0.12500000000000000000          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// 1. 4 * 16^-2&amp;#160;&amp;#160;&amp;#160; 0.01562500000000000000          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// 2. 3 * 16^-3&amp;#160;&amp;#160;&amp;#160; 0.00073242187500000000          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// 3. F * 16^-4&amp;#160;&amp;#160;&amp;#160; 0.00022888183593750000          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// 4. 6 * 16^-5&amp;#160;&amp;#160;&amp;#160; 0.00000572204589843750          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// 5. A * 16^-6&amp;#160;&amp;#160;&amp;#160; 0.00000059604644775391          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// 6. 8 * 16^-7&amp;#160;&amp;#160;&amp;#160; 0.00000002980232238770          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// 7. 8 * 16^-8&amp;#160;&amp;#160;&amp;#160; 0.00000000186264514923          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// 8. 8 * 16^-9&amp;#160;&amp;#160;&amp;#160; 0.00000000011641532183          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// 9. 5 * 16^-10&amp;#160;&amp;#160; 0.00000000000454747351          &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; +----------------------          &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; 0.14159265358921400000          &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; ^^^^^^^^^^^^          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; /// &lt;font color="#808080"&gt;&amp;lt;/example&amp;gt;&lt;/font&gt;          &lt;br /&gt;&lt;/font&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;static string &lt;/font&gt;ToHex(&lt;font color="#0000ff"&gt;double &lt;/font&gt;d)        &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; &lt;font color="#0000ff"&gt;char&lt;/font&gt;[] c = &lt;font color="#0000ff"&gt;new char&lt;/font&gt;[10]; &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;font color="#0000ff"&gt;for &lt;/font&gt;(&lt;font color="#0000ff"&gt;int &lt;/font&gt;i = 0; i &amp;lt; c.Length; i++)        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {        &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; d = 16 * (d - (&lt;font color="#0000ff"&gt;int&lt;/font&gt;)d);        &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; c[i] = HEX[(&lt;font color="#0000ff"&gt;int&lt;/font&gt;)d];        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return new string&lt;/font&gt;(c);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; } &lt;/font&gt;&lt;font face="Courier New"&gt;       &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Putting futures to work&lt;/h1&gt;  &lt;p&gt;The actual implementation is actually of little interest in this context; using it with futures is more of interest now. Here&amp;#39;s a sample use of it:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/ParallelExtensionsUsingFuturestoCalculat_2AF4/image_12.png"&gt;&lt;img style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="344" alt="image" src="http://bartdesmet.info/images_wlw/ParallelExtensionsUsingFuturestoCalculat_2AF4/image_thumb_12.png" width="609" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;And here&amp;#39;s the result:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/ParallelExtensionsUsingFuturestoCalculat_2AF4/image_13.png"&gt;&lt;img style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="104" alt="image" src="http://bartdesmet.info/images_wlw/ParallelExtensionsUsingFuturestoCalculat_2AF4/image_thumb_13.png" width="323" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The parallel version only takes &lt;strong&gt;58%&lt;/strong&gt; of the original sequential execution! Before going any further, there&amp;#39;s a little interesting thing in the implementation above: some manual partitioning. The first future calculates from 0 to 7000 and the second one from 7000 to 10000. In general with work-stealing applied in the scheduler such partitioning can be eliminated as long as the individual work items that get executed by tasks or futures do not have a clear predictable relative execution duration. For this particular case however, we have intrinsic knowledge about the algorithm and the fact it actually scales linearly based on the position of the hexadecimal digits requested. In particular, if you&amp;#39;d plot the duration of calculations of chunks against the time it takes, you&amp;#39;d see something along those lines:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/ParallelExtensionsUsingFuturestoCalculat_2AF4/image_14.png"&gt;&lt;img style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="291" alt="image" src="http://bartdesmet.info/images_wlw/ParallelExtensionsUsingFuturestoCalculat_2AF4/image_thumb_14.png" width="483" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;To partition the total work correctly it suffices to solve one quadratic equation derived from an integration so that the yellow (0 to x) and blue (x to 10000) portions have the same surface:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/ParallelExtensionsUsingFuturestoCalculat_2AF4/image_15.png"&gt;&lt;img style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="291" alt="image" src="http://bartdesmet.info/images_wlw/ParallelExtensionsUsingFuturestoCalculat_2AF4/image_thumb_15.png" width="483" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;You&amp;#39;ll find x to be about 7000 in this case which indicates the optimum partitioning for calculation of digits 0 to 10000. If you&amp;#39;d partition around 5000, it&amp;#39;s clear that the second future would have a longer execution time than the first one as seen from the surface under the curve (line) in the graph above. Also, the fact we&amp;#39;re partitioning in two halves implies we&amp;#39;re not optimizing for anything beyond dual core (higher-order partitioning of the problem is less trivial but still possible). Also, with arbitrary inputs from the user we&amp;#39;d have to calculate the partitioning at runtime instead.&lt;/p&gt;  &lt;p&gt;So, how does execution look like?&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/ParallelExtensionsUsingFuturestoCalculat_2AF4/image_16.png"&gt;&lt;img style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="457" alt="image" src="http://bartdesmet.info/images_wlw/ParallelExtensionsUsingFuturestoCalculat_2AF4/image_thumb_16.png" width="412" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Clearly, in the sequential case (between the first two red lines) not all processors are busy but in the case with futures (between the last two red lines), both processors go up to 100% utilization and as one can observe, the algorithm runs faster. In terms of threads you&amp;#39;ll see this in the Performance Monitor:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/ParallelExtensionsUsingFuturestoCalculat_2AF4/image_17.png"&gt;&lt;img style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="484" alt="image" src="http://bartdesmet.info/images_wlw/ParallelExtensionsUsingFuturestoCalculat_2AF4/image_thumb_17.png" width="530" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;As soon as the parallel execution kicks in, three additional threads are created (of which two are doing work for our futures). In the curve above this is observed by the jump from 6 to 9 threads.&lt;/p&gt;&lt;img src="http://community.bartdesmet.net/aggbug.aspx?PostID=13730" width="1" height="1"&gt;</description><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/Parallel+Extensions/default.aspx">Parallel Extensions</category></item><item><title>A Lap Around Microsoft "Velocity" - Cache It NOW!</title><link>http://community.bartdesmet.net/blogs/bart/archive/2008/06/30/a-lap-around-microsoft-quot-velocity-quot-cache-it-now.aspx</link><pubDate>Mon, 30 Jun 2008 20:08:30 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:13720</guid><dc:creator>bart</dc:creator><slash:comments>9</slash:comments><description>&lt;p&gt;At the beginning of this month, we released the first CTP of Velocity, an early preview of our distributed object cache solution. You can &lt;a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=B24C3708-EEFF-4055-A867-19B5851E7CD2&amp;amp;displaylang=en"&gt;download it here&lt;/a&gt;. Notice it&amp;#39;s a &lt;strong&gt;very early preview&lt;/strong&gt; so things will definitely change moving forward. This post introduces how to install and use Velocity.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Introduction&lt;/h1&gt;  &lt;p&gt;But first... what&amp;#39;s in a name? Multi-tiered distributed applications are common-sense nowadays and with cloud computing within reach the need to build scalable distributed services has never been bigger. One of the core aspects in enabling those scenarios is to have intelligent caching of objects, not only to reduce the number of accesses to the underlying data source but also to boost availability by employing scale out techniques. Obviously, developers want to be able to do all of this without having to worry about the complexities that this brings, having to deal with load balancing and availability themselves. That&amp;#39;s where Velocity comes into play.&lt;/p&gt;  &lt;p&gt;The core idea is very straightforward: we have a &lt;em&gt;cache &lt;/em&gt;that behind the scenes is distributed and replicated across a bunch of machines called the &lt;em&gt;cluster&lt;/em&gt;. Storing data in the distributed cache is as easy as calling some &lt;em&gt;Add&lt;/em&gt; or &lt;em&gt;Put&lt;/em&gt; method, and retrieving it is as easy as calling &lt;em&gt;Get&lt;/em&gt;. With some creative stealing from the documentation we end up with the following picture:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/ALapAroundMicrosoftVelocityCacheItNOW_6AE/image.png"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="373" alt="image" src="http://bartdesmet.info/images_wlw/ALapAroundMicrosoftVelocityCacheItNOW_6AE/image_thumb_6.png" width="555" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;An important thing to emphasize is the fact the cache clients deal with regular .NET objects all the time and don&amp;#39;t have to worry about storing those objects. Indeed, .NET serialization takes care of the rest. There are more concepts to it such as &lt;em&gt;cache eviction policies &lt;/em&gt;(when objects are removed from the cache, such as least-recently used or LRU), the distribution mechanism where &lt;em&gt;simple clients&lt;/em&gt; just contact the cluster &amp;quot;in the cloud&amp;quot; through any cache host and get redirected to whatever host the object is available on versus &lt;em&gt;routing clients&lt;/em&gt; that have awareness of object placement through a &lt;em&gt;routing table&lt;/em&gt;. Other important pieces include the supported concurrency models and associated locking mechanisms but let&amp;#39;s not go there in this introductory post.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Installation&lt;/h1&gt;  &lt;p&gt;Installing Velocity is fairly straightforward. Just run the MSI. After a while you&amp;#39;ll see the following window:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/ALapAroundMicrosoftVelocityCacheItNOW_6AE/image_6.png"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="402" alt="image" src="http://bartdesmet.info/images_wlw/ALapAroundMicrosoftVelocityCacheItNOW_6AE/image_thumb_7.png" width="526" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;This is where you configure the &amp;quot;cache host&amp;quot;. Under Cluster Configuration Share you can enter the UNC path to the cluster&amp;#39;s configuration share. This is the place where an XML file is kept that makes sure that configuration settings are consistent across all hosts in the cluster. Create this folder and &lt;u&gt;grant the Everyone account full access to it&lt;/u&gt;; this is known issue in the CTP which by no means will become the final design. Also notice that currently in the first CTP this is a single point of failure: if the share goes down, the cluster can die. Obviously this will be addressed in subsequent releases. For now, we&amp;#39;ll just specify a local path and enter a new name under &amp;quot;Cluster Name&amp;quot;. The Cluster Size is self-explanatory and for the purpose of this introductory sample, we&amp;#39;ll stick with a one-host cluster (a degenerate case of a cluster if you will...).&lt;/p&gt;  &lt;p&gt;Next, two ports are being specified: the service port and the cluster port. The defaults are just fine here. Basically the service port number is what clients connect to in order to talk to the cache host. The cluster port on the other hand is used by the servers in the cluster to talk to one another (there&amp;#39;s another port, called the arbitration port which is listening on cluster+1, i.e. 22235 in the sample above).&lt;/p&gt;  &lt;p&gt;Last but not least, there&amp;#39;s the Max Server Memory setting which defaults to half of the available physical memory. I&amp;#39;ve reduced it to 256 MB since I&amp;#39;m using my main dev machine as my playground but obviously in production scenarios boxes will get dedicated to the distributed cache cluster, where it makes sense to boost this.&lt;/p&gt;  &lt;p&gt;After clicking Save &amp;amp; Close, setup will ask you to open the required ports on the firewall, which can be done easily by allowing the DistributedCache.exe program (that runs as a service) through the firewall.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/ALapAroundMicrosoftVelocityCacheItNOW_6AE/image_7.png"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="197" alt="image" src="http://bartdesmet.info/images_wlw/ALapAroundMicrosoftVelocityCacheItNOW_6AE/image_thumb_8.png" width="329" border="0" /&gt;&lt;/a&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;Doing so isn&amp;#39;t hard at all. Geeks can go the &lt;em&gt;netsh&lt;/em&gt; way as illustrated below. Alternatively one can use the Firewall Settings in the Control Panel (click to enlarge):&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/ALapAroundMicrosoftVelocityCacheItNOW_6AE/image_8.png"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="244" alt="image" src="http://bartdesmet.info/images_wlw/ALapAroundMicrosoftVelocityCacheItNOW_6AE/image_thumb_9.png" width="479" border="0" /&gt;&lt;/a&gt;&amp;#160;&lt;a href="http://bartdesmet.info/images_wlw/ALapAroundMicrosoftVelocityCacheItNOW_6AE/image_9.png"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="244" alt="image" src="http://bartdesmet.info/images_wlw/ALapAroundMicrosoftVelocityCacheItNOW_6AE/image_thumb_10.png" width="209" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;With this, setup has completed.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Configuration&lt;/h1&gt;  &lt;p&gt;Before we can start to use the service, we need to make a few changes to its configuration. Let&amp;#39;s take a look at the configuration share&amp;#39;s file structure first:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/ALapAroundMicrosoftVelocityCacheItNOW_6AE/image_10.png"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="309" alt="image" src="http://bartdesmet.info/images_wlw/ALapAroundMicrosoftVelocityCacheItNOW_6AE/image_thumb_11.png" width="710" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;The XML file contains the configuration that&amp;#39;s shared by all hosts in the cluster. In addition the ConfigStore file is a SQL CE 3.5 database that keeps additional information about partitions, nodes, regions, etc which you can find more information about in the CTP&amp;#39;s documentation. Notice that you won&amp;#39;t find the cached data here since we&amp;#39;re talking about an &lt;u&gt;in memory&lt;/u&gt; distributed cache. Geeks can investigate what goes inside this little database, but we&amp;#39;ll instead just focus on the XML file:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/ALapAroundMicrosoftVelocityCacheItNOW_6AE/image_11.png"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="570" alt="image" src="http://bartdesmet.info/images_wlw/ALapAroundMicrosoftVelocityCacheItNOW_6AE/image_thumb_12.png" width="677" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;In here you can find the list of hosts and caches that are part of the cluster. We&amp;#39;ll take a look again at this file in just a minute when we&amp;#39;ve altered the cluster configuration. In order to configure the service, Velocity comes with a command-line driven tool named originally the &amp;quot;Administration Tool&amp;quot; which you can find through the start menu (click to enlarge).&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/ALapAroundMicrosoftVelocityCacheItNOW_6AE/image_12.png"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="244" alt="image" src="http://bartdesmet.info/images_wlw/ALapAroundMicrosoftVelocityCacheItNOW_6AE/image_thumb_13.png" width="196" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;In the configuration steps below, we&amp;#39;re adding a cache to the cluster after investigating the hosts and caches that are part of the cluster. Once we&amp;#39;ve added the cache, the cluster is started which puts all the hosts online by starting their Windows Services.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/ALapAroundMicrosoftVelocityCacheItNOW_6AE/image_13.png"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="412" alt="image" src="http://bartdesmet.info/images_wlw/ALapAroundMicrosoftVelocityCacheItNOW_6AE/image_thumb_14.png" width="677" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;The service is called DistributedCacheService which is kept in the cacheHostName property in the XML file:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/ALapAroundMicrosoftVelocityCacheItNOW_6AE/image_14.png"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="268" alt="image" src="http://bartdesmet.info/images_wlw/ALapAroundMicrosoftVelocityCacheItNOW_6AE/image_thumb_15.png" width="640" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Taking a look back the XML file, you&amp;#39;ll notice a new cache configuration entry has been added:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/ALapAroundMicrosoftVelocityCacheItNOW_6AE/image_15.png"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="570" alt="image" src="http://bartdesmet.info/images_wlw/ALapAroundMicrosoftVelocityCacheItNOW_6AE/image_thumb_1