PageRenderTime 91ms CodeModel.GetById 7ms app.highlight 46ms RepoModel.GetById 1ms app.codeStats 2ms

/atom.xml

https://github.com/efvincent/efvincent.github.io
XML | 3407 lines | 2953 code | 441 blank | 13 comment | 0 complexity | c1da7adda36d3fc8816553280e9e26fc MD5 | raw file
   1<?xml version="1.0" encoding="utf-8"?>
   2<feed xmlns="http://www.w3.org/2005/Atom">
   3
   4  <title><![CDATA[Curried Functions]]></title>
   5  <link href="http://efvincent.github.io/atom.xml" rel="self"/>
   6  <link href="http://efvincent.github.io/"/>
   7  <updated>2014-08-18T13:03:44-04:00</updated>
   8  <id>http://efvincent.github.io/</id>
   9  <author>
  10    <name><![CDATA[Eric F. Vincent]]></name>
  11    
  12  </author>
  13  <generator uri="http://octopress.org/">Octopress</generator>
  14
  15  
  16  <entry>
  17    <title type="html"><![CDATA[Debounce as a Directive]]></title>
  18    <link href="http://efvincent.github.io/blog/2014/08/18/debounce-as-a-directive/"/>
  19    <updated>2014-08-18T01:28:33-04:00</updated>
  20    <id>http://efvincent.github.io/blog/2014/08/18/debounce-as-a-directive</id>
  21    <content type="html"><![CDATA[<p>Some months ago a co-worker asked if there were a way to buffer the input on a text box
  22so that the handler would not be called more than every X milliseconds. His app was doing
  23the fairly typical chore of searching through a long list as the user types into a
  24search box. Firing a <code>digest</code> (that’s Angular’s re-bind and re-render loop) for each
  25keystroke causes a jumpy, jittery refresh storm.</p>
  26
  27<p>What he was looking for is commonly referred to as to <em>debounce</em> or <em>throttle</em> a
  28function. There are many implementations around, but his question was specifically
  29about debounce in the context of Angular, preferably as a directive.</p>
  30
  31<!-- more -->
  32
  33<p>I found a snippet authored by <a href="http://tommaitland.net">Tom Maitland</a> that does just
  34what we need. I tweaked it slightly (also as a <a href="https://gist.github.com/efvincent/9784923">Gist</a>
  35and <a href="http://jsfiddle.net/efvincent/vkphp2fa/">JSFiddle</a>):</p>
  36
  37<div><table class="CodeRay"><tr>
  38  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
  39<a href="#n2" name="n2">2</a>
  40<a href="#n3" name="n3">3</a>
  41<a href="#n4" name="n4">4</a>
  42<a href="#n5" name="n5">5</a>
  43<a href="#n6" name="n6">6</a>
  44<a href="#n7" name="n7">7</a>
  45<a href="#n8" name="n8">8</a>
  46<a href="#n9" name="n9">9</a>
  47<strong><a href="#n10" name="n10">10</a></strong>
  48<a href="#n11" name="n11">11</a>
  49<a href="#n12" name="n12">12</a>
  50<a href="#n13" name="n13">13</a>
  51<a href="#n14" name="n14">14</a>
  52<a href="#n15" name="n15">15</a>
  53<a href="#n16" name="n16">16</a>
  54<a href="#n17" name="n17">17</a>
  55<a href="#n18" name="n18">18</a>
  56<a href="#n19" name="n19">19</a>
  57<strong><a href="#n20" name="n20">20</a></strong>
  58<a href="#n21" name="n21">21</a>
  59<a href="#n22" name="n22">22</a>
  60<a href="#n23" name="n23">23</a>
  61<a href="#n24" name="n24">24</a>
  62<a href="#n25" name="n25">25</a>
  63<a href="#n26" name="n26">26</a>
  64</pre></td>
  65  <td class="code"><pre><span class="comment">// Defines the module as &quot;app&quot;, this is not best practice for module</span>
  66<span class="comment">// definition or project structure, focus on the directive</span>
  67angular.module(<span class="string"><span class="delimiter">'</span><span class="content">app</span><span class="delimiter">'</span></span>, []).directive(<span class="string"><span class="delimiter">'</span><span class="content">tlDebounce</span><span class="delimiter">'</span></span>, <span class="keyword">function</span>(<span class="predefined">$timeout</span>) {
  68  <span class="keyword">return</span> {
  69    <span class="key">restrict</span>: <span class="string"><span class="delimiter">'</span><span class="content">A</span><span class="delimiter">'</span></span>,
  70    <span class="key">require</span>: <span class="string"><span class="delimiter">'</span><span class="content">ngModel</span><span class="delimiter">'</span></span>,
  71    <span class="key">priority</span>: <span class="integer">99</span>,
  72    <span class="function">link</span>: <span class="keyword">function</span>(scope, elm, attr, ngModelCtrl) {
  73      <span class="keyword">if</span> (attr.type === <span class="string"><span class="delimiter">'</span><span class="content">radio</span><span class="delimiter">'</span></span> || attr.type === <span class="string"><span class="delimiter">'</span><span class="content">checkbox</span><span class="delimiter">'</span></span>) <span class="keyword">return</span>;
  74
  75      elm.unbind(<span class="string"><span class="delimiter">'</span><span class="content">input</span><span class="delimiter">'</span></span>);
  76
  77      <span class="keyword">var</span> debounce;
  78      elm.bind(<span class="string"><span class="delimiter">'</span><span class="content">input</span><span class="delimiter">'</span></span>, <span class="keyword">function</span>() {
  79        <span class="predefined">$timeout</span>.cancel(debounce);
  80          ngModelCtrl.<span class="predefined">$setViewValue</span>(elm.val());
  81        }, attr.tlDebounce || <span class="integer">1000</span>);
  82      });
  83      elm.bind(<span class="string"><span class="delimiter">'</span><span class="content">blur</span><span class="delimiter">'</span></span>, <span class="keyword">function</span>() {
  84        scope.<span class="predefined">$apply</span>(<span class="keyword">function</span>() {
  85          ngModelCtrl.<span class="predefined">$setViewValue</span>(elm.val());
  86        });
  87      });
  88    }
  89  }
  90});
  91</pre></td>
  92</tr></table>
  93</div>
  94
  95<h2 id="examining-the-directive">Examining the directive</h2>
  96
  97<p>The directive starts at line 3 by defining a module and calling the <code>directive</code> function
  98which causes Angular to register a directive in that module. This directive is called <code>tlBounce</code>.
  99To define a directive we pass a function and our function returns a directive definition object.</p>
 100
 101<h3 id="injecting-angulars-timer-service">Injecting Angular’s Timer service</h3>
 102
 103<p>The debounce directive will use a timer to assure that when attached to a text box, the underlying
 104model will only be updated every X milliseconds. We’ll see the algorithm in a bit.</p>
 105
 106<p>When Angular needs an instance of our directive, it will call the function we’ve provided. Angular
 107will inspect the function and detect that it has a dependency; to call the function Angular must
 108provide, or <em>inject</em> something called <code>$timeout</code>, which is one of Angular’s services. Angular offers
 109many <em>services</em> to you as the application developer to use in creating a directive (or factory,
 110filter, controller, or the other Angular things). These services are objects or functions provided by the framework.</p>
 111
 112<p>The tip-off that <code>$timeout</code> is a service is the leading dollar sign. Angular will use its
 113<a href="https://docs.angularjs.org/api/auto/service/$injector#!">Injector</a> service to find a <code>$timeout</code> and pass it
 114to us. We’ll then use the <code>$timeout</code> in our <em>link function</em>.</p>
 115
 116<h3 id="the-link-function">The link function</h3>
 117
 118<p>Without getting into the guts of directive development, suffice it to say that in most
 119cases when writing a directive you’ll want to focus on the <code>link</code> function. For more information
 120on the link function, there’s the <a href="http://angularjs.org/">Angular Docs</a>, and another good source of information is
 121<a href="http://www.angularjshub.com/examples/customdirectives/compilelinkfunctions/">AngularJS Hub</a>.</p>
 122
 123<p>The <code>link</code> function sets up each instance of the directive. You supply the function that can have
 124up to four parameters. <code>link: function(scope, elm, attr, ngModelCtrl)</code>.</p>
 125
 126<h4 id="link-function-parameters">Link function parameters</h4>
 127
 128<p>The first is the directive’s local scope, which is usually used like you use scope in a controller
 129to maintain and bind to the internal state of the directive. We’ll see how <code>scope</code> is used here in a second.</p>
 130
 131<p>Second is the <code>elm</code> or <em>element</em> parameter. This is the DOM element that the directive to which the
 132directive is attached. For debounce, the directive is attached to an input, usually a text box. You can do the
 133usual DOM-stuff to the element, attach event handlers, change content, add children, etc. AAMOF you actually
 134have an Angular wrapper around the element, so you get some additional JQuery like functions on the element.</p>
 135
 136<p>Third is <code>attr</code>, the attributes. This is a map of the attributes on the element to which our directive is
 137attached. In our case, we’re using the <code>attr</code> to detect if we’re attached to a radio button or check box; our
 138deBounce doesn’t have a meaning for those controllers, so we bail if we see that we’re attached to one (line 9).</p>
 139
 140<p>Lastly is the <code>ngModelCtrl</code>, which is the least intuitive. This is a controller requirement of our directive,
 141it says that any directive we’re attached to needs to have an <code>ngModelCtrl</code> controller. This sort of limits
 142our deBouncer, but the target use case is to put this directive on a text box that’s using AngularJS’s binding.</p>
 143
 144<h3 id="debounce-algorithm">DeBounce Algorithm</h3>
 145
 146<p>The strategy is as follows:</p>
 147
 148<ol>
 149  <li>Detach the input handler (line 11) that usually updates the model</li>
 150  <li>Bind a new input handler
 151    <ol>
 152      <li>Cancel any pending debounce timer (line 15)</li>
 153      <li>Set up a new debounce timer
 154        <ol>
 155          <li>It should go off in the time specified by the <code>tl-debounce</code> attribute, or 1,000ms if the attribute is
 156 not specified (line 18).</li>
 157        </ol>
 158      </li>
 159      <li>When it goes off, it should tell the model controller <code>ngModelCtrl</code> to set it’s value <code>.$setViewValue(elm.val())</code></li>
 160    </ol>
 161  </li>
 162  <li>Bind a new blur handler, so when th user leaves the field the model is always updated.
 163    <ol>
 164      <li>Put the call to <code>$setNewValue()</code> inside a <code>scope.apply()</code> so the change causes a digest (Angular rebinds everything).</li>
 165    </ol>
 166  </li>
 167</ol>
 168
 169<h3 id="the-digest">The Digest</h3>
 170<p>One important point - you may be thinking that you could have used the standard JavaScript timer. Why
 171use Angular’s <code>$timer</code> service? It’s because Angular needs to know when the model changes so that it
 172can perform it’s two way binding / model-view synchronization. By using Angular’s timer, you can be assured
 173that Angular will know when the timer goes off and will do all the right Angular binding stuff at that time.</p>
 174
 175<h3 id="but-eric-youre-wrong-and-oh-so-stupid">But Eric, you’re wrong and oh so stupid!</h3>
 176<blockquote>
 177  <p>You <strong>could</strong> use the normal timer, because when you call <code>.$setViewValue()</code>
 178you’re letting Angular know something needs to change, right? I mean, it starts in a dollar sign,
 179so it’s all Angulary, right?  </p>
 180</blockquote>
 181
 182<p>Heh. You’d think so, but you’d be wrong. This is the kind of thing that makes you scratch your head, then waste
 183fifteen minutes, then look up the docs, then unleash a stream of profanities. It happens that <code>.$setViewValue()</code> does
 184<strong>not</strong> cause a digest, probably because of performance or some other really good reason. Doesn’t make it fun though, and
 185it’s the kind of undiscoverable crap that qualifies as a legit complaint about AngularJS. Take your medicine.</p>
 186
 187<p>So that’s DeBounce - it actually works pretty well for things like text boxes that do searches and stuff like that.
 188I use it in production, but there’s no warrentee so YMMV. Have a good one…</p>
 189
 190<p>-e</p>
 191]]></content>
 192  </entry>
 193  
 194  <entry>
 195    <title type="html"><![CDATA[GitHubify(Blog)]]></title>
 196    <link href="http://efvincent.github.io/blog/2014/08/15/Octopress-github-ruby-windows/"/>
 197    <updated>2014-08-15T12:00:11-04:00</updated>
 198    <id>http://efvincent.github.io/blog/2014/08/15/Octopress-github-ruby-windows</id>
 199    <content type="html"><![CDATA[<p>For my shiney new blog I decided to go full hipster and host on GitHub. This means that
 200the entire site, source code as well as the blog website itself, can be seen at
 201<a href="https://github.com/efvincent/efvincent.github.io">my blog’s repository</a>. Of course all of this will be painfully
 202uncool by this time next year. But for the time being it’s fun and the tech is relevant.</p>
 203
 204<p>Dig in if you want to see the ins and outs of setting all this up on a Windows workstation,
 205because Windows is so far out of fashion stuff is starting to not work on it by default. Karma.
 206<!--more -->
 207## Static Site Generation
 208The way GitHub hosted web sites work is that the entire web site is pure static HTML,
 209JavaScript, and CSS. If you work in the industry you realize that all the web site
 210frameworks (server side) like JSP, ASP.NET, Rails, PHP, etc. all <em>generate</em> pages on
 211the fly as the requests come in. This requires a server be running somewhere that can
 212run .NET, Java, Ruby, or whatever.</p>
 213
 214<p>A static site everything is pre-generated, so any server that can respond to requests
 215by serving up a file can host a static site. But no one want’s to hand craft HTML pages
 216for every blog post. So what you have is a generator; some kind of program that can take
 217blog posts written in plain text and <strong>poof!</strong> Generate a static website.</p>
 218
 219<p>The basic idea is that you have a <em>source</em> directory that has your blog posts written
 220in (typically) <a href="https://en.wikipedia.org/wiki/Markdown">markdown</a>, CSS, templates for HTML,
 221and the Ruby / JavaScript / whatever that the generator is written in.</p>
 222
 223<p>There’s typically a command line interface; so you issue the proper command the
 224generator takes your markdown and creates a complete, static web site.</p>
 225
 226<h2 id="github">GitHub</h2>
 227<p>That’s where <a href="www.github.com">GitHub</a> comes in. If you don’t know what GitHub is, or
 228if you’re completely lost at this point, then you probably need to hit up this
 229<a href="https://www.youtube.com/watch?v=oHg5SJYRHA0">everything you need to know to become a modern developer</a>
 230tutorial.</p>
 231
 232<p>Think about it for two seconds, it makes perfect sense. GitHub hosts files in a repository and is a web site.
 233So if you put a static web site’s worth of files <em>in a repository</em>, and GitHub does a tiny bit of magic, it
 234can serve those web pages up. And that’s all a GitHub hosted static site is. You write posts in
 235markdown, you use a generator to create a static site, and you check it into GitHub.</p>
 236
 237<h2 id="octopress">OctoPress</h2>
 238<p>I admittedly don’t have a ton of experience with static site generators. I played with
 239a couple before committing to <a href="www.octopress.org">Octopress</a>. At first I wanted to
 240use a <a href="http://nodejs.org">Node.js</a> based static site generator. I googled around a bit
 241and ended up playing with <a href="https://github.com/jnordberg/wintersmith">Wintersmith</a> for
 242a night. It worked, but GitHub makes it easiest to use a Ruby based generator called <a href="http://jekyllrb.com">Jekyll</a>.
 243A bit more poking around and I ended up with <a href="www.octopress.org">Octopress</a>, which is
 244built on top of Jekyll, offers additional features, and incredibly well written, well
 245documented, and easy to use.</p>
 246
 247<p>When you go to their site you’ll get walked through the installation step by step,
 248and there are some nice Ruby build tools available to get things moving, including
 249configuring your new Octopress generator to work with GitHub web sites. <strong>Highly recommended</strong></p>
 250
 251<h2 id="ruby">Ruby</h2>
 252<p>Ok so <a href="https://www.youtube.com/watch?v=gBkDvqIGSaE">Ruby hates Windows</a>. It might be passive,
 253but the ill feelings are there. Which is fine, everyone can’t love everyone, and Microsoft
 254has kinda earned it by being a dick until very recently. But whatever, I’m not with starting
 255flame war. It happens that I still use Windows for all kinds of reasons, so I needed to
 256get Ruby on my workstation.</p>
 257
 258<p>Actually I had installed Ruby using <a href="http://chocolatey.org/">Chocolately</a> because I
 259love playing with all the languages, but to run Jekyll you’ll need the
 260<a href="http://rubyinstaller.org/downloads/">Ruby Development Kit</a>. The RDK is platform
 261specific, and is needed to build <em>gems</em> (Ruby packages) that are platform specific,
 262which Jekyll either is or depends on indirectly (I didn’t check).</p>
 263
 264<p>There are <a href="https://github.com/oneclick/rubyinstaller/wiki/Development-Kit">very clear instructions</a>
 265that you can follow for getting this set up. Once that’s done you can play along with
 266the <a href="www.octopress.org">Octopress</a> setup instructions, which are great. Just follow the
 267track that has you deploy to GitHub.</p>
 268]]></content>
 269  </entry>
 270  
 271  <entry>
 272    <title type="html"><![CDATA[Abandonment Issues]]></title>
 273    <link href="http://efvincent.github.io/blog/2014/08/15/abandonment-issues/"/>
 274    <updated>2014-08-15T11:52:11-04:00</updated>
 275    <id>http://efvincent.github.io/blog/2014/08/15/abandonment-issues</id>
 276    <content type="html"><![CDATA[<p>I’ve moved my blog from WordPress on my own personal site to GitHub, because … GitHub of course. <em>No One</em> is going
 277to miss my other blog. It had a couple of what I thought were interesting posts on F# and dependency injection in C#. But it’s time
 278for a fresh start.</p>
 279
 280<p>Expect posts on JavaScript and front end development for a little while. After a career spent designing relational
 281databases for finance, insurance and other LOB domains, I’ve been working on SPA style front end enterprise applications for
 282a couple of years. And it’s fun. I may actually have a couple of interesting things to say. We’ll see.</p>
 283]]></content>
 284  </entry>
 285  
 286  <entry>
 287    <title type="html"><![CDATA[DI – Constructor Injection, Bootstrapping]]></title>
 288    <link href="http://efvincent.github.io/blog/2011/06/24/di-bootstrap/"/>
 289    <updated>2011-06-24T02:07:31-04:00</updated>
 290    <id>http://efvincent.github.io/blog/2011/06/24/di-bootstrap</id>
 291    <content type="html"><![CDATA[<h2 id="constructor-injection">Constructor Injection</h2>
 292<p>The idea of dependency injection is that classes are defined such that any dependencies on other classes or services, are <em>injected</em> into the class by some external mechanism, as opposed to being “newed up” directly. The most common form of DI is constructor injection, where a class defines a constructor that has as its parameters the external dependencies required by the class.
 293<!-- more -->
 294There are several benefits to this particular method of injection; the most obvious is that in a well designed system the dependencies of a class are clearly visible in the constructor. In the <a href="http://blog.efvincent.com/practical-di-101">DI 101</a> post a data provider was defined like this:</p>
 295
 296<div><table class="CodeRay"><tr>
 297  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
 298<a href="#n2" name="n2">2</a>
 299<a href="#n3" name="n3">3</a>
 300<a href="#n4" name="n4">4</a>
 301<a href="#n5" name="n5">5</a>
 302<a href="#n6" name="n6">6</a>
 303<a href="#n7" name="n7">7</a>
 304<a href="#n8" name="n8">8</a>
 305<a href="#n9" name="n9">9</a>
 306<strong><a href="#n10" name="n10">10</a></strong>
 307<a href="#n11" name="n11">11</a>
 308<a href="#n12" name="n12">12</a>
 309<a href="#n13" name="n13">13</a>
 310<a href="#n14" name="n14">14</a>
 311</pre></td>
 312  <td class="code"><pre><span class="directive">public</span> <span class="type">class</span> <span class="class">DevDataProvider</span> : IDataProvider {
 313    <span class="directive">private</span> readonly IIdentService _identService;
 314    <span class="directive">private</span> readonly ILogService _logSvc;
 315    <span class="directive">private</span> <span class="directive">static</span> readonly <span class="predefined-type">List</span>&lt;Employee&gt; EmployeeStore = <span class="keyword">new</span> <span class="predefined-type">List</span>&lt;Employee&gt;();
 316
 317    <span class="directive">public</span> DevDataProvider(IIdentService identService, ILogService logSvc) {
 318        <span class="keyword">if</span> (identService == <span class="predefined-constant">null</span>) <span class="keyword">throw</span> <span class="keyword">new</span> ArgumentNullException(<span class="string"><span class="delimiter">&quot;</span><span class="content">identService</span><span class="delimiter">&quot;</span></span>);
 319        <span class="keyword">if</span> (logSvc == <span class="predefined-constant">null</span>) <span class="keyword">throw</span> <span class="keyword">new</span> ArgumentNullException(<span class="string"><span class="delimiter">&quot;</span><span class="content">logSvc</span><span class="delimiter">&quot;</span></span>);
 320        _identService = identService;
 321        _logSvc = logSvc;
 322    }
 323
 324    <span class="comment">// Remaining implementation omitted for brevity</span>
 325}
 326</pre></td>
 327</tr></table>
 328</div>
 329
 330<p>The constructor is on line 6. From this constructor we can see that the DevDataProvider has dependencies on an IIdentityService and an ILogService. There should be no other dependencies in the class other than to well known, stable libraries like the <a href="http://msdn.microsoft.com/en-us/library/hfa3fa08.aspx">BCL</a>.</p>
 331
 332<p>There are other advantages to using constructor injection. Should the list of dependencies get too long, say longer than four parameters, you’ve got a code smell that perhaps the class is doing too much, violating the single responsibility principal.</p>
 333
 334<h2 id="bootstrapping">Bootstrapping</h2>
 335
 336<p>In order to be able to resolve dependencies, the DI container must be configured. This set up is done during the <strong>bootstrapping</strong> phase. Typically this only needs to be done once, but changes to the container make sense in some scenarios like when a DI container is being used to support extensions or plug-ins. In that case components might be added or removed from the DI container while the app is running. These scenarios are out of scope for this post.</p>
 337
 338<p>The container may be configured in several ways – Auto configuring, configuration in code, and configuration files (typically XML / app or web.config files). My current favorite DI framework is AutoFac, and I typically configure in code, but different projects will have different demands, so familiarize yourself with the specifics of your selected framework and understand the tradeoffs involved in the different types of configuration. You can even configure the DI container using more than one method – perhaps Auto configuring for the bulk of the registrations, then code or XML for more specific configuration needs.</p>
 339
 340<h2 id="bootstrapping-a-console-application">Bootstrapping a Console Application</h2>
 341
 342<p>Depending on the type of application you’re working on, there are specific places for bootstrapping to take place. The <em>place</em> to do configuration and bootstrapping is sometimes referred to as the <strong>composition root</strong> <em>(you can read about these concepts in more detail in <a href="http://www.manning.com/seemann/">Mark Seeman’s Dependency Injection</a> book, published by Manning)</em>.</p>
 343
 344<p>In a console application, the static Main() method is a typical place to configure the container. While we rarely write console apps in production (at least I rarely do), the simplicity makes it easy to see the implications of the bootstrapping procedure.</p>
 345
 346<p>In the following sequence diagram, in step one [1] the Main() entry point is called on the console application. Main() is serving as the composition root. From there a private Bootstrap() methods is called [2] and the DI container is configured. The exact mechanism varies by framework.</p>
 347
 348<p><a href="http://blog.efvincent.com/wp-content/uploads/2011/06/Capture.png"><img src="http://blog.efvincent.com/wp-content/uploads/2011/06/Capture_thumb.png" alt="Capture" /></a></p>
 349
 350<p>Once the container is configured, the main entry point requests that the DI container resolve the App type [3]. The DI container creates whatever dependencies are required by the App [4]. This happens hierarchically; dependencies may themselves have dependencies and so on. The DI container sorts all this out and is also responsible for lifetimes of create objects etc. The DI container can create and return the instance off the App [5]. The Main() function can then pass control to the app [6] which will leverage the injected dependencies [7] to do the real work.</p>
 351
 352<h2 id="only-directly-reference-the-di-container-in-the-bootstrapper">Only Directly Reference the DI Container in the Bootstrapper</h2>
 353<p>This is an important point, and if you get nothing else from this post, understand this.</p>
 354
 355<ul>
 356  <li>The DI container is configured in the composition root (Main() in this case)</li>
 357  <li>The DI container is used to resolve or build the App</li>
 358  <li>The app is then run to do the work</li>
 359</ul>
 360
 361<p>Once the app is instantiated, it should have all of its dependencies injected. <strong>The app should not have a reference to the DI container!</strong> If we allow the app or any of its dependencies to have access to the container, then several bad things happen:</p>
 362
 363<h4 id="weve-taken-on-a-dependency-to-the-di-container-itself">We’ve taken on a dependency to the DI Container itself</h4>
 364
 365<p>Yes its true that the assembly has a dependency on the DI container. But for purposes of this discussion the assembly is not the application. The App class and the services (other classes) it depends on is the application. We don’t want to take a dependency on the DI container in those classes; rather, we should be able to switch to a different DI container if needed and not effect the App and the dependent services.</p>
 366
 367<p>In any kind of a significant application the app’s classes would be in a different assembly, and services might be scattered across even more assemblies, and those should not have a dependency on a DI container. They should however be designed and built with the DI pattern in mind – with the dependencies specified in the constructor, with references to abstract types or interfaces, rather than to concrete implementations.</p>
 368
 369<h4 id="were-hiding-a-dependency-inside-the-app">We’re hiding a dependency inside the App</h4>
 370
 371<p>Earlier I mentioned that a benefit of constructor injection is that the dependencies are clearly visible (even <em>documented</em> if you will) in the signature of the constructor. We really don’t want to see lines like this buried in the methods of the classes:</p>
 372
 373<div><table class="CodeRay"><tr>
 374  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
 375<a href="#n2" name="n2">2</a>
 376<a href="#n3" name="n3">3</a>
 377<a href="#n4" name="n4">4</a>
 378<a href="#n5" name="n5">5</a>
 379<a href="#n6" name="n6">6</a>
 380<a href="#n7" name="n7">7</a>
 381<a href="#n8" name="n8">8</a>
 382</pre></td>
 383  <td class="code"><pre><span class="comment">// Anti-pattern - don't use DI container except</span>
 384<span class="comment">// in composition root</span>
 385
 386var dal = <span class="predefined-type">Container</span>.Resolve&lt;IDataAccessService&gt;();
 387
 388<span class="comment">// And defintely don't do this</span>
 389
 390var dal = <span class="keyword">new</span> SqlDataAccessService(connectString);
 391</pre></td>
 392</tr></table>
 393</div>
 394
 395<p>A class that that has these lines buried inside somewhere has hidden dependencies on both the DI container and IDataAccessService (or worse, by using the new keyword directly, on the SqlDataAccessService). These hidden dependencies undermine the benefits of using DI containers at all.</p>
 396
 397<h3 id="bootstrapping-in-other-application-types">Bootstrapping in other Application Types</h3>
 398
 399<p>Other types of apps have different places for bootstrapping and application roots. Unlike a console app, an ASP.NET MVC 3 application isn’t top-down linear, the application must respond to web requests. It does so by creating instances of controllers, and calling methods on those controllers to respond to web requests.</p>
 400
 401<p>A controller in MVC3 is like the app was in our console example above. It will be resolved, or created, by the DI container. Controllers are different in that there will likely be several different controllers in an MVC application. Also, we don’t get to resolve a controller and tell it to run right from the composition root, the ASP.NET MVC framework will be receiving web requests and will need to resolve controllers later, after bootstrapping.</p>
 402
 403<p>In ASP.NET MVC 3 this is accomplished by providing a <em>hook</em>, or a place where we can supply a DI container for ASP.NET MVC 3 to use when creating controllers. The developer configures the DI container, and then wires that container into the MVC framework via an instance of IControllerActivator. In the case of AutoFac, there’s a <a href="http://nuget.org/List/Packages/Autofac.Mvc3">NuGet package called AutoFac.Mvc3</a> that includes classes to integrate with MVC3. The implementation details are beyond the scope of this post – just <a href="http://duckduckgo.com/">DuckDuckGo</a> AutoFac.Mvc and find a wealth of additional detail. Same goes for WCF, WPF, and Silverlight applications. There are best practices for configuring DI containers for each app type.</p>
 404
 405<h3 id="di-unfriendly-application-types">DI Unfriendly Application Types</h3>
 406
 407<p>Some application types just do not lend themselves very easily to dependency injection patterns. Classic ASP.NET pops into mind immediately. It was written before Microsoft was as willing to accept OSS, community driven concepts such as DI Containers. A big red flag with ASP.NET is that all subclasses to the Page class (which is what all your ASP.NET pages are) must have a parameterless default constructor. Well there goes parameter injection!</p>
 408
 409<p>There are other mechanisms for implementing DI patterns in this case, but they’re sub-optimal. Again I’d refer you to <a href="http://www.manning.com/seemann/">Mark Seeman’s Dependency Injection</a> book, which is far and away the best DI book in the .NET space, for advice and examples in dealing with DI unfriendly application types.</p>
 410
 411<h3 id="in-summary">In Summary</h3>
 412
 413<p>Hopefully this was helpful in your understanding of a couple of key aspects of using DI containers. Practice a few console applications, and write some tests too. Once you get the idea, move on to more interesting application types. Before long you’ll be shocked you ever wrote applications <em>without</em> some degree of dependency injection. Yea – it’s that good for you.</p>
 414]]></content>
 415  </entry>
 416  
 417  <entry>
 418    <title type="html"><![CDATA[A Taste of Dependency Injection, Testing, and Mocking]]></title>
 419    <link href="http://efvincent.github.io/blog/2011/05/27/di-mock/"/>
 420    <updated>2011-05-27T20:28:53-04:00</updated>
 421    <id>http://efvincent.github.io/blog/2011/05/27/di-mock</id>
 422    <content type="html"><![CDATA[<p><a href="http://blog.efvincent.com/practical-di-101">My last post</a> provided a brief introduction into dependency injection. To review, the example included a data provider for Employee objects, which included a feature to return the object corresponding to the currently logged in user. In the end the following interfaces were defined:</p>
 423
 424<p><strong>IDataProvider</strong> – the function is obvious from the name. One implementation, the DevDataProvider, uses a static List<employee> as a data store.</employee></p>
 425
 426<p><strong>IIdentityService</strong> – describes a service that supplies the <em>current</em> identity. What current is depends on the implementation of course. A concrete WindowsIdentService defines current as the currently logged in Windows user. The TestIdentService implementation always returned the same username, which is useful for testing as we will see.</p>
 427
 428<p><strong>ILogService</strong> – describes a simple logging service. The ConsoleLogService implementation prints logs to the console.</p>
 429
 430<!-- more -->
 431<p>### Dependency Injection &amp;Testing</p>
 432
 433<p>For this post I’ve added a standard MSTest project and a couple of tests for the data provider. The use of dependency injection patterns in the design of this simple example allows us to easily isolate the code under test.</p>
 434
 435<div><table class="CodeRay"><tr>
 436  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
 437<a href="#n2" name="n2">2</a>
 438<a href="#n3" name="n3">3</a>
 439<a href="#n4" name="n4">4</a>
 440<a href="#n5" name="n5">5</a>
 441<a href="#n6" name="n6">6</a>
 442<a href="#n7" name="n7">7</a>
 443<a href="#n8" name="n8">8</a>
 444<a href="#n9" name="n9">9</a>
 445<strong><a href="#n10" name="n10">10</a></strong>
 446<a href="#n11" name="n11">11</a>
 447<a href="#n12" name="n12">12</a>
 448<a href="#n13" name="n13">13</a>
 449<a href="#n14" name="n14">14</a>
 450</pre></td>
 451  <td class="code"><pre><span class="directive">static</span> IContainer afContainer;
 452
 453[ClassInitialize]
 454<span class="directive">public</span> <span class="directive">static</span> <span class="type">void</span> TestInit(TestContext ctx) {
 455    var idSvc = A.Fake&lt;IIdentService&gt;();
 456    A.CallTo(() =&gt; idSvc.GetCurrentUserName())
 457        .Returns(<span class="string"><span class="delimiter">&quot;</span><span class="content">FAKE-ID</span><span class="delimiter">&quot;</span></span>);
 458
 459    var bldr = <span class="keyword">new</span> ContainerBuilder();
 460    bldr.RegisterInstance(idSvc);
 461    bldr.RegisterInstance(A.Fake&lt;ILogService&gt;());
 462    bldr.RegisterType&lt;DevDataProvider&gt;().As&lt;IDataProvider&gt;();
 463    afContainer = bldr.Build();
 464}
 465</pre></td>
 466</tr></table>
 467</div>
 468
 469<p>The test class has a static DI container instance, initialized in the class initializer. I’m using <a href="http://code.google.com/p/fakeiteasy/">FakeItEasy</a> to create a fake IIdentService at line five. Like six tells the FakeItEasy framework what to return when the GetCurrentUserName() method is called on the fake ident service. Having a fixed response makes testing the data provider a piece of cake.</p>
 470
 471<p>I then register the fake ident service as well as a fake log service. For the log service, we don’t need to specify any behavior for the methods. The FakeItEasy framework will effectively sink any calls to the methods of the fake log service, which is fine for this test.</p>
 472
 473<p>Lastly the data provider we want to test is registered with the DI container builder, and then container is built. The tests go on to use the DI container to resolve an instance of the data provider. The DI container will configure the data provider’s dependencies for a log service and an identity service with the fakes we built.</p>
 474
 475<div><table class="CodeRay"><tr>
 476  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
 477<a href="#n2" name="n2">2</a>
 478<a href="#n3" name="n3">3</a>
 479<a href="#n4" name="n4">4</a>
 480<a href="#n5" name="n5">5</a>
 481<a href="#n6" name="n6">6</a>
 482<a href="#n7" name="n7">7</a>
 483<a href="#n8" name="n8">8</a>
 484</pre></td>
 485  <td class="code"><pre>[TestMethod()]
 486<span class="directive">public</span> <span class="type">void</span> GetCurrentEmployeeTest() {
 487    var e = <span class="keyword">new</span> Employee { WindowsUsername = <span class="string"><span class="delimiter">&quot;</span><span class="content">FAKE-ID</span><span class="delimiter">&quot;</span></span> };
 488    var dal = afContainer.Resolve&lt;IDataProvider&gt;();
 489    dal.AddEmployee(e);
 490    var result = dal.GetCurrentEmployee();
 491    Assert.AreEqual(e.WindowsUsername, result.WindowsUsername);
 492}
 493</pre></td>
 494</tr></table>
 495</div>
 496
 497<p>This is just a small example of using a DI container in combination with a mock / fake framework for testing. The AutoFac DI container can handle much more complex scenarios than what we’ve thrown at it here. The same is true for the FakeItEasy component. Both of these components are well used, well maintained open source projects. You can find lots of documentation and examples for both. Or you can use any number of other DI containers and mocking frameworks to achieve equivalent results.</p>
 498
 499<p>The source code for the example is available <a href="https://bitbucket.org/efvincent/blog-post-dependency-injection-101">here</a>, and the blog entry the precedes this one is available <a href="http://blog.efvincent.com/practical-di-101/">here</a>.</p>
 500]]></content>
 501  </entry>
 502  
 503  <entry>
 504    <title type="html"><![CDATA[Practical Dependency Injection 101]]></title>
 505    <link href="http://efvincent.github.io/blog/2011/05/27/practical-di-101/"/>
 506    <updated>2011-05-27T13:08:27-04:00</updated>
 507    <id>http://efvincent.github.io/blog/2011/05/27/practical-di-101</id>
 508    <content type="html"><![CDATA[<p>In this post we take a look at dependency injection (DI). Target audience is competent .NET developers, C# specifically (but VB’ers who read C# can benefit just as much), who’ve heard of DI but haven’t gotten around to figuring out how it fits in their day to day.</p>
 509
 510<!-- more -->
 511<p>### What is Dependency Injection</p>
 512
 513<p>The first question that we need to address is: What is it that DI does for us? What problem is being solved? DI is about coupling; the degree to which program unit refers to other units. In .NET the units we’re typically worried about are classes, interfaces, components, and assemblies. Dependency injection facilitates reduction these interdependencies. Are DI patterns a silver bullet? Of course not. You can always write bad code regardless of patterns. That being said, if you’re already writing decent code and have good fundamentals, but are not using DI patterns, you’ve got the opportunity to take a leap forward.</p>
 514
 515<p>How does DI reduce help reduce coupling? The easiest way to describe it is by diving directly into an example.</p>
 516
 517<h3 id="example-scenario">Example Scenario</h3>
 518
 519<p>We’ll work on a hypothetical in-house app where the Windows AD authenticates employees, and their Windows username is used to index a database with Employee information. It’s pretty common to see stuff like this happening in-house with line of business applications.</p>
 520
 521<p>The example uses a provider pattern – all the data access will go through a data access provider, allowing us to build a simple provider that stores records in memory during this, our prototype phase. Theoretically we’d replace this as development continued with a provider that leverages persistent storage later.</p>
 522
 523<p>Here’s the base level example program with no consideration for dependency injection:</p>
 524
 525<div><table class="CodeRay"><tr>
 526  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
 527<a href="#n2" name="n2">2</a>
 528<a href="#n3" name="n3">3</a>
 529<a href="#n4" name="n4">4</a>
 530<a href="#n5" name="n5">5</a>
 531<a href="#n6" name="n6">6</a>
 532<a href="#n7" name="n7">7</a>
 533<a href="#n8" name="n8">8</a>
 534<a href="#n9" name="n9">9</a>
 535<strong><a href="#n10" name="n10">10</a></strong>
 536<a href="#n11" name="n11">11</a>
 537<a href="#n12" name="n12">12</a>
 538<a href="#n13" name="n13">13</a>
 539<a href="#n14" name="n14">14</a>
 540<a href="#n15" name="n15">15</a>
 541<a href="#n16" name="n16">16</a>
 542<a href="#n17" name="n17">17</a>
 543<a href="#n18" name="n18">18</a>
 544<a href="#n19" name="n19">19</a>
 545<strong><a href="#n20" name="n20">20</a></strong>
 546<a href="#n21" name="n21">21</a>
 547<a href="#n22" name="n22">22</a>
 548<a href="#n23" name="n23">23</a>
 549<a href="#n24" name="n24">24</a>
 550<a href="#n25" name="n25">25</a>
 551<a href="#n26" name="n26">26</a>
 552<a href="#n27" name="n27">27</a>
 553<a href="#n28" name="n28">28</a>
 554<a href="#n29" name="n29">29</a>
 555<strong><a href="#n30" name="n30">30</a></strong>
 556<a href="#n31" name="n31">31</a>
 557<a href="#n32" name="n32">32</a>
 558<a href="#n33" name="n33">33</a>
 559<a href="#n34" name="n34">34</a>
 560<a href="#n35" name="n35">35</a>
 561<a href="#n36" name="n36">36</a>
 562<a href="#n37" name="n37">37</a>
 563<a href="#n38" name="n38">38</a>
 564<a href="#n39" name="n39">39</a>
 565<strong><a href="#n40" name="n40">40</a></strong>
 566<a href="#n41" name="n41">41</a>
 567<a href="#n42" name="n42">42</a>
 568<a href="#n43" name="n43">43</a>
 569<a href="#n44" name="n44">44</a>
 570<a href="#n45" name="n45">45</a>
 571<a href="#n46" name="n46">46</a>
 572<a href="#n47" name="n47">47</a>
 573<a href="#n48" name="n48">48</a>
 574<a href="#n49" name="n49">49</a>
 575<strong><a href="#n50" name="n50">50</a></strong>
 576<a href="#n51" name="n51">51</a>
 577<a href="#n52" name="n52">52</a>
 578<a href="#n53" name="n53">53</a>
 579<a href="#n54" name="n54">54</a>
 580<a href="#n55" name="n55">55</a>
 581<a href="#n56" name="n56">56</a>
 582<a href="#n57" name="n57">57</a>
 583<a href="#n58" name="n58">58</a>
 584<a href="#n59" name="n59">59</a>
 585<strong><a href="#n60" name="n60">60</a></strong>
 586<a href="#n61" name="n61">61</a>
 587</pre></td>
 588  <td class="code"><pre><span class="type">class</span> <span class="class">Program</span> {
 589    <span class="directive">static</span> <span class="type">void</span> Main(string<span class="type">[]</span> args) {
 590
 591        <span class="comment">// ** Without using an DI Container approach **</span>
 592
 593        <span class="comment">// Create a new provider aka data access layer</span>
 594        var dal = <span class="keyword">new</span> DevDataProvider();
 595
 596        <span class="comment">// New up an employee that's supposed to represent the currently logged in user</span>
 597        var e = <span class="keyword">new</span> Employee() {
 598            WindowsUsername = <span class="string"><span class="delimiter">&quot;</span><span class="content">thanos</span><span class="char">\\</span><span class="content">efvincent</span><span class="delimiter">&quot;</span></span>,
 599            EmployeeId = <span class="string"><span class="delimiter">&quot;</span><span class="content">0001</span><span class="delimiter">&quot;</span></span>,
 600            FName = <span class="string"><span class="delimiter">&quot;</span><span class="content">Eric</span><span class="delimiter">&quot;</span></span>,
 601            LName = <span class="string"><span class="delimiter">&quot;</span><span class="content">Vincent</span><span class="delimiter">&quot;</span></span>
 602        };
 603
 604        <span class="comment">// Add it to the data access layer</span>
 605        dal.AddEmployee(e);
 606
 607        <span class="comment">// See if the dal can find the current user</span>
 608        e = dal.GetCurrentEmployee();
 609
 610        Console.WriteLine(
 611            <span class="string"><span class="delimiter">&quot;</span><span class="content">Current logged in person is: {0}</span><span class="delimiter">&quot;</span></span>, e == <span class="predefined-constant">null</span> ? <span class="string"><span class="delimiter">&quot;</span><span class="content">unknown</span><span class="delimiter">&quot;</span></span> : e.FName);
 612
 613        <span class="comment">// End</span>
 614        Console.Write(<span class="string"><span class="delimiter">&quot;</span><span class="content">Press any key...</span><span class="delimiter">&quot;</span></span>);
 615        Console.ReadKey(<span class="predefined-constant">true</span>);
 616
 617    }
 618}
 619
 620<span class="directive">public</span> <span class="type">class</span> <span class="class">DevDataProvider</span> {
 621    <span class="directive">private</span> <span class="directive">static</span> readonly <span class="predefined-type">List</span>&lt;Employee&gt; EmployeeStore = <span class="keyword">new</span> <span class="predefined-type">List</span>&lt;Employee&gt;();
 622
 623    <span class="directive">public</span> Employee GetCurrentEmployee() {
 624        var emp = EmployeeStore.FirstOrDefault(
 625            e =&gt; e.WindowsUsername.Equals(GetCurrentUserName(), StringComparison.OrdinalIgnoreCase));
 626        <span class="keyword">return</span> emp;
 627    }
 628
 629    <span class="directive">public</span> <span class="type">void</span> AddEmployee(Employee e) {
 630        EmployeeStore.Add(e);
 631    }
 632
 633    <span class="directive">public</span> IQueryable&lt;Employee&gt; Employees() {
 634        <span class="keyword">return</span> EmployeeStore.AsQueryable();
 635    }
 636
 637    <span class="directive">private</span> <span class="directive">static</span> string GetCurrentUserName() {
 638        var wu = WindowsIdentity.GetCurrent();
 639        <span class="keyword">return</span> wu == <span class="predefined-constant">null</span> ? string.Empty : wu.Name;
 640    }
 641}
 642
 643<span class="directive">public</span> <span class="type">class</span> <span class="class">Employee</span> {
 644    <span class="directive">public</span> string WindowsUsername { get; set; }
 645    <span class="directive">public</span> string EmployeeId { get; set; }
 646    <span class="directive">public</span> string FName { get; set; }
 647    <span class="directive">public</span> string LName { get; set; }
 648}
 649</pre></td>
 650</tr></table>
 651</div>
 652
 653<p>In Main() we new up the data access layer, create a new employee, and add it to our store using the data access layer. At line 21 we ask the data access layer to retrieve the employee record for the currently logged in user. Looks pretty typical, so how can IoC help? Let’s look at the coupling here – what classes are dependent on what other classes?</p>
 654
 655<p><a href="http://blog.efvincent.com/wp-content/uploads/2011/05/image.png"><img src="http://blog.efvincent.com/wp-content/uploads/2011/05/image_thumb.png" alt="image" /></a></p>
 656
 657<p>Our main program depends on the DevDataProvider class, and that depends on System.Security to find the Windows username of the currently logged in user. Asking the data access layer to determine the currently logged in user isn’t the best idea, but this is blog post code created to check out dependency injection, so deal with that for the moment.</p>
 658
 659<p>Why are these dependencies undesirable? First consider how flexible this software is. Or rather, inflexible. We created a “quick” DevDataProvider that stores stuff in a static list. As we continue to build a system, we’d have to refer to DevDataProvider from more and more classes, creating a brittle, tightly coupled system. Replacing DevDataProvider becomes more of a maintenance problem.</p>
 660
 661<p>Next think about testability. In real life there are unit tests (there should be anyway). One reason why people find excuses not to unit test is because their code is difficult to test. In this example, if we want to test DevDataProvider.GetCurrentEmployee() we have to consider that under the covers it’s calling the Windows API to get the current username. This makes that method harder to than it needs to be.</p>
 662
 663<h3 id="step-one--leveraging-interfaces">Step One – Leveraging Interfaces</h3>
 664
 665<p>In this version, we’ve factored out an interface called IDataProvider, and one called IIdentService. The IDataProvider should be pretty obvious – but IIdentService? The idea here is to decouple from the Windows API itself. A developer should understand <em>everywhere _that the application makes contact with _any</em> external modules, including the operating system, and then consider what the repercussions of that contact are. In this example, coupling to the Windows API to get then logged in username so directly is undesirable. We want to use a <em>service</em> that would supply us with credentials. That way if we’re testing, we can create a fake service that provides a predictable answer, and is therefore easier to test.</p>
 666
 667<p>Coding to an interface also allows us to radically change the behavior of the service without having to alter its dependencies. If we move to a ASP.NET environment for example, we won’t want to use the current Windows Identity, we may want to use user information from the http context.</p>
 668
 669<div><table class="CodeRay"><tr>
 670  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
 671<a href="#n2" name="n2">2</a>
 672<a href="#n3" name="n3">3</a>
 673<a href="#n4" name="n4">4</a>
 674<a href="#n5" name="n5">5</a>
 675<a href="#n6" name="n6">6</a>
 676<a href="#n7" name="n7">7</a>
 677<a href="#n8" name="n8">8</a>
 678<a href="#n9" name="n9">9</a>
 679<strong><a href="#n10" name="n10">10</a></strong>
 680<a href="#n11" name="n11">11</a>
 681<a href="#n12" name="n12">12</a>
 682<a href="#n13" name="n13">13</a>
 683<a href="#n14" name="n14">14</a>
 684<a href="#n15" name="n15">15</a>
 685<a href="#n16" name="n16">16</a>
 686<a href="#n17" name="n17">17</a>
 687<a href="#n18" name="n18">18</a>
 688<a href="#n19" name="n19">19</a>
 689<strong><a href="#n20" name="n20">20</a></strong>
 690<a href="#n21" name="n21">21</a>
 691<a href="#n22" name="n22">22</a>
 692<a href="#n23" name="n23">23</a>
 693<a href="#n24" name="n24">24</a>
 694<a href="#n25" name="n25">25</a>
 695<a href="#n26" name="n26">26</a>
 696<a href="#n27" name="n27">27</a>
 697<a href="#n28" name="n28">28</a>
 698<a href="#n29" name="n29">29</a>
 699<strong><a href="#n30" name="n30">30</a></strong>
 700<a href="#n31" name="n31">31</a>
 701<a href="#n32" name="n32">32</a>
 702<a href="#n33" name="n33">33</a>
 703<a href="#n34" name="n34">34</a>
 704<a href="#n35" name="n35">35</a>
 705<a href="#n36" name="n36">36</a>
 706<a href="#n37" name="n37">37</a>
 707<a href="#n38" name="n38">38</a>
 708<a href="#n39" name="n39">39</a>
 709<strong><a href="#n40" name="n40">40</a></strong>
 710<a href="#n41" name="n41">41</a>
 711<a href="#n42" name="n42">42</a>
 712<a href="#n43" name="n43">43</a>
 713<a href="#n44" name="n44">44</a>
 714<a href="#n45" name="n45">45</a>
 715<a href="#n46" name="n46">46</a>
 716<a href="#n47" name="n47">47</a>
 717</pre></td>
 718  <td class="code"><pre><span class="comment">// Interface defining an identity service</span>
 719<span class="directive">public</span> <span class="type">interface</span> <span class="class">IIdentService</span> {
 720    string GetCurrentUserName();
 721}
 722
 723<span class="comment">// Implementation of an identity service that returns the current</span>
 724<span class="comment">// logged in windows username</span>
 725<span class="directive">public</span> <span class="type">class</span> <span class="class">WindowsIdentService</span> : IIdentService {
 726    <span class="directive">public</span> string GetCurrentUserName() {
 727        var wu = WindowsIdentity.GetCurrent();
 728        <span class="keyword">return</span> wu == <span class="predefined-constant">null</span> ? string.Empty : wu.Name;
 729    }
 730}
 731
 732<span class="comment">// Interface defining a data provider service</span>
 733<span class="directive">public</span> <span class="type">interface</span> <span class="class">IDataProvider</span> {
 734    Employee GetCurrentEmployee();
 735    <span class="type">void</span> AddEmployee(Employee e);
 736    IQueryable&lt;Employee&gt; Employees();
 737}
 738
 739<span class="comment">// Our development data provider now implements the interface</span>
 740<span class="directive">public</span> <span class="type">class</span> <span class="class">DevDataProvider</span> : IDataProvider {
 741    <span class="directive">private</span> readonly IIdentService _identService;
 742    <span class="directive">private</span> <span class="directive">static</span> readonly <span class="predefined-type">List</span>&lt;Employee&gt; EmployeeStore = <span class="keyword">new</span> <span class="predefined-type">List</span>&lt;Employee&gt;();
 743
 744    <span class="directive">public</span> DevDataProvider(IIdentService identService) {
 745        <span class="keyword">if</span> (identService == <span class="predefined-constant">null</span>) <span class="keyword">throw</span> <span class="keyword">new</span> ArgumentNullException(<span class="string"><span class="delimiter">&quot;</span><span class="content">identService</span><span class="delimiter">&quot;</span></span>);
 746        _identService = identService;
 747    }
 748
 749    <span class="directive">public</span> Employee GetCurrentEmployee() {
 750        var emp = EmployeeStore.FirstOrDefault(
 751                        e =&gt; e.WindowsUsername.Equals(
 752                            _identService.GetCurrentUserName(),
 753                            StringComparison.OrdinalIgnoreCase));
 754        <span class="keyword">return</span> emp;
 755    }
 756
 757    <span class="directive">public</span> <span class="type">void</span> AddEmployee(Employee e) {
 758        EmployeeStore.Add(e);
 759    }
 760
 761    <span class="directive">public</span> IQueryable&lt;Employee&gt; Employees() {
 762        <span class="keyword">return</span> EmployeeStore.AsQueryable();
 763    }
 764}
 765</pre></td>
 766</tr></table>
 767</div>
 768
 769<p>We’re part of the way to where we need to be. Altering DevDataProvider to depend on the IIdentService interface frees it from a hard dependency on a particular identity implementation. The downside is we’ve made creation of the DevDataProvider a bit more complex, as we need to supply the new instance with an IIdentityService instance.</p>
 770
 771<p>~~~C#
 772// Create a new ident service, required for the DAL
 773IIdentService identSvc = new WindowsIdentService();</p>
 774
 775<p>// Create a new DAL
 776IDataProvider dal = new DevDataProvider(identSvc);
 777~~~</p>
 778
 779<p>The DevDataProvider now takes a constructor parameter of type IIdentService. This is where the <em>injection</em> in dependency injection comes from. DevDataProvider has a dependency, but instead of hard coding it into the definition of DevDataProvider, we inject it. There are different ways of injecting dependencies, but constructor injection is very popular and works well in many, or even most cases.</p>
 780
 781<p>The complexity of constructing instances increases when we add a simple logging service which logs information or errors messages.</p>
 782
 783<p>~~~C#
 784// Interface defining a logging service
 785public interface ILogService {
 786    void LogInfo(string msg, params object[] args);
 787    void LogError(string msg, params object[] args);
 788}</p>
 789
 790<p>// Implementation of a console logging service
 791public class ConsoleLogger : ILogService {
 792    public void LogInfo(string msg, params object[] args) {
 793        Console.WriteLine(
 794            “{0} INFO: {1}”, DateTime.Now,
 795            string.Format(msg, args));
 796    }</p>
 797
 798<pre><code>public void LogError(string msg, params object[] args) {
 799    Console.WriteLine(
 800        "{0} ERROR: {1}", DateTime.Now,
 801        string.Format(msg, args));
 802} } ~~~
 803</code></pre>
 804
 805<p>The ILogService is implemented by a simple console logger. Now both the WindowsIdentService and the DevDataProvider can leverage the logger. They’re both modified to have ILogService instance injected via their respective constructors.</p>
 806
 807<div><table class="CodeRay"><tr>
 808  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
 809<a href="#n2" name="n2">2</a>
 810<a href="#n3" name="n3">3</a>
 811<a href="#n4" name="n4">4</a>
 812<a href="#n5" name="n5">5</a>
 813<a href="#n6" name="n6">6</a>
 814<a href="#n7" name="n7">7</a>
 815<a href="#n8" name="n8">8</a>
 816<a href="#n9" name="n9">9</a>
 817<strong><a href="#n10" name="n10">10</a></strong>
 818<a href="#n11" name="n11">11</a>
 819<a href="#n12" name="n12">12</a>
 820<a href="#n13" name="n13">13</a>
 821<a href="#n14" name="n14">14</a>
 822<a href="#n15" name="n15">15</a>
 823<a href="#n16" name="n16">16</a>
 824<a href="#n17" name="n17">17</a>
 825<a href="#n18" name="n18">18</a>
 826<a href="#n19" name="n19">19</a>
 827<strong><a href="#n20" name="n20">20</a></strong>
 828<a href="#n21" name="n21">21</a>
 829<a href="#n22" name="n22">22</a>
 830<a href="#n23" name="n23">23</a>
 831<a href="#n24" name="n24">24</a>
 832<a href="#n25" name="n25">25</a>
 833<a href="#n26" name="n26">26</a>
 834<a href="#n27" name="n27">27</a>
 835<a href="#n28" name="n28">28</a>
 836<a href="#n29" name="n29">29</a>
 837<strong><a href="#n30" name="n30">30</a></strong>
 838<a href="#n31" name="n31">31</a>
 839<a href="#n32" name="n32">32</a>
 840<a href="#n33" name="n33">33</a>
 841<a href="#n34" name="n34">34</a>
 842<a href="#n35" name="n35">35</a>
 843<a href="#n36" name="n36">36</a>
 844<a href="#n37" name="n37">37</a>
 845<a href="#n38" name="n38">38</a>
 846<a href="#n39" name="n39">39</a>
 847<strong><a href="#n40" name="n40">40</a></strong>
 848<a href="#n41" name="n41">41</a>
 849<a href="#n42" name="n42">42</a>
 850<a href="#n43" name="n43">43</a>
 851<a href="#n44" name="n44">44</a>
 852<a href="#n45" name="n45">45</a>
 853<a href="#n46" name="n46">46</a>
 854<a href="#n47" name="n47">47</a>
 855<a href="#n48" name="n48">48</a>
 856<a href="#n49" name="n49">49</a>
 857</pre></td>
 858  <td class="code"><pre><span class="comment">// Implementation of an identity service that returns the current</span>
 859<span class="comment">// logged in windows username</span>
 860<span class="directive">public</span> <span class="type">class</span> <span class="class">WindowsIdentService</span> : IIdentService {
 861    <span class="directive">private</span> readonly ILogService _logSvc;
 862
 863    <span class="directive">public</span> WindowsIdentService(ILogService logSvc) {
 864        <span class="keyword">if</span> (logSvc == <span class="predefined-constant">null</span>) <span class="keyword">throw</span> <span class="keyword">new</span> ArgumentNullException(<span class="string"><span class="delimiter">&quot;</span><span class="content">logSvc</span><span class="delimiter">&quot;</span></span>);
 865        _logSvc = logSvc;
 866    }
 867
 868    <span class="directive">public</span> string GetCurrentUserName() {
 869        var wu = WindowsIdentity.GetCurrent();
 870        var un = wu == <span class="predefined-constant">null</span> ? string.Empty : wu.Name;
 871        _logSvc.LogInfo(<span class="string"><span class="delimiter">&quot;</span><span class="content">Identified current user as: {0}</span><span class="delimiter">&quot;</span></span>, un);
 872        <span class="keyword">return</span> un;
 873    }
 874}
 875
 876<span class="comment">// Our development data provider now implements the interface</span>
 877<span class="directive">public</span> <span class="type">class</span> <span class="class">DevDataProvider</span> : IDataProvider {
 878    <span class="directive">private</span> readonly IIdentService _identService;
 879    <span class="directive">private</span> readonly ILogService _logSvc;
 880    <span class="directive">private</span> <span class="directive">static</span> readonly <span class="predefined-type">List</span>&lt;Employee&gt; EmployeeStore = <span class="keyword">new</span> <span class="predefined-type">List</span>&lt;Employee&gt;();
 881
 882    <span class="directive">public</span> DevDataProvider(IIdentService identService, ILogService logSvc) {
 883        <span class="keyword">if</span> (identService == <span class="predefined-constant">null</span>) <span class="keyword">throw</span> <span class="keyword">new</span> ArgumentNullException(<span class="string"><span class="delimiter">&quot;</span><span class="content">identService</span><span class="delimiter">&quot;</span></span>);
 884        <span class="keyword">if</span> (logSvc == <span class="predefined-constant">null</span>) <span class="keyword">throw</span> <span class="keyword">new</span> ArgumentNullException(<span class="string"><span class="delimiter">&quot;</span><span class="content">logSvc</span><span class="delimiter">&quot;</span></span>);
 885        _identService = identService;
 886        _logSvc = logSvc;
 887    }
 888
 889    <span class="directive">public</span> Employee GetCurrentEmployee() {
 890        var un = _identService.GetCurrentUserName();
 891        var emp = EmployeeStore.FirstOrDefault(
 892                        e =&gt; e.WindowsUsername.Equals(un,
 893                            StringComparison.OrdinalIgnoreCase));
 894        <span class="keyword">if</span> (emp == <span class="predefined-constant">null</span>) _logSvc.LogInfo(<span class="string"><span class="delimiter">&quot;</span><span class="content">Current employee {0} not found</span><span class="delimiter">&quot;</span></span>, un);
 895        <span class="keyword">return</span> emp;
 896    }
 897
 898    <span class="directive">public</span> <span class="type">void</span> AddEmployee(Employee e) {
 899        EmployeeStore.Add(e);
 900        _logSvc.LogInfo(<span class="string"><span class="delimiter">&quot;</span><span class="content">Added employee with id {0}</span><span class="delimiter">&quot;</span></span>, e.EmployeeId);
 901    }
 902
 903    <span class="directive">public</span> IQueryable&lt;Employee&gt; Employees() {
 904        <span class="keyword">return</span> EmployeeStore.AsQueryable();
 905    }
 906}
 907</pre></td>
 908</tr></table>
 909</div>
 910
 911<p>Now the services are getting more robust and they’re not tightly coupled to each other, they refer only to interfaces of the services they depend on. Main() however, where construction is going on, is getting messy.</p>
 912
 913<div><table class="CodeRay"><tr>
 914  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
 915<a href="#n2" name="n2">2</a>
 916<a href="#n3" name="n3">3</a>
 917<a href="#n4" name="n4">4</a>
 918<a href="#n5" name="n5">5</a>
 919<a href="#n6" name="n6">6</a>
 920<a href="#n7" name="n7">7</a>
 921<a href="#n8" name="n8">8</a>
 922<a href="#n9" name="n9">9</a>
 923<strong><a href="#n10" name="n10">10</a></strong>
 924<a href="#n11" name="n11">11</a>
 925<a href="#n12" name="n12">12</a>
 926</pre></td>
 927  <td class="code"><pre><span class="directive">static</span> <span class="type">void</span> Main(string<span class="type">[]</span> args) {
 928
 929    <span class="comment">// ** Without using an DI Container approach **</span>
 930
 931    <span class="comment">// Create a new logging service, required for uh.. everything</span>
 932    ILogService consoleLog = <span class="keyword">new</span> ConsoleLogger();
 933
 934    <span class="comment">// Create a new ident service, required for the DAL</span>
 935    IIdentService identSvc = <span class="keyword">new</span> WindowsIdentService(consoleLog);
 936
 937    <span class="comment">// Create a new DAL</span>
 938    IDataProvider dal = <span class="keyword">new</span> DevDataProvider(identSvc, consoleLog);
 939</pre></td>
 940</tr></table>
 941</div>
 942
 943<p>Finally we’re at the point where we can see the benefit of an dependency injection container. One thing about DI containers is that they’re already written. Several mature, robust, open-source DI containers exist. We’ll use AutoFac, because that’s what I’ve been using lately. We include <a href="http://www.nuget.org/List/Packages/Autofac">AutoFac</a> using <a href="http://www.nuget.org">NuGet</a>.</p>
 944
 945<pre><code>// Create a singleton dependency injection container
 946private static readonly IContainer Container = ConfigureContainer();
 947
 948// Configure the container
 949static IContainer ConfigureContainer() {
 950    // This is how AutoFac works. Other DI containers have similar
 951    // mechanisms for configuring the container
 952    var bld = new ContainerBuilder();
 953
 954    // Register the types that implement the interfaces that are required
 955    // for injection. Note that we have robust control over lifetime, in
 956    // this case ILogService and IIdentService will be singletons, and
 957    // IDataProvider will provide a new instance each time it's requested
 958    bld.RegisterType&lt;ConsoleLogger&gt;().As&lt;ILogService&gt;().SingleInstance();
 959    bld.RegisterType&lt;WindowsIdentService&gt;().As&lt;IIdentService&gt;().SingleInstance();
 960    bld.RegisterType&lt;DevDataProvider&gt;().As&lt;IDataProvider&gt;();
 961    return bld.Build();
 962}
 963
 964static void Main(string[] args) {
 965
 966    // ** Using an IoC Container approach **
 967    var dal = Container.Resolve&lt;IDataProvider&gt;();
 968</code></pre>
 969
 970<p>We’ve created a static instance of IContainer (an AutoFac DI container). When we start the app we configure the container, which fundamentally consists of mapping the interfaces to concrete types that will be injected. For example, line 14 specifies that when there’s a need for an instance of ILogService, we will create an instance of ConsoleLogger. It further says that the DI container should use a SingleInstance() of ConsoleLogger. This has the effect of making ConsoleLogger a singleton. In our example, both the WindowsIdentService and the DevDataProvider will be handed the same instance of ConsoleLogger.</p>
 971
 972<p>The magic happens when we call Container.Resolve<idataprovider>(). The container determines what concrete class to create, and it looks for any dependencies in the constructor. It will see that to build a DevDataProvider, it needs an ILogService and an IWindowsIdentService, it will recursively resolve those as well.</idataprovider></p>
 973
 974<p>These are the basics of dependency injection. Even in this simple example, it should be obvious that the components and classes that we can create can be designed with very low coupling and cohesion using this technique. There are anti-patterns for using DI as well. You should endeavor to practice this technique, do research and learn the most effective uses; there’s plenty of material out there.</p>
 975
 976<p>I hope this example was helpful. Next post I’ll extend this sample by looking at testing, and mock objects, and how DI injection can make testing far easier.</p>
 977
 978<p>Source code samples can be found at this <a href="https://bitbucket.org/efvincent/blog-post-dependency-injection-101">bitbucket repository</a>.</p>
 979
 980<p><em>Update:</em> Follow up post - <a href="http://efvincent.github.io/2011/05/28/di-mock">Dependency Injection, Testing, and Mocking</a></p>
 981]]></content>
 982  </entry>
 983  
 984  <entry>
 985    <title type="html"><![CDATA[NuGet – Galleries of Geeky Goodness.]]></title>
 986    <link href="http://efvincent.github.io/blog/2011/01/12/nuget-geeky-goodness/"/>
 987    <updated>2011-01-12T18:27:26-05:00</updated>
 988    <id>http://efvincent.github.io/blog/2011/01/12/nuget-geeky-goodness</id>
 989    <content type="html"><![CDATA[<p>In a <a href="http://blog.efvincent.com/open-source-nuget-and-more/">previous post</a> I described how Scott Hanselman’s <a href="http://www.hanselman.com/blog/PDC10BuildingABlogWithMicrosoftUnnamedPackageOfWebLove.aspx">presentation</a> during PDC 2010 introduced me to several wonderful and interesting technologies that are either just now out or about to be. The first one I’ll discuss is <a href="http://nuget.codeplex.com">NuGet</a>. There are many excellent introductions to NuGet by <a href="http://www.hanselman.com/blog/IntroducingNuPackPackageManagementForNETAnotherPieceOfTheWebStack.aspx">Hanselman</a> and others. I’ll see if I can make a meaningful contribution.</p>
 990
 991<p>NuGet is an add-on to VS2010. It allows us to access <em>packages</em> that have been published either locally or publicly on the web. The main NuGet gallery just went live today at <a href="http://nuget.org">http://nuget.org</a>. These packages make it easy to install, update, and remove libraries and tools in Visual Studio 2010.</p>
 992
 993<!-- more -->
 994
 995<h2 id="installation">Installation</h2>
 996
 997<p>NuGet, like dozens of other useful add-ins, is available through the Visual Studio Extension Manager, reached under _Tools… Extension Manager…. _</p>
 998
 999<p><a href="http://blog.efvincent.com/wp-content/uploads/2011/01/image.png"><img src="http://blog.efvincent.com/wp-content/uploads/2011/01/image_thumb.png" alt="image" /></a></p>
1000
1001<p>From the Extension Manager choose (1) the online gallery, and then (2) search for NuGet. A restart of Visual Studio is required.</p>
1002
1003<h2 id="the-nuget-package-manager-console">The NuGet Package Manager Console</h2>
1004
1005<p>NuGet has two user interfaces. There’s a PowerShell powered console window. This is the UI I was first introduced to and have gravitated towards. The console gives you a more complete sense of control over the process. Open the console by selecting <em>View… Other Windows… Package Manager Console</em>.</p>
1006
1007<p><a href="http://blog.efvincent.com/wp-content/uploads/2011/01/image1.png"><img src="http://blog.efvincent.com/wp-content/uploads/2011/01/image_thumb1.png" alt="image" /></a></p>
1008
1009<p>The <em>Package Source</em> drop down defaults to the official NuGet package gallery. There are already hundreds of packages out in the gallery, and you can expect it to grow rapidly. You can list the packages in the official library with:</p>
1010
1011<p>List-Packages –remote</p>
1012
1013<p>There are a lot of them, and since the console is PowerShell we can take advantage of a PowerShell grid display:</p>
1014
1015<table>
1016  <tbody>
1017    <tr>
1018      <td>List-Packages –remote</td>
1019      <td>out-GridView</td>
1020    </tr>
1021  </tbody>
1022</table>
1023
1024<p><a href="http://blog.efvincent.com/wp-content/uploads/2011/01/image2.png"><img src="http://blog.efvincent.com/wp-content/uploads/2011/01/image_thumb2.png" alt="image" /></a></p>
1025
1026<h2 id="installing-and-removing-packages">Installing and Removing Packages</h2>
1027
1028<p>Now comes the really cool part. The whole idea of NuGet is to be able to install / add external libraries to your project without having to find them on the web, download a zip or msi file, install it somewhere on your local machine, figure out what the instructions are for incorporating them into your project, and patching it in manually.</p>
1029
1030<p>Let’s take for example, the latest CTP5 version of Entity Framework, that allows for <em>Code First</em> use of the Entity Framework. EF4 will justify at least one future dedicated post, but we’ll use it here for a quick example. Normally, if you want to try out something like a new version of Entity Framework, there’s downloading, installing, shaving the chicken, bla bla bla that you’ve got to do. Not with NuGet. NuGet can effectively _“_xcopy deploy” it into our project.</p>
1031
1032<p>Create a new console application in Visual Studio. From the Package Manager Console, type <em>Install-Package EF</em> and press the tab key. An intellisense window will pop up showing packages that begin with EF.</p>
1033
1034<p><a href="http://blog.efvincent.com/wp-content/uploads/2011/01/image3.png"><img src="http://blog.efvincent.com/wp-content/uploads/2011/01/image_thumb3.png" alt="image" /></a></p>
1035
1036<p>At the time of this writing, there are five packages. The EFCTP4 ones are obsolete, from the last CTP. For this example, choose <em>EFCodeFirst</em> and press enter. The console displays license info, downloads the EFCodeFirst package, and incorporates it into your project. In the solution explorer, we can see a reference  (1) and a file (2) added to the project.</p>
1037
1038<p><a href="http://blog.efvincent.com/wp-content/uploads/2011/01/image4.png"><img src="http://blog.efvincent.com/wp-content/uploads/2011/01/image_thumb4.png" alt="image" /></a></p>
1039
1040<p>Checking the properties of the reference to EntityFramework, you can see that it’s not installed to the GAC, it’s local to the solution. NuGet creates a solution level folder called <em>packages</em>. In that folder, in addition to components used as references, is all the data that NuGet needs to install and uninstall packages. All local, without changing any configuration on the machine. More details of the inner workings of NuGet and its packages will come at a later date, plus there’s information out there you can dig up if you’re so inclined.</p>
1041
1042<h2 id="using-entity-framework">Using Entity Framework</h2>
1043
1044<p>Now that we’ve got it installed, let’s quickly use EFCodeFirst just to prove it’s working. For this example, you’ll need SQL Server installed (there are other options, but one thing at a time). I’ve got Express which works fine. In another post I’ll show the new SQL Server Compact Edition 4, which coincidentally you can add to a project using NuGet <img src="http://blog.efvincent.com/wp-content/uploads/2011/01/wlEmoticon-smile.png" alt="Smile" />.</p>
1045
1046<p>EFCodeFirst allows you to build POCO objects and use them to build a DB. Let’s build a quick model. There are a few examples floating around modeling blog posts and comments, so lets <em>not</em> do that. Let’s do (super simple) prescriptions and medications. It’s on my mind because I’m recovering from knee surgery. This code is entered directly into the Program.cs source file for this example.</p>
1047
1048<div><table class="CodeRay"><tr>
1049  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
1050<a href="#n2" name="n2">2</a>
1051<a href="#n3" name="n3">3</a>
1052<a href="#n4" name="n4">4</a>
1053<a href="#n5" name="n5">5</a>
1054<a href="#n6" name="n6">6</a>
1055<a href="#n7" name="n7">7</a>
1056<a href="#n8" name="n8">8</a>
1057<a href="#n9" name="n9">9</a>
1058<strong><a href="#n10" name="n10">10</a></strong>
1059<a href="#n11" name="n11">11</a>
1060<a href="#n12" name="n12">12</a>
1061<a href="#n13" name="n13">13</a>
1062<a href="#n14" name="n14">14</a>
1063<a href="#n15" name="n15">15</a>
1064<a href="#n16" name="n16">16</a>
1065<a href="#n17" name="n17">17</a>
1066<a href="#n18" name="n18">18</a>
1067<a href="#n19" name="n19">19</a>
1068<strong><a href="#n20" name="n20">20</a></strong>
1069<a href="#n21" name="n21">21</a>
1070<a href="#n22" name="n22">22</a>
1071<a href="#n23" name="n23">23</a>
1072<a href="#n24" name="n24">24</a>
1073<a href="#n25" name="n25">25</a>
1074<a href="#n26" name="n26">26</a>
1075<a href="#n27" name="n27">27</a>
1076<a href="#n28" name="n28">28</a>
1077<a href="#n29" name="n29">29</a>
1078<strong><a href="#n30" name="n30">30</a></strong>
1079<a href="#n31" name="n31">31</a>
1080<a href="#n32" name="n32">32</a>
1081<a href="#n33" name="n33">33</a>
1082<a href="#n34" name="n34">34</a>
1083<a href="#n35" name="n35">35</a>
1084<a href="#n36" name="n36">36</a>
1085<a href="#n37" name="n37">37</a>
1086<a href="#n38" name="n38">38</a>
1087<a href="#n39" name="n39">39</a>
1088<strong><a href="#n40" name="n40">40</a></strong>
1089<a href="#n41" name="n41">41</a>
1090<a href="#n42" name="n42">42</a>
1091<a href="#n43" name="n43">43</a>
1092<a href="#n44" name="n44">44</a>
1093<a href="#n45" name="n45">45</a>
1094<a href="#n46" name="n46">46</a>
1095<a href="#n47" name="n47">47</a>
1096<a href="#n48" name="n48">48</a>
1097<a href="#n49" name="n49">49</a>
1098<strong><a href="#n50" name="n50">50</a></strong>
1099<a href="#n51" name="n51">51</a>
1100<a href="#n52" name="n52">52</a>
1101<a href="#n53" name="n53">53</a>
1102<a href="#n54" name="n54">54</a>
1103<a href="#n55" name="n55">55</a>
1104<a href="#n56" name="n56">56</a>
1105<a href="#n57" name="n57">57</a>
1106<a href="#n58" name="n58">58</a>
1107<a href="#n59" name="n59">59</a>
1108<strong><a href="#n60" name="n60">60</a></strong>
1109<a href="#n61" name="n61">61</a>
1110<a href="#n62" name="n62">62</a>
1111<a href="#n63" name="n63">63</a>
1112<a href="#n64" name="n64">64</a>
1113<a href="#n65" name="n65">65</a>
1114<a href="#n66" name="n66">66</a>
1115<a href="#n67" name="n67">67</a>
1116<a href="#n68" name="n68">68</a>
1117<a href="#n69" name="n69">69</a>
1118<strong><a href="#n70" name="n70">70</a></strong>
1119<a href="#n71" name="n71">71</a>
1120<a href="#n72" name="n72">72</a>
1121<a href="#n73" name="n73">73</a>
1122<a href="#n74" name="n74">74</a>
1123<a href="#n75" name="n75">75</a>
1124<a href="#n76" name="n76">76</a>
1125<a href="#n77" name="n77">77</a>
1126<a href="#n78" name="n78">78</a>
1127<a href="#n79" name="n79">79</a>
1128<strong><a href="#n80" name="n80">80</a></strong>
1129<a href="#n81" name="n81">81</a>
1130<a href="#n82" name="n82">82</a>
1131<a href="#n83" name="n83">83</a>
1132<a href="#n84" name="n84">84</a>
1133<a href="#n85" name="n85">85</a>
1134<a href="#n86" name="n86">86</a>
1135<a href="#n87" name="n87">87</a>
1136<a href="#n88" name="n88">88</a>
1137<a href="#n89" name="n89">89</a>
1138<strong><a href="#n90" name="n90">90</a></strong>
1139<a href="#n91" name="n91">91</a>
1140<a href="#n92" name="n92">92</a>
1141<a href="#n93" name="n93">93</a>
1142<a href="#n94" name="n94">94</a>
1143<a href="#n95" name="n95">95</a>
1144<a href="#n96" name="n96">96</a>
1145<a href="#n97" name="n97">97</a>
1146<a href="#n98" name="n98">98</a>
1147<a href="#n99" name="n99">99</a>
1148<strong><a href="#n100" name="n100">100</a></strong>
1149<a href="#n101" name="n101">101</a>
1150<a href="#n102" name="n102">102</a>
1151<a href="#n103" name="n103">103</a>
1152<a href="#n104" name="n104">104</a>
1153<a href="#n105" name="n105">105</a>
1154<a href="#n106" name="n106">106</a>
1155<a href="#n107" name="n107">107</a>
1156<a href="#n108" name="n108">108</a>
1157<a href="#n109" name="n109">109</a>
1158<strong><a href="#n110" name="n110">110</a></strong>
1159<a href="#n111" name="n111">111</a>
1160<a href="#n112" name="n112">112</a>
1161<a href="#n113" name="n113">113</a>
1162<a href="#n114" name="n114">114</a>
1163<a href="#n115" name="n115">115</a>
1164<a href="#n116" name="n116">116</a>
1165<a href="#n117" name="n117">117</a>
1166<a href="#n118" name="n118">118</a>
1167<a href="#n119" name="n119">119</a>
1168<strong><a href="#n120" name="n120">120</a></strong>
1169<a href="#n121" name="n121">121</a>
1170<a href="#n122" name="n122">122</a>
1171<a href="#n123" name="n123">123</a>
1172<a href="#n124" name="n124">124</a>
1173<a href="#n125" name="n125">125</a>
1174<a href="#n126" name="n126">126</a>
1175<a href="#n127" name="n127">127</a>
1176<a href="#n128" name="n128">128</a>
1177<a href="#n129" name="n129">129</a>
1178<strong><a href="#n130" name="n130">130</a></strong>
1179</pre></td>
1180  <td class="code"><pre><span class="directive">public</span> <span class="type">class</span> <span class="class">Prescription</span> {
1181    <span class="directive">public</span> <span class="type">int</span> Id { get; set; }
1182    <span class="directive">public</span> string MedName { get; set; }
1183    <span class="directive">public</span> string Directions { get; set; }
1184    <span class="directive">public</span> <span class="type">int</span> Quantity { get; set; }
1185    <span class="directive">public</span> <span class="type">int</span> Refills { get; set; }
1186    <span class="directive">public</span> <span class="type">int</span> RefillsRemaining { get; set; }
1187    <span class="directive">public</span> ICollection&lt;FilledScript&gt; FilledScripts { get; set; }
1188}
1189
1190<span class="directive">public</span> <span class="type">class</span> <span class="class">FilledScript</span> {
1191    <span class="directive">public</span> <span class="type">int</span> Id { get; set; }
1192    <span class="directive">public</span> Prescription Script { get; set; }
1193    <span class="directive">public</span> DateTime Filled { get; set; }
1194    <span class="directive">public</span> <span class="type">int</span> Doses { get; set; }
1195}
1196
1197<span class="directive">public</span> <span class="type">class</span> <span class="class">MedContext</span> : DbContext {
1198    <span class="directive">public</span> DbSet&lt;Prescription&gt; Prescriptions { get; set; }
1199    <span class="directive">public</span> DbSet&lt;FilledScript&gt; FilledScripts { get; set; }
1200}
1201&lt;div <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">bogus-wrapper</span><span class="delimiter">'</span></span>&gt;&lt;<span class="class">notextile</span>&gt;&lt;figure <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">code</span><span class="delimiter">'</span></span>&gt;&lt;<span class="class">div</span> <span class="type">class</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">highlight</span><span class="delimiter">&quot;</span></span>&gt;&lt;<span class="class">table</span>&gt;&lt;tr&gt;&lt;td <span class="type">class</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">gutter</span><span class="delimiter">&quot;</span></span>&gt;&lt;<span class="class">pre</span> <span class="type">class</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">line-numbers</span><span class="delimiter">&quot;</span></span>&gt;&lt;<span class="class">span</span> <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">1</span>&lt;/<span class="class">span</span>&gt;
1202&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">2</span>&lt;/<span class="class">span</span>&gt;
1203&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">3</span>&lt;/<span class="class">span</span>&gt;
1204&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">4</span>&lt;/<span class="class">span</span>&gt;
1205&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">5</span>&lt;/<span class="class">span</span>&gt;
1206&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">6</span>&lt;/<span class="class">span</span>&gt;
1207&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">7</span>&lt;/<span class="class">span</span>&gt;
1208&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">8</span>&lt;/<span class="class">span</span>&gt;
1209&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">9</span>&lt;/<span class="class">span</span>&gt;
1210&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">10</span>&lt;/<span class="class">span</span>&gt;
1211&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">11</span>&lt;/<span class="class">span</span>&gt;
1212&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">12</span>&lt;/<span class="class">span</span>&gt;
1213&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">13</span>&lt;/<span class="class">span</span>&gt;
1214&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">14</span>&lt;/<span class="class">span</span>&gt;
1215&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">15</span>&lt;/<span class="class">span</span>&gt;
1216&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">16</span>&lt;/<span class="class">span</span>&gt;
1217&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">17</span>&lt;/<span class="class">span</span>&gt;
1218&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">18</span>&lt;/<span class="class">span</span>&gt;
1219&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">19</span>&lt;/<span class="class">span</span>&gt;
1220&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">20</span>&lt;/<span class="class">span</span>&gt;
1221&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">21</span>&lt;/<span class="class">span</span>&gt;
1222&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">22</span>&lt;/<span class="class">span</span>&gt;
1223&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">23</span>&lt;/<span class="class">span</span>&gt;
1224&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">24</span>&lt;/<span class="class">span</span>&gt;
1225&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">25</span>&lt;/<span class="class">span</span>&gt;
1226&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">26</span>&lt;/<span class="class">span</span>&gt;
1227&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">27</span>&lt;/<span class="class">span</span>&gt;
1228&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">28</span>&lt;/<span class="class">span</span>&gt;
1229&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">29</span>&lt;/<span class="class">span</span>&gt;
1230&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">30</span>&lt;/<span class="class">span</span>&gt;
1231&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">31</span>&lt;/<span class="class">span</span>&gt;
1232&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">32</span>&lt;/<span class="class">span</span>&gt;
1233&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">33</span>&lt;/<span class="class">span</span>&gt;
1234&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">34</span>&lt;/<span class="class">span</span>&gt;
1235&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">35</span>&lt;/<span class="class">span</span>&gt;
1236&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">36</span>&lt;/<span class="class">span</span>&gt;
1237&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">37</span>&lt;/<span class="class">span</span>&gt;
1238&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">38</span>&lt;/<span class="class">span</span>&gt;
1239&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">39</span>&lt;/<span class="class">span</span>&gt;
1240&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">40</span>&lt;/<span class="class">span</span>&gt;
1241&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">41</span>&lt;/<span class="class">span</span>&gt;
1242&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line-number</span><span class="delimiter">'</span></span>&gt;<span class="integer">42</span>&lt;/<span class="class">span</span>&gt;
1243&lt;/pre&gt;&lt;/td&gt;&lt;td <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">code</span><span class="delimiter">'</span></span>&gt;&lt;<span class="class">pre</span>&gt;&lt;code <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="delimiter">'</span></span>&gt;&lt;<span class="class">span</span> <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;
1244&lt;/<span class="class">span</span>&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;<span class="class">We</span> have a <span class="type">class</span> <span class="class">for</span> a Prescription, and one <span class="keyword">for</span> a FilledScript (filled prescription). We give each one an integer Id, which EF will interpret (by convention) as the primary key and identity <span class="keyword">for</span> each entity. A relation is created between them, again by convention. On the <span class="error">“</span>one<span class="error">”</span> side,<span class="error"> </span> the Prescription has a collection of filled scripts, and on the <span class="error">“</span>many<span class="error">”</span> side, the filled script has a reference to its prescription.
1245&lt;/span&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;
1246&lt;/<span class="class">span</span>&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;<span class="class">The</span> _MedContext_ <span class="type">class</span> <span class="class">inherits</span> from EF<span class="error">’</span>s DbContext, and pulls the model together. Each DbSet&amp;lt;<span class="error">…</span>&amp;gt; identifies an entity to EF. In <span class="local-variable">this</span> minimal <span class="keyword">case</span>, that<span class="error">’</span>s all that<span class="error">’</span>s required to define a model using EFCodeFirst. Lets take a look at using it:
1247&lt;/span&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;
1248&lt;/<span class="class">span</span>&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;~~~<span class="class">java</span>  
1249&lt;/span&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;<span class="class">static</span> <span class="type">void</span> Main(string<span class="type">[]</span> args) {
1250&lt;/span&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;
1251&lt;/<span class="class">span</span>&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;    <span class="class">DbDatabase</span>.SetInitializer(<span class="keyword">new</span> DropCreateDatabaseAlways&amp;lt;MedContext&amp;gt;());
1252&lt;/span&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;
1253&lt;/<span class="class">span</span>&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;    <span class="class">var</span> ctx = <span class="keyword">new</span> MedContext();
1254&lt;/span&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;    <span class="class">var</span> p = <span class="keyword">new</span> Prescription() {
1255&lt;/span&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;        <span class="class">MedName</span> = <span class="string"><span class="delimiter">&quot;</span><span class="content">Vicoden</span><span class="delimiter">&quot;</span></span>,
1256&lt;/span&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;        <span class="class">Directions</span> = <span class="string"><span class="delimiter">&quot;</span><span class="content">One every 4 hours as needed for pain</span><span class="delimiter">&quot;</span></span>,
1257&lt;/span&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;        <span class="class">Quantity</span> = <span class="integer">60</span>,
1258&lt;/span&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;        <span class="class">Refills</span> = <span class="integer">2</span>,
1259&lt;/span&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;        <span class="class">RefillsRemaining</span> = <span class="integer">1</span>,
1260&lt;/span&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;        <span class="class">FilledScripts</span> = <span class="keyword">new</span><span class="type">[]</span> {
1261&lt;/span&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;            <span class="class">new</span> FilledScript() {
1262&lt;/span&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;                <span class="class">Filled</span> = DateTime.Parse(<span class="string"><span class="delimiter">&quot;</span><span class="content">12/28/2010</span><span class="delimiter">&quot;</span></span>),
1263&lt;/span&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;                <span class="class">Doses</span> = <span class="integer">0</span>
1264&lt;/span&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;            },
1265&lt;/<span class="class">span</span>&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;            <span class="class">new</span> FilledScript() {
1266&lt;/span&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;                <span class="class">Filled</span> = DateTime.Parse(<span class="string"><span class="delimiter">&quot;</span><span class="content">1/12/2011</span><span class="delimiter">&quot;</span></span>),
1267&lt;/span&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;                <span class="class">Doses</span> = <span class="integer">48</span>
1268&lt;/span&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;            }
1269&lt;/<span class="class">span</span>&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;        }
1270&lt;/<span class="class">span</span>&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;    };
1271&lt;/<span class="class">span</span>&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;
1272&lt;/<span class="class">span</span>&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;    <span class="class">ctx</span>.Prescriptions.Add(p);
1273&lt;/span&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;    <span class="class">ctx</span>.SaveChanges();
1274&lt;/span&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;
1275&lt;/<span class="class">span</span>&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;    <span class="class">foreach</span> (var script in ctx.Prescriptions) {
1276&lt;/span&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;        <span class="class">Console</span>.WriteLine(<span class="string"><span class="delimiter">&quot;</span><span class="content">Script for {0}, filled {1} time(s), we have {2} doses on hand</span><span class="delimiter">&quot;</span></span>,
1277&lt;/span&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;            <span class="class">script</span>.MedName,
1278&lt;/span&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;            <span class="class">script</span>.FilledScripts.Count(),
1279&lt;/span&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;            <span class="class">script</span>.FilledScripts.Sum(fs =&amp;gt; fs.Doses));
1280&lt;/span&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;    }
1281&lt;/<span class="class">span</span>&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;
1282&lt;/<span class="class">span</span>&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;    <span class="class">Console</span>.Write(<span class="string"><span class="delimiter">&quot;</span><span class="char">\n</span><span class="content">Press any key...</span><span class="delimiter">&quot;</span></span>);
1283&lt;/span&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;    <span class="class">Console</span>.ReadKey(<span class="predefined-constant">true</span>);
1284&lt;/span&gt;&lt;span <span class="type">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">line</span><span class="delimiter">'</span></span>&gt;}&lt;/<span class="class">span</span>&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/notextile&gt;&lt;/div&gt;
1285
1286For <span class="local-variable">this</span> simple example I<span class="error">’</span>m just adding some data and retrieving it right from the main() function of the console app. Line <span class="integer">3</span> probably the only line that needs explanation. It<span class="error">’</span>s a call to the <span class="directive">static</span> method SetInitializer() on the <span class="directive">static</span> DbDatabase <span class="type">class</span> <span class="class">of</span> EF. The parameter is a <span class="keyword">new</span> instance of DropCreateDatabaseAlways&lt;MedContext&gt;. Creating <span class="local-variable">this</span> initializer with it<span class="error">’</span>s type parameter set to our MedContext tells the EF engine that it should always drop the database and recreate it, every time the app is run. This is part of EF<span class="error">’</span>s <span class="keyword">new</span> fluent <span class="type">interface</span>. Under <span class="class">almost</span> no circumstance would you actually use <span class="local-variable">this</span> initializer, but it<span class="error">’</span>s handy <span class="keyword">for</span> testing and playing around. This way you can iterate over your model getting a <span class="keyword">new</span> database <span class="keyword">for</span> each run.
1287
1288The rest of the function adds a Prescription object with two FilledScript objects, and saves it in the context. It then loops through the prescriptions and writes some info to the console about each. No rocket science there.
1289
1290
1291<span class="error">#</span><span class="error">#</span> Where did EF Create the Database?
1292
1293
1294One cool thing about EFCodeFirst is that you can leave off pretty much all the configuration information. We didn<span class="error">’</span>t tell EF anything about how or where to create the database. It came up with some reasonable defaults. If you open SSMS and connect to your instance of SQL Express, you can see the database it created. Here<span class="error">’</span>s a DB diagram in SSMS from what EF created:
1295
1296[![image](http:<span class="comment">//blog.efvincent.com/wp-content/uploads/2011/01/image_thumb5.png)](http://blog.efvincent.com/wp-content/uploads/2011/01/image5.png)</span>
1297
1298The database it created (<span class="integer">1</span>) is named according to the context that it stores, MedContext <span class="keyword">for</span> us. It created tables (<span class="integer">2</span> &amp; <span class="integer">3</span>) <span class="keyword">for</span> the entities we created, and to implement the one to many relationship, it added a foreign key to the FilledScripts table linking it to the Prescriptions table. There<span class="error">’</span>s always a DBA to disagree with an auto-generated schema, but in <span class="local-variable">this</span> simple <span class="keyword">case</span>, you must admit there<span class="error">’</span>s not a whole lot you could <span class="keyword">do</span> differently. If we select the records out of the database after our run you get the expected results:
1299
1300[![image](http:<span class="comment">//blog.efvincent.com/wp-content/uploads/2011/01/image_thumb6.png)](http://blog.efvincent.com/wp-content/uploads/2011/01/image6.png)</span>
1301
1302All of <span class="local-variable">this</span> was created by convention, and can also be overridden and specified explicitly using either attributes on the classes that make up the model, or by using EF<span class="error">’</span>s fluent API. This barely scratches the surface, but hopefully gets you interested. I<span class="error">’</span>ll cover EF in more depth in a future post, plus there<span class="error">’</span>s plenty of info out there already.
1303
1304
1305<span class="error">#</span><span class="error">#</span> Back to NuGet <span class="error">–</span> Removing a <span class="predefined-type">Package</span>
1306
1307
1308Ok, we<span class="error">’</span>ve seen how easy it is to add a <span class="keyword">package</span> <span class="namespace">like</span> <span class="namespace">EFCodeFirst</span> (<span class="namespace">and</span> <span class="namespace">how</span> <span class="namespace">cool</span> <span class="namespace">EF</span> <span class="namespace">itself</span> <span class="namespace">is</span>). <span class="namespace">NuGet</span> <span class="namespace">also</span> <span class="namespace">allows</span> <span class="namespace">you</span> <span class="namespace">to</span> <span class="namespace">remove</span> <span class="namespace">a</span> <span class="namespace">package</span> <span class="namespace">easily</span>. <span class="namespace">In</span> <span class="namespace">the</span> <span class="namespace">Package</span> <span class="namespace">Manager</span> <span class="namespace">Console</span> <span class="namespace">window</span>, <span class="namespace">issue</span> <span class="namespace">the</span> <span class="namespace">command</span>:
1309
1310</pre></td>
1311</tr></table>
1312</div>
1313<p>PM&gt; Uninstall-Package EFCodeFirst
1314Successfully removed ‘EFCodeFirst 0.8’ from ConsoleApplication2
1315Successfully uninstalled ‘EFCodeFirst 0.8’
1316~~~</p>
1317
1318<p>NuGet will remove all traces of the package from your project. For EFCodeFirst there’s not much to remove. But other packages are far more complicated, even pulling in prerequisite packages, and modifying the web or app.config. NuGet undoes all these changes when a package is removed.</p>
1319
1320<h2 id="try-it-yourself">Try it yourself!</h2>
1321
1322<p>One great thing about NuGet is how painless it makes trying out new things. You’re not fouling up your precious work machine with a bunch of installations. You can create a quick test project, add a bunch of things you’ve always wanted to try, and just blow it all away when you’re done. No evidence you’ve been <em>learning</em>.</p>
1323
1324<p>Ever want to try Fluent NHibernate but didn’t feel like dealing with all the crap that goes with tracking it down and installing it? How about Ninject, Castle, ELMAH, iTextSharp, Moq, or Prism? They’re all out there. Just NuGet them and start playing / learning.</p>
1325
1326<h2 id="what-else">What else?</h2>
1327
1328<p>I didn’t even mention the wizardy, non-console approach. Right click on your project, and select Add Library Package Reference… and you get a pretty UI that lets you click instead of type. But you’re a coder. You can type.</p>
1329
1330<p>Publishing your own package. You can create any package you want. Perhaps one that pulls in some of your favorite utility classes. Or perhaps you’ve got some corporate libraries and frameworks that you want to be able to incorporate using NuGet. You can create your own private or a corporate NuGet gallery. Or if you have something worth while, publish it up to the official NuGet gallery, it’s own to the public.</p>
1331
1332<p>I hope you’ve found this ramble of mine useful. Search around for more NuGet goodness. There are plenty of bloggers way more interesting then me publishing good information.</p>
1333
1334<p>Happy Coding!</p>
1335]]></content>
1336  </entry>
1337  
1338  <entry>
1339    <title type="html"><![CDATA[Open Source, MVC, MVVM, Entity Framework, NuGet, and More…]]></title>
1340    <link href="http://efvincent.github.io/blog/2011/01/12/open-source-nuget-and-more/"/>
1341    <updated>2011-01-12T08:53:31-05:00</updated>
1342    <id>http://efvincent.github.io/blog/2011/01/12/open-source-nuget-and-more</id>
1343    <content type="html"><![CDATA[<p><strong>Updated</strong>: see the <a href="http://blog.efvincent.com/nuget-geeky-goodness/">NuGet post</a></p>
1344
1345<p>The 2010 PDC was a few months ago. There was plenty of interesting and exciting tech news coming from the conference, but the one session that really sparked something with me was Scott Hanselman’s Presentation, <em><a href="http://www.hanselman.com/blog/PDC10BuildingABlogWithMicrosoftUnnamedPackageOfWebLove.aspx">ASP.NET + Packaging + Open Source = Crazy Delicious</a></em>. Officially, I was mining PDC for Azure and Windows Identity Foundation material for the project I was (and still am) working on. But I <em>love</em> Hanselman’s presentation style; is stuff is always entertaining, stimulating, and <strong>packed</strong> with information. This one was no exception.
1346<!-- more -->
1347In a nutshell, the presentation described several different new and pre-release technologies mashed up together into a single very technical demo. All of these techs are interesting, and over the last couple of months I’ve dived into several, if not all of them and I’ve learned a whole lot. I plan on writing about these techs, mostly because when I do I end up learning a lot in the process. But also so I can promote some of these in some small way. In the coming [random time period] I’ll be posting on:</p>
1348
1349<p><a href="http://nuget.codeplex.com/"><strong>NuGet</strong></a> – <em>a free, open source developer focused package management system for the .NET platform intent on simplifying the process of incorporating third party libraries into a .NET application during development</em>. (that’s quoted from the Codeplex page). It’s way cooler then it sounds… you’ll see.</p>
1350
1351<p><strong><a href="http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-development-with-entity-framework-4.aspx">Entity Framework Magic Unicorn Edition</a></strong> – That’s what Hanselman called it, it’s got one of those painful Microsoft names in real life, but Magic Unicorn sounds better. It’s Entity Framework 4, the Code Only Entity Framework. EF without boxes and lines. It’s super cool and you’ll love it. Trust me.</p>
1352
1353<p><strong><a href="http://weblogs.asp.net/scottgu/archive/2010/12/10/announcing-asp-net-mvc-3-release-candidate-2.aspx">ASP.NET MVC</a> –</strong> Not bleeding edge, it’s been around for a couple of years now. Version 3 is in beta right now, and it’s getting tight. Time to take a look. Even if you’re not going to use it at work next week, it’s important to start thinking about web development done differently then ASP.NET (some would argue, correctly).</p>
1354
1355<p><strong>MVVM Pattern in WPF and Silverlight</strong> – Ok this one is not from Hanselman’s talk, but at the same time I’ve been looking at all the other tech I’ve had to dive into some WPF UI work for a project, and I figured I’d see what all the chatter was about with MVVM. I’ve spent so many years server side, I decided to approach UI with a clean slate.</p>
1356
1357<p>I’m sure there’ll be more. I’m rehabbing from knee replacement surgery, so I have some extra time behind the keyboard. Now – <a href="http://blog.efvincent.com/nuget-geeky-goodness/">on to NuGet</a>.</p>
1358]]></content>
1359  </entry>
1360  
1361  <entry>
1362    <title type="html"><![CDATA[In Car Video–Carolina Motorsports Park]]></title>
1363    <link href="http://efvincent.github.io/blog/2010/08/22/in-car-videocarolina-motorsports-park/"/>
1364    <updated>2010-08-22T19:57:06-04:00</updated>
1365    <id>http://efvincent.github.io/blog/2010/08/22/in-car-videocarolina-motorsports-park</id>
1366    <content type="html"><![CDATA[<p>I’ve just finished uploading a new in-car video from the Hurricane region PCA Driver’s Ed event at Carolina Motorsports Park in South Carolina. View it embedded here, or click the link below the picture to go to Vimeo.</p>
1367
1368<p><a href="http://vimeo.com/14339850">PCA DE CMP August 2010</a> from <a href="http://vimeo.com/efvincent">Eric Vincent</a> on <a href="http://vimeo.com">Vimeo</a>.</p>
1369
1370<p><!-- more --></p>
1371
1372<p>Some notes about the video and data acquisition, for those interested in the gory, geeky details:</p>
1373
1374<p>· Video was shot on a <a href="http://www.amazon.com/gp/product/B002VA57XC">GoPro HD</a>. Last year I tried a ContourHD, but the picture wasn’t quite as good and the sound was terrible – the GoPro does a better job dealing with the wind noise.</p>
1375
1376<p>· The data (speedo, Tach, Throttle position) was collected using a <a href="http://www.amazon.com/PLX-Devices-2340-KIWI-Wifi/dp/B002ICSOTC">PLX 2340 KIWI Wifi</a>. This device interfaces with the OBD-II port of your car (also used by mechanics to read diagnostics), and transmits several different types of metrics in real time over Wi-Fi at with an observed sample rate of about 3 samples / second.</p>
1377
1378<p>· The data was then recorded using <a href="http://www.devtoaster.com/products/rev/">Rev by DevToaster</a> for iPhone. This app is compatible with the PLX, so it can collect data being transmitted by your car. It also adds accelerometer data. There’s GPS too, but the iPhone’s GPS is completely unusable for track purposes. The sampling frequency is too low, and it does some very funky interpolation which in the end renders the GPS data useless. For example, here’s a simple plot (graphed using F#) of one of the runs:</p>
1379
1380<p><a href="http://blog.efvincent.com/wp-content/uploads/2010/08/GPSPlot10081401.png"><img src="http://blog.efvincent.com/wp-content/uploads/2010/08/GPSPlot10081401_thumb.png" alt="GPS Plot 100814-01" /></a></p>
1381
1382<p>· The data is then exported from the phone as an emailed comma separated value file (.csv).</p>
1383
1384<p>· A small program I wrote in F# reads the file and transforms the timestamps in to frame numbers (29.97 frames/second), and the data into either rotational data (for the analog gauges) or simple integers (for the digital gauges).</p>
1385
1386<p>· That data can then be imported into Adobe After Effects. Images of the gauges (drawn from scratch in Adobe Illustrator) are animated into a video overlay using the PLX/Rev data.</p>
1387
1388<p>· Adobe Premiere then takes the gauges and overlays them on top of the video from the track. There’s some fiddling involved to get the gauge data and video in sync. Premiere then renders the video (20 minutes took 6 hours… not sure if I’m doing that right).</p>
1389
1390<p>· That rendered video is HD and is pretty big, so I used Microsoft Expression Encoder (Adobe has an encoder too) to re-encode the video into a smaller MP4 format that Vimeo wanted for uploading.</p>
1391]]></content>
1392  </entry>
1393  
1394  <entry>
1395    <title type="html"><![CDATA[Combinators in C#]]></title>
1396    <link href="http://efvincent.github.io/blog/2010/05/03/combinators-in-c/"/>
1397    <updated>2010-05-03T01:15:43-04:00</updated>
1398    <id>http://efvincent.github.io/blog/2010/05/03/combinators-in-c</id>
1399    <content type="html"><![CDATA[<p>As C# has evolved it has acquired more and more of what some people refer to has functional programming features and constructs. One such concept is the idea that a function is a “first class” value. This is a fancy way of saying that functions are values that can be passed to and returned from other functions. A function that operates on other functions is called a high-order function.</p>
1400
1401<!-- more -->
1402
1403<p>Combinators are high order functions that compose, combine, or otherwise modify functions in useful and interesting ways. These types of operations are not typically seen in C#, but expanding your problem solving toolkit to include these concepts is not only fun and interesting, but can result in new, efficient, robust solutions.</p>
1404
1405<h2 id="the-timer">The Timer</h2>
1406
1407<p>Imagine you’ve got a method that you want to put a stopwatch on. For example, in the following code, you need to see how long it’s taking each download to complete, for debugging information.</p>
1408
1409<div><table class="CodeRay"><tr>
1410  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
1411<a href="#n2" name="n2">2</a>
1412<a href="#n3" name="n3">3</a>
1413<a href="#n4" name="n4">4</a>
1414<a href="#n5" name="n5">5</a>
1415<a href="#n6" name="n6">6</a>
1416<a href="#n7" name="n7">7</a>
1417<a href="#n8" name="n8">8</a>
1418<a href="#n9" name="n9">9</a>
1419<strong><a href="#n10" name="n10">10</a></strong>
1420<a href="#n11" name="n11">11</a>
1421<a href="#n12" name="n12">12</a>
1422<a href="#n13" name="n13">13</a>
1423<a href="#n14" name="n14">14</a>
1424<a href="#n15" name="n15">15</a>
1425<a href="#n16" name="n16">16</a>
1426<a href="#n17" name="n17">17</a>
1427<a href="#n18" name="n18">18</a>
1428<a href="#n19" name="n19">19</a>
1429<strong><a href="#n20" name="n20">20</a></strong>
1430<a href="#n21" name="n21">21</a>
1431<a href="#n22" name="n22">22</a>
1432<a href="#n23" name="n23">23</a>
1433<a href="#n24" name="n24">24</a>
1434<a href="#n25" name="n25">25</a>
1435</pre></td>
1436  <td class="code"><pre><span class="type">class</span> <span class="class">Program</span> {
1437
1438    <span class="directive">static</span> string url;
1439
1440    <span class="directive">static</span> <span class="type">void</span> Main(string<span class="type">[]</span> args) {
1441
1442        url = <span class="string"><span class="delimiter">&quot;</span><span class="content">http://microsoft.com</span><span class="delimiter">&quot;</span></span>;
1443        RetrieveFromWeb();
1444
1445        url = <span class="string"><span class="delimiter">&quot;</span><span class="content">http://amazon.com</span><span class="delimiter">&quot;</span></span>;
1446        RetrieveFromWeb();
1447
1448        url = <span class="string"><span class="delimiter">&quot;</span><span class="content">http://dpreview.com</span><span class="delimiter">&quot;</span></span>;
1449        RetrieveFromWeb();
1450
1451        Console.Write(<span class="string"><span class="delimiter">&quot;</span><span class="content">Press any key...</span><span class="delimiter">&quot;</span></span>);
1452        Console.ReadKey(<span class="predefined-constant">true</span>);
1453    }
1454
1455    <span class="directive">static</span> <span class="type">void</span> RetrieveFromWeb() {
1456        <span class="predefined-type">System</span>.Net.WebClient wc = <span class="keyword">new</span> <span class="predefined-type">System</span>.Net.WebClient();
1457        var s = wc.DownloadString(url);
1458        Console.WriteLine(<span class="string"><span class="delimiter">&quot;</span><span class="content">URL: {0} - string length is {1}</span><span class="delimiter">&quot;</span></span>, url, s.Length);
1459    }
1460}
1461</pre></td>
1462</tr></table>
1463</div>
1464
1465<p>An ugly solution would be to do this.</p>
1466
1467<div><table class="CodeRay"><tr>
1468  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
1469<a href="#n2" name="n2">2</a>
1470<a href="#n3" name="n3">3</a>
1471<a href="#n4" name="n4">4</a>
1472<a href="#n5" name="n5">5</a>
1473<a href="#n6" name="n6">6</a>
1474<a href="#n7" name="n7">7</a>
1475<a href="#n8" name="n8">8</a>
1476<a href="#n9" name="n9">9</a>
1477<strong><a href="#n10" name="n10">10</a></strong>
1478<a href="#n11" name="n11">11</a>
1479<a href="#n12" name="n12">12</a>
1480<a href="#n13" name="n13">13</a>
1481<a href="#n14" name="n14">14</a>
1482<a href="#n15" name="n15">15</a>
1483<a href="#n16" name="n16">16</a>
1484<a href="#n17" name="n17">17</a>
1485<a href="#n18" name="n18">18</a>
1486<a href="#n19" name="n19">19</a>
1487<strong><a href="#n20" name="n20">20</a></strong>
1488<a href="#n21" name="n21">21</a>
1489</pre></td>
1490  <td class="code"><pre><span class="directive">static</span> <span class="type">void</span> Main(string<span class="type">[]</span> args) {
1491    var sw = <span class="keyword">new</span> <span class="predefined-type">System</span>.Diagnostics.Stopwatch();
1492
1493    sw.Start();
1494    url = <span class="string"><span class="delimiter">&quot;</span><span class="content">http://microsoft.com</span><span class="delimiter">&quot;</span></span>;
1495    RetrieveFromWeb();
1496    Console.WriteLine(<span class="string"><span class="delimiter">&quot;</span><span class="content">{0:#,##0}ms</span><span class="delimiter">&quot;</span></span>, sw.ElapsedMilliseconds);
1497
1498    sw.Restart();
1499    url = <span class="string"><span class="delimiter">&quot;</span><span class="content">http://amazon.com</span><span class="delimiter">&quot;</span></span>;
1500    RetrieveFromWeb();
1501    Console.WriteLine(<span class="string"><span class="delimiter">&quot;</span><span class="content">{0:#,##0}ms</span><span class="delimiter">&quot;</span></span>, sw.ElapsedMilliseconds);
1502
1503    sw.Restart();
1504    url = <span class="string"><span class="delimiter">&quot;</span><span class="content">http://dpreview.com</span><span class="delimiter">&quot;</span></span>;
1505    RetrieveFromWeb();
1506    Console.WriteLine(<span class="string"><span class="delimiter">&quot;</span><span class="content">{0:#,##0}ms</span><span class="delimiter">&quot;</span></span>, sw.ElapsedMilliseconds);
1507
1508    Console.Write(<span class="string"><span class="delimiter">&quot;</span><span class="content">Press any key...</span><span class="delimiter">&quot;</span></span>);
1509    Console.ReadKey(<span class="predefined-constant">true</span>);
1510}
1511</pre></td>
1512</tr></table>
1513</div>
1514
1515<p>Try not to get physically ill. You and I both know there’s plenty of code running around in the wild that looks a lot like this. Red flags – you see repeated code – starting, stopping, printing the time. Should we go into the RetrieveFromWeb() method and modify it for timing? Let’s not. Lets try this instead. Step one, let’s define a variable for the method we’re calling. Leaving out the timing code for now, we make this change:</p>
1516
1517<div><table class="CodeRay"><tr>
1518  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
1519<a href="#n2" name="n2">2</a>
1520<a href="#n3" name="n3">3</a>
1521<a href="#n4" name="n4">4</a>
1522<a href="#n5" name="n5">5</a>
1523<a href="#n6" name="n6">6</a>
1524<a href="#n7" name="n7">7</a>
1525<a href="#n8" name="n8">8</a>
1526<a href="#n9" name="n9">9</a>
1527<strong><a href="#n10" name="n10">10</a></strong>
1528<a href="#n11" name="n11">11</a>
1529<a href="#n12" name="n12">12</a>
1530<a href="#n13" name="n13">13</a>
1531<a href="#n14" name="n14">14</a>
1532</pre></td>
1533  <td class="code"><pre><span class="directive">static</span> <span class="type">void</span> Main(string<span class="type">[]</span> args) {&lt;/p&gt;&lt;p&gt;    <span class="comment">// Create a delegate, set it to the method of interest&lt;/p&gt;&lt;p&gt;    Action retrieveFromWeb = RetrieveFromWeb;</span>
1534
1535    url = <span class="string"><span class="delimiter">&quot;</span><span class="content">http://microsoft.com</span><span class="delimiter">&quot;</span></span>;
1536    retrieveFromWeb();
1537
1538    url = <span class="string"><span class="delimiter">&quot;</span><span class="content">http://amazon.com</span><span class="delimiter">&quot;</span></span>;
1539    retrieveFromWeb();
1540
1541    url = <span class="string"><span class="delimiter">&quot;</span><span class="content">http://dpreview.com</span><span class="delimiter">&quot;</span></span>;
1542    retrieveFromWeb();
1543
1544    Console.Write(<span class="string"><span class="delimiter">&quot;</span><span class="content">Press any key...</span><span class="delimiter">&quot;</span></span>);
1545    Console.ReadKey(<span class="predefined-constant">true</span>);
1546}
1547</pre></td>
1548</tr></table>
1549</div>
1550
1551<p>I’ve added a local variable of type <em>Action, _and set it equal to the call to the method _RetrieveFromWeb(),</em> and now we’re calling that method indirectly. It has the same exact effect, the method gets called three times. Only we’ve added a layer of indirection. We do this all the time in OO programming; for example, you might have a Person object, but rather than coding directly to that object, you create an IPerson interface, and code to that, opening up the possibility of mocking the object, decorating it, etc. Similar thing here. Rather than “binding” the call sites directly to the method, we’re binding to a variable that points to the method.</p>
1552
1553<p>We’re doing this because now we’ve got a value that can be altered or augmented to add additional functionality. This is where a combinator comes in. This is a simple timer combinator:</p>
1554
1555<div><table class="CodeRay"><tr>
1556  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
1557<a href="#n2" name="n2">2</a>
1558<a href="#n3" name="n3">3</a>
1559<a href="#n4" name="n4">4</a>
1560<a href="#n5" name="n5">5</a>
1561<a href="#n6" name="n6">6</a>
1562<a href="#n7" name="n7">7</a>
1563<a href="#n8" name="n8">8</a>
1564<a href="#n9" name="n9">9</a>
1565<strong><a href="#n10" name="n10">10</a></strong>
1566<a href="#n11" name="n11">11</a>
1567<a href="#n12" name="n12">12</a>
1568<a href="#n13" name="n13">13</a>
1569<a href="#n14" name="n14">14</a>
1570</pre></td>
1571  <td class="code"><pre><span class="type">class</span> <span class="class">Combinators</span> {
1572
1573    <span class="directive">public</span> <span class="directive">static</span> <span class="predefined-type">Action</span> <span class="predefined-type">Time</span>(<span class="predefined-type">Action</span> a) {
1574        <span class="keyword">return</span> () =&gt; {
1575            var sw = <span class="keyword">new</span> <span class="predefined-type">System</span>.Diagnostics.Stopwatch();
1576            sw.Start();
1577            <span class="keyword">try</span> {
1578                a();
1579            } <span class="keyword">finally</span> {
1580                Console.WriteLine(<span class="string"><span class="delimiter">&quot;</span><span class="content">{0:#,##0}ms</span><span class="delimiter">&quot;</span></span>, sw.ElapsedMilliseconds);
1581            }
1582        };
1583    }
1584}
1585</pre></td>
1586</tr></table>
1587</div>
1588
1589<p>This combinator takes an <em>Action</em> and returns a new action (aka a new function), that has timing included. At line 8 the parameter action is being called, the timing is what’s added. The only change we have to make to the main method is where the delegate is being defined:</p>
1590
1591<div><table class="CodeRay"><tr>
1592  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
1593</pre></td>
1594  <td class="code"><pre><span class="predefined-type">Action</span> retrieveFromWeb = Combinators.Time(RetrieveFromWeb);&lt;/p&gt;
1595</pre></td>
1596</tr></table>
1597</div>
1598
1599<p>The rest of the method stays the same, but now, there’s timing added. This is a super-simple, contrived example, but you should be starting to see what’s possible. Let’s take this a step further. Here’s an example simulating retrieval of information from the database:</p>
1600
1601<div><table class="CodeRay"><tr>
1602  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
1603<a href="#n2" name="n2">2</a>
1604<a href="#n3" name="n3">3</a>
1605<a href="#n4" name="n4">4</a>
1606<a href="#n5" name="n5">5</a>
1607<a href="#n6" name="n6">6</a>
1608<a href="#n7" name="n7">7</a>
1609<a href="#n8" name="n8">8</a>
1610<a href="#n9" name="n9">9</a>
1611<strong><a href="#n10" name="n10">10</a></strong>
1612<a href="#n11" name="n11">11</a>
1613<a href="#n12" name="n12">12</a>
1614<a href="#n13" name="n13">13</a>
1615<a href="#n14" name="n14">14</a>
1616<a href="#n15" name="n15">15</a>
1617<a href="#n16" name="n16">16</a>
1618<a href="#n17" name="n17">17</a>
1619<a href="#n18" name="n18">18</a>
1620<a href="#n19" name="n19">19</a>
1621<strong><a href="#n20" name="n20">20</a></strong>
1622<a href="#n21" name="n21">21</a>
1623<a href="#n22" name="n22">22</a>
1624<a href="#n23" name="n23">23</a>
1625</pre></td>
1626  <td class="code"><pre><span class="directive">static</span> <span class="type">void</span> Main(string<span class="type">[]</span> args) {
1627
1628    Func&lt;string, Guid&gt; lookupUser = LookupUser;
1629
1630    var emails = <span class="keyword">new</span><span class="type">[]</span> {
1631        <span class="string"><span class="delimiter">&quot;</span><span class="content">eric@work.com</span><span class="delimiter">&quot;</span></span>, <span class="string"><span class="delimiter">&quot;</span><span class="content">joel@office.com</span><span class="delimiter">&quot;</span></span>, <span class="string"><span class="delimiter">&quot;</span><span class="content">cole@school.com</span><span class="delimiter">&quot;</span></span>,
1632        <span class="string"><span class="delimiter">&quot;</span><span class="content">karin@job.com</span><span class="delimiter">&quot;</span></span>, <span class="string"><span class="delimiter">&quot;</span><span class="content">haley@home.com</span><span class="delimiter">&quot;</span></span> };
1633
1634    foreach (var em in emails) {
1635        var id = lookupUser(em);
1636        Console.WriteLine(<span class="string"><span class="delimiter">&quot;</span><span class="content">user {0} id = {1}</span><span class="delimiter">&quot;</span></span>, em, id);
1637    }
1638
1639    Console.Write(<span class="string"><span class="delimiter">&quot;</span><span class="content">Press any key...</span><span class="delimiter">&quot;</span></span>);
1640    Console.ReadKey(<span class="predefined-constant">true</span>);
1641}
1642
1643<span class="directive">static</span> Guid LookupUser(string email) {
1644    <span class="comment">// Fake looking up a user in the database</span>
1645    var rnd = <span class="keyword">new</span> <span class="predefined-type">Random</span>(<span class="predefined-type">System</span>.DateTime.Now.Millisecond);
1646    <span class="predefined-type">Thread</span>.Sleep(rnd.Next(<span class="integer">250</span>, <span class="integer">2500</span>));
1647    <span class="keyword">return</span> Guid.NewGuid();
1648}
1649</pre></td>
1650</tr></table>
1651</div>
1652
1653<p>Memoization is the idea that a function can remember the results for given parameters. It’s like caching, but the term is specific to caching function results based on input. Here’s a simple Memoization combinator for C#:</p>
1654
1655<div><table class="CodeRay"><tr>
1656  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
1657<a href="#n2" name="n2">2</a>
1658<a href="#n3" name="n3">3</a>
1659<a href="#n4" name="n4">4</a>
1660<a href="#n5" name="n5">5</a>
1661<a href="#n6" name="n6">6</a>
1662<a href="#n7" name="n7">7</a>
1663<a href="#n8" name="n8">8</a>
1664<a href="#n9" name="n9">9</a>
1665<strong><a href="#n10" name="n10">10</a></strong>
1666<a href="#n11" name="n11">11</a>
1667</pre></td>
1668  <td class="code"><pre><span class="directive">public</span> <span class="directive">static</span> Func&lt;A, B&gt; Memoize&lt;A, B&gt;(Func&lt;A, B&gt; fn) {
1669    var dict = <span class="keyword">new</span> <span class="predefined-type">Dictionary</span>&lt;A, B&gt;();
1670    <span class="keyword">return</span> a =&gt; {
1671        B b = <span class="keyword">default</span>(B);
1672        <span class="keyword">if</span> (!dict.TryGetValue(a, out b)) {
1673            b = fn(a);
1674            dict.Add(a, b);
1675        }
1676        <span class="keyword">return</span> b;
1677    };
1678}
1679</pre></td>
1680</tr></table>
1681</div>
1682
1683<p>It’s simple, but it demonstrates some very useful and interesting functional programming concepts. First, it’s takes and returns Func&lt;A,B&gt;. This is a delegate with a parameter of type A that returns a type B. This will work for effectively any method with that signature. Next point of interest, a dictionary is created, then the lambda is created and returned. The lambda refers to the dictionary defined outside the lambda. It is said that the dictionary is <em>captured</em> in a <em>closure</em>. It’s not important that you remember the terms, but look over the code and see if the concept is clicking for you. This function will return (effectively) a function, the dictionary is <em>captured</em> by that function. Even when the call to Memoize() goes out of scope, the dict variable will still exist in the returned function. Enough talk. We modify the main program just slightly:</p>
1684
1685<div><table class="CodeRay"><tr>
1686  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
1687</pre></td>
1688  <td class="code"><pre>Func&lt;string, Guid&gt; lookupUser = Combinators.Memoize(LookupUser);
1689</pre></td>
1690</tr></table>
1691</div>
1692
1693<p>The Memoize function will create a new function, one that caches results of the LookupUser function <em>automatically.</em> Nothing else has to change in the program to take advantage of this. Want to be sure that it’s actually working? Time it! The non-memoized LookupUser() has a built in Thread.Sleep(2500), and so takes 2.5sec * number of lookups to run. The memoized version will run almost instantly, so we can prove the memoizer is working by timing. The time combinator we created earlier was for timing Actions. I’ve created a overload of the time combinator that has the signature we need - Func&lt;A,B&gt;:</p>
1694
1695<div><table class="CodeRay"><tr>
1696  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
1697<a href="#n2" name="n2">2</a>
1698<a href="#n3" name="n3">3</a>
1699<a href="#n4" name="n4">4</a>
1700<a href="#n5" name="n5">5</a>
1701<a href="#n6" name="n6">6</a>
1702<a href="#n7" name="n7">7</a>
1703<a href="#n8" name="n8">8</a>
1704<a href="#n9" name="n9">9</a>
1705<strong><a href="#n10" name="n10">10</a></strong>
1706<a href="#n11" name="n11">11</a>
1707</pre></td>
1708  <td class="code"><pre><span class="directive">public</span> <span class="directive">static</span> Func&lt;A, B&gt; <span class="predefined-type">Time</span>&lt;A, B&gt;(Func&lt;A, B&gt; fn) {
1709    <span class="keyword">return</span> a =&gt; {
1710        var sw = <span class="keyword">new</span> <span class="predefined-type">System</span>.Diagnostics.Stopwatch();
1711        sw.Start();
1712        <span class="keyword">try</span> {
1713            <span class="keyword">return</span> fn(a);
1714        } <span class="keyword">finally</span> {
1715            Console.WriteLine(<span class="string"><span class="delimiter">&quot;</span><span class="content">{0:#,##0}ms</span><span class="delimiter">&quot;</span></span>, sw.ElapsedMilliseconds);
1716        }
1717    };
1718}
1719</pre></td>
1720</tr></table>
1721</div>
1722
1723<p>and added it to the definition of lookUpUser in the main function</p>
1724
1725<div><table class="CodeRay"><tr>
1726  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
1727<a href="#n2" name="n2">2</a>
1728<a href="#n3" name="n3">3</a>
1729</pre></td>
1730  <td class="code"><pre>Func&lt;string, Guid&gt; lookupUser =
1731  Combinators.Time(
1732      Combinators.Memoize&lt;string,Guid&gt;(LookupUser));&lt;/p&gt;
1733</pre></td>
1734</tr></table>
1735</div>
1736
1737<p>Again without modifying the main code, we’ve augmented the method. Throw in some duplicate email addresses to test it out. The real power of these techniques becomes more evident the more you use them. Functional programming developers have been using these are similar techniques for years, and now with the added ability and flexibility of C#, we can employ these patters as well.</p>
1738]]></content>
1739  </entry>
1740  
1741  <entry>
1742    <title type="html"><![CDATA[Parsing Json Using F#]]></title>
1743    <link href="http://efvincent.github.io/blog/2010/04/27/parsing-json-using-f/"/>
1744    <updated>2010-04-27T14:29:49-04:00</updated>
1745    <id>http://efvincent.github.io/blog/2010/04/27/parsing-json-using-f</id>
1746    <content type="html"><![CDATA[<p>I was in one of those curious moods the other day, and decided to check out the API for the service behind my RSS reader, <a href="http://www.newsgator.com/Individuals/FeedDemon/Default.aspx">FeedDemon</a>. I like this reader because it keeps my subscriptions and read / unread data synchronized across machines and my iPhone via an app called <a href="http://netnewswireapp.com/iphone/">NetNewsWire</a>.</p>
1747
1748<!-- more -->
1749
1750<p>Well it ends up that Google has gobbled up the service and it’s now Google Reader. Fair enough. It means you can also read your RSS feeds on the web at the Google reader site. Whatevs. It also turns out that Google has not publicized the API for that service yet. Yuck. But there are a couple of people out there (like <a href="http://code.google.com/p/pyrfeed/wiki/GoogleReaderAPI">here</a> and <a href="http://blog.martindoms.com/2009/08/15/using-the-google-reader-api-part-1/">here</a>) who have picked it apart using fiddler or some such thing.</p>
1751
1752<p>Well to put this meandering story to an end, I was playing with the API and it seems that some of the methods only return JSON. Others return XML, and others still are switchable. Messy. No wonder it’s not public yet. So that brings me to the point of this post… Parsing Json using F#.</p>
1753
1754<h3 id="why-f">Why F#?</h3>
1755
1756<p>I’ve avoided posting about F# to date, even though I love “playing” with it; I feel that posts about C# are more relevant. People are using F#, but I’ve never had the chance to use it on the job, and I don’t know anyone personally who has either. But since it’s <em>mainstream</em> now, what the heck. Plus parsing is one of those tasks that’s right up F#’s alley. If you haven’t worked with a functional language since college (or ever), give it a whirl. It’s refreshingly different from pure, straight, intensely object oriented thinking.</p>
1757
1758<h3 id="json-briefly">Json, Briefly</h3>
1759
1760<p>Most everyone knows what Json is by now. It’s just a tad more horrifying in real life as the supernatural killer from the Friday the 13th movies with whom it homophonetically shares its name. It’s a text format for representing data that can be evaluated in that wonderfully fast and lose language of the web, JavaScript, resulting in actual JavaScript objects. Read about it from the <a href="http://json.org">experts here</a>. Here’s an example of some awesome <a href="http://json.org">Json</a>:</p>
1761
1762<div><table class="CodeRay"><tr>
1763  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
1764<a href="#n2" name="n2">2</a>
1765<a href="#n3" name="n3">3</a>
1766<a href="#n4" name="n4">4</a>
1767<a href="#n5" name="n5">5</a>
1768<a href="#n6" name="n6">6</a>
1769<a href="#n7" name="n7">7</a>
1770<a href="#n8" name="n8">8</a>
1771<a href="#n9" name="n9">9</a>
1772<strong><a href="#n10" name="n10">10</a></strong>
1773<a href="#n11" name="n11">11</a>
1774<a href="#n12" name="n12">12</a>
1775<a href="#n13" name="n13">13</a>
1776<a href="#n14" name="n14">14</a>
1777<a href="#n15" name="n15">15</a>
1778<a href="#n16" name="n16">16</a>
1779<a href="#n17" name="n17">17</a>
1780<a href="#n18" name="n18">18</a>
1781<a href="#n19" name="n19">19</a>
1782<strong><a href="#n20" name="n20">20</a></strong>
1783<a href="#n21" name="n21">21</a>
1784<a href="#n22" name="n22">22</a>
1785</pre></td>
1786  <td class="code"><pre>{
1787    <span class="key"><span class="delimiter">&quot;</span><span class="content">glossary</span><span class="delimiter">&quot;</span></span>: {
1788        <span class="key"><span class="delimiter">&quot;</span><span class="content">title</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">example glossary</span><span class="delimiter">&quot;</span></span>,
1789        <span class="key"><span class="delimiter">&quot;</span><span class="content">GlossDiv</span><span class="delimiter">&quot;</span></span>: {
1790            <span class="key"><span class="delimiter">&quot;</span><span class="content">title</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">S</span><span class="delimiter">&quot;</span></span>,
1791            <span class="key"><span class="delimiter">&quot;</span><span class="content">GlossList</span><span class="delimiter">&quot;</span></span>: {
1792                <span class="key"><span class="delimiter">&quot;</span><span class="content">GlossEntry</span><span class="delimiter">&quot;</span></span>: {
1793                    <span class="key"><span class="delimiter">&quot;</span><span class="content">ID</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">SGML</span><span class="delimiter">&quot;</span></span>,
1794                    <span class="key"><span class="delimiter">&quot;</span><span class="content">SortAs</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">SGML</span><span class="delimiter">&quot;</span></span>,
1795                    <span class="key"><span class="delimiter">&quot;</span><span class="content">GlossTerm</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">Standard Generalized Markup Language</span><span class="delimiter">&quot;</span></span>,
1796                    <span class="key"><span class="delimiter">&quot;</span><span class="content">Acronym</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">SGML</span><span class="delimiter">&quot;</span></span>,
1797                    <span class="key"><span class="delimiter">&quot;</span><span class="content">Abbrev</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">ISO 8879:1986</span><span class="delimiter">&quot;</span></span>,
1798                    <span class="key"><span class="delimiter">&quot;</span><span class="content">GlossDef</span><span class="delimiter">&quot;</span></span>: {
1799                        <span class="key"><span class="delimiter">&quot;</span><span class="content">para</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">A meta-markup language, used to create markup languages such as DocBook.</span><span class="delimiter">&quot;</span></span>,
1800                        <span class="key"><span class="delimiter">&quot;</span><span class="content">GlossSeeAlso</span><span class="delimiter">&quot;</span></span>: [<span class="string"><span class="delimiter">&quot;</span><span class="content">GML</span><span class="delimiter">&quot;</span></span>, <span class="string"><span class="delimiter">&quot;</span><span class="content">XML</span><span class="delimiter">&quot;</span></span>]
1801                    },
1802                    <span class="key"><span class="delimiter">&quot;</span><span class="content">GlossSee</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">markup</span><span class="delimiter">&quot;</span></span>
1803                }
1804            }
1805        }
1806    }
1807}
1808</pre></td>
1809</tr></table>
1810</div>
1811
1812<h3 id="the-tokenizer">The Tokenizer</h3>
1813
1814<p>I’m no parsing / compiler / language expert, but I do know that tokenizing is the first step. This is when we run through the string and create tokens; identifying the open and close braces, the name value pairs, etc.</p>
1815
1816<p>First thing we want to look at is the Token type, which is a discriminated union. This type defines the <em>logical</em> things that are in the Json string. For example, an open quote, some characters, and a close quote is a string.</p>
1817
1818<div><table class="CodeRay"><tr>
1819  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
1820<a href="#n2" name="n2">2</a>
1821<a href="#n3" name="n3">3</a>
1822<a href="#n4" name="n4">4</a>
1823<a href="#n5" name="n5">5</a>
1824<a href="#n6" name="n6">6</a>
1825</pre></td>
1826  <td class="code"><pre>type <span class="constant">Token</span> =
1827  | <span class="constant">OpenBracket</span> | <span class="constant">CloseBracket</span>
1828  | <span class="constant">OpenArray</span> | <span class="constant">CloseArray</span>
1829  | <span class="constant">Colon</span> | <span class="constant">Comma</span>
1830  | <span class="constant">String</span> of string
1831  | <span class="constant">Number</span> of string
1832</pre></td>
1833</tr></table>
1834</div>
1835
1836<p>For this simple parser, the tokens are as above, open and close bracket and square bracket (aka array), colon, comma, numbers, and strings. This is a good reason to start with Json, it’s painfully simple. The tokenize function below turns the string into a list of tokens.</p>
1837
1838<div><table class="CodeRay"><tr>
1839  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
1840<a href="#n2" name="n2">2</a>
1841<a href="#n3" name="n3">3</a>
1842<a href="#n4" name="n4">4</a>
1843<a href="#n5" name="n5">5</a>
1844<a href="#n6" name="n6">6</a>
1845<a href="#n7" name="n7">7</a>
1846<a href="#n8" name="n8">8</a>
1847<a href="#n9" name="n9">9</a>
1848<strong><a href="#n10" name="n10">10</a></strong>
1849<a href="#n11" name="n11">11</a>
1850<a href="#n12" name="n12">12</a>
1851<a href="#n13" name="n13">13</a>
1852<a href="#n14" name="n14">14</a>
1853<a href="#n15" name="n15">15</a>
1854<a href="#n16" name="n16">16</a>
1855<a href="#n17" name="n17">17</a>
1856<a href="#n18" name="n18">18</a>
1857<a href="#n19" name="n19">19</a>
1858<strong><a href="#n20" name="n20">20</a></strong>
1859<a href="#n21" name="n21">21</a>
1860<a href="#n22" name="n22">22</a>
1861<a href="#n23" name="n23">23</a>
1862<a href="#n24" name="n24">24</a>
1863<a href="#n25" name="n25">25</a>
1864<a href="#n26" name="n26">26</a>
1865<a href="#n27" name="n27">27</a>
1866<a href="#n28" name="n28">28</a>
1867<a href="#n29" name="n29">29</a>
1868<strong><a href="#n30" name="n30">30</a></strong>
1869<a href="#n31" name="n31">31</a>
1870<a href="#n32" name="n32">32</a>
1871<a href="#n33" name="n33">33</a>
1872<a href="#n34" name="n34">34</a>
1873<a href="#n35" name="n35">35</a>
1874<a href="#n36" name="n36">36</a>
1875<a href="#n37" name="n37">37</a>
1876<a href="#n38" name="n38">38</a>
1877<a href="#n39" name="n39">39</a>
1878<strong><a href="#n40" name="n40">40</a></strong>
1879</pre></td>
1880  <td class="code"><pre>let tokenize source =
1881
1882  let rec parseString acc = function
1883    | <span class="string"><span class="delimiter">'</span><span class="char">\\</span><span class="delimiter">'</span></span> :: <span class="string"><span class="delimiter">'</span><span class="content">&quot;</span><span class="delimiter">'</span></span> :: t -&gt; <span class="regexp"><span class="delimiter">/</span><span class="delimiter">/</span></span> escaped quote
1884                          parseString (acc + <span class="string"><span class="delimiter">&quot;</span><span class="char">\&quot;</span><span class="delimiter">&quot;</span></span>) t
1885    | <span class="string"><span class="delimiter">'</span><span class="content">&quot;</span><span class="delimiter">'</span></span> :: t -&gt; <span class="regexp"><span class="delimiter">/</span><span class="delimiter">/</span></span> closing quote terminates
1886                  acc, t
1887    | c :: t -&gt; <span class="regexp"><span class="delimiter">/</span><span class="delimiter">/</span></span> otherwise accumulate
1888                parseString (acc + (c.ToString())) t
1889    | _ -&gt; failwith <span class="string"><span class="delimiter">&quot;</span><span class="content">Malformed string.</span><span class="delimiter">&quot;</span></span>
1890
1891  let rec token acc = function
1892    | (<span class="string"><span class="delimiter">'</span><span class="content">)</span><span class="delimiter">'</span></span> :: _) as t -&gt; acc, t <span class="regexp"><span class="delimiter">/</span><span class="delimiter">/</span></span> closing paren terminates
1893    | (<span class="string"><span class="delimiter">'</span><span class="content">:</span><span class="delimiter">'</span></span> :: _) as t -&gt; acc, t <span class="regexp"><span class="delimiter">/</span><span class="delimiter">/</span></span> colon terminates
1894    | (<span class="string"><span class="delimiter">'</span><span class="content">,</span><span class="delimiter">'</span></span> :: _) as t -&gt; acc, t <span class="regexp"><span class="delimiter">/</span><span class="delimiter">/</span></span> comma terminates
1895    | w :: t <span class="keyword">when</span> <span class="constant">Char</span>.IsWhiteSpace(w) -&gt; acc, t <span class="regexp"><span class="delimiter">/</span><span class="delimiter">/</span></span> whitespace terminates
1896    | [] -&gt; acc, [] /<span class="regexp"><span class="delimiter">/</span><span class="content"> end of list terminates
1897    | c :: t -&gt; token (acc + (c.ToString())) t </span><span class="delimiter">/</span></span>/ otherwise accumulate chars
1898
1899  let rec tokenize<span class="string"><span class="delimiter">'</span><span class="content"> acc = function
1900    | w :: t when Char.IsWhiteSpace(w) -&gt; tokenize</span><span class="delimiter">'</span></span> acc t   <span class="regexp"><span class="delimiter">/</span><span class="delimiter">/</span></span> skip whitespace
1901    | <span class="string"><span class="delimiter">'</span><span class="content">{</span><span class="delimiter">'</span></span> :: t -&gt; tokenize<span class="string"><span class="delimiter">'</span><span class="content"> (OpenBracket :: acc) t
1902    | </span><span class="delimiter">'</span></span>}<span class="string"><span class="delimiter">'</span><span class="content"> :: t -&gt; tokenize</span><span class="delimiter">'</span></span> (<span class="constant">CloseBracket</span> :: acc) t
1903    | <span class="string"><span class="delimiter">'</span><span class="content">[</span><span class="delimiter">'</span></span> :: t -&gt; tokenize<span class="string"><span class="delimiter">'</span><span class="content"> (OpenArray :: acc) t
1904    | </span><span class="delimiter">'</span></span>]<span class="string"><span class="delimiter">'</span><span class="content"> :: t -&gt; tokenize</span><span class="delimiter">'</span></span> (<span class="constant">CloseArray</span> :: acc) t
1905    | <span class="string"><span class="delimiter">'</span><span class="content">:</span><span class="delimiter">'</span></span> :: t -&gt; tokenize<span class="string"><span class="delimiter">'</span><span class="content"> (Colon :: acc) t
1906    | </span><span class="delimiter">'</span></span>,<span class="string"><span class="delimiter">'</span><span class="content"> :: t -&gt; tokenize</span><span class="delimiter">'</span></span> (<span class="constant">Comma</span> :: acc) t
1907    | <span class="string"><span class="delimiter">'</span><span class="content">&quot;</span><span class="delimiter">'</span></span> :: t -&gt; <span class="regexp"><span class="delimiter">/</span><span class="delimiter">/</span></span> start of string
1908      let s, t<span class="string"><span class="delimiter">'</span><span class="content"> = parseString &quot;&quot; t
1909      tokenize</span><span class="delimiter">'</span></span> (<span class="constant">Token</span>.String(s) :: acc) t<span class="string"><span class="delimiter">'</span><span class="content">
1910    | </span><span class="delimiter">'</span></span>-<span class="string"><span class="delimiter">'</span><span class="content"> :: d :: t when Char.IsDigit(d) -&gt; // start of negative number
1911        let n, t</span><span class="delimiter">'</span></span> = token (<span class="string"><span class="delimiter">&quot;</span><span class="content">-</span><span class="delimiter">&quot;</span></span> + d.ToString()) t
1912        tokenize<span class="string"><span class="delimiter">'</span><span class="content"> (Token.Number(n) :: acc) t</span><span class="delimiter">'</span></span>
1913    | <span class="string"><span class="delimiter">'</span><span class="content">+</span><span class="delimiter">'</span></span> :: d :: t | d :: t <span class="keyword">when</span> <span class="constant">Char</span>.IsDigit(d) -&gt; <span class="regexp"><span class="delimiter">/</span><span class="delimiter">/</span></span> start of positive number
1914        let n, t<span class="string"><span class="delimiter">'</span><span class="content"> = token (d.ToString()) t
1915        tokenize</span><span class="delimiter">'</span></span> (<span class="constant">Token</span>.Number(n) :: acc) t<span class="string"><span class="delimiter">'</span><span class="content">
1916    | [] -&gt; List.rev acc // end of list terminates
1917    | _ -&gt; failwith &quot;Tokinzation error&quot;
1918
1919  tokenize</span><span class="delimiter">'</span></span> [] source
1920</pre></td>
1921</tr></table>
1922</div>
1923
1924<p>We don’t have time for the full treatment of F#. If there’s any interest, I’ll post up some tutorials or at least links to some of the very many existing good tutorials out there already. For now, assume we have an understanding of the syntax, and the logic of tokenizing and parsing is what we’re after here.</p>
1925
1926<p>One of the first things we see is that <em>tokenize</em> defines a few functions within the function. Great feature of F#, allowing definitions of inner functions; it allows the coder to partition logic without having function explosion.</p>
1927
1928<p>The driving inner function is <em>tokenize’</em>, whose signature is (Token list –&gt; char list –&gt; Token list). This means it takes a Token list and a char list, and returns a Token list. The first token list (acc) is an accumulator. This list is built up as the procedure calls itself recursively. This is a common pattern in functional languages, to “thread” an accumulator through recursive calls. The second parameter is a char list, or a list of characters from the source string.</p>
1929
1930<p>We don’t see the char list explicitly because of the use of the <em>function</em> keyword at like 20, this keyword means that the last parameter (the char list) is implicitly used in a match statement, the cases of which follow after the function keyword. The syntax would be equivalent to:</p>
1931
1932<div><table class="CodeRay"><tr>
1933  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
1934<a href="#n2" name="n2">2</a>
1935<a href="#n3" name="n3">3</a>
1936<a href="#n4" name="n4">4</a>
1937<a href="#n5" name="n5">5</a>
1938</pre></td>
1939  <td class="code"><pre>let rec tokenize<span class="string"><span class="delimiter">'</span><span class="content"> acc sourceChars =
1940  match sourceChars with
1941  | w :: t when Char.IsWhiteSpace(w) -&gt; tokenize</span><span class="delimiter">'</span></span> acc t   <span class="regexp"><span class="delimiter">/</span><span class="delimiter">/</span></span> skip whitespace
1942  | <span class="string"><span class="delimiter">'</span><span class="content">{</span><span class="delimiter">'</span></span> :: t -&gt; tokenize<span class="string"><span class="delimiter">'</span><span class="content"> (OpenBracket :: acc) t
1943  | </span><span class="delimiter">'</span></span>}<span class="string"><span class="delimiter">'</span><span class="content"> :: t -&gt; tokenize</span><span class="delimiter">'</span></span> (<span class="constant">CloseBracket</span> :: acc) t
1944</pre></td>
1945</tr></table>
1946</div>
1947
1948<p>The idea that the sourceChars variable being passed immediately to the match..with construct is so common in F# that the <em>function</em> keyword is used as a contraction, allowing the elimination of what is an unnecessary variable. In many cases, this construct allows for a one line function definition.</p>
1949
1950<p>Most of the cases in the block matches a character which in turn maps to a token, which is appended to the accumulator (acc : Token list), and passed to a recursive call of tokenize’. This way the tokens are built up (in reverse order) as the string is traversed. This is seen in lines 22-27. Line 21 skips whitespace by calling tokenize’ without adding a token to the accumulator first.</p>
1951
1952<p>Things are a bit more interesting at lines 28, 31, and 34. Line 28 detects the beginning of a string, and starts a new recursive thread with the <em>parseString</em> function, the signature of which is (string –&gt; char list –&gt; string * char list). So the accumulator is a string, the “work” is being done on a char list, to which is passed our source char list, and the return is a tuple of string * char list, which is our parsed string and the rest of the source char list. One (of I’m sure <strong>many</strong>) optimizations that could be made is to use a mutable StringBuilder as the accumulator in parseString.</p>
1953
1954<p>The <em>token</em> function on line 12 does a similar job for non-string literals (numbers in this case, there are no bools in Json).</p>
1955
1956<p>Lastly, line 37 handles the case where we run out of source characters. The Token list we’ve been accumulating is backwards; we’ve been “appending” to the front of the list all this time. This is a common pattern. At the end, we return the reverse of the list. When the Json at the top is put through the tokenizer, we get this:</p>
1957
1958<div><table class="CodeRay"><tr>
1959  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
1960<a href="#n2" name="n2">2</a>
1961<a href="#n3" name="n3">3</a>
1962<a href="#n4" name="n4">4</a>
1963<a href="#n5" name="n5">5</a>
1964<a href="#n6" name="n6">6</a>
1965<a href="#n7" name="n7">7</a>
1966<a href="#n8" name="n8">8</a>
1967<a href="#n9" name="n9">9</a>
1968<strong><a href="#n10" name="n10">10</a></strong>
1969<a href="#n11" name="n11">11</a>
1970<a href="#n12" name="n12">12</a>
1971<a href="#n13" name="n13">13</a>
1972<a href="#n14" name="n14">14</a>
1973<a href="#n15" name="n15">15</a>
1974<a href="#n16" name="n16">16</a>
1975<a href="#n17" name="n17">17</a>
1976<a href="#n18" name="n18">18</a>
1977</pre></td>
1978  <td class="code"><pre>&gt; let tk = tokenize source;;
1979
1980val tk : <span class="constant">Token</span> list =
1981  [<span class="constant">OpenBracket</span>; <span class="constant">String</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">glossary</span><span class="delimiter">&quot;</span></span>; <span class="constant">Colon</span>; <span class="constant">OpenBracket</span>; <span class="constant">String</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">title</span><span class="delimiter">&quot;</span></span>; <span class="constant">Colon</span>;
1982   <span class="constant">String</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">example glossary</span><span class="delimiter">&quot;</span></span>; <span class="constant">Comma</span>; <span class="constant">String</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">GlossDiv</span><span class="delimiter">&quot;</span></span>; <span class="constant">Colon</span>; <span class="constant">OpenBracket</span>;
1983   <span class="constant">String</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">title</span><span class="delimiter">&quot;</span></span>; <span class="constant">Colon</span>; <span class="constant">String</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">S</span><span class="delimiter">&quot;</span></span>; <span class="constant">Comma</span>; <span class="constant">String</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">GlossList</span><span class="delimiter">&quot;</span></span>; <span class="constant">Colon</span>;
1984   <span class="constant">OpenBracket</span>; <span class="constant">String</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">GlossEntry</span><span class="delimiter">&quot;</span></span>; <span class="constant">Colon</span>; <span class="constant">OpenBracket</span>; <span class="constant">String</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">ID</span><span class="delimiter">&quot;</span></span>; <span class="constant">Colon</span>;
1985   <span class="constant">String</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">SGML</span><span class="delimiter">&quot;</span></span>; <span class="constant">Comma</span>; <span class="constant">String</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">SortAs</span><span class="delimiter">&quot;</span></span>; <span class="constant">Colon</span>; <span class="constant">String</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">SGML</span><span class="delimiter">&quot;</span></span>; <span class="constant">Comma</span>;
1986   <span class="constant">String</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">GlossTerm</span><span class="delimiter">&quot;</span></span>; <span class="constant">Colon</span>; <span class="constant">String</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">Standard Generalized Markup Language</span><span class="delimiter">&quot;</span></span>;
1987   <span class="constant">Comma</span>; <span class="constant">String</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">Acronym</span><span class="delimiter">&quot;</span></span>; <span class="constant">Colon</span>; <span class="constant">String</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">SGML</span><span class="delimiter">&quot;</span></span>; <span class="constant">Comma</span>; <span class="constant">String</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">Abbrev</span><span class="delimiter">&quot;</span></span>;
1988   <span class="constant">Colon</span>; <span class="constant">String</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">ISO 8879:1986</span><span class="delimiter">&quot;</span></span>; <span class="constant">Comma</span>; <span class="constant">String</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">GlossDef</span><span class="delimiter">&quot;</span></span>; <span class="constant">Colon</span>; <span class="constant">OpenBracket</span>;
1989   <span class="constant">String</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">para</span><span class="delimiter">&quot;</span></span>; <span class="constant">Colon</span>;
1990   <span class="constant">String</span>
1991     <span class="string"><span class="delimiter">&quot;</span><span class="content">A meta-markup language, used to create markup languages such as DocBook.</span><span class="delimiter">&quot;</span></span>;
1992   <span class="constant">Comma</span>; <span class="constant">String</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">GlossSeeAlso</span><span class="delimiter">&quot;</span></span>; <span class="constant">Colon</span>; <span class="constant">OpenArray</span>; <span class="constant">String</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">GML</span><span class="delimiter">&quot;</span></span>; <span class="constant">Comma</span>;
1993   <span class="constant">String</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">XML</span><span class="delimiter">&quot;</span></span>; <span class="constant">CloseArray</span>; <span class="constant">CloseBracket</span>; <span class="constant">Comma</span>; <span class="constant">String</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">GlossSee</span><span class="delimiter">&quot;</span></span>; <span class="constant">Colon</span>;
1994   <span class="constant">String</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">markup</span><span class="delimiter">&quot;</span></span>; <span class="constant">CloseBracket</span>; <span class="constant">CloseBracket</span>; <span class="constant">CloseBracket</span>; <span class="constant">CloseBracket</span>;
1995   <span class="constant">CloseBracket</span>]
1996</pre></td>
1997</tr></table>
1998</div>
1999
2000<p>This list of tokens is an intermediate step. From here, we could go in several directions. For my purposes, I wanted to see it as XML. To get there, I created a parser that takes the token list and returns an XElement.</p>
2001
2002<div><table class="CodeRay"><tr>
2003  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
2004<a href="#n2" name="n2">2</a>
2005<a href="#n3" name="n3">3</a>
2006<a href="#n4" name="n4">4</a>
2007<a href="#n5" name="n5">5</a>
2008<a href="#n6" name="n6">6</a>
2009<a href="#n7" name="n7">7</a>
2010<a href="#n8" name="n8">8</a>
2011<a href="#n9" name="n9">9</a>
2012<strong><a href="#n10" name="n10">10</a></strong>
2013<a href="#n11" name="n11">11</a>
2014<a href="#n12" name="n12">12</a>
2015<a href="#n13" name="n13">13</a>
2016<a href="#n14" name="n14">14</a>
2017<a href="#n15" name="n15">15</a>
2018<a href="#n16" name="n16">16</a>
2019<a href="#n17" name="n17">17</a>
2020<a href="#n18" name="n18">18</a>
2021<a href="#n19" name="n19">19</a>
2022<strong><a href="#n20" name="n20">20</a></strong>
2023<a href="#n21" name="n21">21</a>
2024<a href="#n22" name="n22">22</a>
2025<a href="#n23" name="n23">23</a>
2026<a href="#n24" name="n24">24</a>
2027<a href="#n25" name="n25">25</a>
2028<a href="#n26" name="n26">26</a>
2029<a href="#n27" name="n27">27</a>
2030<a href="#n28" name="n28">28</a>
2031<a href="#n29" name="n29">29</a>
2032<strong><a href="#n30" name="n30">30</a></strong>
2033<a href="#n31" name="n31">31</a>
2034<a href="#n32" name="n32">32</a>
2035<a href="#n33" name="n33">33</a>
2036<a href="#n34" name="n34">34</a>
2037<a href="#n35" name="n35">35</a>
2038<a href="#n36" name="n36">36</a>
2039<a href="#n37" name="n37">37</a>
2040<a href="#n38" name="n38">38</a>
2041<a href="#n39" name="n39">39</a>
2042<strong><a href="#n40" name="n40">40</a></strong>
2043<a href="#n41" name="n41">41</a>
2044<a href="#n42" name="n42">42</a>
2045<a href="#n43" name="n43">43</a>
2046<a href="#n44" name="n44">44</a>
2047<a href="#n45" name="n45">45</a>
2048<a href="#n46" name="n46">46</a>
2049<a href="#n47" name="n47">47</a>
2050<a href="#n48" name="n48">48</a>
2051<a href="#n49" name="n49">49</a>
2052<strong><a href="#n50" name="n50">50</a></strong>
2053<a href="#n51" name="n51">51</a>
2054<a href="#n52" name="n52">52</a>
2055<a href="#n53" name="n53">53</a>
2056<a href="#n54" name="n54">54</a>
2057<a href="#n55" name="n55">55</a>
2058<a href="#n56" name="n56">56</a>
2059<a href="#n57" name="n57">57</a>
2060<a href="#n58" name="n58">58</a>
2061<a href="#n59" name="n59">59</a>
2062<strong><a href="#n60" name="n60">60</a></strong>
2063</pre></td>
2064  <td class="code"><pre>let parseToXml source =
2065let map = function
2066  | <span class="constant">Token</span>.Number(n) -&gt; n.ToString()
2067  | <span class="constant">Token</span>.String(x) -&gt; x
2068  | v -&gt; failwith <span class="string"><span class="delimiter">&quot;</span><span class="content">Syntax Error, unrecognized token in map()</span><span class="delimiter">&quot;</span></span>
2069
2070let rec parseValue (<span class="key">acc</span>:<span class="constant">XElement</span>) = function
2071  | <span class="constant">OpenBracket</span> :: t -&gt;
2072    let newElement, t<span class="string"><span class="delimiter">'</span><span class="content"> = parseElement acc t
2073    newElement, t</span><span class="delimiter">'</span></span>
2074  | <span class="constant">OpenArray</span> :: t -&gt;
2075    let name = acc.Name.LocalName
2076    <span class="keyword">if</span> name.EndsWith(<span class="string"><span class="delimiter">&quot;</span><span class="content">ies</span><span class="delimiter">&quot;</span></span>) &amp;&amp; name.Length &gt; <span class="integer">3</span> <span class="keyword">then</span>
2077      let childName = name.Substring(<span class="integer">0</span>, name.Length - <span class="integer">3</span>) + <span class="string"><span class="delimiter">&quot;</span><span class="content">y</span><span class="delimiter">&quot;</span></span>
2078      let newListElement, t<span class="string"><span class="delimiter">'</span><span class="content"> = parseArray childName acc t
2079      newListElement, t</span><span class="delimiter">'</span></span>
2080    elif name.EndsWith(<span class="string"><span class="delimiter">&quot;</span><span class="content">s</span><span class="delimiter">&quot;</span></span>) &amp;&amp; name.Length &gt; <span class="integer">1</span> <span class="keyword">then</span>
2081      let childName = name.Substring(<span class="integer">0</span>, name.Length - <span class="integer">1</span>)
2082      let newListElement, t<span class="string"><span class="delimiter">'</span><span class="content"> = parseArray childName acc t
2083      newListElement, t</span><span class="delimiter">'</span></span>
2084    <span class="keyword">else</span>
2085      let childName = acc.Name.LocalName
2086      acc.Name &lt;- <span class="constant">XName</span>.Get(childName + <span class="string"><span class="delimiter">&quot;</span><span class="content">s</span><span class="delimiter">&quot;</span></span>)
2087      let newListElement, t<span class="string"><span class="delimiter">'</span><span class="content"> = parseArray childName acc t
2088      newListElement, t</span><span class="delimiter">'</span></span>
2089  | h :: t -&gt;
2090    acc.Value &lt;- map(h)
2091    acc, t
2092  | _ -&gt; failwith <span class="string"><span class="delimiter">&quot;</span><span class="content">bad value</span><span class="delimiter">&quot;</span></span>
2093
2094<span class="keyword">and</span> parseArray name acc = function
2095  | <span class="constant">Comma</span> :: t -&gt; parseArray name acc t
2096  | <span class="constant">CloseArray</span> :: t -&gt;  acc, t
2097  | t -&gt;
2098    let newElement = XElement(<span class="constant">XName</span>.Get(name))
2099    let acc<span class="string"><span class="delimiter">'</span><span class="content">, t</span><span class="delimiter">'</span></span> = parseValue newElement t
2100    acc.Add(acc<span class="string"><span class="delimiter">'</span><span class="content">)
2101    parseArray name acc t</span><span class="delimiter">'</span></span>
2102
2103<span class="keyword">and</span> parseElement (acc : <span class="constant">XElement</span>) = function
2104  | <span class="constant">Comma</span> :: t -&gt;
2105    parseElement acc t
2106  | <span class="constant">Token</span>.String(n) :: <span class="constant">Colon</span> :: t -&gt;
2107    let newElement = XElement(<span class="constant">XName</span>.Get(n))
2108    let v, t<span class="string"><span class="delimiter">'</span><span class="content"> = parseValue newElement t
2109    acc.Add(v)
2110    parseElement acc t</span><span class="delimiter">'</span></span>
2111  | <span class="constant">CloseBracket</span> :: t -&gt;
2112    acc, t
2113  | _ -&gt; failwith <span class="string"><span class="delimiter">&quot;</span><span class="content">Malformed JSON object</span><span class="delimiter">&quot;</span></span>
2114
2115let root = XElement(<span class="constant">XName</span>.Get(<span class="string"><span class="delimiter">&quot;</span><span class="content">root</span><span class="delimiter">&quot;</span></span>))
2116let tokens = tokenize source
2117
2118match tokens with
2119  | <span class="constant">OpenBracket</span> :: t -&gt;
2120    let result, t<span class="string"><span class="delimiter">'</span><span class="content"> = parseElement root t
2121    result
2122  | _ -&gt; failwith &quot;Json did not begin with an object&quot;
2123</span><span class="delimiter">'</span></span>
2124</pre></td>
2125</tr></table>
2126</div>
2127
2128<p>There is still syntax checking happening in the parse step. The tokenizer would have found illegal tokens, but the parse function will find illegal Json structure. It works in a similar way to the tokenizer, except instead of a raw stream of characters, we’ve got a stream of tokens, which is examined one by one and passed to a set of recursive functions which accumulates the XML, in this case as an XElement.</p>
2129
2130<p>parseToXml defines inner functions <em>map</em>, <em>parseValue</em>, <em>parseArray</em>, and <em>parseElement.</em> It then gets to work by creating a root XElement, and getting the Token list. Json should start with an OpenBracket token. Anything else and we failwith an error (like C#’s throw). When we find that OpenBracket, the recursion begins with a call to parseElement. The root XElement serves as the accumulator, and the Token list is the “work” to be done.</p>
2131
2132<p>You should be able to see what’s happening if you’re somewhat comfortable with F#. The parseValue function does some extra work to wrap arrays in nodes where the singularity / plurality of the node makes it read a bit better (in English, most of the time). The other point of interest is that the accumulator is a mutable object in parseToXml, unlike the Token list was in tokenize. At lines 37 and 46, the newly created elements are added to the accumulator using the Add(XElement) method, which mutates the accumulator and keeps using it. This is a departure from “purer” functional techniques, but that’s what’s cool about F#, you can make those departures where it makes sense. In this case, leveraging the XElement class of the .NET framework was worth it. Consuming this class from C# is that much easier and more intuitive.</p>
2133
2134<p>After all is said and done, this is the XML that is emitted.</p>
2135
2136<div><table class="CodeRay"><tr>
2137  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
2138<a href="#n2" name="n2">2</a>
2139<a href="#n3" name="n3">3</a>
2140<a href="#n4" name="n4">4</a>
2141<a href="#n5" name="n5">5</a>
2142<a href="#n6" name="n6">6</a>
2143<a href="#n7" name="n7">7</a>
2144<a href="#n8" name="n8">8</a>
2145<a href="#n9" name="n9">9</a>
2146<strong><a href="#n10" name="n10">10</a></strong>
2147<a href="#n11" name="n11">11</a>
2148<a href="#n12" name="n12">12</a>
2149<a href="#n13" name="n13">13</a>
2150<a href="#n14" name="n14">14</a>
2151<a href="#n15" name="n15">15</a>
2152<a href="#n16" name="n16">16</a>
2153<a href="#n17" name="n17">17</a>
2154<a href="#n18" name="n18">18</a>
2155<a href="#n19" name="n19">19</a>
2156<strong><a href="#n20" name="n20">20</a></strong>
2157<a href="#n21" name="n21">21</a>
2158<a href="#n22" name="n22">22</a>
2159<a href="#n23" name="n23">23</a>
2160<a href="#n24" name="n24">24</a>
2161<a href="#n25" name="n25">25</a>
2162</pre></td>
2163  <td class="code"><pre><span class="tag">&lt;root&gt;</span>
2164  <span class="tag">&lt;glossary&gt;</span>
2165    <span class="tag">&lt;title&gt;</span>example glossary<span class="tag">&lt;/title&gt;</span>
2166    <span class="tag">&lt;GlossDiv&gt;</span>
2167      <span class="tag">&lt;title&gt;</span>S<span class="tag">&lt;/title&gt;</span>
2168      <span class="tag">&lt;GlossList&gt;</span>
2169        <span class="tag">&lt;GlossEntry&gt;</span>
2170          <span class="tag">&lt;ID&gt;</span>SGML<span class="tag">&lt;/ID&gt;</span>
2171          <span class="tag">&lt;SortAs&gt;</span>SGML<span class="tag">&lt;/SortAs&gt;</span>
2172          <span class="tag">&lt;GlossTerm&gt;</span>Standard Generalized Markup Language<span class="tag">&lt;/GlossTerm&gt;</span>
2173          <span class="tag">&lt;Acronym&gt;</span>SGML<span class="tag">&lt;/Acronym&gt;</span>
2174          <span class="tag">&lt;Abbrev&gt;</span>ISO 8879:1986<span class="tag">&lt;/Abbrev&gt;</span>
2175          <span class="tag">&lt;GlossDef&gt;</span>
2176            <span class="tag">&lt;para&gt;</span>A meta-markup language, used to create markup languages such as DocBook.<span class="tag">&lt;/para&gt;</span>
2177            <span class="tag">&lt;GlossSeeAlsos&gt;</span>
2178              <span class="tag">&lt;GlossSeeAlso&gt;</span>GML<span class="tag">&lt;/GlossSeeAlso&gt;</span>
2179              <span class="tag">&lt;GlossSeeAlso&gt;</span>XML<span class="tag">&lt;/GlossSeeAlso&gt;</span>
2180            <span class="tag">&lt;/GlossSeeAlsos&gt;</span>
2181          <span class="tag">&lt;/GlossDef&gt;</span>
2182          <span class="tag">&lt;GlossSee&gt;</span>markup<span class="tag">&lt;/GlossSee&gt;</span>
2183        <span class="tag">&lt;/GlossEntry&gt;</span>
2184      <span class="tag">&lt;/GlossList&gt;</span>
2185    <span class="tag">&lt;/GlossDiv&gt;</span>
2186  <span class="tag">&lt;/glossary&gt;</span>
2187<span class="tag">&lt;/root&gt;</span>
2188</pre></td>
2189</tr></table>
2190</div>
2191
2192<p>It isn’t the most sophisticated, performant, or I’m sure accurate Json parser out there. But it does the trick for my immediate need, is a good starting point for more sophistication later if needed, and was an excellent exercise in parsing and F#. It was fun to write, and hopefully it stimulates some curiosities. Let me know if you’ve got any questions or comments.</p>
2193]]></content>
2194  </entry>
2195  
2196  <entry>
2197    <title type="html"><![CDATA[Roll Your Own Language Constructs]]></title>
2198    <link href="http://efvincent.github.io/blog/2010/02/02/roll-your-own-language-constructs/"/>
2199    <updated>2010-02-02T23:24:18-05:00</updated>
2200    <id>http://efvincent.github.io/blog/2010/02/02/roll-your-own-language-constructs</id>
2201    <content type="html"><![CDATA[<p>My last couple of blog entries were ostensibly about lambda functions (<a href="http://blog.efvincent.com/c-nuts-and-bolts-lambdas/">last one</a>, <a href="http://blog.efvincent.com/c-nuts-and-bolts-lambdas02">one before</a>). With these ideas, or a general comfort level with lambdas and the Action&lt;&gt; and Func&lt;&gt; delegate types in the back of your mind, consider this.</p>
2202
2203<!-- more -->
2204
2205<p>I was working on a project where the development team was instructed to implement a retry logic into our data access layer. In other words, if we experience database connectivity problems, retry the operation as seems reasonable.</p>
2206
2207<p>Here’s some code we’re going to use as a basis for the conversation:</p>
2208
2209<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
2210<span class="line-number">2</span>
2211<span class="line-number">3</span>
2212<span class="line-number">4</span>
2213<span class="line-number">5</span>
2214<span class="line-number">6</span>
2215<span class="line-number">7</span>
2216<span class="line-number">8</span>
2217<span class="line-number">9</span>
2218<span class="line-number">10</span>
2219<span class="line-number">11</span>
2220<span class="line-number">12</span>
2221<span class="line-number">13</span>
2222<span class="line-number">14</span>
2223<span class="line-number">15</span>
2224<span class="line-number">16</span>
2225<span class="line-number">17</span>
2226<span class="line-number">18</span>
2227<span class="line-number">19</span>
2228<span class="line-number">20</span>
2229<span class="line-number">21</span>
2230<span class="line-number">22</span>
2231<span class="line-number">23</span>
2232<span class="line-number">24</span>
2233<span class="line-number">25</span>
2234<span class="line-number">26</span>
2235<span class="line-number">27</span>
2236<span class="line-number">28</span>
2237<span class="line-number">29</span>
2238<span class="line-number">30</span>
2239<span class="line-number">31</span>
2240<span class="line-number">32</span>
2241</pre></td><td class="code"><pre><code class="C#"><span class="line"><span class="k">class</span> <span class="nc">Program</span> <span class="p">{</span>
2242</span><span class="line">    <span class="k">static</span> <span class="k">void</span> <span class="nf">Main</span><span class="p">(</span><span class="kt">string</span><span class="p">[]</span> <span class="n">args</span><span class="p">)</span> <span class="p">{</span>
2243</span><span class="line">
2244</span><span class="line">        <span class="k">try</span> <span class="p">{</span>
2245</span><span class="line">            <span class="n">Retry01</span><span class="p">();</span>
2246</span><span class="line">        <span class="p">}</span> <span class="k">catch</span> <span class="p">(</span><span class="n">Exception</span> <span class="n">ex</span><span class="p">)</span> <span class="p">{</span>
2247</span><span class="line">            <span class="n">Console</span><span class="p">.</span><span class="n">WriteLine</span><span class="p">(</span><span class="n">ex</span><span class="p">.</span><span class="n">Message</span><span class="p">);</span>
2248</span><span class="line">        <span class="p">}</span>
2249</span><span class="line">        <span class="n">Console</span><span class="p">.</span><span class="n">Write</span><span class="p">(</span><span class="s">&quot;Press any key...&quot;</span><span class="p">);</span>
2250</span><span class="line">        <span class="n">Console</span><span class="p">.</span><span class="n">ReadKey</span><span class="p">(</span><span class="k">true</span><span class="p">);</span>
2251</span><span class="line">    <span class="p">}</span>
2252</span><span class="line">
2253</span><span class="line">    <span class="k">static</span> <span class="k">void</span> <span class="nf">Retry01</span><span class="p">()</span> <span class="p">{</span>
2254</span><span class="line">        <span class="c1">// Iterate through the directories on the C:\ drive</span>
2255</span><span class="line">        <span class="k">foreach</span> <span class="p">(</span><span class="kt">var</span> <span class="n">dir</span> <span class="k">in</span> <span class="n">Directory</span><span class="p">.</span><span class="n">EnumerateDirectories</span><span class="p">(</span><span class="s">&quot;C:\\&quot;</span><span class="p">))</span> <span class="p">{</span>
2256</span><span class="line">            <span class="n">OccasionallyThrow</span><span class="p">(</span><span class="m">0.1d</span><span class="p">);</span>
2257</span><span class="line">            <span class="n">Console</span><span class="p">.</span><span class="n">WriteLine</span><span class="p">(</span><span class="s">&quot;dir: {0}&quot;</span><span class="p">,</span> <span class="n">dir</span><span class="p">);</span>
2258</span><span class="line">        <span class="p">}</span>
2259</span><span class="line">    <span class="p">}</span>
2260</span><span class="line">
2261</span><span class="line">    <span class="k">static</span> <span class="n">Random</span> <span class="n">_rnd</span> <span class="p">=</span> <span class="k">new</span> <span class="n">Random</span><span class="p">(</span><span class="n">DateTime</span><span class="p">.</span><span class="n">Now</span><span class="p">.</span><span class="n">Millisecond</span><span class="p">);</span>
2262</span><span class="line">    <span class="c1">/// &lt;summary&gt;</span>
2263</span><span class="line">    <span class="c1">/// Occasionally throw an exception</span>
2264</span><span class="line">    <span class="c1">/// &lt;/summary&gt;</span>
2265</span><span class="line">    <span class="c1">/// &lt;param name=&quot;freq&quot;&gt;Percentage (as a fraction) of the time to</span>
2266</span><span class="line">    <span class="c1">/// throw an exception. Uses a random number generator, so</span>
2267</span><span class="line">    <span class="c1">/// this is not an exact measure&lt;/param&gt;</span>
2268</span><span class="line">    <span class="k">static</span> <span class="k">void</span> <span class="nf">OccasionallyThrow</span><span class="p">(</span><span class="kt">double</span> <span class="n">freq</span><span class="p">)</span> <span class="p">{</span>
2269</span><span class="line">        <span class="k">if</span> <span class="p">(</span><span class="n">_rnd</span><span class="p">.</span><span class="n">NextDouble</span><span class="p">()</span> <span class="p">&lt;=</span> <span class="n">freq</span><span class="p">)</span>
2270</span><span class="line">            <span class="k">throw</span> <span class="k">new</span> <span class="nf">InvalidOperationException</span><span class="p">(</span><span class="s">&quot;An occasional exception&quot;</span><span class="p">);</span>
2271</span><span class="line">    <span class="p">}</span>
2272</span><span class="line"><span class="p">}</span>
2273</span></code></pre></td></tr></table></div></figure></notextile></div>
2274
2275<p>We’ve got a method, <code>OccasionallyThrow(freq)</code> that, occasionally throws an exception (duh). We’ve got a method that iterates through directories on the C:\ drive and pretty much can’t get through it without throwing.</p>
2276
2277<p>So first pass, let’s fix <code>Retry01()</code> so it actually retries.</p>
2278
2279<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
2280<span class="line-number">2</span>
2281<span class="line-number">3</span>
2282<span class="line-number">4</span>
2283<span class="line-number">5</span>
2284<span class="line-number">6</span>
2285<span class="line-number">7</span>
2286<span class="line-number">8</span>
2287<span class="line-number">9</span>
2288<span class="line-number">10</span>
2289<span class="line-number">11</span>
2290<span class="line-number">12</span>
2291<span class="line-number">13</span>
2292<span class="line-number">14</span>
2293<span class="line-number">15</span>
2294<span class="line-number">16</span>
2295<span class="line-number">17</span>
2296<span class="line-number">18</span>
2297<span class="line-number">19</span>
2298<span class="line-number">20</span>
2299<span class="line-number">21</span>
2300<span class="line-number">22</span>
2301<span class="line-number">23</span>
2302<span class="line-number">24</span>
2303<span class="line-number">25</span>
2304<span class="line-number">26</span>
2305<span class="line-number">27</span>
2306<span class="line-number">28</span>
2307<span class="line-number">29</span>
2308<span class="line-number">30</span>
2309</pre></td><td class="code"><pre><code class="C#"><span class="line"><span class="k">static</span> <span class="k">void</span> <span class="nf">Retry01</span><span class="p">()</span> <span class="p">{</span>
2310</span><span class="line">    <span class="c1">// Iterate through the directories on the C:\ drive</span>
2311</span><span class="line">    <span class="k">foreach</span> <span class="p">(</span><span class="kt">var</span> <span class="n">dir</span> <span class="k">in</span> <span class="n">Directory</span><span class="p">.</span><span class="n">EnumerateDirectories</span><span class="p">(</span><span class="s">&quot;C:\\&quot;</span><span class="p">))</span> <span class="p">{</span>
2312</span><span class="line">
2313</span><span class="line">        <span class="kt">int</span> <span class="n">retryCount</span> <span class="p">=</span> <span class="m">0</span><span class="p">;</span>
2314</span><span class="line">        <span class="kt">bool</span> <span class="n">done</span> <span class="p">=</span> <span class="k">false</span><span class="p">;</span>
2315</span><span class="line">        <span class="k">do</span> <span class="p">{</span>
2316</span><span class="line">            <span class="k">try</span> <span class="p">{</span>
2317</span><span class="line">
2318</span><span class="line">                <span class="n">OccasionallyThrow</span><span class="p">(</span><span class="m">0.25d</span><span class="p">);</span>
2319</span><span class="line">                <span class="n">Console</span><span class="p">.</span><span class="n">WriteLine</span><span class="p">(</span><span class="s">&quot;dir: {0}&quot;</span><span class="p">,</span> <span class="n">dir</span><span class="p">);</span>
2320</span><span class="line">
2321</span><span class="line">                <span class="n">done</span> <span class="p">=</span> <span class="k">true</span><span class="p">;</span>
2322</span><span class="line">
2323</span><span class="line">            <span class="p">}</span> <span class="k">catch</span> <span class="p">(</span><span class="n">Exception</span> <span class="n">ex</span><span class="p">)</span> <span class="p">{</span>
2324</span><span class="line">                <span class="k">if</span> <span class="p">(</span><span class="n">ex</span> <span class="k">is</span> <span class="n">InvalidOperationException</span><span class="p">)</span> <span class="p">{</span>
2325</span><span class="line">                    <span class="k">if</span> <span class="p">(</span><span class="n">retryCount</span><span class="p">++</span> <span class="p">&lt;</span> <span class="m">3</span><span class="p">)</span> <span class="p">{</span>
2326</span><span class="line">                        <span class="c1">// can try again. Under the limit</span>
2327</span><span class="line">                        <span class="n">Console</span><span class="p">.</span><span class="n">WriteLine</span><span class="p">(</span><span class="s">&quot;Caught exception, retry #{0}&quot;</span><span class="p">,</span> <span class="n">retryCount</span><span class="p">);</span>
2328</span><span class="line">                        <span class="n">done</span> <span class="p">=</span> <span class="k">false</span><span class="p">;</span>
2329</span><span class="line">                    <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
2330</span><span class="line">                        <span class="c1">// retried too many times already</span>
2331</span><span class="line">                        <span class="n">Console</span><span class="p">.</span><span class="n">WriteLine</span><span class="p">(</span><span class="s">&quot;Exceeded retry count. Throwing.&quot;</span><span class="p">);</span>
2332</span><span class="line">                        <span class="k">throw</span><span class="p">;</span>
2333</span><span class="line">                    <span class="p">}</span>
2334</span><span class="line">                <span class="p">}</span>
2335</span><span class="line">            <span class="p">}</span>
2336</span><span class="line">        <span class="p">}</span> <span class="k">while</span> <span class="p">(!</span><span class="n">done</span><span class="p">);</span>
2337</span><span class="line">    <span class="p">}</span>
2338</span><span class="line"><span class="p">}</span>
2339</span></code></pre></td></tr></table></div></figure></notextile></div>
2340
2341<p>Yikes. That’s a bunch of code. Assuming we want to make this construct generally available, some refactoring is in order. Worse, the boilerplate code that manages retries <em>surrounds</em> the code we want to apply it to, at lines 10 and 11 of a 30 line block of code. This is a similar problem to the one described in <a href="http://blog.efvincent.com/c-nuts-and-bolts-lambdas02">my last post</a>, so you may see where this is going. Here’s one approach to solving the problem.</p>
2342
2343<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
2344<span class="line-number">2</span>
2345<span class="line-number">3</span>
2346<span class="line-number">4</span>
2347<span class="line-number">5</span>
2348<span class="line-number">6</span>
2349<span class="line-number">7</span>
2350<span class="line-number">8</span>
2351<span class="line-number">9</span>
2352<span class="line-number">10</span>
2353<span class="line-number">11</span>
2354<span class="line-number">12</span>
2355<span class="line-number">13</span>
2356<span class="line-number">14</span>
2357<span class="line-number">15</span>
2358<span class="line-number">16</span>
2359<span class="line-number">17</span>
2360<span class="line-number">18</span>
2361<span class="line-number">19</span>
2362<span class="line-number">20</span>
2363<span class="line-number">21</span>
2364<span class="line-number">22</span>
2365<span class="line-number">23</span>
2366<span class="line-number">24</span>
2367<span class="line-number">25</span>
2368<span class="line-number">26</span>
2369<span class="line-number">27</span>
2370<span class="line-number">28</span>
2371<span class="line-number">29</span>
2372<span class="line-number">30</span>
2373<span class="line-number">31</span>
2374</pre></td><td class="code"><pre><code class="C#"><span class="line"><span class="k">static</span> <span class="k">void</span> <span class="nf">Retry</span><span class="p">(</span><span class="n">Action</span> <span class="n">action</span><span class="p">,</span> <span class="kt">int</span> <span class="n">maxRetries</span> <span class="p">=</span> <span class="m">3</span><span class="p">)</span> <span class="p">{</span>
2375</span><span class="line">    <span class="kt">int</span> <span class="n">retryCount</span> <span class="p">=</span> <span class="m">0</span><span class="p">;</span>
2376</span><span class="line">    <span class="kt">bool</span> <span class="n">done</span> <span class="p">=</span> <span class="k">false</span><span class="p">;</span>
2377</span><span class="line">    <span class="k">do</span> <span class="p">{</span>
2378</span><span class="line">        <span class="k">try</span> <span class="p">{</span>
2379</span><span class="line">            <span class="n">action</span><span class="p">();</span>
2380</span><span class="line">            <span class="n">done</span> <span class="p">=</span> <span class="k">true</span><span class="p">;</span>
2381</span><span class="line">        <span class="p">}</span> <span class="k">catch</span> <span class="p">(</span><span class="n">Exception</span> <span class="n">ex</span><span class="p">)</span> <span class="p">{</span>
2382</span><span class="line">            <span class="k">if</span> <span class="p">(</span><span class="n">ex</span> <span class="k">is</span> <span class="n">InvalidOperationException</span><span class="p">)</span> <span class="p">{</span>
2383</span><span class="line">                <span class="k">if</span> <span class="p">(</span><span class="n">retryCount</span><span class="p">++</span> <span class="p">&lt;</span> <span class="n">maxRetries</span><span class="p">)</span> <span class="p">{</span>
2384</span><span class="line">                    <span class="c1">// can try again. Under the limit</span>
2385</span><span class="line">                    <span class="n">Console</span><span class="p">.</span><span class="n">WriteLine</span><span class="p">(</span><span class="s">&quot;Caught exception, retry #{0}&quot;</span><span class="p">,</span> <span class="n">retryCount</span><span class="p">);</span>
2386</span><span class="line">                    <span class="n">done</span> <span class="p">=</span> <span class="k">false</span><span class="p">;</span>
2387</span><span class="line">                <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
2388</span><span class="line">                    <span class="c1">// retried too many times already</span>
2389</span><span class="line">                    <span class="n">Console</span><span class="p">.</span><span class="n">WriteLine</span><span class="p">(</span><span class="s">&quot;Exceeded retry count. Throwing.&quot;</span><span class="p">);</span>
2390</span><span class="line">                    <span class="k">throw</span><span class="p">;</span>
2391</span><span class="line">                <span class="p">}</span>
2392</span><span class="line">            <span class="p">}</span>
2393</span><span class="line">        <span class="p">}</span>
2394</span><span class="line">    <span class="p">}</span> <span class="k">while</span> <span class="p">(!</span><span class="n">done</span><span class="p">);</span>
2395</span><span class="line"><span class="p">}</span>
2396</span><span class="line">
2397</span><span class="line"><span class="k">static</span> <span class="k">void</span> <span class="nf">Retry02</span><span class="p">()</span> <span class="p">{</span>
2398</span><span class="line">    <span class="k">foreach</span> <span class="p">(</span><span class="kt">var</span> <span class="n">dir</span> <span class="k">in</span> <span class="n">Directory</span><span class="p">.</span><span class="n">EnumerateDirectories</span><span class="p">(</span><span class="s">&quot;C:\\&quot;</span><span class="p">))</span> <span class="p">{</span>
2399</span><span class="line">        <span class="n">Retry</span><span class="p">(()</span> <span class="p">=&gt;</span> <span class="p">{</span>
2400</span><span class="line">            <span class="n">OccasionallyThrow</span><span class="p">(</span><span class="m">0.25d</span><span class="p">);</span>
2401</span><span class="line">            <span class="n">Console</span><span class="p">.</span><span class="n">WriteLine</span><span class="p">(</span><span class="s">&quot;dir: {0}&quot;</span><span class="p">,</span> <span class="n">dir</span><span class="p">);</span>
2402</span><span class="line">        <span class="p">},</span> <span class="m">3</span><span class="p">);</span>
2403</span><span class="line">    <span class="p">}</span>
2404</span><span class="line"><span class="p">}</span>
2405</span></code></pre></td></tr></table></div></figure></notextile></div>
2406
2407<p>This approach solves many of the problems we’ve identified. The retry logic is encapsulated in a function that’s trivial to reuse. One point of interest here… if you’re not familiar with the syntax and techniques, it may look a bit strange. But it also should look a little familiar; consider the “using” block:</p>
2408
2409<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
2410<span class="line-number">2</span>
2411<span class="line-number">3</span>
2412<span class="line-number">4</span>
2413<span class="line-number">5</span>
2414</pre></td><td class="code"><pre><code class="C#"><span class="line"><span class="kt">byte</span> <span class="n">someByte</span> <span class="p">=</span> <span class="m">100</span><span class="p">;</span>
2415</span><span class="line"><span class="k">using</span> <span class="p">(</span><span class="kt">var</span> <span class="n">stream</span> <span class="p">=</span> <span class="n">File</span><span class="p">.</span><span class="n">Open</span><span class="p">(</span><span class="s">&quot;C:\\data.dat&quot;</span><span class="p">,</span> <span class="n">FileMode</span><span class="p">.</span><span class="n">CreateNew</span><span class="p">))</span> <span class="p">{</span>
2416</span><span class="line">    <span class="k">for</span> <span class="p">(</span><span class="kt">byte</span> <span class="n">i</span> <span class="p">=</span> <span class="m">0</span><span class="p">;</span> <span class="n">i</span> <span class="p">&lt;</span> <span class="n">someByte</span><span class="p">;</span> <span class="n">i</span><span class="p">++)</span>
2417</span><span class="line">        <span class="n">stream</span><span class="p">.</span><span class="n">WriteByte</span><span class="p">(</span><span class="n">i</span><span class="p">);</span>
2418</span><span class="line"><span class="p">}</span>
2419</span></code></pre></td></tr></table></div></figure></notextile></div>
2420
2421<p>The C# using block has a similar pattern. There’s some construct (using), and then a block of code to which the construct applies. It has a similar feel to our Retry() solution. Hmmm… could we use the Retry() approach to write our own using?</p>
2422
2423<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
2424<span class="line-number">2</span>
2425<span class="line-number">3</span>
2426<span class="line-number">4</span>
2427<span class="line-number">5</span>
2428<span class="line-number">6</span>
2429<span class="line-number">7</span>
2430<span class="line-number">8</span>
2431<span class="line-number">9</span>
2432<span class="line-number">10</span>
2433<span class="line-number">11</span>
2434<span class="line-number">12</span>
2435<span class="line-number">13</span>
2436<span class="line-number">14</span>
2437<span class="line-number">15</span>
2438<span class="line-number">16</span>
2439</pre></td><td class="code"><pre><code class="C#"><span class="line"><span class="k">static</span> <span class="k">void</span> <span class="n">Using</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;(</span><span class="n">T</span> <span class="n">disposableVar</span><span class="p">,</span> <span class="n">Action</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;</span> <span class="n">usingBlock</span><span class="p">)</span> <span class="k">where</span> <span class="n">T</span> <span class="p">:</span> <span class="n">IDisposable</span> <span class="p">{</span>
2440</span><span class="line">    <span class="k">try</span> <span class="p">{</span>
2441</span><span class="line">        <span class="n">usingBlock</span><span class="p">(</span><span class="n">disposableVar</span><span class="p">);</span>
2442</span><span class="line">    <span class="p">}</span> <span class="k">finally</span> <span class="p">{</span>
2443</span><span class="line">        <span class="n">disposableVar</span><span class="p">.</span><span class="n">Dispose</span><span class="p">();</span>
2444</span><span class="line">    <span class="p">}</span>
2445</span><span class="line"><span class="p">}</span>
2446</span><span class="line">
2447</span><span class="line"><span class="k">static</span> <span class="k">void</span> <span class="nf">UsingMyUsing</span><span class="p">()</span> <span class="p">{</span>
2448</span><span class="line">    <span class="kt">byte</span> <span class="n">someByte</span> <span class="p">=</span> <span class="m">100</span><span class="p">;</span>
2449</span><span class="line">
2450</span><span class="line">    <span class="n">Using</span><span class="p">(</span><span class="n">File</span><span class="p">.</span><span class="n">Open</span><span class="p">(</span><span class="s">&quot;C:\\data.dat&quot;</span><span class="p">,</span> <span class="n">FileMode</span><span class="p">.</span><span class="n">CreateNew</span><span class="p">),</span> <span class="n">stream</span> <span class="p">=&gt;</span> <span class="p">{</span>
2451</span><span class="line">        <span class="k">for</span> <span class="p">(</span><span class="kt">byte</span> <span class="n">i</span> <span class="p">=</span> <span class="m">0</span><span class="p">;</span> <span class="n">i</span> <span class="p">&lt;</span> <span class="n">someByte</span><span class="p">;</span> <span class="n">i</span><span class="p">++)</span>
2452</span><span class="line">            <span class="n">stream</span><span class="p">.</span><span class="n">WriteByte</span><span class="p">(</span><span class="n">i</span><span class="p">);</span>
2453</span><span class="line">    <span class="p">});</span>
2454</span><span class="line"><span class="p">}</span>
2455</span></code></pre></td></tr></table></div></figure></notextile></div>
2456
2457<p>See that’s why I like coding so much… that’s definitely cool. It’s not exactly character for character like the using statement, but it’s pretty darn close (actually, mine is a couple of characters shorter). And it’s equivalent (at least it is superficially, I haven’t checked thoroughly, it’s almost 1am after all). It had to get a little fancier with the generics, but we’ve recreated a C# language construct.</p>
2458
2459<p>This article is long enough, and I’m sure you get the picture. To me, this is a great example of how functional thinking can lead to interesting, robust solutions to problems. Let me know if you’ve got any questions or comments. Until then, have fun!</p>
2460]]></content>
2461  </entry>
2462  
2463  <entry>
2464    <title type="html"><![CDATA[Lambdas – Exposing Disposable Resources in Your API]]></title>
2465    <link href="http://efvincent.github.io/blog/2010/02/02/c-nuts-and-bolts-lambdas02/"/>
2466    <updated>2010-02-02T13:51:56-05:00</updated>
2467    <id>http://efvincent.github.io/blog/2010/02/02/c-nuts-and-bolts-lambdas02</id>
2468    <content type="html"><![CDATA[<p>The <a href="http://blog.efvincent.com/c-nuts-and-bolts-lambdas/">last article</a> described the absolute (and I mean really absolute) basics of lambdas in C#. Assuming you’re continuing from there, where to next? Let’s use some lambdas. There are two approaches we can use. First is using lambdas in places you traditionally used other approaches. Second is using them in new and interesting ways. Hmmm. Which to choose.
2469<!-- more --></p>
2470
2471<h3 id="new-and-interesting-code-constructs-using-lambdas">New and Interesting Code Constructs using Lambdas</h3>
2472
2473<p>Yea that’ll do. Let’s take an example situation. You’re tasked with writing part of a data access layer. It’s a low level data access layer, we’re not using Entity Framework, no Linq to SQL. No NHibernate. Just you and the keyboard. Sweet.</p>
2474
2475<p>The team decides they’re comfortable with the forward only read only data reader. Ok. So you start sketching out your code and end up with this:</p>
2476
2477<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
2478<span class="line-number">2</span>
2479<span class="line-number">3</span>
2480<span class="line-number">4</span>
2481<span class="line-number">5</span>
2482<span class="line-number">6</span>
2483<span class="line-number">7</span>
2484<span class="line-number">8</span>
2485</pre></td><td class="code"><pre><code class="C#"><span class="line"><span class="k">public</span> <span class="k">static</span> <span class="n">IDataReader</span> <span class="nf">GetSomeData</span><span class="p">()</span> <span class="p">{</span>
2486</span><span class="line">    <span class="k">using</span> <span class="p">(</span><span class="kt">var</span> <span class="n">con</span> <span class="p">=</span> <span class="k">new</span> <span class="n">SqlConnection</span><span class="p">(</span><span class="n">conString</span><span class="p">))</span>
2487</span><span class="line">    <span class="k">using</span> <span class="p">(</span><span class="kt">var</span> <span class="n">cmd</span> <span class="p">=</span> <span class="k">new</span> <span class="n">SqlCommand</span><span class="p">(</span><span class="n">cmdString</span><span class="p">,</span> <span class="n">con</span><span class="p">))</span> <span class="p">{</span>
2488</span><span class="line">        <span class="n">con</span><span class="p">.</span><span class="n">Open</span><span class="p">();</span>
2489</span><span class="line">        <span class="n">IDataReader</span> <span class="n">rdr</span> <span class="p">=</span> <span class="n">cmd</span><span class="p">.</span><span class="n">ExecuteReader</span><span class="p">();</span>
2490</span><span class="line">        <span class="k">return</span> <span class="n">rdr</span><span class="p">;</span>
2491</span><span class="line">    <span class="p">}</span>
2492</span><span class="line"><span class="p">}</span>
2493</span></code></pre></td></tr></table></div></figure></notextile></div>
2494
2495<p>Well, this won’t work. Trying to return the reader, but you’ve got a command and a connection both in using blocks. On returning, those blocks will terminate, disposing of the connection and command (which is good). What now? Briefly consider <em>not</em> using using blocks, not disposing of anything and just returning the reader. Nah – just can’t do that. Ok, so bail on data reader and go with a data set or some other statefull representation of the data I guess.</p>
2496
2497<p>But WAIT! Don’t punch out just yet. What’s happening here is we’ve got a disposable resource we want to use in a spot that’s surrounded if you will by other important code. Let’s take a look at this:</p>
2498
2499<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
2500<span class="line-number">2</span>
2501<span class="line-number">3</span>
2502<span class="line-number">4</span>
2503<span class="line-number">5</span>
2504<span class="line-number">6</span>
2505<span class="line-number">7</span>
2506<span class="line-number">8</span>
2507<span class="line-number">9</span>
2508</pre></td><td class="code"><pre><code class="C#"><span class="line"><span class="k">public</span> <span class="k">static</span> <span class="k">void</span> <span class="nf">UsingReaderGetSomeData</span><span class="p">(</span><span class="n">Action</span><span class="p">&lt;</span><span class="n">IDataReader</span><span class="p">&gt;</span> <span class="n">processor</span><span class="p">)</span> <span class="p">{</span>
2509</span><span class="line">    <span class="k">using</span> <span class="p">(</span><span class="kt">var</span> <span class="n">con</span> <span class="p">=</span> <span class="k">new</span> <span class="n">SqlConnection</span><span class="p">(</span><span class="n">conString</span><span class="p">))</span>
2510</span><span class="line">    <span class="k">using</span> <span class="p">(</span><span class="kt">var</span> <span class="n">cmd</span> <span class="p">=</span> <span class="k">new</span> <span class="n">SqlCommand</span><span class="p">(</span><span class="n">cmdString</span><span class="p">,</span> <span class="n">con</span><span class="p">))</span> <span class="p">{</span>
2511</span><span class="line">        <span class="n">con</span><span class="p">.</span><span class="n">Open</span><span class="p">();</span>
2512</span><span class="line">        <span class="k">using</span> <span class="p">(</span><span class="n">IDataReader</span> <span class="n">rdr</span> <span class="p">=</span> <span class="n">cmd</span><span class="p">.</span><span class="n">ExecuteReader</span><span class="p">())</span> <span class="p">{</span>
2513</span><span class="line">            <span class="n">processor</span><span class="p">(</span><span class="n">rdr</span><span class="p">);</span>
2514</span><span class="line">        <span class="p">}</span>
2515</span><span class="line">    <span class="p">}</span>
2516</span><span class="line"><span class="p">}</span>
2517</span></code></pre></td></tr></table></div></figure></notextile></div>
2518
2519<p>Now we’ve got a method that does all the right things with the data reader. The reader, its connection, and its command are all in using blocks so they’ll be properly disposed of. We ask the caller to supply an <code>Action&lt;IDataReader&gt;</code>, and we’ll apply that action to our well protected data reader.</p>
2520
2521<p>This looks reasonable, but since it’s a data reader, won’t the caller always be doing the <code>while(rdr.Read())</code> thing? Let’s take care of that for them.</p>
2522
2523<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
2524<span class="line-number">2</span>
2525<span class="line-number">3</span>
2526<span class="line-number">4</span>
2527<span class="line-number">5</span>
2528<span class="line-number">6</span>
2529<span class="line-number">7</span>
2530<span class="line-number">8</span>
2531<span class="line-number">9</span>
2532<span class="line-number">10</span>
2533<span class="line-number">11</span>
2534</pre></td><td class="code"><pre><code class="C#"><span class="line"><span class="k">public</span> <span class="k">static</span> <span class="k">void</span> <span class="nf">UsingReaderGetSomeData</span><span class="p">(</span><span class="n">Action</span><span class="p">&lt;</span><span class="n">IDataRecord</span><span class="p">&gt;</span> <span class="n">processor</span><span class="p">)</span> <span class="p">{</span>
2535</span><span class="line">    <span class="k">using</span> <span class="p">(</span><span class="kt">var</span> <span class="n">con</span> <span class="p">=</span> <span class="k">new</span> <span class="n">SqlConnection</span><span class="p">(</span><span class="n">conString</span><span class="p">))</span>
2536</span><span class="line">    <span class="k">using</span> <span class="p">(</span><span class="kt">var</span> <span class="n">cmd</span> <span class="p">=</span> <span class="k">new</span> <span class="n">SqlCommand</span><span class="p">(</span><span class="n">cmdString</span><span class="p">,</span> <span class="n">con</span><span class="p">))</span> <span class="p">{</span>
2537</span><span class="line">        <span class="n">con</span><span class="p">.</span><span class="n">Open</span><span class="p">();</span>
2538</span><span class="line">        <span class="k">using</span> <span class="p">(</span><span class="n">IDataReader</span> <span class="n">rdr</span> <span class="p">=</span> <span class="n">cmd</span><span class="p">.</span><span class="n">ExecuteReader</span><span class="p">())</span> <span class="p">{</span>
2539</span><span class="line">            <span class="k">while</span><span class="p">(</span><span class="n">rdr</span><span class="p">.</span><span class="n">Read</span><span class="p">())</span> <span class="p">{</span>
2540</span><span class="line">                <span class="n">processor</span><span class="p">(</span><span class="n">rdr</span><span class="p">);</span>
2541</span><span class="line">            <span class="p">}</span>
2542</span><span class="line">        <span class="p">}</span>
2543</span><span class="line">    <span class="p">}</span>
2544</span><span class="line"><span class="p">}</span>
2545</span></code></pre></td></tr></table></div></figure></notextile></div>
2546
2547<p>Now instead of asking for an <code>Action&lt;IDataReader&gt;</code>, we’re asking for an <code>Action&lt;IDataRecord&gt;</code> that will be called once for each record. Our function can iterate the data reader and call the processor once for each result. Here’s a sample caller that builds an HTML ordered list and writes the results to the console:</p>
2548
2549<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
2550<span class="line-number">2</span>
2551<span class="line-number">3</span>
2552<span class="line-number">4</span>
2553<span class="line-number">5</span>
2554<span class="line-number">6</span>
2555<span class="line-number">7</span>
2556<span class="line-number">8</span>
2557<span class="line-number">9</span>
2558<span class="line-number">10</span>
2559<span class="line-number">11</span>
2560<span class="line-number">12</span>
2561<span class="line-number">13</span>
2562<span class="line-number">14</span>
2563<span class="line-number">15</span>
2564</pre></td><td class="code"><pre><code class="C#"><span class="line"><span class="k">static</span> <span class="k">void</span> <span class="nf">Main</span><span class="p">(</span><span class="kt">string</span><span class="p">[]</span> <span class="n">args</span><span class="p">)</span> <span class="p">{</span>
2565</span><span class="line">
2566</span><span class="line">    <span class="n">StringBuilder</span> <span class="n">sb</span> <span class="p">=</span> <span class="k">new</span> <span class="n">StringBuilder</span><span class="p">();</span>
2567</span><span class="line">    <span class="n">sb</span><span class="p">.</span><span class="n">AppendLine</span><span class="p">(</span><span class="s">&quot;&lt;ol&gt;&quot;</span><span class="p">);</span>
2568</span><span class="line">    <span class="n">Dal</span><span class="p">.</span><span class="n">UsingReaderGetSomeData</span><span class="p">(</span><span class="n">dr</span> <span class="p">=&gt;</span> <span class="p">{</span>
2569</span><span class="line">        <span class="n">sb</span><span class="p">.</span><span class="n">Append</span><span class="p">(</span><span class="s">&quot; &lt;li&gt;&quot;</span><span class="p">);</span>
2570</span><span class="line">        <span class="n">sb</span><span class="p">.</span><span class="n">Append</span><span class="p">(</span><span class="n">dr</span><span class="p">[</span><span class="m">0</span><span class="p">]);</span>
2571</span><span class="line">        <span class="n">sb</span><span class="p">.</span><span class="n">AppendLine</span><span class="p">(</span><span class="s">&quot;&lt;/li&gt;&quot;</span><span class="p">);</span>
2572</span><span class="line">    <span class="p">});</span>
2573</span><span class="line">    <span class="n">sb</span><span class="p">.</span><span class="n">AppendLine</span><span class="p">(</span><span class="s">&quot;&lt;/ol&gt;&quot;</span><span class="p">);</span>
2574</span><span class="line">    <span class="n">Console</span><span class="p">.</span><span class="n">WriteLine</span><span class="p">(</span><span class="n">sb</span><span class="p">);</span>
2575</span><span class="line">
2576</span><span class="line">    <span class="n">Console</span><span class="p">.</span><span class="n">Write</span><span class="p">(</span><span class="s">&quot;Press any key...&quot;</span><span class="p">);</span>
2577</span><span class="line">    <span class="n">Console</span><span class="p">.</span><span class="n">ReadKey</span><span class="p">(</span><span class="k">true</span><span class="p">);</span>
2578</span><span class="line"><span class="p">}</span>
2579</span></code></pre></td></tr></table></div></figure></notextile></div>
2580
2581<p>A client uses our function like a loop. Everything it puts in the curly braces from line 5 – 9 is like the the body of the loop. With this approach, we’re getting the benefits of the data reader, it’s fast and forward only. The construct is similar to a loop, so the consumers (our team mates) should be able to understand how to use this. And finally, we’re taking proper care to dispose of the resources.</p>
2582
2583<p>To summarize, this approach allows you define functions that accept functions as parameters, and build more complex behavior. This technique is called <em>functional composition</em>. It’s one of the core principal concepts of Functional Programming, but as we’ve seen here, it can be applied to solutions in imperative programming languages like C# to great effect. Using techniques like this help you break your code down in smaller and smaller chunks, with some functions doing little bits of work, and other functions serving as glue or framework code. All this makes your code easier to test and less prone to errors if done correctly.</p>
2584
2585<h3 id="taking-it-further-or-something-more-like-real-production-code">Taking it Further, or, Something More like Real Production Code</h3>
2586
2587<p>Alright, that was interesting. And as far as blog posts go, that’s all I was really trying to get across. But if you’re curious about what production code might look like that uses an approach like this, here’s an example:</p>
2588
2589<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
2590<span class="line-number">2</span>
2591<span class="line-number">3</span>
2592<span class="line-number">4</span>
2593<span class="line-number">5</span>
2594<span class="line-number">6</span>
2595<span class="line-number">7</span>
2596<span class="line-number">8</span>
2597<span class="line-number">9</span>
2598<span class="line-number">10</span>
2599<span class="line-number">11</span>
2600<span class="line-number">12</span>
2601<span class="line-number">13</span>
2602<span class="line-number">14</span>
2603<span class="line-number">15</span>
2604<span class="line-number">16</span>
2605<span class="line-number">17</span>
2606<span class="line-number">18</span>
2607<span class="line-number">19</span>
2608<span class="line-number">20</span>
2609<span class="line-number">21</span>
2610<span class="line-number">22</span>
2611<span class="line-number">23</span>
2612<span class="line-number">24</span>
2613<span class="line-number">25</span>
2614<span class="line-number">26</span>
2615<span class="line-number">27</span>
2616<span class="line-number">28</span>
2617<span class="line-number">29</span>
2618<span class="line-number">30</span>
2619<span class="line-number">31</span>
2620<span class="line-number">32</span>
2621<span class="line-number">33</span>
2622<span class="line-number">34</span>
2623<span class="line-number">35</span>
2624<span class="line-number">36</span>
2625<span class="line-number">37</span>
2626<span class="line-number">38</span>
2627<span class="line-number">39</span>
2628<span class="line-number">40</span>
2629<span class="line-number">41</span>
2630<span class="line-number">42</span>
2631<span class="line-number">43</span>
2632<span class="line-number">44</span>
2633<span class="line-number">45</span>
2634<span class="line-number">46</span>
2635<span class="line-number">47</span>
2636<span class="line-number">48</span>
2637<span class="line-number">49</span>
2638<span class="line-number">50</span>
2639</pre></td><td class="code"><pre><code class="C#"><span class="line"><span class="k">private</span> <span class="k">static</span> <span class="k">void</span> <span class="nf">UsingReader</span><span class="p">(</span>
2640</span><span class="line">    <span class="kt">string</span> <span class="n">command</span><span class="p">,</span>
2641</span><span class="line">    <span class="n">Action</span><span class="p">&lt;</span><span class="n">SqlCommand</span><span class="p">&gt;</span> <span class="n">preAction</span> <span class="p">=</span> <span class="k">null</span><span class="p">,</span>
2642</span><span class="line">    <span class="n">IEnumerable</span><span class="p">&lt;</span><span class="n">Action</span><span class="p">&lt;</span><span class="n">IDataRecord</span><span class="p">&gt;&gt;</span> <span class="n">recordProcessors</span> <span class="p">=</span> <span class="k">null</span><span class="p">,</span>
2643</span><span class="line">    <span class="n">Action</span><span class="p">&lt;</span><span class="n">SqlCommand</span><span class="p">&gt;</span> <span class="n">postAction</span> <span class="p">=</span> <span class="k">null</span><span class="p">)</span> <span class="p">{</span>
2644</span><span class="line">
2645</span><span class="line">    <span class="c1">// Instantiate connection and command, open the connection</span>
2646</span><span class="line">    <span class="k">using</span> <span class="p">(</span><span class="kt">var</span> <span class="n">con</span> <span class="p">=</span> <span class="k">new</span> <span class="n">SqlConnection</span><span class="p">(</span><span class="n">conString</span><span class="p">))</span>
2647</span><span class="line">    <span class="k">using</span> <span class="p">(</span><span class="kt">var</span> <span class="n">cmd</span> <span class="p">=</span> <span class="k">new</span> <span class="n">SqlCommand</span><span class="p">(</span><span class="n">command</span><span class="p">,</span> <span class="n">con</span><span class="p">))</span> <span class="p">{</span>
2648</span><span class="line">        <span class="n">con</span><span class="p">.</span><span class="n">Open</span><span class="p">();</span>
2649</span><span class="line">
2650</span><span class="line">        <span class="c1">// Execute a pre-action if specified</span>
2651</span><span class="line">        <span class="k">if</span> <span class="p">(</span><span class="n">preAction</span> <span class="p">!=</span> <span class="k">null</span><span class="p">)</span> <span class="n">preAction</span><span class="p">(</span><span class="n">cmd</span><span class="p">);</span>
2652</span><span class="line">
2653</span><span class="line">        <span class="c1">// If the reader processing blocks are supplied</span>
2654</span><span class="line">        <span class="k">if</span> <span class="p">(</span><span class="n">recordProcessors</span> <span class="p">!=</span> <span class="k">null</span><span class="p">)</span> <span class="p">{</span>
2655</span><span class="line">
2656</span><span class="line">            <span class="c1">// Get an enumerator for the processing blocks &amp; move</span>
2657</span><span class="line">            <span class="c1">// to the first processor</span>
2658</span><span class="line">            <span class="kt">var</span> <span class="n">processorEnumerator</span> <span class="p">=</span> <span class="n">recordProcessors</span><span class="p">.</span><span class="n">GetEnumerator</span><span class="p">();</span>
2659</span><span class="line">            <span class="k">if</span> <span class="p">(!</span><span class="n">processorEnumerator</span><span class="p">.</span><span class="n">MoveNext</span><span class="p">())</span>
2660</span><span class="line">                <span class="k">throw</span> <span class="k">new</span> <span class="nf">InvalidOperationException</span><span class="p">(</span>
2661</span><span class="line">                    <span class="s">&quot;Supply at least one record processor&quot;</span><span class="p">);</span>
2662</span><span class="line">
2663</span><span class="line">            <span class="c1">// Open the reader</span>
2664</span><span class="line">            <span class="k">using</span> <span class="p">(</span><span class="kt">var</span> <span class="n">reader</span> <span class="p">=</span> <span class="n">cmd</span><span class="p">.</span><span class="n">ExecuteReader</span><span class="p">(</span><span class="n">CommandBehavior</span><span class="p">.</span><span class="n">CloseConnection</span><span class="p">))</span> <span class="p">{</span>
2665</span><span class="line">
2666</span><span class="line">                <span class="k">do</span> <span class="p">{</span>
2667</span><span class="line">                    <span class="c1">// Get the current record processing block</span>
2668</span><span class="line">                    <span class="kt">var</span> <span class="n">recordProcessor</span> <span class="p">=</span> <span class="n">processorEnumerator</span><span class="p">.</span><span class="n">Current</span><span class="p">;</span>
2669</span><span class="line">
2670</span><span class="line">                    <span class="c1">// Iterate the records of the IDataReader using the current block</span>
2671</span><span class="line">                    <span class="k">while</span> <span class="p">(</span><span class="n">reader</span><span class="p">.</span><span class="n">Read</span><span class="p">())</span>
2672</span><span class="line">                        <span class="n">recordProcessor</span><span class="p">(</span><span class="n">reader</span><span class="p">);</span>
2673</span><span class="line">
2674</span><span class="line">                    <span class="c1">// The loop condition advances both IDataReader and enumerator</span>
2675</span><span class="line">                    <span class="c1">// in sync continuing as long as there&#39;s a next resultSet and a</span>
2676</span><span class="line">                    <span class="c1">// processor to process it</span>
2677</span><span class="line">                <span class="p">}</span> <span class="k">while</span> <span class="p">(</span><span class="n">reader</span><span class="p">.</span><span class="n">NextResult</span><span class="p">()</span> <span class="p">&amp;&amp;</span> <span class="n">processorEnumerator</span><span class="p">.</span><span class="n">MoveNext</span><span class="p">());</span>
2678</span><span class="line">            <span class="p">}</span>
2679</span><span class="line">
2680</span><span class="line">        <span class="p">}</span> <span class="k">else</span>
2681</span><span class="line">            <span class="c1">// If there are no actions to execute using data reader, just execute query</span>
2682</span><span class="line">            <span class="n">cmd</span><span class="p">.</span><span class="n">ExecuteNonQuery</span><span class="p">();</span>
2683</span><span class="line">
2684</span><span class="line">        <span class="c1">// Do any clean up that might be needed</span>
2685</span><span class="line">        <span class="k">if</span> <span class="p">(</span><span class="n">postAction</span> <span class="p">!=</span> <span class="k">null</span><span class="p">)</span>
2686</span><span class="line">            <span class="n">postAction</span><span class="p">(</span><span class="n">cmd</span><span class="p">);</span>
2687</span><span class="line">    <span class="p">}</span>
2688</span><span class="line"><span class="p">}</span>
2689</span></code></pre></td></tr></table></div></figure></notextile></div>
2690
2691<p>Here we pass optional pre- and post- actions that allow the caller to optionally manipulate the command before and after it’s executed. We also accept a set of actions we’re calling record processors, to handle the case when a stored procedure or command is returning multiple result sets. In the case of multiple result sets, we’d expect the caller to send a different record processor for each result set it expects.</p>
2692
2693<p>So this seems like a lot of code. Why bother? The way I approached it was that this code is a private method of the data access layer, and the public methods would leverage this method to avoid repeating the gory details of working with data readers. Leveraging the above method, our original <code>GetSomeData()</code> now looks like:</p>
2694
2695<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
2696<span class="line-number">2</span>
2697<span class="line-number">3</span>
2698</pre></td><td class="code"><pre><code class="C#"><span class="line"><span class="k">public</span> <span class="k">static</span> <span class="k">void</span> <span class="nf">UsingReaderGetSomeData</span><span class="p">(</span><span class="n">Action</span><span class="p">&lt;</span><span class="n">IDataRecord</span><span class="p">&gt;</span> <span class="n">recordProcessor</span><span class="p">)</span> <span class="p">{</span>
2699</span><span class="line">    <span class="n">UsingReader</span><span class="p">(</span><span class="n">cmdString</span><span class="p">,</span> <span class="k">null</span><span class="p">,</span> <span class="k">new</span> <span class="n">Action</span><span class="p">&lt;</span><span class="n">IDataRecord</span><span class="p">&gt;[]</span> <span class="p">{</span> <span class="n">recordProcessor</span> <span class="p">});</span>
2700</span><span class="line"><span class="p">}</span>
2701</span></code></pre></td></tr></table></div></figure></notextile></div>
2702
2703<p>And if we had a data access method that took a couple of parameters, it would look like this:</p>
2704
2705<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
2706<span class="line-number">2</span>
2707<span class="line-number">3</span>
2708<span class="line-number">4</span>
2709<span class="line-number">5</span>
2710</pre></td><td class="code"><pre><code class="C#"><span class="line"><span class="k">public</span> <span class="k">static</span> <span class="k">void</span> <span class="nf">UsingReaderGetSearch</span><span class="p">(</span><span class="kt">string</span> <span class="n">criteria</span><span class="p">,</span> <span class="n">Action</span><span class="p">&lt;</span><span class="n">IDataRecord</span><span class="p">&gt;</span> <span class="n">resultProcessor</span><span class="p">)</span> <span class="p">{</span>
2711</span><span class="line">    <span class="n">UsingReader</span><span class="p">(</span><span class="n">cmdString</span><span class="p">,</span>
2712</span><span class="line">        <span class="n">cmd</span> <span class="p">=&gt;</span> <span class="n">cmd</span><span class="p">.</span><span class="n">Parameters</span><span class="p">.</span><span class="n">Add</span><span class="p">(</span><span class="k">new</span> <span class="n">SqlParameter</span><span class="p">(</span><span class="s">&quot;@searchCriteria&quot;</span><span class="p">,</span> <span class="n">criteria</span><span class="p">)),</span>
2713</span><span class="line">        <span class="k">new</span> <span class="n">Action</span><span class="p">&lt;</span><span class="n">IDataRecord</span><span class="p">&gt;[]</span> <span class="p">{</span> <span class="n">resultProcessor</span> <span class="p">});</span>
2714</span><span class="line"><span class="p">}</span>
2715</span></code></pre></td></tr></table></div></figure></notextile></div>
2716
2717<p>I hope this has proved helpful. I’ll keep throwing more of these posts out there, let me know if there’s something you’d like to see.</p>
2718]]></content>
2719  </entry>
2720  
2721  <entry>
2722    <title type="html"><![CDATA[C# Nuts and Bolts: Lambdas]]></title>
2723    <link href="http://efvincent.github.io/blog/2010/02/01/c-nuts-and-bolts-lambdas/"/>
2724    <updated>2010-02-01T14:19:41-05:00</updated>
2725    <id>http://efvincent.github.io/blog/2010/02/01/c-nuts-and-bolts-lambdas</id>
2726    <content type="html"><![CDATA[<p>You don’t need to use Lambdas to make a living writing code in .NET. You can probably get away with not even knowing what Linq is. You can also still find work coding in .NET 2.0. But that’s painfully BORING. So to avoid the stinging monotony of working in a 5 year reverse time-shift, let’s take a look at lambdas.</p>
2727
2728<!-- more -->
2729
2730<p>The (arguably) simplest lambda.</p>
2731
2732<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
2733<span class="line-number">2</span>
2734<span class="line-number">3</span>
2735<span class="line-number">4</span>
2736<span class="line-number">5</span>
2737<span class="line-number">6</span>
2738</pre></td><td class="code"><pre><code class="C#"><span class="line"><span class="kt">string</span> <span class="n">message</span> <span class="p">=</span> <span class="s">&quot;Hello World&quot;</span><span class="p">;</span>
2739</span><span class="line"><span class="n">Action</span> <span class="n">simpleLambda</span> <span class="p">=</span> <span class="p">()</span> <span class="p">=&gt;</span> <span class="n">Console</span><span class="p">.</span><span class="n">WriteLine</span><span class="p">(</span><span class="n">message</span><span class="p">);</span>
2740</span><span class="line">
2741</span><span class="line"><span class="n">Console</span><span class="p">.</span><span class="n">WriteLine</span><span class="p">(</span><span class="err">“</span><span class="n">Get</span> <span class="n">ready</span> <span class="k">for</span> <span class="n">a</span> <span class="n">message</span><span class="p">!</span><span class="err">”</span><span class="p">);</span>
2742</span><span class="line"><span class="n">simpleLambda</span><span class="p">();</span>
2743</span><span class="line"><span class="n">Console</span><span class="p">.</span><span class="n">WriteLine</span><span class="p">(</span><span class="err">“</span><span class="n">That</span> <span class="n">was</span> <span class="n">the</span> <span class="n">message</span><span class="p">!</span><span class="err">”</span><span class="p">);</span>
2744</span></code></pre></td></tr></table></div></figure></notextile></div>
2745
2746<p>The the type “Action” is a delegate, which can be thought of as a function pointer. The variable “simpleLambda” is now a function. The same way that “message” is a string. In reality, there are delegates and pointers involved, but for the day to day, just think of “simpleLambda” as a function. It can be called just like you would any function, which is what we’ve done here.</p>
2747
2748<p>There are two different Types that are generally used for these functions. They are “Action” and “Func”. Action, which we just saw, is a function that doesn’t return anything. It’s a void function. When we want to define a function that returns something, we use the “Func” type. Remember back to your early days of Visual Basic, Pascal, etc., when there were different keywords that you’d use to specify if there was a return value or not? Same kinda thing here. Func returns, Action doesn’t. So here’s a Func example.</p>
2749
2750<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
2751<span class="line-number">2</span>
2752<span class="line-number">3</span>
2753<span class="line-number">4</span>
2754<span class="line-number">5</span>
2755<span class="line-number">6</span>
2756</pre></td><td class="code"><pre><code class="C#"><span class="line"><span class="c1">// Define a func that returns something</span>
2757</span><span class="line">
2758</span><span class="line"><span class="n">Func</span><span class="p">&lt;</span><span class="kt">string</span><span class="p">&gt;</span> <span class="n">minutesAndSeconds</span> <span class="p">=</span> <span class="p">()</span> <span class="p">=&gt;</span> <span class="kt">string</span><span class="p">.</span><span class="n">Format</span><span class="p">(</span><span class="s">&quot;{0:mm:ss.ffff}&quot;</span><span class="p">,</span> <span class="n">DateTime</span><span class="p">.</span><span class="n">Now</span><span class="p">);</span>
2759</span><span class="line">
2760</span><span class="line"><span class="n">Console</span><span class="p">.</span><span class="n">Write</span><span class="p">(</span><span class="s">&quot;Current Minutes and seconds are: &quot;</span><span class="p">);</span>
2761</span><span class="line"><span class="n">Console</span><span class="p">.</span><span class="n">WriteLine</span><span class="p">(</span><span class="n">minutesAndSeconds</span><span class="p">());</span>
2762</span></code></pre></td></tr></table></div></figure></notextile></div>
2763
2764<p>Here’s a function that returns a string. It’s type is Func<string>, which you can read as a function that returns a string. Let’s break down the syntax of the lambda itself. It centers around the lambda operator “=&gt;”, which some people read as “goes to”. In both our examples, simpleLambda and minutesAndSeconds are functions that take no parameters. So on the left of the lambda operator are empty parenthesis. Means no parameters to the function. Easy. On the right is the body of the function.</string></p>
2765
2766<p>There are two ways of expressing the body of the function. If the body is a single statement, you can just put that statement. This is called an Expression Lambda. If you need more than one statement on the right of the Lambda operator, you end up with something like this:</p>
2767
2768<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
2769<span class="line-number">2</span>
2770<span class="line-number">3</span>
2771<span class="line-number">4</span>
2772<span class="line-number">5</span>
2773<span class="line-number">6</span>
2774<span class="line-number">7</span>
2775</pre></td><td class="code"><pre><code class="C#"><span class="line"><span class="n">Func</span><span class="p">&lt;</span><span class="kt">string</span><span class="p">,</span> <span class="kt">string</span><span class="p">&gt;</span> <span class="n">hasher</span> <span class="p">=</span>
2776</span><span class="line">    <span class="n">s</span> <span class="p">=&gt;</span> <span class="p">{</span>
2777</span><span class="line">        <span class="kt">var</span> <span class="n">sha</span> <span class="p">=</span> <span class="k">new</span> <span class="n">System</span><span class="p">.</span><span class="n">Security</span><span class="p">.</span><span class="n">Cryptography</span><span class="p">.</span><span class="n">SHA1CryptoServiceProvider</span><span class="p">();</span>
2778</span><span class="line">        <span class="k">return</span> <span class="n">Convert</span><span class="p">.</span><span class="n">ToBase64String</span><span class="p">(</span><span class="n">sha</span><span class="p">.</span><span class="n">ComputeHash</span><span class="p">(</span><span class="n">ASCIIEncoding</span><span class="p">.</span><span class="n">UTF8</span><span class="p">.</span><span class="n">GetBytes</span><span class="p">(</span><span class="n">s</span><span class="p">)));</span>
2779</span><span class="line">    <span class="p">};</span>
2780</span><span class="line">
2781</span><span class="line"><span class="n">Console</span><span class="p">.</span><span class="n">WriteLine</span><span class="p">(</span><span class="s">&quot;The base64 encoded SHA1 hash of \&quot;Hello World\&quot; is {0}&quot;</span><span class="p">,</span> <span class="n">hasher</span><span class="p">(</span><span class="s">&quot;Hello World&quot;</span><span class="p">));</span>
2782</span></code></pre></td></tr></table></div></figure></notextile></div>
2783
2784<p>A couple of differences here… first there’s some added whitespace to make stuff more readable. Don’t let it throw you. Whitespace == good. Second, the type is now Func&lt;string, string&gt;. The key to reading the Func type is that the last generic type specification is the return type. So it reads “a function that takes a string and returns a string”. Since this lambda takes a string as a parameter, to the left of the lambda operator goes the parameter. You can name this parameter anything you want, just like when you’re defining a regular function. This parameter is bound to the input to the function.</p>
2785
2786<p>The next thing that’s different is there are open and close curly brackets, just like a function definition, after the lambda operator. This is the body, it’s just like a function body. You declare local variables in here, and when you’re done, you return something. Or if this is an Action instead of a Func, you don’t need to return anything (remember, Action is like a void function). This is the same function except as a statically defined method on a class:</p>
2787
2788<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
2789<span class="line-number">2</span>
2790<span class="line-number">3</span>
2791<span class="line-number">4</span>
2792</pre></td><td class="code"><pre><code class="C#"><span class="line"><span class="k">public</span> <span class="k">static</span> <span class="kt">string</span> <span class="nf">Hasher</span><span class="p">(</span><span class="kt">string</span> <span class="n">s</span><span class="p">)</span> <span class="p">{</span>
2793</span><span class="line">    <span class="kt">var</span> <span class="n">sha</span> <span class="p">=</span> <span class="k">new</span> <span class="n">System</span><span class="p">.</span><span class="n">Security</span><span class="p">.</span><span class="n">Cryptography</span><span class="p">.</span><span class="n">SHA1CryptoServiceProvider</span><span class="p">();</span>
2794</span><span class="line">    <span class="k">return</span> <span class="n">Convert</span><span class="p">.</span><span class="n">ToBase64String</span><span class="p">(</span><span class="n">sha</span><span class="p">.</span><span class="n">ComputeHash</span><span class="p">(</span><span class="n">ASCIIEncoding</span><span class="p">.</span><span class="n">UTF8</span><span class="p">.</span><span class="n">GetBytes</span><span class="p">(</span><span class="n">s</span><span class="p">)));</span>
2795</span><span class="line"><span class="p">}</span>
2796</span></code></pre></td></tr></table></div></figure></notextile></div>
2797
2798<p>Thaaaaatts pretty much it. There’re plenty of implementation details under the covers, and there’s a whole world of design patterns and techniques to explore with regards to <em>using</em> lambdas. But as far as what they are, you’re looking at it. I’ll push it a little further in the next blog post. If you’ve got any questions or want to dive deeper into this or any other subject I write about, let me know in the comments. In the mean time, have fun!</p>
2799]]></content>
2800  </entry>
2801  
2802  <entry>
2803    <title type="html"><![CDATA[Applied Functional: Getting User Input]]></title>
2804    <link href="http://efvincent.github.io/blog/2010/01/31/applied-functional-01/"/>
2805    <updated>2010-01-31T22:12:13-05:00</updated>
2806    <id>http://efvincent.github.io/blog/2010/01/31/applied-functional-01</id>
2807    <content type="html"><![CDATA[<p>The thing with spending time on functional programming is that the typical .NET programmer will not likely be able to write production code in F#, and almost certainly not in Haskell. But what you are able to do is apply a new set of problem solving approaches to your every day work.
2808<!-- more -->
2809So here’s a simple problem that we see all the time; you’re writing a console application to test a component. Here’s the pseudo code:</p>
2810
2811<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
2812<span class="line-number">2</span>
2813<span class="line-number">3</span>
2814<span class="line-number">4</span>
2815</pre></td><td class="code"><pre><code class="C#"><span class="line"><span class="c1">/// While still processing</span>
2816</span><span class="line"><span class="c1">///     Get a string from the user</span>
2817</span><span class="line"><span class="c1">///     Process the string</span>
2818</span><span class="line"><span class="c1">/// End While</span>
2819</span></code></pre></td></tr></table></div></figure></notextile></div>
2820
2821<p>Super duper simple. So here’s a straight forward way to code it:</p>
2822
2823<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
2824<span class="line-number">2</span>
2825<span class="line-number">3</span>
2826<span class="line-number">4</span>
2827<span class="line-number">5</span>
2828<span class="line-number">6</span>
2829<span class="line-number">7</span>
2830<span class="line-number">8</span>
2831<span class="line-number">9</span>
2832<span class="line-number">10</span>
2833<span class="line-number">11</span>
2834<span class="line-number">12</span>
2835<span class="line-number">13</span>
2836<span class="line-number">14</span>
2837<span class="line-number">15</span>
2838<span class="line-number">16</span>
2839<span class="line-number">17</span>
2840<span class="line-number">18</span>
2841<span class="line-number">19</span>
2842<span class="line-number">20</span>
2843<span class="line-number">21</span>
2844<span class="line-number">22</span>
2845<span class="line-number">23</span>
2846<span class="line-number">24</span>
2847<span class="line-number">25</span>
2848<span class="line-number">26</span>
2849<span class="line-number">27</span>
2850</pre></td><td class="code"><pre><code class="C#"><span class="line"><span class="k">static</span> <span class="k">void</span> <span class="nf">Main</span><span class="p">(</span><span class="kt">string</span><span class="p">[]</span> <span class="n">args</span><span class="p">)</span> <span class="p">{</span>
2851</span><span class="line">    <span class="n">NonReusableLoop</span><span class="p">();</span>
2852</span><span class="line"><span class="p">}</span>
2853</span><span class="line">
2854</span><span class="line"><span class="k">static</span> <span class="k">void</span> <span class="nf">NonReusableLoop</span><span class="p">()</span> <span class="p">{</span>
2855</span><span class="line">    <span class="kt">string</span> <span class="n">input</span> <span class="p">=</span> <span class="kt">string</span><span class="p">.</span><span class="n">Empty</span><span class="p">;</span>
2856</span><span class="line">    <span class="kt">bool</span> <span class="n">done</span> <span class="p">=</span> <span class="k">false</span><span class="p">;</span>
2857</span><span class="line">    <span class="k">do</span> <span class="p">{</span>
2858</span><span class="line">        <span class="n">Console</span><span class="p">.</span><span class="n">Write</span><span class="p">(</span><span class="s">&quot;Enter a web site to process. Press enter to end: &quot;</span><span class="p">);</span>
2859</span><span class="line">        <span class="n">input</span> <span class="p">=</span> <span class="n">Console</span><span class="p">.</span><span class="n">ReadLine</span><span class="p">();</span>
2860</span><span class="line">        <span class="k">if</span> <span class="p">(</span><span class="kt">string</span><span class="p">.</span><span class="n">IsNullOrEmpty</span><span class="p">(</span><span class="n">input</span><span class="p">))</span> <span class="p">{</span>
2861</span><span class="line">            <span class="n">done</span> <span class="p">=</span> <span class="k">true</span><span class="p">;</span>
2862</span><span class="line">        <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
2863</span><span class="line">            <span class="n">ProcessWebSite</span><span class="p">(</span><span class="n">input</span><span class="p">,</span> <span class="k">true</span><span class="p">);</span>    <span class="c1">// don&#39;t really care about second parameter</span>
2864</span><span class="line">        <span class="p">}</span>
2865</span><span class="line">    <span class="p">}</span> <span class="k">while</span> <span class="p">(!</span><span class="n">done</span><span class="p">);</span>
2866</span><span class="line"><span class="p">}</span>
2867</span><span class="line">
2868</span><span class="line"><span class="k">static</span> <span class="k">void</span> <span class="nf">ProcessWebSite</span><span class="p">(</span><span class="kt">string</span> <span class="n">webSite</span><span class="p">,</span> <span class="kt">bool</span> <span class="n">someOtherParameter</span><span class="p">)</span> <span class="p">{</span>
2869</span><span class="line">    <span class="c1">// Do some fake work</span>
2870</span><span class="line">    <span class="k">if</span> <span class="p">(!</span><span class="n">webSite</span><span class="p">.</span><span class="n">StartsWith</span><span class="p">(</span><span class="s">&quot;http://&quot;</span><span class="p">,</span> <span class="n">StringComparison</span><span class="p">.</span><span class="n">OrdinalIgnoreCase</span><span class="p">))</span> <span class="p">{</span>
2871</span><span class="line">        <span class="k">throw</span> <span class="k">new</span> <span class="nf">InvalidOperationException</span><span class="p">(</span><span class="s">&quot;Poorly formed web site name&quot;</span><span class="p">);</span>
2872</span><span class="line">    <span class="p">}</span>
2873</span><span class="line">    <span class="n">Console</span><span class="p">.</span><span class="n">WriteLine</span><span class="p">(</span><span class="s">&quot;Processing web site {0}&quot;</span><span class="p">,</span> <span class="n">webSite</span><span class="p">);</span>
2874</span><span class="line">    <span class="kt">var</span> <span class="n">rnd</span> <span class="p">=</span> <span class="k">new</span> <span class="n">Random</span><span class="p">(</span><span class="n">DateTime</span><span class="p">.</span><span class="n">Now</span><span class="p">.</span><span class="n">Millisecond</span><span class="p">);</span>
2875</span><span class="line">    <span class="n">Console</span><span class="p">.</span><span class="n">WriteLine</span><span class="p">(</span><span class="s">&quot;Web site has {0:#,##0} pages!&quot;</span><span class="p">,</span> <span class="n">rnd</span><span class="p">.</span><span class="n">Next</span><span class="p">(</span><span class="m">1</span><span class="p">,</span> <span class="m">1000</span><span class="p">));</span>
2876</span><span class="line"><span class="p">}</span>
2877</span></code></pre></td></tr></table></div></figure></notextile></div>
2878
2879<p>So lets say we want to extract something reusable out of this. Lets say we regularly churn up little console apps and we’re tired of writing this over and over again.</p>
2880
2881<p>There are a couple of approaches that seem obvious you if you’ve got your functional thinking cap on. For example, this first pass looks like a function that does the interesting work (calls ProcessWebSite()) in the middle of a bunch of other stuff (getting user input, looping, checking for the quit condition). Let’s go with that observation:</p>
2882
2883<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
2884<span class="line-number">2</span>
2885<span class="line-number">3</span>
2886<span class="line-number">4</span>
2887<span class="line-number">5</span>
2888<span class="line-number">6</span>
2889<span class="line-number">7</span>
2890<span class="line-number">8</span>
2891<span class="line-number">9</span>
2892<span class="line-number">10</span>
2893<span class="line-number">11</span>
2894<span class="line-number">12</span>
2895<span class="line-number">13</span>
2896<span class="line-number">14</span>
2897<span class="line-number">15</span>
2898<span class="line-number">16</span>
2899<span class="line-number">17</span>
2900<span class="line-number">18</span>
2901<span class="line-number">19</span>
2902<span class="line-number">20</span>
2903<span class="line-number">21</span>
2904<span class="line-number">22</span>
2905<span class="line-number">23</span>
2906<span class="line-number">24</span>
2907<span class="line-number">25</span>
2908<span class="line-number">26</span>
2909<span class="line-number">27</span>
2910</pre></td><td class="code"><pre><code class="C#"><span class="line"><span class="k">static</span> <span class="k">void</span> <span class="nf">Main</span><span class="p">(</span><span class="kt">string</span><span class="p">[]</span> <span class="n">args</span><span class="p">)</span> <span class="p">{</span>
2911</span><span class="line">    <span class="n">ProcessUserInput</span><span class="p">(</span><span class="s">&quot;Enter a web site url&quot;</span><span class="p">,</span> <span class="n">input</span> <span class="p">=&gt;</span> <span class="n">ProcessWebSite</span><span class="p">(</span><span class="n">input</span><span class="p">,</span> <span class="k">true</span><span class="p">));</span>
2912</span><span class="line"><span class="p">}</span>
2913</span><span class="line">
2914</span><span class="line"><span class="k">static</span> <span class="k">void</span> <span class="nf">ProcessUserInput</span><span class="p">(</span><span class="kt">string</span> <span class="n">prompt</span><span class="p">,</span> <span class="n">Action</span><span class="p">&lt;</span><span class="kt">string</span><span class="p">&gt;</span> <span class="n">fn</span><span class="p">)</span> <span class="p">{</span>
2915</span><span class="line">    <span class="k">if</span> <span class="p">(</span><span class="n">fn</span> <span class="p">==</span> <span class="k">null</span><span class="p">)</span> <span class="k">return</span><span class="p">;</span>
2916</span><span class="line">    <span class="kt">string</span> <span class="n">input</span> <span class="p">=</span> <span class="kt">string</span><span class="p">.</span><span class="n">Empty</span><span class="p">;</span>
2917</span><span class="line">    <span class="kt">bool</span> <span class="n">done</span> <span class="p">=</span> <span class="k">false</span><span class="p">;</span>
2918</span><span class="line">    <span class="k">do</span> <span class="p">{</span>
2919</span><span class="line">        <span class="n">Console</span><span class="p">.</span><span class="n">Write</span><span class="p">(</span><span class="s">&quot;{0}. Press enter to end: &quot;</span><span class="p">,</span> <span class="n">prompt</span><span class="p">);</span>
2920</span><span class="line">        <span class="n">input</span> <span class="p">=</span> <span class="n">Console</span><span class="p">.</span><span class="n">ReadLine</span><span class="p">();</span>
2921</span><span class="line">        <span class="k">if</span> <span class="p">(</span><span class="kt">string</span><span class="p">.</span><span class="n">IsNullOrEmpty</span><span class="p">(</span><span class="n">input</span><span class="p">))</span> <span class="p">{</span>
2922</span><span class="line">            <span class="n">done</span> <span class="p">=</span> <span class="k">true</span><span class="p">;</span>
2923</span><span class="line">        <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
2924</span><span class="line">            <span class="k">try</span> <span class="p">{</span>
2925</span><span class="line">                <span class="n">fn</span><span class="p">(</span><span class="n">input</span><span class="p">);</span>
2926</span><span class="line">            <span class="p">}</span> <span class="k">catch</span> <span class="p">(</span><span class="n">Exception</span> <span class="n">ex</span><span class="p">)</span> <span class="p">{</span>
2927</span><span class="line">                <span class="n">Console</span><span class="p">.</span><span class="n">WriteLine</span><span class="p">(</span><span class="s">&quot;Exception thrown: {0}&quot;</span><span class="p">,</span> <span class="n">ex</span><span class="p">.</span><span class="n">Message</span><span class="p">);</span>
2928</span><span class="line">                <span class="n">Console</span><span class="p">.</span><span class="n">Write</span><span class="p">(</span><span class="s">&quot;Show exception stack? (y/N):&quot;</span><span class="p">);</span>
2929</span><span class="line">                <span class="kt">var</span> <span class="n">exInput</span> <span class="p">=</span> <span class="n">Console</span><span class="p">.</span><span class="n">ReadLine</span><span class="p">();</span>
2930</span><span class="line">                <span class="k">if</span> <span class="p">(</span><span class="n">exInput</span><span class="p">.</span><span class="n">Equals</span><span class="p">(</span><span class="s">&quot;y&quot;</span><span class="p">,</span> <span class="n">StringComparison</span><span class="p">.</span><span class="n">OrdinalIgnoreCase</span><span class="p">))</span> <span class="p">{</span>
2931</span><span class="line">                    <span class="n">Console</span><span class="p">.</span><span class="n">WriteLine</span><span class="p">(</span><span class="n">ex</span><span class="p">.</span><span class="n">ToString</span><span class="p">());</span>
2932</span><span class="line">                <span class="p">}</span>
2933</span><span class="line">            <span class="p">}</span>
2934</span><span class="line">        <span class="p">}</span>
2935</span><span class="line">    <span class="p">}</span> <span class="k">while</span> <span class="p">(!</span><span class="n">done</span><span class="p">);</span>
2936</span><span class="line"><span class="p">}</span>
2937</span></code></pre></td></tr></table></div></figure></notextile></div>
2938
2939<p>Now we’ve got a function that does the collection of the user strings, checking for the quit condition, and even adds some simple error handling to catch any exceptions that the “work” might throw. The parameter is an “Action<string>”. This is the .NET way of describing a function that returns void and has a single string parameter. This is a functional way of looking at the problem, because in functional programming passing functions around and working on functions is a fundamental technique. Getting used to doing this is a powerful tool.</string></p>
2940
2941<p>But there’s a better way of looking at it. What if we think of the strings the user is entering as a set of strings. We end up with something like this:</p>
2942
2943<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
2944<span class="line-number">2</span>
2945<span class="line-number">3</span>
2946<span class="line-number">4</span>
2947<span class="line-number">5</span>
2948<span class="line-number">6</span>
2949<span class="line-number">7</span>
2950<span class="line-number">8</span>
2951<span class="line-number">9</span>
2952<span class="line-number">10</span>
2953<span class="line-number">11</span>
2954<span class="line-number">12</span>
2955<span class="line-number">13</span>
2956<span class="line-number">14</span>
2957<span class="line-number">15</span>
2958<span class="line-number">16</span>
2959<span class="line-number">17</span>
2960<span class="line-number">18</span>
2961<span class="line-number">19</span>
2962<span class="line-number">20</span>
2963<span class="line-number">21</span>
2964<span class="line-number">22</span>
2965<span class="line-number">23</span>
2966</pre></td><td class="code"><pre><code class="C#"><span class="line"><span class="k">static</span> <span class="k">void</span> <span class="nf">Main</span><span class="p">(</span><span class="kt">string</span><span class="p">[]</span> <span class="n">args</span><span class="p">)</span> <span class="p">{</span>
2967</span><span class="line">    <span class="n">ProcessStrings</span><span class="p">(</span>
2968</span><span class="line">        <span class="n">SetOfUserInput</span><span class="p">(</span><span class="s">&quot;Enter a web site url&quot;</span><span class="p">),</span>
2969</span><span class="line">        <span class="n">str</span> <span class="p">=&gt;</span> <span class="n">ProcessWebSite</span><span class="p">(</span><span class="n">str</span><span class="p">,</span> <span class="k">true</span><span class="p">));</span>
2970</span><span class="line"><span class="p">}</span>
2971</span><span class="line">
2972</span><span class="line"><span class="k">static</span> <span class="k">void</span> <span class="nf">ProcessStrings</span><span class="p">(</span><span class="n">IEnumerable</span><span class="p">&lt;</span><span class="kt">string</span><span class="p">&gt;</span> <span class="n">setOfStrings</span><span class="p">,</span> <span class="n">Action</span><span class="p">&lt;</span><span class="kt">string</span><span class="p">&gt;</span> <span class="n">fn</span><span class="p">)</span> <span class="p">{</span>
2973</span><span class="line">    <span class="k">foreach</span> <span class="p">(</span><span class="kt">var</span> <span class="n">item</span> <span class="k">in</span> <span class="n">setOfStrings</span><span class="p">)</span> <span class="n">fn</span><span class="p">(</span><span class="n">item</span><span class="p">);</span>
2974</span><span class="line"><span class="p">}</span>
2975</span><span class="line">
2976</span><span class="line"><span class="k">static</span> <span class="n">IEnumerable</span><span class="p">&lt;</span><span class="kt">string</span><span class="p">&gt;</span> <span class="n">SetOfUserInput</span><span class="p">(</span><span class="kt">string</span> <span class="n">prompt</span><span class="p">)</span> <span class="p">{</span>
2977</span><span class="line">    <span class="kt">string</span> <span class="n">input</span> <span class="p">=</span> <span class="kt">string</span><span class="p">.</span><span class="n">Empty</span><span class="p">;</span>
2978</span><span class="line">    <span class="kt">bool</span> <span class="n">done</span> <span class="p">=</span> <span class="k">false</span><span class="p">;</span>
2979</span><span class="line">    <span class="k">do</span> <span class="p">{</span>
2980</span><span class="line">        <span class="n">Console</span><span class="p">.</span><span class="n">Write</span><span class="p">(</span><span class="s">&quot;{0}. Press enter to end: &quot;</span><span class="p">,</span> <span class="n">prompt</span><span class="p">);</span>
2981</span><span class="line">        <span class="n">input</span> <span class="p">=</span> <span class="n">Console</span><span class="p">.</span><span class="n">ReadLine</span><span class="p">();</span>
2982</span><span class="line">        <span class="k">if</span> <span class="p">(</span><span class="kt">string</span><span class="p">.</span><span class="n">IsNullOrEmpty</span><span class="p">(</span><span class="n">input</span><span class="p">))</span> <span class="p">{</span>
2983</span><span class="line">            <span class="n">done</span> <span class="p">=</span> <span class="k">true</span><span class="p">;</span>
2984</span><span class="line">        <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
2985</span><span class="line">            <span class="k">yield</span> <span class="k">return</span> <span class="n">input</span><span class="p">;</span>
2986</span><span class="line">        <span class="p">}</span>
2987</span><span class="line">    <span class="p">}</span> <span class="k">while</span> <span class="p">(!</span><span class="n">done</span><span class="p">);</span>
2988</span><span class="line"><span class="p">}</span>
2989</span></code></pre></td></tr></table></div></figure></notextile></div>
2990
2991<p>Now we’ve got a function that returns a set of strings (IEnumerable<string> is the .NET way of saying a set of strings), and a function that takes a set of strings and applies a function to each member. The yield keyword makes the SetOfUserInput() method into a set. Each time the yield return keyword is hit, the value is passed out to the caller. When the caller attempts to retrieve the next value from the set, control is passed to the line after the yield return. This construct is called a continuation, and it’s a powerful concept.</string></p>
2992
2993<p>These two simple concepts, that functions can be passed around and worked on, and that you can generate sets of data using continuations, are simple and fundamental to functional programming. But as these examples show you can use these techniques to your advantage in C#, solving real, every day problems.</p>
2994]]></content>
2995  </entry>
2996  
2997  <entry>
2998    <title type="html"><![CDATA[C# Nuts and Bolts: Delegates and Functions, Part I]]></title>
2999    <link href="http://efvincent.github.io/blog/2009/08/24/nuts-bolts-delegates-functions-1/"/>
3000    <updated>2009-08-24T23:32:21-04:00</updated>
3001    <id>http://efvincent.github.io/blog/2009/08/24/nuts-bolts-delegates-functions-1</id>
3002    <content type="html"><![CDATA[<p>Two years ago I took up the <a href="http://en.wikipedia.org/wiki/OCaml">OCaml</a> programming language, purely out of intellectual curiosity. For me, <a href="http://en.wikipedia.org/wiki/OCaml">OCaml</a> was a gateway drug to functional programming in general. I’ve since spent a good bit of time with <a href="http://msdn.microsoft.com/en-us/fsharp/default.aspx">F#</a> and <a href="http://en.wikipedia.org/wiki/Haskell_(programming_language)">Haskell</a>. With the consulting work I do I don’t have the opportunity to use these languages in production, but I have found that using these languages has unlocked a new worlds of problem solving techniques.</p>
3003
3004<p>This series lays down a groundwork of C# understanding upon which we can build a library of modern problem solving techniques, where we take the most useful functional approaches, and see how to apply them to C# programming in .NET. Even if you’ve not any interest in functional programming, this series can be of service helping you understand some of the less obvious aspects of C# programming.
3005<!-- more --></p>
3006
3007<h2 id="delegates">Delegates</h2>
3008
3009<p>C++ has pointers to functions. C# has delegates. A <a href="http://msdn.microsoft.com/en-us/library/ms173171(VS.80).aspx">delegate</a> is a .NET type that can be thought of as a type safe function pointer. A function pointer is a variable that instead of pointing to or containing data, points to a function. This variable can be used to invoke, or call, the function it is pointing at.</p>
3010
3011<p><em>Type safe</em> refers to the fact that a delegate variable cannot point to just any function, it can only point to a function that matches the delegate’s <em>signature</em>. Signature refers to the parameters and return value of the function. Together, the parameters and return type form a fingerprint for a function which must match that the delegate.</p>
3012
3013<p>In this example, a delegate is created at line 5 called <code>GetStatsDelegate </code>where the signature specifies a single <code>string</code> parameter and an <code>integer</code> return value. Judging from the name, the delegate should point to a function that gets some stats about a string.</p>
3014
3015<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
3016<span class="line-number">2</span>
3017<span class="line-number">3</span>
3018<span class="line-number">4</span>
3019<span class="line-number">5</span>
3020<span class="line-number">6</span>
3021<span class="line-number">7</span>
3022<span class="line-number">8</span>
3023<span class="line-number">9</span>
3024<span class="line-number">10</span>
3025<span class="line-number">11</span>
3026<span class="line-number">12</span>
3027<span class="line-number">13</span>
3028<span class="line-number">14</span>
3029<span class="line-number">15</span>
3030<span class="line-number">16</span>
3031<span class="line-number">17</span>
3032<span class="line-number">18</span>
3033<span class="line-number">19</span>
3034<span class="line-number">20</span>
3035<span class="line-number">21</span>
3036<span class="line-number">22</span>
3037<span class="line-number">23</span>
3038<span class="line-number">24</span>
3039</pre></td><td class="code"><pre><code class="C#"><span class="line"><span class="k">class</span> <span class="nc">Program</span>
3040</span><span class="line"><span class="p">{</span>
3041</span><span class="line">    <span class="c1">// define a delegate type for a function that takes a</span>
3042</span><span class="line">    <span class="c1">// string and returns an int</span>
3043</span><span class="line">    <span class="k">delegate</span> <span class="kt">int</span> <span class="nf">GetStatsDelegate</span><span class="p">(</span><span class="kt">string</span> <span class="n">str</span><span class="p">);</span>
3044</span><span class="line">
3045</span><span class="line">    <span class="k">public</span> <span class="k">static</span> <span class="k">void</span> <span class="nf">main</span><span class="p">()</span> <span class="p">{</span>
3046</span><span class="line">
3047</span><span class="line">        <span class="c1">// Define a variable of our new delegate type, and</span>
3048</span><span class="line">        <span class="c1">// assign it a value. Any method with the same signature</span>
3049</span><span class="line">        <span class="c1">// can be assigned to this variable.</span>
3050</span><span class="line">        <span class="n">GetStatsDelegate</span> <span class="n">myFunc</span> <span class="p">=</span> <span class="n">GetLengthWithoutSpaces</span><span class="p">;</span>
3051</span><span class="line">
3052</span><span class="line">        <span class="c1">// Both these print 0</span>
3053</span><span class="line">        <span class="n">Console</span><span class="p">.</span><span class="n">WriteLine</span><span class="p">(</span><span class="n">myFunc</span><span class="p">(</span><span class="s">&quot;Hello&quot;</span><span class="p">));</span>
3054</span><span class="line">        <span class="n">Console</span><span class="p">.</span><span class="n">WriteLine</span><span class="p">(</span><span class="n">GetLengthWithoutSpaces</span><span class="p">(</span><span class="s">&quot;Hello&quot;</span><span class="p">));</span>
3055</span><span class="line">    <span class="p">}</span>
3056</span><span class="line">
3057</span><span class="line">    <span class="c1">// This is a function that we can point to, because it has</span>
3058</span><span class="line">    <span class="c1">// the right signature for our delegate</span>
3059</span><span class="line">    <span class="k">public</span> <span class="k">static</span> <span class="kt">int</span> <span class="nf">GetLengthWithoutSpaces</span><span class="p">(</span><span class="kt">string</span> <span class="n">s</span><span class="p">)</span> <span class="p">{</span>
3060</span><span class="line">        <span class="k">return</span> <span class="m">0</span><span class="p">;</span>
3061</span><span class="line">    <span class="p">}</span>
3062</span><span class="line"><span class="p">}</span>
3063</span></code></pre></td></tr></table></div></figure></notextile></div>
3064
3065<p>At line 12 the delegate we created (which is a type) is used to define a variable, <code>myFunc</code>. We then set <code>myFunc’s</code> value equal to <code>GetLengthWithoutSpaces</code>, which is a function. Lines 15 and 16 call the function, once using the delegate, and once the traditional way.<a href="http://blog.efvincent.com/wp-content/uploads/2009/08/image.png"><img src="http://blog.efvincent.com/wp-content/uploads/2009/08/image_thumb.png" alt="image" /></a></p>
3066
3067<p>Here’s where it starts to get interesting. This is a snip from <a href="http://www.red-gate.com/products/reflector/">Reflector</a>, looking at how <code>GetStatsDelegate</code> is defined.  We defined it as a delegate, but the compiler has built what looks like a standard class which inherits from the MulticastDelegate framework class.</p>
3068
3069<p>This is good to know. C# treats delegates in a special way. They’ve been granted their own keyword and a special unique way of declaration. The declaration declares a subclass for us, saving us the trouble of building out a subclass ourselves. If we use Reflector to dig into the base class (System.Delegate), we see these properties and fields:</p>
3070
3071<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
3072<span class="line-number">2</span>
3073<span class="line-number">3</span>
3074<span class="line-number">4</span>
3075<span class="line-number">5</span>
3076<span class="line-number">6</span>
3077<span class="line-number">7</span>
3078<span class="line-number">8</span>
3079<span class="line-number">9</span>
3080<span class="line-number">10</span>
3081<span class="line-number">11</span>
3082<span class="line-number">12</span>
3083<span class="line-number">13</span>
3084<span class="line-number">14</span>
3085<span class="line-number">15</span>
3086<span class="line-number">16</span>
3087<span class="line-number">17</span>
3088</pre></td><td class="code"><pre><code class="C#"><span class="line"><span class="c1">// *** From Delegate ***</span>
3089</span><span class="line">
3090</span><span class="line"><span class="c1">// Properties</span>
3091</span><span class="line"><span class="k">public</span> <span class="n">MethodInfo</span> <span class="n">Method</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="p">}</span>
3092</span><span class="line"><span class="k">public</span> <span class="kt">object</span> <span class="n">Target</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="p">}</span>
3093</span><span class="line">
3094</span><span class="line"><span class="c1">// Fields</span>
3095</span><span class="line"><span class="k">internal</span> <span class="n">MethodBase</span> <span class="n">_methodBase</span><span class="p">;</span>
3096</span><span class="line"><span class="k">internal</span> <span class="n">IntPtr</span> <span class="n">_methodPtr</span><span class="p">;</span>
3097</span><span class="line"><span class="k">internal</span> <span class="n">IntPtr</span> <span class="n">_methodPtrAux</span><span class="p">;</span>
3098</span><span class="line"><span class="k">internal</span> <span class="kt">object</span> <span class="n">_target</span><span class="p">;</span>
3099</span><span class="line">
3100</span><span class="line"><span class="c1">// *** From MulticastDelegate ***</span>
3101</span><span class="line">
3102</span><span class="line"><span class="c1">// Fields</span>
3103</span><span class="line"><span class="k">private</span> <span class="n">IntPtr</span> <span class="n">_invocationCount</span><span class="p">;</span>
3104</span><span class="line"><span class="k">private</span> <span class="kt">object</span> <span class="n">_invocationList</span><span class="p">;</span>
3105</span></code></pre></td></tr></table></div></figure></notextile></div>
3106
3107<p>These fields tell us a few things. An instance of a delegate has reflection information about the method it points to, this is what the <code>MethodInfo</code> public property. The pointer to the function itself is of type <code>IntPtr</code>, which we can think about as a pointer to memory.</p>
3108
3109<p>The <code>_target</code> field is important too. In the case of a delegate that points to an instance method (ie a non-static method on a non-null object), the <code>_target</code> field points to the object with the method. This is important because it is not obvious from looking at code that a delegate holds a reference to the object with the method. It’s possible for this to be the source of memory leaks, where objects cannot be garbage collected because a delegate is holding a reference. You see this most often in events. Being delegates, events hold references that need to be <em>unregistered</em> in order to release these references.</p>
3110
3111<p>Also we have something called <code>_invocationList</code>, which if we dig through the disassembly we come to find is an array of Delegates implemented as a linked list using pointers (<code>IntPtr</code>) directly for performance reasons. This means that <code>MulticastDelegates</code> are delegates that have a chain of additional delegates. This is used heavily in .NET’s event mechanism, where an <em>event</em> can have multiple <em>handlers</em>. The handlers are simply functions wrapped in delegates added to the linked list of a the event <code>MulticastDelegate</code>.</p>
3112
3113<p>Next post we’ll look at using delegates, not as events (which anyone who has ever dropped a button on a form knows about), but as function pointers and objects, and start looking at some novel approaches to solving common problems.</p>
3114
3115<p><em>As always if you’ve got questions or topics you’d like me to follow up on, please leave a not in the comments!</em></p>
3116]]></content>
3117  </entry>
3118  
3119  <entry>
3120    <title type="html"><![CDATA[Adding Concurrency Optimization in Silverlight 3]]></title>
3121    <link href="http://efvincent.github.io/blog/2009/08/18/concurrency-optimization-silverlight/"/>
3122    <updated>2009-08-18T01:33:22-04:00</updated>
3123    <id>http://efvincent.github.io/blog/2009/08/18/concurrency-optimization-silverlight</id>
3124    <content type="html"><![CDATA[<p>About a week ago Joa Ebert posted <a href="http://blog.joa-ebert.com/2009/08/10/flirting-with-silverlight/">Flirting with Silverlight</a>, in which he discussed his experiences with a cool little Lorenz attractor application. The <em>strange attractor</em> app (which you can check at his <a href="http://blog.joa-ebert.com/2009/08/10/flirting-with-silverlight/">blog</a>) was his way of playing around with the newly released Silverlight 3 (Props to Joa for some very cool work BTW). It calculates a shape in 3D defined by some 300,000 particles, and animates the spinning and rotating of this shape as the user moves the mouse across the display surface.</p>
3125
3126<p>His point was to relate his first Silverlight experience, and how the non-optimized Silverlight application compared very favorably with the significantly optimized AS3 version. The HTML5 Javascript version was a non-starter, barely able to achieve a few frames per second compared to 30 for AS3 and SL3.
3127<!-- more -->
3128Joa made <a href="http://blog.joa-ebert.com/2009/08/10/flirting-with-silverlight/">his code</a> available. After looking at the SL3 source code I thought it would be trivial to add some basic concurrency that would <em>significantly</em> increase performance. Here’s a comparison of different implementations:</p>
3129
3130<ul>
3131  <li><a href="http://www.joa-ebert.com/swf/index.php?swf=alchemy/Example03">Flash AS3 Version</a>, Optimized</li>
3132  <li><a href="http://www.joa-ebert.com/files/xpa/attractor/">Original Silverlight Version</a>, naive implementation</li>
3133  <li><a href="http://efvincent.com/poc/strangeattractor/">Silverlight Version</a>, optimized to leverage Concurrency</li>
3134  <li><a href="http://mediaerror.com/lab/javascript/strangeattractor">HTML 5 Version</a></li>
3135</ul>
3136
3137<p>A point of interest, as far as I know there is <a href="http://blogs.adobe.com/aharui/2008/01/threads_in_actionscript_3.html">no way to do concurrency in Action Script 3</a>. In Joa’s application, the bulk of the hard work is done in a loop that executes every frame:</p>
3138
3139<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
3140<span class="line-number">2</span>
3141<span class="line-number">3</span>
3142<span class="line-number">4</span>
3143<span class="line-number">5</span>
3144<span class="line-number">6</span>
3145<span class="line-number">7</span>
3146<span class="line-number">8</span>
3147<span class="line-number">9</span>
3148<span class="line-number">10</span>
3149<span class="line-number">11</span>
3150<span class="line-number">12</span>
3151<span class="line-number">13</span>
3152<span class="line-number">14</span>
3153<span class="line-number">15</span>
3154<span class="line-number">16</span>
3155<span class="line-number">17</span>
3156<span class="line-number">18</span>
3157<span class="line-number">19</span>
3158<span class="line-number">20</span>
3159<span class="line-number">21</span>
3160<span class="line-number">22</span>
3161<span class="line-number">23</span>
3162<span class="line-number">24</span>
3163<span class="line-number">25</span>
3164<span class="line-number">26</span>
3165<span class="line-number">27</span>
3166<span class="line-number">28</span>
3167<span class="line-number">29</span>
3168<span class="line-number">30</span>
3169<span class="line-number">31</span>
3170<span class="line-number">32</span>
3171<span class="line-number">33</span>
3172<span class="line-number">34</span>
3173<span class="line-number">35</span>
3174<span class="line-number">36</span>
3175<span class="line-number">37</span>
3176<span class="line-number">38</span>
3177<span class="line-number">39</span>
3178<span class="line-number">40</span>
3179<span class="line-number">41</span>
3180<span class="line-number">42</span>
3181<span class="line-number">43</span>
3182<span class="line-number">44</span>
3183<span class="line-number">45</span>
3184<span class="line-number">46</span>
3185<span class="line-number">47</span>
3186<span class="line-number">48</span>
3187<span class="line-number">49</span>
3188<span class="line-number">50</span>
3189<span class="line-number">51</span>
3190<span class="line-number">52</span>
3191<span class="line-number">53</span>
3192<span class="line-number">54</span>
3193<span class="line-number">55</span>
3194</pre></td><td class="code"><pre><code class="C#"><span class="line"><span class="k">void</span> <span class="nf">OnStoryboardCompleted</span><span class="p">(</span><span class="kt">object</span> <span class="n">sender</span><span class="p">,</span> <span class="n">EventArgs</span> <span class="n">eventArgs</span><span class="p">)</span>
3195</span><span class="line"><span class="p">{</span>
3196</span><span class="line">    <span class="n">targetX</span> <span class="p">+=</span> <span class="p">(</span><span class="n">mouseX</span> <span class="p">-</span> <span class="n">targetX</span><span class="p">)</span> <span class="p">*</span> <span class="m">0.1</span><span class="p">;</span>
3197</span><span class="line">    <span class="n">targetY</span> <span class="p">+=</span> <span class="p">(</span><span class="n">mouseY</span> <span class="p">-</span> <span class="n">targetY</span><span class="p">)</span> <span class="p">*</span> <span class="m">0.1</span><span class="p">;</span>
3198</span><span class="line">
3199</span><span class="line">    <span class="kt">var</span> <span class="n">index</span> <span class="p">=</span> <span class="n">MaxScreen</span><span class="p">;</span>
3200</span><span class="line">    <span class="kt">var</span> <span class="n">maxIndex</span> <span class="p">=</span> <span class="n">MaxScreen</span><span class="p">;</span>
3201</span><span class="line">
3202</span><span class="line">    <span class="k">while</span> <span class="p">(--</span><span class="n">index</span> <span class="p">&gt;</span> <span class="p">-</span><span class="m">1</span><span class="p">)</span>
3203</span><span class="line">        <span class="n">bitmap</span><span class="p">.</span><span class="n">Pixels</span><span class="p">[</span><span class="n">index</span><span class="p">]</span> <span class="p">=</span> <span class="m">0</span><span class="n">x000000</span><span class="p">;</span>
3204</span><span class="line">
3205</span><span class="line">    <span class="kt">var</span> <span class="n">particle</span> <span class="p">=</span> <span class="n">particles</span><span class="p">;</span>
3206</span><span class="line">    <span class="kt">var</span> <span class="n">matrix</span> <span class="p">=</span> <span class="n">Matrix4x4</span><span class="p">.</span><span class="n">RotationY</span><span class="p">(</span><span class="n">targetX</span> <span class="p">*</span> <span class="m">0.05</span><span class="p">)</span> <span class="p">*</span> <span class="n">Matrix4x4</span><span class="p">.</span><span class="n">RotationX</span><span class="p">(</span><span class="n">targetY</span> <span class="p">*</span> <span class="m">0.05</span><span class="p">)</span> <span class="p">*</span> <span class="n">translationMatrix</span><span class="p">;</span>
3207</span><span class="line">
3208</span><span class="line">    <span class="kt">var</span> <span class="n">cx</span> <span class="p">=</span> <span class="m">275.0</span><span class="p">;</span>
3209</span><span class="line">    <span class="kt">var</span> <span class="n">cy</span> <span class="p">=</span> <span class="m">200.0</span><span class="p">;</span>
3210</span><span class="line">
3211</span><span class="line">    <span class="kt">var</span> <span class="n">w</span> <span class="p">=</span> <span class="m">0.0</span><span class="p">;</span>
3212</span><span class="line">    <span class="kt">var</span> <span class="n">xi</span> <span class="p">=</span> <span class="m">0</span><span class="p">;</span>
3213</span><span class="line">    <span class="kt">var</span> <span class="n">yi</span> <span class="p">=</span> <span class="m">0</span><span class="p">;</span>
3214</span><span class="line">    <span class="kt">var</span> <span class="n">x</span> <span class="p">=</span> <span class="m">0.0</span><span class="p">;</span>
3215</span><span class="line">    <span class="kt">var</span> <span class="n">y</span> <span class="p">=</span> <span class="m">0.0</span><span class="p">;</span>
3216</span><span class="line">    <span class="kt">var</span> <span class="n">z</span> <span class="p">=</span> <span class="m">0.0</span><span class="p">;</span>
3217</span><span class="line">    <span class="kt">var</span> <span class="n">pz</span> <span class="p">=</span> <span class="m">0.0</span><span class="p">;</span>
3218</span><span class="line">
3219</span><span class="line">    <span class="k">while</span> <span class="p">(</span><span class="k">null</span> <span class="p">!=</span> <span class="n">particle</span><span class="p">)</span>
3220</span><span class="line">    <span class="p">{</span>
3221</span><span class="line">        <span class="n">x</span> <span class="p">=</span> <span class="n">particle</span><span class="p">.</span><span class="n">X</span><span class="p">;</span>
3222</span><span class="line">        <span class="n">y</span> <span class="p">=</span> <span class="n">particle</span><span class="p">.</span><span class="n">Y</span><span class="p">;</span>
3223</span><span class="line">        <span class="n">z</span> <span class="p">=</span> <span class="n">particle</span><span class="p">.</span><span class="n">Z</span><span class="p">;</span>
3224</span><span class="line">
3225</span><span class="line">        <span class="n">pz</span> <span class="p">=</span> <span class="n">focalLength</span> <span class="p">+</span> <span class="n">x</span> <span class="p">*</span> <span class="n">matrix</span><span class="p">.</span><span class="n">I02</span> <span class="p">+</span> <span class="n">y</span> <span class="p">*</span> <span class="n">matrix</span><span class="p">.</span><span class="n">I12</span> <span class="p">+</span> <span class="n">z</span> <span class="p">*</span> <span class="n">matrix</span><span class="p">.</span><span class="n">I22</span> <span class="p">+</span> <span class="n">matrix</span><span class="p">.</span><span class="n">I32</span><span class="p">;</span>
3226</span><span class="line">
3227</span><span class="line">        <span class="k">if</span> <span class="p">(</span><span class="m">0.0</span> <span class="p">&lt;</span> <span class="n">pz</span><span class="p">)</span>
3228</span><span class="line">        <span class="p">{</span>
3229</span><span class="line">            <span class="n">xi</span> <span class="p">=</span> <span class="p">(</span><span class="kt">int</span><span class="p">)(</span> <span class="p">(</span> <span class="n">w</span> <span class="p">=</span> <span class="n">focalLength</span> <span class="p">/</span> <span class="n">pz</span> <span class="p">)</span> <span class="p">*</span> <span class="p">(</span> <span class="n">x</span> <span class="p">*</span> <span class="n">matrix</span><span class="p">.</span><span class="n">I00</span> <span class="p">+</span> <span class="n">y</span> <span class="p">*</span> <span class="n">matrix</span><span class="p">.</span><span class="n">I10</span> <span class="p">+</span> <span class="n">z</span> <span class="p">*</span> <span class="n">matrix</span><span class="p">.</span><span class="n">I20</span> <span class="p">)</span> <span class="p">+</span> <span class="n">cx</span> <span class="p">);</span>
3230</span><span class="line">            <span class="n">yi</span> <span class="p">=</span> <span class="p">(</span><span class="kt">int</span><span class="p">)(</span> <span class="n">w</span> <span class="p">*</span> <span class="p">(</span> <span class="n">x</span> <span class="p">*</span> <span class="n">matrix</span><span class="p">.</span><span class="n">I01</span> <span class="p">+</span> <span class="n">y</span> <span class="p">*</span> <span class="n">matrix</span><span class="p">.</span><span class="n">I11</span> <span class="p">+</span> <span class="n">z</span> <span class="p">*</span> <span class="n">matrix</span><span class="p">.</span><span class="n">I21</span> <span class="p">)</span> <span class="p">+</span> <span class="n">cy</span> <span class="p">);</span>
3231</span><span class="line">
3232</span><span class="line">            <span class="n">index</span> <span class="p">=</span> <span class="n">xi</span> <span class="p">+</span> <span class="n">yi</span> <span class="p">*</span> <span class="n">ScreenWidth</span><span class="p">;</span>
3233</span><span class="line">
3234</span><span class="line">            <span class="k">if</span> <span class="p">(</span><span class="n">index</span> <span class="p">&gt;</span> <span class="p">-</span><span class="m">1</span> <span class="p">&amp;&amp;</span> <span class="n">index</span> <span class="p">&lt;</span> <span class="n">maxIndex</span><span class="p">)</span>
3235</span><span class="line">            <span class="p">{</span>
3236</span><span class="line">                <span class="kt">var</span> <span class="n">color</span> <span class="p">=</span> <span class="n">bitmap</span><span class="p">.</span><span class="n">Pixels</span><span class="p">[</span><span class="n">index</span><span class="p">]</span> <span class="p">+</span> <span class="m">0</span><span class="n">x202020</span><span class="p">;</span>
3237</span><span class="line">                <span class="n">bitmap</span><span class="p">.</span><span class="n">Pixels</span><span class="p">[</span><span class="n">index</span><span class="p">]</span> <span class="p">=</span> <span class="n">color</span> <span class="p">&gt;</span> <span class="m">0</span><span class="n">xffffff</span> <span class="p">?</span> <span class="m">0</span><span class="n">xffffff</span> <span class="p">:</span> <span class="n">color</span><span class="p">;</span>
3238</span><span class="line">           <span class="p">}</span>
3239</span><span class="line">        <span class="p">}</span>
3240</span><span class="line">
3241</span><span class="line">        <span class="n">particle</span> <span class="p">=</span> <span class="n">particle</span><span class="p">.</span><span class="n">Next</span><span class="p">;</span>
3242</span><span class="line">    <span class="p">}</span>
3243</span><span class="line">
3244</span><span class="line">    <span class="n">bitmap</span><span class="p">.</span><span class="n">Invalidate</span><span class="p">();</span>
3245</span><span class="line">
3246</span><span class="line">    <span class="n">storyboard</span><span class="p">.</span><span class="n">Begin</span><span class="p">();</span>
3247</span><span class="line">  <span class="p">}</span>
3248</span><span class="line"><span class="p">}</span>
3249</span></code></pre></td></tr></table></div></figure></notextile></div>
3250
3251<p>What he’s doing here is writing pixels into a bitmap. At line 9, he sets all the pixels to zero (black), erasing the previous frame. At line 23 he starts a loop that will calculate each pixel that should be turned on for the upcoming frame. In both these cases he’s dealing with a one dimensional array of pixels. This is the perfect case for data parallelism. The work of setting pixels can be divided between processors.</p>
3252
3253<p>In general, concurrency is not a simple technique to implement correctly. The number and type of problems that one can run into are <strong>way</strong> beyond the scope of anything short of a very thick book. But this perhaps the simplest case; simple <em>static composition data parallelism</em>. It’s static because you can pre-assign the amount of work each thread will do. It’s data parallelism because each thread will be doing the same kind of work (calculating and flipping pixels), as opposed to a solution where one thread does one thing (like talk on the network) while another thread does something else (like shred xml files).</p>
3254
3255<p>We get this done by building a function that behaves like a <code>For()</code> loop, but executes the body in parallel between several threads. If you’ve played with the recently released Visual Studio 2010 beta that has the .NET 4.0 framework, you’ll recognize this function which is in the next version of the framework (but in a far more sophisticated and powerful form).</p>
3256
3257<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
3258<span class="line-number">2</span>
3259<span class="line-number">3</span>
3260<span class="line-number">4</span>
3261<span class="line-number">5</span>
3262<span class="line-number">6</span>
3263<span class="line-number">7</span>
3264<span class="line-number">8</span>
3265<span class="line-number">9</span>
3266<span class="line-number">10</span>
3267<span class="line-number">11</span>
3268<span class="line-number">12</span>
3269<span class="line-number">13</span>
3270<span class="line-number">14</span>
3271<span class="line-number">15</span>
3272<span class="line-number">16</span>
3273<span class="line-number">17</span>
3274<span class="line-number">18</span>
3275<span class="line-number">19</span>
3276<span class="line-number">20</span>
3277<span class="line-number">21</span>
3278<span class="line-number">22</span>
3279<span class="line-number">23</span>
3280<span class="line-number">24</span>
3281</pre></td><td class="code"><pre><code class="C#"><span class="line"><span class="k">void</span> <span class="nf">ParallelFor</span><span class="p">(</span><span class="kt">int</span> <span class="n">lo</span><span class="p">,</span> <span class="kt">int</span> <span class="n">hi</span><span class="p">,</span> <span class="n">Action</span><span class="p">&lt;</span><span class="kt">int</span><span class="p">&gt;</span> <span class="n">body</span><span class="p">,</span> <span class="kt">int</span> <span class="n">p</span><span class="p">)</span>
3282</span><span class="line"><span class="p">{</span>
3283</span><span class="line">    <span class="kt">int</span> <span class="n">chunk</span> <span class="p">=</span> <span class="p">(</span><span class="n">hi</span> <span class="p">-</span> <span class="n">lo</span><span class="p">)</span> <span class="p">/</span> <span class="n">p</span><span class="p">;</span>      <span class="c1">// Iterations per thread</span>
3284</span><span class="line">
3285</span><span class="line">    <span class="n">AutoResetEvent</span><span class="p">[]</span> <span class="n">latch</span> <span class="p">=</span> <span class="k">new</span> <span class="n">AutoResetEvent</span><span class="p">[</span><span class="n">p</span><span class="p">];</span>
3286</span><span class="line">    <span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="p">=</span> <span class="m">0</span><span class="p">;</span> <span class="n">i</span> <span class="p">&lt;</span> <span class="n">p</span><span class="p">;</span> <span class="n">i</span><span class="p">++)</span> <span class="n">latch</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="p">=</span> <span class="k">new</span> <span class="n">AutoResetEvent</span><span class="p">(</span><span class="k">false</span><span class="p">);</span>
3287</span><span class="line">
3288</span><span class="line">    <span class="c1">// Schedule the events to run in parallel</span>
3289</span><span class="line">    <span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="p">=</span> <span class="m">0</span><span class="p">;</span> <span class="n">i</span> <span class="p">&lt;</span> <span class="n">p</span><span class="p">;</span> <span class="n">i</span><span class="p">++)</span>
3290</span><span class="line">    <span class="p">{</span>
3291</span><span class="line">        <span class="n">ThreadPool</span><span class="p">.</span><span class="n">QueueUserWorkItem</span><span class="p">((</span><span class="n">ob</span><span class="p">)</span> <span class="p">=&gt;</span>
3292</span><span class="line">        <span class="p">{</span>
3293</span><span class="line">            <span class="kt">int</span> <span class="n">pid</span> <span class="p">=</span> <span class="p">(</span><span class="kt">int</span><span class="p">)</span><span class="n">ob</span><span class="p">;</span>
3294</span><span class="line">            <span class="kt">int</span> <span class="n">start</span> <span class="p">=</span> <span class="n">lo</span> <span class="p">+</span> <span class="n">pid</span> <span class="p">*</span> <span class="n">chunk</span><span class="p">;</span>
3295</span><span class="line">            <span class="kt">int</span> <span class="n">end</span> <span class="p">=</span> <span class="n">pid</span> <span class="p">==</span> <span class="n">p</span> <span class="p">-</span> <span class="m">1</span> <span class="p">?</span> <span class="n">hi</span> <span class="p">:</span> <span class="n">start</span> <span class="p">+</span> <span class="n">chunk</span><span class="p">;</span>
3296</span><span class="line">            <span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">j</span> <span class="p">=</span> <span class="n">start</span><span class="p">;</span> <span class="n">j</span> <span class="p">&lt;</span> <span class="n">end</span><span class="p">;</span> <span class="n">j</span><span class="p">++)</span>
3297</span><span class="line">            <span class="p">{</span>
3298</span><span class="line">                <span class="n">body</span><span class="p">(</span><span class="n">j</span><span class="p">);</span>
3299</span><span class="line">            <span class="p">}</span>
3300</span><span class="line">            <span class="n">latch</span><span class="p">[</span><span class="n">pid</span><span class="p">].</span><span class="n">Set</span><span class="p">();</span>
3301</span><span class="line">        <span class="p">},</span> <span class="n">i</span><span class="p">);</span>
3302</span><span class="line">    <span class="p">}</span>
3303</span><span class="line">    <span class="n">WaitHandle</span><span class="p">.</span><span class="n">WaitAll</span><span class="p">(</span><span class="n">latch</span><span class="p">);</span>
3304</span><span class="line"><span class="p">}</span>
3305</span></code></pre></td></tr></table></div></figure></notextile></div>
3306
3307<p>ParallelFor() takes lo and hi values, an <code>Action&lt;int&gt;</code>, and the degree of desired parallelism. The <code>Action&lt;int&gt; </code>is a delegate, which is like a pointer to a function. In this case, it’s a pointer to a function that has a single int parameter, and returns void. This function is the work that happens every iteration. Silverlight, .NET, and C# make it possible (I think it’s easy, but I’ve been doing this a while) to use anonymous methods and what amount to functional techniques to make Joa’s code multithreaded.  It may be best to illustrate by example.</p>
3308
3309<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
3310<span class="line-number">2</span>
3311</pre></td><td class="code"><pre><code class="C#"><span class="line"><span class="k">while</span> <span class="p">(--</span><span class="n">index</span> <span class="p">&gt;</span> <span class="p">-</span><span class="m">1</span><span class="p">)</span>
3312</span><span class="line">    <span class="n">bitmap</span><span class="p">.</span><span class="n">Pixels</span><span class="p">[</span><span class="n">index</span><span class="p">]</span> <span class="p">=</span> <span class="m">0</span><span class="n">x000000</span><span class="p">;</span>
3313</span></code></pre></td></tr></table></div></figure></notextile></div>
3314
3315<p>Joa’s code above, which initializes the pixels in the bitmap, becomes:</p>
3316
3317<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
3318</pre></td><td class="code"><pre><code class="C#"><span class="line"><span class="n">ParallelFor</span><span class="p">(</span><span class="m">0</span><span class="p">,</span> <span class="n">buffer</span><span class="p">.</span><span class="n">Pixels</span><span class="p">.</span><span class="n">Length</span><span class="p">,</span> <span class="p">(</span><span class="n">i</span><span class="p">)</span> <span class="p">=&gt;</span> <span class="n">buffer</span><span class="p">.</span><span class="n">Pixels</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="p">=</span> <span class="m">0</span><span class="n">x0</span><span class="p">,</span> <span class="n">numComputationThreads</span><span class="p">);</span>
3319</span></code></pre></td></tr></table></div></figure></notextile></div>
3320
3321<p>The parameters of ParallelFor are zero for where to start the for loop, Pixels.Length for where to end the loop, the lambda <code>function (i) =&gt; buffer.Pixels[i] = 0x0</code>, and the number of threads to use to do the work. The lambda function is anonymous (i.e. we don’t have to create a function with a name). The type of “i” is <em>inferred</em> from context to be an int. The body of the lambda (the part after the “=&gt;”), is the work that is done each time through the loop.</p>
3322
3323<p>This makes the clearing of last frame’s bitmap concurrent. To make the rendering of the next frame concurrent is a bit more invasive, but still not bad. Here’s the concurrent version.</p>
3324
3325<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
3326<span class="line-number">2</span>
3327<span class="line-number">3</span>
3328<span class="line-number">4</span>
3329<span class="line-number">5</span>
3330<span class="line-number">6</span>
3331<span class="line-number">7</span>
3332<span class="line-number">8</span>
3333<span class="line-number">9</span>
3334<span class="line-number">10</span>
3335<span class="line-number">11</span>
3336<span class="line-number">12</span>
3337<span class="line-number">13</span>
3338<span class="line-number">14</span>
3339<span class="line-number">15</span>
3340<span class="line-number">16</span>
3341<span class="line-number">17</span>
3342<span class="line-number">18</span>
3343<span class="line-number">19</span>
3344<span class="line-number">20</span>
3345<span class="line-number">21</span>
3346<span class="line-number">22</span>
3347<span class="line-number">23</span>
3348<span class="line-number">24</span>
3349<span class="line-number">25</span>
3350<span class="line-number">26</span>
3351<span class="line-number">27</span>
3352<span class="line-number">28</span>
3353<span class="line-number">29</span>
3354<span class="line-number">30</span>
3355<span class="line-number">31</span>
3356<span class="line-number">32</span>
3357<span class="line-number">33</span>
3358</pre></td><td class="code"><pre><code class="C#"><span class="line"><span class="n">ParallelFor</span><span class="p">(</span><span class="m">0</span><span class="p">,</span> <span class="n">particles</span><span class="p">.</span><span class="n">Length</span><span class="p">,</span> <span class="p">(</span><span class="n">i</span><span class="p">)</span> <span class="p">=&gt;</span>
3359</span><span class="line"><span class="p">{</span>
3360</span><span class="line">    <span class="n">Particle</span> <span class="n">part</span> <span class="p">=</span> <span class="n">particles</span><span class="p">[</span><span class="n">i</span><span class="p">];</span>
3361</span><span class="line">    <span class="kt">var</span> <span class="n">x</span> <span class="p">=</span> <span class="n">part</span><span class="p">.</span><span class="n">X</span><span class="p">;</span>
3362</span><span class="line">    <span class="kt">var</span> <span class="n">y</span> <span class="p">=</span> <span class="n">part</span><span class="p">.</span><span class="n">Y</span><span class="p">;</span>
3363</span><span class="line">    <span class="kt">var</span> <span class="n">z</span> <span class="p">=</span> <span class="n">part</span><span class="p">.</span><span class="n">Z</span><span class="p">;</span>
3364</span><span class="line">
3365</span><span class="line">    <span class="kt">var</span> <span class="n">w</span> <span class="p">=</span> <span class="m">0.0</span><span class="p">;</span>
3366</span><span class="line">    <span class="kt">var</span> <span class="n">xi</span> <span class="p">=</span> <span class="m">0</span><span class="p">;</span>
3367</span><span class="line">    <span class="kt">var</span> <span class="n">yi</span> <span class="p">=</span> <span class="m">0</span><span class="p">;</span>
3368</span><span class="line">
3369</span><span class="line">    <span class="kt">var</span> <span class="n">pz</span> <span class="p">=</span> <span class="n">focalLength</span> <span class="p">+</span> <span class="n">x</span> <span class="p">*</span> <span class="n">matrix</span><span class="p">.</span><span class="n">I02</span> <span class="p">+</span> <span class="n">y</span> <span class="p">*</span> <span class="n">matrix</span><span class="p">.</span><span class="n">I12</span> <span class="p">+</span> <span class="n">z</span> <span class="p">*</span> <span class="n">matrix</span><span class="p">.</span><span class="n">I22</span> <span class="p">+</span> <span class="n">matrix</span><span class="p">.</span><span class="n">I32</span><span class="p">;</span>
3370</span><span class="line">
3371</span><span class="line">    <span class="k">if</span> <span class="p">(</span><span class="m">0.0</span> <span class="p">&lt;</span> <span class="n">pz</span><span class="p">)</span>
3372</span><span class="line">    <span class="p">{</span>
3373</span><span class="line">        <span class="n">xi</span> <span class="p">=</span> <span class="p">(</span><span class="kt">int</span><span class="p">)((</span><span class="n">w</span> <span class="p">=</span> <span class="n">focalLength</span> <span class="p">/</span> <span class="n">pz</span><span class="p">)</span> <span class="p">*</span> <span class="p">(</span><span class="n">x</span> <span class="p">*</span> <span class="n">matrix</span><span class="p">.</span><span class="n">I00</span> <span class="p">+</span> <span class="n">y</span> <span class="p">*</span> <span class="n">matrix</span><span class="p">.</span><span class="n">I10</span> <span class="p">+</span> <span class="n">z</span> <span class="p">*</span> <span class="n">matrix</span><span class="p">.</span><span class="n">I20</span><span class="p">)</span> <span class="p">+</span> <span class="n">cx</span><span class="p">);</span>
3374</span><span class="line">        <span class="n">yi</span> <span class="p">=</span> <span class="p">(</span><span class="kt">int</span><span class="p">)(</span><span class="n">w</span> <span class="p">*</span> <span class="p">(</span><span class="n">x</span> <span class="p">*</span> <span class="n">matrix</span><span class="p">.</span><span class="n">I01</span> <span class="p">+</span> <span class="n">y</span> <span class="p">*</span> <span class="n">matrix</span><span class="p">.</span><span class="n">I11</span> <span class="p">+</span> <span class="n">z</span> <span class="p">*</span> <span class="n">matrix</span><span class="p">.</span><span class="n">I21</span><span class="p">)</span> <span class="p">+</span> <span class="n">cy</span><span class="p">);</span>
3375</span><span class="line">
3376</span><span class="line">        <span class="kt">var</span> <span class="n">index</span> <span class="p">=</span> <span class="n">xi</span> <span class="p">+</span> <span class="n">yi</span> <span class="p">*</span> <span class="n">ScreenWidth</span><span class="p">;</span>
3377</span><span class="line">
3378</span><span class="line">        <span class="k">if</span> <span class="p">(</span><span class="n">index</span> <span class="p">&gt;</span> <span class="p">-</span><span class="m">1</span> <span class="p">&amp;&amp;</span> <span class="n">index</span> <span class="p">&lt;</span> <span class="n">maxIndex</span><span class="p">)</span>
3379</span><span class="line">        <span class="p">{</span>
3380</span><span class="line">            <span class="kt">var</span> <span class="n">color</span> <span class="p">=</span> <span class="n">buffer</span><span class="p">.</span><span class="n">Pixels</span><span class="p">[</span><span class="n">index</span><span class="p">]</span> <span class="p">+</span> <span class="m">0</span><span class="n">x202020</span><span class="p">;</span>
3381</span><span class="line">            <span class="n">buffer</span><span class="p">.</span><span class="n">Pixels</span><span class="p">[</span><span class="n">index</span><span class="p">]</span> <span class="p">=</span> <span class="n">color</span> <span class="p">&gt;</span> <span class="m">0</span><span class="n">xffffff</span> <span class="p">?</span> <span class="m">0</span><span class="n">xffffff</span> <span class="p">:</span> <span class="n">color</span><span class="p">;</span>
3382</span><span class="line">        <span class="p">}</span>
3383</span><span class="line">    <span class="p">}</span>
3384</span><span class="line">
3385</span><span class="line"><span class="p">},</span> <span class="n">numComputationThreads</span><span class="p">);</span>
3386</span><span class="line">
3387</span><span class="line"><span class="n">buffer</span><span class="p">.</span><span class="n">Invalidate</span><span class="p">();</span>
3388</span><span class="line"><span class="n">lastRender</span> <span class="p">=</span> <span class="n">elapsed</span><span class="p">;</span>
3389</span><span class="line">
3390</span><span class="line"><span class="p">}</span>
3391</span></code></pre></td></tr></table></div></figure></notextile></div>
3392
3393<p>There are a few changes that I made to make the optimization a bit easier. Joa used a linked list of particles, I captured an array, just because it was a bit easier to make concurrent. But the significant difference is the body of Joa’s loop is now in an anonymous function. Values that will change in the body of the loop are now defined in the loop (x,y,z, etc). This is because if the loop used the variables defined outside the lambda, then the different threads would try to use the same variables as one another, which is obviously a problem. Other than that, the code is pretty much the same.</p>
3394
3395<p>So how much of an improvement is there? Yea, a lot. I put a frame counter on Joa’s original code and on my MBP dual Core Duo 2.4Ghz 4Gig ram running Windows 7 release, it was getting about 30 frames per second. On OS X it was about the same. With the concurrency, and set to use 4 threads, it got up to 45 fps. On my quad core Dell M6400 Core 2 Exreme Q9300 at 2.54 Ghz with 8gig ram, it went up to 65 fps. If found it was best to use more threads then you have cores. So 4 threads was good on the dual core, 8 on the quad core.</p>
3396
3397<p>Of course, this means the app will absolutely peg the processor, which is good if you want max speed. But you can also throttle the frame rate back, say hold it at 30, and use less processor to get the same fps as the original.</p>
3398
3399<p>Silverlight 3 has caused a bit of a splash in the RIA community if the Twitter chatter is any indication. There is some venomous talk out there; you know the such and such tech sucks, such and such tech rules, and of course Microsoft is evil. I choose to stay out of that fray, perhaps it’s hitting 40 that did it. I don’t care to argue with Fanbois. I will say that the the community will discover that the .NET framework and C# (even VB.NET) make for a serious development platform that will benefit the community at large. It’s a very good time to be a developer!</p>
3400
3401<p>Here’s a link to a zip file containing my version of the project: <a href="https://skydrive.live.com/?cid=db16741b8ce498b0#">Strange Attractor Project</a></p>
3402
3403<p>Would you like to see the concepts in this post expanded? Want to know more about concurrency, functional patterns, generics? Leave me a note in the comments or send me a Twitter reply at @efvincent. Oh, and thanks for reading!</p>
3404]]></content>
3405  </entry>
3406  
3407</feed>