<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

  <title><![CDATA[Wizards of Smart]]></title>
  <link href="http://wizardsofsmart.net/atom.xml" rel="self"/>
  <link href="http://wizardsofsmart.net/"/>
  <updated>2013-04-23T11:03:26-05:00</updated>
  <id>http://wizardsofsmart.net/</id>
  <author>
    <name><![CDATA[The Wizards of Smart]]></name>
    
  </author>
  <generator uri="http://octopress.org/">Octopress</generator>

  
  <entry>
    <title type="html"><![CDATA[Windows Azure Dev Camps]]></title>
    <link href="http://wizardsofsmart.net/post/windows-azure-dev-camps/"/>
    <updated>2013-04-11T17:04:00-05:00</updated>
    <id>http://wizardsofsmart.net/post/windows-azure-dev-camps</id>
    <content type="html"><![CDATA[<p><a href="http://www.catapultsystems.com/">Catapult Systems</a>, my employer, is hosting several of the upcoming <a href="http://windowsazure.com/">Windows Azure</a> Dev Camps.
I&#8217;ll be helping out with two in <a href="http://www.microsoft.com/click/services/Redirect2.ashx?CR_CC=200199470&amp;CR_EAC=300088238">Denver</a> (April 25)
and <a href="https://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032547354&amp;Culture=en-US&amp;community=0">Houston</a> (April 29).
The Dev Camps will provide you with an overview of Windows Azure and an opportunity to complete several
Hands-on Labs, including topics such as <a href="http://www.windowsazure.com/en-us/home/scenarios/virtual-machines/">IaaS</a>
and <a href="http://www.windowsazure.com/en-us/home/scenarios/mobile-services/">Azure Mobile Services</a>.</p>

<p>If you plan to attend one of these events, or if you are just curious to see what Azure can offer, sign up for a <a href="http://aka.ms/90day">free 90-day Azure trial</a>.
If you are a student, you should also sign up for <a href="https://www.dreamspark.com/">Dreamspark</a>, which includes a
<a href="https://www.dreamspark.com/Student/Windows-8-App-Development.aspx">free Windows Store developer license</a>.
(You need the Windows Store developer license to send push notifications to a Windows 8 client.)</p>

<h2>Sponsors</h2>

<p><a href="http://Pluralsight.com/"><img src="http://s.pluralsight.com/mn/img/logo/pluralsight-fullcolor-500x109-v1.png" title="'Pluralsight - Hardcore Developer Training'" ></a></p>

<p><a href="http://pluralsight.com/">Pluralsight</a> was kind enough to provide an Annual subscription to their <a href="http://pluralsight.com/training/Courses">online developer training library of over 450 video courses</a>, a $299 value, as a raffle prize.</p>

<p><a href="http://telerik.com/"><img src="http://db.tt/dLOjFP0f" title="'Telerik - deliver more than expected'" ></a></p>

<p><a href="http://telerik.com/">Telerik</a> also provided a <a href="http://www.telerik.com/purchase/faqs/devcraft.aspx">DevCraft Complete license</a> for the raffle!</p>

<p>Please note that you must be present to receive one of the above prizes during the raffle at the end of the camp.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Web API and Dynamic Data Access]]></title>
    <link href="http://wizardsofsmart.net/post/web-api-and-dynamic-data-access/"/>
    <updated>2013-03-21T21:25:00-05:00</updated>
    <id>http://wizardsofsmart.net/post/web-api-and-dynamic-data-access</id>
    <content type="html"><![CDATA[<p>In <a href="http://dotnetrocks.com/">.NET Rocks</a> <a href="http://dotnetrocks.com/default.aspx?showNum=855">episode 855</a>,
Jeff Fritz commented on <a href="http://www.asp.net/web-api/">ASP.NET Web API</a>
being somewhat confusing in terms of its intended use. I don&#8217;t tend to agree,
but I thought I would address one point he made in particular: that Web API
is perhaps just another form of repository.</p>

<p>Web API is much more than a repository. And yes, it is indeed a protocol
mapping layer. As Uncle Bob once noted, a web or api front end is just a mapping
layer and is not really your application.</p>

<p>In many cases, however, one could argue that a web-api-as-repository is a
fairly solid use case. OData is a great example. However, I was thinking of
yet another argument I&#8217;ve heard for dynamic languages:
when you are just going from web to database and back, you are not really
working with types.</p>

<p>In that spirit, I set out to write a simple Web API using SQL and JSON with
no explicit class definitions. You can see the results in this gist:</p>

<div><script src='https://gist.github.com/5212462.js'></script>
<noscript><pre><code></code></pre></noscript></div>


<p>I used <a href="http://code.google.com/p/dapper-dot-net/">Dapper</a> to simplify the data
access, though I just as well could have used
<a href="https://github.com/robconery/massive">Massive</a>,
<a href="http://www.toptensoftware.com/petapoco/">PetaPoco</a>,
or <a href="https://github.com/markrendle/Simple.Data">Simple.Data</a>.
Mostly I wanted to use SQL, so I went with Dapper.</p>

<p>I also model bind to a <code>JObject</code>, which I immediately cast to <code>dynamic</code>. I use an anonymous object to supply the values for the parameters in the SQL statements, casting the fields from the dynamic object to satisfy Dapper.</p>

<p>All in all, I kinda like this. Everything is tiny, and I can work directly
with SQL, which doesn&#8217;t bother me one bit. I have a single class to manage my
data access and API translation, but the ultimate goal of each method is still
small: retrieve data and present it over HTTP. That violates SRP, but I don&#8217;t
mind in this case. The code above is not very testable, but with an API
like this I&#8217;d be more inclined to do top level testing anyway.
It&#8217;s just not deep enough to require a lot of very specific, low-level testing,
IMHO.</p>

<p>Also, note again that this is just retrieving data and pushing it up through an API. This is not rocket science. An F# type provider over SQL would give a good enough sanity check. Why bother generating a bunch of types?</p>

<p>Which brings up another point for another post: what would I do if I needed to
add some logic to process or transform the data I retrieved?</p>

<p>As a future exercise, I want to see what it would take to cap this with the Web API OData extensions. That could be fun.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[F# WSDL Type Provider and HTTPS]]></title>
    <link href="http://wizardsofsmart.net/post/f-number-wsdl-type-provider-and-https/"/>
    <updated>2013-02-07T06:48:00-06:00</updated>
    <id>http://wizardsofsmart.net/post/f-number-wsdl-type-provider-and-https</id>
    <content type="html"><![CDATA[<p>I recently ran into a problem with accessing a WCF web service over https.
I used the <a href="http://msdn.microsoft.com/en-us/library/hh156503.aspx">WSDL Type Provider</a>
to generate the service client for me. I referenced <code>System</code> and <code>System.ServiceModel</code>
like a good boy, yet I couldn&#8217;t find any way to set the credentials for the service.
I began by trying to use the generated client: <code>MyService.GetWSHttpBinding_IDataService</code>.
Unfortunately, that didn&#8217;t have a the <code>ClientCredentials</code> property I expected. So I then
tried creating a new client:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>let endpoint = "WSHttpBinding_Test"
</span><span class='line'>let username = ""
</span><span class='line'>let password = ""
</span><span class='line'>let client = new MyService.DataServiceClient(endpoint)
</span><span class='line'>client.ClientCredentials.Windows.ClientCredential &lt;- new NetworkCredential(username, password)</span></code></pre></td></tr></table></div></figure>


<p>Unfortunately, the issue persisted. I then noticed a little message noting that I was missing an assembly reference.
Turns out you must also open <code>System.IdentityModel</code>. Problem solved.</p>

<p>NOTE: If anyone knows of an https hosted WCF service in the wild, I&#8217;d be happy to share the full code.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[F# Manifest]]></title>
    <link href="http://wizardsofsmart.net/post/f-number-manifest/"/>
    <updated>2012-12-29T22:33:00-06:00</updated>
    <id>http://wizardsofsmart.net/post/f-number-manifest</id>
    <content type="html"><![CDATA[<p>I would like to propose an alternative compilation structure for building
F# projects. I&#8217;m currently calling it an F# manifest, though the actual
idea is less focused on the creation of a single file and rather on a different,
language-first approach to building projects. My idea stems from a technique
I&#8217;ve started using more regularly and that I&#8217;ve seen from Tomas Petricek.
This technique uses compiler directives for toggling <code>#r</code> and <code>#load</code> commands
for F# Interactive. Using these, you can typically run a script or compile and
run an executable. The overall process would roughly appear as follows:</p>

<ol>
<li>Look for a Main.fs or Manifest.fsx file.</li>
<li>If a Manifest.fsx file doesn&#8217;t exist, generate the Manifest.fsx from <code>#if INTERACTIVE</code>, <code>#r</code> and <code>#load</code> references</li>
<li>Do this for all referenced files so that the Manifest.fsx lists the dependencies for the primary script</li>
<li>Search for references without a path in the local directory, then the GAC, and finally NuGet</li>
</ol>


<h2>Why an alternate build system?</h2>

<p>Today I saw a question about docs for <a href="https://github.com/fsharp/fsharpx">F#x</a>
on the F#x mailing list. The first reply, from Art, referenced Tomas&#8217;
<a href="https://github.com/tpetricek/FSharp.Formatting">FSharp.Formatting</a> project.
I hadn&#8217;t seen Tomas&#8217; project in some time, so I went to check it out.
The last I looked at it, FSharp.Formatting provided a Markdown parser.
Tomas has extended it to cover a much larger feature set, including a
version of literate programming. Literate programming was the ultimate goal
of my halted <a href="https://github.com/panesofglass/focco">focco</a> project.
As I had always intended of pulling in several of Tomas&#8217; other projects
to finish focco, and FSharp.Formatting now provides many of those features,
I will now be moving what I can from focco over to FSharp.Formatting.</p>

<p>That was what I had originally planned to write about. Instead, worn out
from the holidays, I lost focus and instead started thinking too much
about true <a href="http://www.literateprogramming.com/">literate programming</a>.
(Disclaimer: I have not investigated Tomas&#8217; implementation in any detail, so some of what follows may be inaccurate.)
Knuth&#8217;s idea of &#8220;literate&#8221; programming allow programmers to write for people
and use a tool to strip out the code and re-organize it for the computer.
This sort of thing is more necessary in languages such as F# and Pascal
you must first declare a procedure or function before you can use it.
Neither focco nor FSharp.Formatting currently addresses this.</p>

<p>Before literate programming in F# is really possible, we need a build system
that can work more directly from raw files. Well, that&#8217;s not entirely true,
but I&#8217;ve long wished to see less XML and more F# in my F# builds.</p>

<h2>Is this really a necessity to literate programming in F#?</h2>

<p>No, of course not. I just found myself thinking through all this and thought
I would write it down for posterity. If I really thought it necessary, I would
have instead started writing some code to feel this out. Instead, I&#8217;m planning to
get some sleep and try to focus and get F# project support added to FSharp.Formatting.
Once that is done, we&#8217;ll see about allowing a mechanism to allow authors to
list their code in an arbitrary manner and then reassemble it. And after that,
maybe a look at a new build system is in order.</p>

<p>And no, I haven&#8217;t forgotten about FAKE. If nothing else, I would probably make this
an optional extension via FAKE. Then again, you can already do some of this
with a single .fsx script several loose .fs files, and some assemblies.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Nested Controllers in the latest Web API Source]]></title>
    <link href="http://wizardsofsmart.net/post/nested-controllers-in-the-latest-web-api-source/"/>
    <updated>2012-09-04T08:34:00-05:00</updated>
    <id>http://wizardsofsmart.net/post/nested-controllers-in-the-latest-web-api-source</id>
    <content type="html"><![CDATA[<p>I just happened to drop over to the <a href="http://aspnetwebstack.codeplex.com/">ASP.NET Web Stack</a> and noticed that
<a href="http://aspnetwebstack.codeplex.com/SourceControl/changeset/c44fb644c5fc">nested controllers are now allowed</a> in Web API!
This is terrific news for you F# developers who, like me, think that grouping related functionality,
including controllers, within modules is a convenient practice. Note, that this is only in the source.
You won&#8217;t be able to update your NuGet packages to get this functionality, though it is easy to replace
the offending <code>DefaultHttpControllerTypeResolver</code> with this updated copy:</p>

<figure class='code'><figcaption><span>Replace DefaultHttpControllerTypeResolver  </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="n">config</span><span class="p">.</span><span class="n">Services</span><span class="p">.</span><span class="n">Replace</span><span class="p">(</span><span class="k">typeof</span><span class="p">(</span><span class="n">IHttpControllerTypeResolver</span><span class="p">),</span> <span class="k">new</span> <span class="n">MyHttpControllerTypeResolver</span><span class="p">())</span>
</span></code></pre></td></tr></table></div></figure>



]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The Origin of RESTful URLs]]></title>
    <link href="http://wizardsofsmart.net/post/the-origin-of-restful-urls/"/>
    <updated>2012-09-01T23:54:00-05:00</updated>
    <id>http://wizardsofsmart.net/post/the-origin-of-restful-urls</id>
    <content type="html"><![CDATA[<p>For at least the past year, I have repeatedly found my appreciation for the literal offended by the term &#8220;RESTful URLs.&#8221;
I recently spent a bit of time trying to explain how this term is oxymoronic on the <a href="http://forums.asp.net/t/1833887.aspx/1?Any+movement+on+versioning+">Web API Forums</a>.
While URIs are important as a means of identifying unique resources, REST doesn&#8217;t specify any other requirements for URIs.
I often note that a RESTful URI could be a GUID. While this is certainly not very meaningful to humans, it satisfies the
<a href="http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm">REST constraints</a>.</p>

<p>While pondering <a href="http://www.strathweb.com/2012/05/attribute-based-routing-in-asp-net-web-api/">nested resources in Web API</a> yet again, I realized where I think this term originates.
<a href="http://rubyonrails.org/">Ruby on Rails</a> used the term <a href="http://guides.rubyonrails.org/routing.html#adding-more-restful-actions">&#8220;RESTful routing&#8221;</a>
to describe their approach to building Controllers along the line of resources and using a convention to route controllers in a hierarchy based on the controller name.
The goal, I think, was to correctly model and mount resources at unique URIs. However, you get what I would call <a href="http://www.bing.com/search?setmkt=en-US&amp;q=pretty+urls">&#8220;pretty URLs&#8221;</a> for free.</p>

<p>If you use the term &#8220;RESTful URLs,&#8221; please stop. While RESTful Routing makes sense, RESTful URLs are just nonsense. Do use &#8220;RESTful Routing.&#8221; Do use &#8220;Pretty URLs.&#8221; Just don&#8217;t confuse your terms. Thanks!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The Functional Web, Part 1]]></title>
    <link href="http://wizardsofsmart.net/post/the-functional-web/"/>
    <updated>2012-08-12T22:26:00-05:00</updated>
    <id>http://wizardsofsmart.net/post/the-functional-web</id>
    <content type="html"><![CDATA[<p>I finally published the <a href="http://youtu.be/G3bVEsrYJ_A">first</a> in a series of short, video tutorials describing web programming in the functional paradigm.
The first video briefly introduces the tools I&#8217;ll be using: <a href="http://fsharp.net/">F#</a> and <a href="http://asp.net/web-api">ASP.NET Web API</a>.</p>

<p>Here&#8217;s part 1:</p>

<iframe width="640" height="360" src="http://www.youtube.com/embed/G3bVEsrYJ_A" frameborder="0" allowfullscreen></iframe>



]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Knockoutjs and RxJS]]></title>
    <link href="http://wizardsofsmart.net/post/knockoutjs-and-rxjs/"/>
    <updated>2012-08-10T09:02:00-05:00</updated>
    <id>http://wizardsofsmart.net/post/knockoutjs-and-rxjs</id>
    <content type="html"><![CDATA[<p>I&#8217;ve been using a big of <a href="http://knockoutjs.com/">knockout.js</a> of late, and while I don&#8217;t mind the <code>ko</code> namespace stuff,
I do wish that this had used <a href="http://reactive-extensions.github.com/RxJS/">RxJS</a> instead. I know Steve tried that early on
and all; it would just be nice to be able to leverage something with which I&#8217;m more familiar. Perhaps
<a href="http://twitter.com/mattpodwysocki">Matt Podwysocki</a> or <a href="http://twitter.com/bennage">Christopher Bennage</a> will come up
with something.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[New Names for Old Things]]></title>
    <link href="http://wizardsofsmart.net/Patterns/new-names-for-old-things/"/>
    <updated>2012-08-09T22:40:00-05:00</updated>
    <id>http://wizardsofsmart.net/Patterns/new-names-for-old-things</id>
    <content type="html"><![CDATA[<p>[This is the third in a <a href="http://wizardsofsmart.net/Patterns/the-problem-with-the-mvc-frameworks-introduction/">series</a>
started long ago on the use of MVC for building web &#8220;applications&#8221;.]</p>

<p>I&#8217;m glad I&#8217;m only getting back to this series now. I&#8217;ve had an opportunity
to build many more web applications and have a much better appreciation
for the poor terminology used to define web applications. For starters, this
MV? business silly. We&#8217;ll get to that.</p>

<p>I know I&#8217;m a bit of an extremist in some things. Specifically, I like things
to mean what they mean. When we abuse terms, we don&#8217;t communicate well. REST.
There, I said it. I feel better. Stop using the term. Most people have a wrong
idea of what it means b/c of all the silliness that has been done in its name.
I don&#8217;t claim to know exactly myself. I don&#8217;t think it&#8217;s possible to rescue
the term from the abuses heaped upon it. There, you see? I&#8217;m an extremist.</p>

<p>Now that we&#8217;ve covered that, on to MVC. I&#8217;m not sure who decided this was an
accurate description for what happens on the server-side of the web, but it&#8217;s
just flat wrong. As noted previously, HTTP uses a
<a href="http://wizardsofsmart.net/post/http-and-functional-programming/">functional interface</a>.
It&#8217;s an IO-bound <code>Request -&gt; Response</code> function. Can you use patterns on either side
to help maintainability? Certainly! Just don&#8217;t confuse things. Let&#8217;s start with Views.</p>

<h2>Views</h2>

<p>What is a view?</p>

<blockquote><p>The [view or viewport] is responsible for mapping graphics onto a device.<br/>A viewport typically has a one to one correspondence with a display surface<br/>and knows how to render to it. A viewport attaches to a model and renders<br/>its contents to the display surface. In addition, when the model changes,<br/>the viewport automatically redraws the affected part of the image to reflect<br/>those changes. [&#8230;] there can be multiple viewports onto the same model and<br/>each of these viewports can render the contents of the model to a different<br/>display surface.</p><footer><strong>http://ootips.org/mvc-pattern.html</strong></footer></blockquote>


<p>If a view was merely a serialization of a model, this would make sense for building
web applications. Unfortunately, there&#8217;s a problem. The definition suggests that
the view automatically updates whenever the model changes. How do you do that with
HTTP? HTTP doesn&#8217;t define any mechanism for hooking up observation of a server model.
Before you say JavaScript, consider first the current use of View, or even UI.
People commonly mean HTML. HTML is not a UI. HTML is a serialization format. The
client (normally a browser) must interpret that HTML. Many of you will remember when
that wasn&#8217;t so standard.</p>

<p>Can we achieve MVC today? Possibly. You might be able to leverage web sockets to reach
across a client/server architecture such as that presented by HTTP. However, you are more
likely to find that &#8220;MVC&#8221; on the server is just limiting. You are typically better
off building a sort of restricted data access service, a.k.a
<a href="http://asp.net/web-api">Web API</a> (subtle hint). There&#8217;s really no point in trying
to enrich a serialization format to make it work more like true MVC across the
client and server.</p>

<h2>Controllers</h2>

<p>This is no different than routing. Instead of calling your Router a Controller, you
split them up. However, most frameworks really just use the router as a top level
dispatcher and the controller as a lower-level dispatcher. Otherwise, I&#8217;d say web
frameworks stay a lot closer to the original meaning than a lot of the other MV?
patterns. (Hence the ?, of course.)</p>

<h2>Models</h2>

<p>This really is the crux. HTML is a model. I noted this last time. It&#8217;s just a
serialization of data you want displayed. It happens to be a lot richer, but it&#8217;s
still just a data model. HTML is a great way to bootstrap an application that
otherwise uses JavaScript as a model serialization format. If you want to disagree,
ask why HTML5 removes the presentation elements. Why has layout and style moved to
CSS? CSS and the browser define the actual rendering. In a no-script web application,
you don&#8217;t have to build a view. You get it for free.</p>

<h2>Conclusion</h2>

<p>So what? Am I just ranting that I don&#8217;t like how people abuse terms? Possibly. However,
I think this goes deeper. When you allow the slippery slope, you get caught on it, as well.
It&#8217;s inevitable. The bigger, lurking danger is that we start to confuse useful patterns
and use them in the wrong places. Many people use MVC frameworks today to build
web APIs. However, that&#8217;s not MVC. So if you then switch to a desktop app to write MVC
applications, you are either confused or delighted to find that it&#8217;s so much richer.</p>

<p>I don&#8217;t know what I would call what we build for the web; I know I wouldn&#8217;t call it MVC.
In my experiments with <a href="http://github.com/frank-fs/frank">Frank</a>, I&#8217;ve found that writing
simple functions and nesting them with rules makes a very easy mechanism for building
web APIs. I think that would essentially just be a Command pattern. Simple, elegant, and
very easy to understand. YMMV.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Web API RC Released]]></title>
    <link href="http://wizardsofsmart.net/News/web-api-rc-released/"/>
    <updated>2012-06-01T10:52:00-05:00</updated>
    <id>http://wizardsofsmart.net/News/web-api-rc-released</id>
    <content type="html"><![CDATA[<p>If you have been trying out <a href="http://asp.net/web-api">ASP.NET Web API</a>, you will be happy to know that the RC is finally available.
No more struggling with building the sources yourself or fumbling with installing the nightlies to the GAC.
<a href="http://blogs.msdn.com/b/henrikn">Henrik</a> has posted a <a href="http://blogs.msdn.com/b/henrikn/archive/2012/04/23/using-cookies-with-asp-net-web-api.aspx">few</a>
<a href="http://blogs.msdn.com/b/henrikn/archive/2012/04/27/asp-net-web-api-updates-april-27.aspx">articles</a>
<a href="http://blogs.msdn.com/b/henrikn/archive/2012/05/03/asp-net-web-api-updates-may-3.aspx">on the</a> <a href="http://blogs.msdn.com/b/henrikn/archive/2012/05/14/asp-net-web-api-updates-may-14.aspx">changes</a>, as well as a follow up to
<a href="http://blogs.msdn.com/b/henrikn/archive/2012/06/01/using-nightly-asp-net-web-stack-nuget-packages-with-vs-2012-rc.aspx">using the nightlies with the RC release</a>, if you must.
One final note: the assembly names have changed, I assume to allow you to install the MVC4 for VS2010 alongside a VS11 installation, which was previously not possible.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Thank you]]></title>
    <link href="http://wizardsofsmart.net/post/thank-you/"/>
    <updated>2012-04-08T21:30:00-05:00</updated>
    <id>http://wizardsofsmart.net/post/thank-you</id>
    <content type="html"><![CDATA[<p>This past April 1, Microsoft renewed my MVP for Visual F#. I want to thank Microsoft and the MVP program for this honor,
and I would like to thank the F# team and community specifically for making it such a joy to work with F#.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The Functional Nature of Web API]]></title>
    <link href="http://wizardsofsmart.net/post/the-functional-nature-of-web-api/"/>
    <updated>2012-03-05T22:33:00-06:00</updated>
    <id>http://wizardsofsmart.net/post/the-functional-nature-of-web-api</id>
    <content type="html"><![CDATA[<p>Since my last post on the functional nature of the web, I&#8217;ve given
<a href="http://www.slideshare.net/panesofglass/the-functional-web">two</a>
<a href="http://www.slideshare.net/panesofglass/frank-the-web-api-dsl">presentations</a>
describing this idea in more detail.
Unfortunately, circumstances have conspired against me such that I have been unable to build any good sample apps.
That&#8217;s about to change, as I&#8217;ve started working on screencasts on <a href="http://www.asp.net/web-api">Web API</a> that I&#8217;ll
be posting here and on <a href="http://fpish.net/">fpish.net</a> as I complete them.</p>

<p>As a preview, In this post I&#8217;ll describe the inherent functional nature of Web API.
You have looked into Web API at all, you&#8217;ve probably seen the
<a href="http://code.msdn.microsoft.com/Contact-Manager-Web-API-0e8e373d">Contact Manager</a> sample application,
originally created by the infamous <a href="http://twitter.com/gblock">&#8220;2C&#8221;</a>. (Kudos to Dan Roth on the Web API team for keeping it alive!)
The controller-based goodness baked into Web API hides a lot of the functional nature,
so I will understand if you think I&#8217;m a little crazy for my statement above.</p>

<div><script src='https://gist.github.com/1984816.js?file=MyHttpMessageHandler.cs'></script>
<noscript><pre><code>class MyHttpMessageHandler : System.Net.Http.HttpMessageHandler
{
    protected override Task&lt;HttpResponseMessage&gt; SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        return base.SendAsync(request, cancellationToken);
    }
}
</code></pre></noscript></div>


<p>See? Not so much? Okay, how about in F#?</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>type MyMessageHandler() =
</span><span class='line'>  inherit System.Net.Http.HttpMessageHandler()
</span><span class='line'>  override x.SendAsync(request, cancellationToken) =
</span><span class='line'>    (* Implementation ... *)</span></code></pre></td></tr></table></div></figure>


<p>Eh, let&#8217;s try again.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>val app : HttpRequestMessage -> Async&lt;HttpResponseMessage>
</span><span class='line'>let app request = async { return response }
</span><span class='line'>
</span><span class='line'>let makeHandler app =
</span><span class='line'>  { new System.Net.Http.HttpMessageHandler() with
</span><span class='line'>      override x.SendAsync(request, cancellationToken) =
</span><span class='line'>        Async.StartAsTask &lt;| app request }</span></code></pre></td></tr></table></div></figure>


<p>Here I use several unique features of F# to emphasize the point. The type signature should be familiar from my last post.
I then create a handler using F#&#8217;s object initialization syntax, which creates an instance from a base class using the <code>app</code> from above.
I think I&#8217;ve made my point that, at its heart, the <code>HttpMessageHandler</code> is functional in its core.</p>

<p>Okay, let&#8217;s translate back to C#-land. We don&#8217;t have object initialization syntax, but we can create pure,
functional approaches for C#. Also, we&#8217;ll use <code>DelegatingHandler</code>, as that&#8217;s the actual type you&#8217;ll need to inherit
in order to use it in Web API. (I apologize now for making your eyes bleed with the type signatures.)</p>

<div><script src='https://gist.github.com/1984816.js?file=ApplicationHandler.cs'></script>
<noscript><pre><code>class ApplicationHandler : DelegatingHandler
{
    private readonly Func&lt;HttpRequestMessage, Task&lt;HttpResponseMessage&gt;&gt; _app;

    public ApplicationHandler(Func&lt;HttpRequestMessage, Task&lt;HttpResponseMessage&gt;&gt; app)
        : base()
    {
        _app = app;
    }

    protected override Task&lt;HttpResponseMessage&gt; SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        return _app(request);
    }
}
</code></pre></noscript></div>


<h2>Why is this core?</h2>

<p>I&#8217;ve mentioned this is core, but if you&#8217;ve only used Web API with controllers, you may never have interacted with <code>HttpMessageHandler</code>s.
<code>HttpMessageHandler</code>s are at the root of everything. <code>HttpClient</code>, <code>HttpServer</code>, and everything else that uses these types all inherit <code>HttpMessageHandler</code>.
If you look deep into Web API, you find this consistency of <code>HttpMessageHandler</code> at the core. What does that mean? It means &#8220;it&#8217;s [functions] all the way down.&#8221;</p>

<h2>A quick example</h2>

<p>You can see this in action in the <a href="http://nuget.org/packages/AspNetWebApi.Conneg">AspNetWebApi.Conneg</a>
<a href="https://github.com/panesofglass/WebApi.Conneg/blob/master/samples/WebApi.Conneg.Web/SimpleHandler.cs">sample application</a>.</p>

<div><script src='https://gist.github.com/1984816.js?file=SimpleHandler.cs'></script>
<noscript><pre><code>using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace WebApi.Conneg.Web
{
    public class SimpleHandler : DelegatingHandler
    {
        private readonly IFormatterSelector _formatterSelector;
        private readonly IDictionary&lt;string, string&gt; _formatters;

        public SimpleHandler()
        {
            _formatterSelector = new FormatterSelector();
            _formatters = new Dictionary&lt;string, string&gt;
            {
                { &quot;application/xml&quot;, @&quot;&lt;?xml version=&quot;&quot;1.0&quot;&quot;?&gt;
&lt;root&gt;
    &lt;string&gt;{0}&lt;/string&gt;
&lt;/root&gt;&quot; },
                { &quot;application/json&quot;, @&quot;{{&quot;&quot;result&quot;&quot;:&quot;&quot;{0}&quot;&quot;}}&quot; },
                { &quot;text/html&quot;, @&quot;&lt;!doctype html&gt;
&lt;html lang=&quot;&quot;en&quot;&quot;&gt;
    &lt;head&gt;
        &lt;meta charset=&quot;&quot;utf-8&quot;&quot; /&gt;
        &lt;title&gt;Simple&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;section&gt;
            &lt;header&gt;
                &lt;h2&gt;Simple&lt;/h2&gt;
            &lt;/header&gt;
            {0}
        &lt;/section&gt;
    &lt;/body&gt;
&lt;/html&gt;&quot; },
            };
        }

        protected override Task&lt;HttpResponseMessage&gt; SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var mediaType = _formatterSelector.Negotiate(_formatters.Keys, request.Headers.Accept);
            var content = ApplyTemplate(&quot;value&quot;, mediaType);
            var tcs = new TaskCompletionSource&lt;string&gt;();
            tcs.SetResult(content);
            return tcs.Task;
        }

        private HttpContent ApplyTemplate(string content, string mediaType)
        {
            // This could run Razor or some other template engine.
            var result = string.Format(_formatters[mediaType], content);
            return new StringContent(result, Encoding.UTF8, mediaType);
        }
    }
}</code></pre></noscript></div>


<p>Okay, so now we have our &#8220;function.&#8221; How would you hook this up? That&#8217;s also quite simple.
<code>HttpApplication</code> now has a <code>GlobalConfiguration</code> courtesy <code>System.Web.Http</code>.
This provides you access to an instance of <code>HttpConfiguration</code>, which provides you all the extensibility points for managing your Web API.
The Self Host option let&#8217;s you create your own. Attaching a handler is dead simple:</p>

<div><script src='https://gist.github.com/1984816.js?file=Global.asax.cs'></script>
<noscript><pre><code>using System.Web;
using System.Web.Http;

namespace WebApi.Conneg.Web
{
    public class WebApiApplication : HttpApplication
    {
        public static void RegisterApis(HttpConfiguration config)
        {
            // NOTE: There is nothing similar to the MVC {path*} that appears to work.
            config.Routes.MapHttpRoute(&quot;Root&quot;, &quot;{path}&quot;, new { path = RouteParameter.Optional });
            config.Routes.MapHttpRoute(&quot;Default&quot;, &quot;{controller}/{id}&quot;, new { id = RouteParameter.Optional });
        }

        protected void Application_Start()
        {
            GlobalConfiguration.Configuration.MessageHandlers.Add(new SimpleHandler());
            RegisterApis(GlobalConfiguration.Configuration);
        }
    }
}
</code></pre></noscript></div>


<h2>The point</h2>

<p>By no means am I trying to convince you to give up all the ease of built-in model binding and conneg.
I only want to drive home the point that the core of Web API is really just functions. As I mentioned
previously, HTTP exhibits a very strong functional side. Web API really addresses this head on and provides
a very solid core for building web applicaitons, whether using a more MVC-style or functions directly.</p>

<p>Try it out. For really simple applications, you are likely to find that these are all you need.
You may also appreciate that you can implement your own routing and other mechanisms directly within
a composed set of functions. We&#8217;ll explore this more as we continue in this series, so stay tuned.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[From Iteratees to Conduits]]></title>
    <link href="http://wizardsofsmart.net/post/from-iteratees-to-conduits/"/>
    <updated>2012-01-29T21:07:00-06:00</updated>
    <id>http://wizardsofsmart.net/post/from-iteratees-to-conduits</id>
    <content type="html"><![CDATA[<p>I&#8217;ve still got <em>Iteratee for F#: Part 2</em> coming. While tinkering with other approaches for building
iteratees in F#, I&#8217;ve tried a number of different approaches, including a special <code>ISubject&lt;'TIn, 'TOut&gt;</code>
using <a href="http://msdn.microsoft.com/en-us/data/gg577609"><acronym title="Reactive Extensions">Rx</acronym></a>
and agents. I came across <a href="http://www.yesodweb.com/book/conduit">an article</a> today that describes a new
Haskell library called <a href="http://hackage.haskell.org/package/conduit/">Conduit</a>, which is now used in the
<a href="http://www.yesodweb.com/">Yesod</a> web framework in place of the <a href="http://hackage.haskell.org/package/enumerator">enumerator</a>
library, which is the basis for the current implementation of Iteratee in <a href="http://github.com/fsharp/fsharpx">FSharpx</a>.</p>

<p>I hope you find it interesting. I certainly have, as it&#8217;s helped me solidify some ideas about the approach
I&#8217;ve been taking lately. Stay tuned for Part 2, as well as the other posts on functional HTTP.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[HTTP and Functional Programming]]></title>
    <link href="http://wizardsofsmart.net/post/http-and-functional-programming/"/>
    <updated>2012-01-08T14:01:00-06:00</updated>
    <id>http://wizardsofsmart.net/post/http-and-functional-programming</id>
    <content type="html"><![CDATA[<p>I made what some might consider a bold claim on Twitter this past Friday,
that HTTP holds to the functional programming paradigm. For the purposes
of demonstration, I&#8217;ll be using F# as a means of declaring function and
type signatures, though you can use any language in a functional style.
I&#8217;ll further use type names from Microsoft&#8217;s new <a href="http://wcf.codeplex.com/">Web API</a>
library. (Actually, I&#8217;ll be sticking to the <code>System.Net.Http</code> types, which are
already generally available in the <a href="http://nuget.org/packages/httpclient">HttpClient NuGet package</a>
and will be part of <a href="http://msdn.microsoft.com/en-us/library/system.net.http(v=vs.110).aspx">.NET 4.5</a>.)</p>

<h2>The Basics</h2>

<p>At the bare minimum, HTTP supports an interface in which a client submits
an <code>HttpRequestMessage</code> and responds with an <code>HttpResponseMessage</code>. This
contract can be represented as a function with the following signature:</p>

<figure class='code'><figcaption><span>The HTTP Interface </span></figcaption>
<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>HttpRequestMessage -> HttpResponseMessage</span></code></pre></td></tr></table></div></figure>


<p>I could try to just leave it here and say, &#8220;See, it&#8217;s a function!&#8221; but that would
be cheating a bit. Nevertheless, the essential contract for HTTP is a simple
function. That&#8217;s at least something.</p>

<h2>Summary</h2>

<p>Let&#8217;s dive a bit deeper. What precisely might one mean by &#8220;functional programming paradigm&#8221;?
Typically, you&#8217;ll see some variation on the following list (which is by no means exhaustive):</p>

<ul>
<li><strong>Declarative</strong> - what not how</li>
<li><strong>Pure functions</strong> - a function with no side-effects such as I/O or mutating global state</li>
<li><strong>First-class and higher-order functions</strong> - functions can be created and passed as parameters just like other values</li>
<li><strong>Referential transparency</strong> - an expression can be replaced with its value without changing program behavior</li>
<li><strong>Memoization</strong> - a performance enhancing technique made possible by referential transparency</li>
</ul>


<p>Aligning the above items with ideas found in HTTP, we get:</p>

<ul>
<li><strong>Declarative</strong> -> <code>HttpRequestMessage</code> headers</li>
<li><strong>Pure functions</strong> -> <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1">Safe, idempotent HTTP methods such GET and HEAD</a></li>
<li><strong>First-class and higher-order functions</strong> -> Hypermedia controls and content negotiation</li>
<li><strong>Referential transparency and Memoization</strong> -> Cache control mechanisms</li>
</ul>


<h2>Discussion</h2>

<h3>Declarative HTTP</h3>

<p>This is the easiest to demonstrate. Request headers are nothing other than a means
to declare what you want (e.g. Request Line) and set expectations (e.g. Accept).
The entire <code>HttpRequestMessage</code> exists as a means of expressing intent. As a client,
you have absolutely no chance of instructing the server on how to process your request.
Even <acronym title="Remote Procedure Call">RPC</acronym>-style calls must abide
by this constraint, at least as it concerns the request message.</p>

<h3>Pure Functions</h3>

<p>Some may argue this point due to the prevalence of non-conforming web applications that
allow side effects on safe, idempotent methods. Nevertheless, HTTP as it is defined
specifies that <code>GET</code> and <code>HEAD</code> methods <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1">should be safe</a>.
This is quite important for other attributes of HTTP, such as the ability to cache
representations, which I&#8217;ll discuss a bit further down.</p>

<h3>First-class and Higher-order Functions</h3>

<p>I will acknowledge that this is my weakest point. However, the fact that both the client
and server are able to communicate &#8220;callable&#8221; options appears very close to the very
mechanism used when supplying callbacks or continuations in functional programming.
It&#8217;s close enough for me. You are free to disagree.</p>

<h3>Referential Transparency and Memoization</h3>

<p>Referential transparency, which is supported by the presence of pure functions (see above),
allows us to safely support caching, known as memoization in functional programming.
In functional programming languages, memoization allows us to offset the cost of
immutability by calling a function once and then re-using the original value rather
than continuously invoking the function over and over. It&#8217;s especially useful for
expensive operations. In much the same way, HTTP provides the ability to cache
representations at intermediaries to speed the process of returning a response.</p>

<h3>What About Non-Safe-Idempotent and Non-Idempotent Methods?</h3>

<p>Very few functional languages are considered pure, Haskell arguably the most popular.
F#, OCaml, Lisp, Scala, JavaScript and others all support mutation. Truly, you would
be unable to do very much without the ability to change state somewhere. Thus, these
other methods are both useful and in no way against the idea that HTTP supports the
functional style. Much as even Haskell can eventually persist data in mutable storage
such as a database, HTTP supports controlled mutation (albeit without explicit monads;
count your blessings).</p>

<h2>Conclusion</h2>

<p>I think the above arguments support my original idea pretty well, but I&#8217;m curious
what you think. Also, I certainly am using this as a means of drawing attention
to a project I&#8217;ve been working and churning on, related to both <a href="http://tryfsharp.org/">F#</a>
and <a href="http://wcf.codeplex.com/">Web API</a>. In upcoming posts, I&#8217;ll introduce
<a href="http://frankfs.net/">Frank</a>, which is finally approaching a fairly stable api.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Web Architecture Done Right]]></title>
    <link href="http://wizardsofsmart.net/Patterns/web-architecture-done-right/"/>
    <updated>2012-01-02T12:41:00-06:00</updated>
    <id>http://wizardsofsmart.net/Patterns/web-architecture-done-right</id>
    <content type="html"><![CDATA[<p>I&#8217;ll go ahead and confess that a single right way to design for the web doesn&#8217;t exist. If someone wants you to believe otherwise, they are just wrong.
That said, I do think that you&#8217;ll have a hard time going wrong by starting with one simple rule: <strong>start with a web api</strong>.</p>

<p>Why should you start with a web api rather than just building a web site/app that has HTML and JavaScript all working together? Frankly it&#8217;s because
you can&#8217;t properly decouple the api from the serialization format well enough. When you are designing an api for the web, you (should be) thinking
in terms of resources and representations. That&#8217;s representations in the plural form. You may not know exactly what forms you&#8217;ll need, but you should
consider that you will eventually have many. When you start with a web site/app with HTML in mind, you&#8217;ve coupled yourself to a single format, and extracting
that out later could (will) be difficult. Don&#8217;t just take my word for it. <a href="http://twitter.com/mamund">Mike Amundsen</a> has an
<a href="http://amundsen.com/blog/archives/1115">excellent post on the right way to think about these things</a>.</p>

<p>There are certainly some instances where this may be overkill, but I hate rewriting software unless it really is a prototype or just an exploratory attempt
to get something up. In those cases, go for the quick and dirty. If you are working on something you want to last a long time, however, you owe it to yourself
to consider the evolvability of your app by focusing on api design. You&#8217;ll then be able to take advantage of a number of client options. Certainly, supporting
the growing number of clients is one of the biggest challenges continuing to face developers as we head into 2012.</p>

<p>Let&#8217;s suppose you agree with me on this point. How do you go about building a really solid api design? I don&#8217;t think I could articulate it better than
<a href="http://www.bizcoder.com/index.php/2011/04/11/web-apis-dont-be-a-victim-of-your-success/">Darrel Miller already has</a>. His goals for good apis are suitable
both for internal teams and external customers. Who wouldn&#8217;t love gaining visibility b/c a customer was able to accelerate their business by using your
api in an unforseen way that drives additional business for your own company? How nice is it to knock out not just one project but several b/c you are able
to leverage existing platforms for new projects? We&#8217;re doing that at <a href="http://www.logos.com/">Logos</a>, in large part because we moved to <a href="http://asp.net/mvc">MVC</a>
and took a more service-oriented approach to building our apps. The number of new projects has grown tremendously, but we are also able to respond much more
quickly b/c the services are ready for consumption.</p>

<p>I&#8217;ll be continuing to discuss this topic in future posts. In the meantime, check out Mike&#8217;s book,
<a href="http://www.amazon.com/gp/product/1449306578/ref=as_li_ss_tl?ie=UTF8&amp;tag=panesofglass-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=1449306578"><em>Building Hypermedia APIs with HTML5 and Node</em></a>.
It uses HTML5 and Node to illustrate, but the concepts are excellent and portable to other platforms.
I also highly recommend <a href="http://www.amazon.com/gp/product/0596805829/ref=as_li_ss_tl?ie=UTF8&amp;tag=panesofglass-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0596805829"><em>REST in Practice</em></a>
as an excellent resource for understanding the fullness of what HTTP offers for building apis. Enjoy!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[A New Web for .NET: FubuMVC and Chad's response to AR Considered Harmful]]></title>
    <link href="http://wizardsofsmart.net/Patterns/a-new-web-for-net-fubumvc-and-chads-response-to-ar-considered-harmful/"/>
    <updated>2011-12-30T15:14:00-06:00</updated>
    <id>http://wizardsofsmart.net/Patterns/a-new-web-for-net-fubumvc-and-chads-response-to-ar-considered-harmful</id>
    <content type="html"><![CDATA[<p>I caught a few interesting posts this week that reminded me of an <a href="http://wizardsofsmart.net/Patterns/the-problem-with-the-mvc-frameworks-introduction.html">unfinished series on .NET web frameworks I started in 2009</a>.
The series, as it was initially planned, ties in very well with <a href="http://lostechies.com/chadmyers/sweet-sweet-vindication/">a recent post from Chad Myers</a>,
who responded to another post claiming the <a href="http://blog.steveklabnik.com/posts/2011-12-30-active-record-considered-harmful">ActiveRecord (and Rails) Considered Harmful</a>.</p>

<p>Before I go any further, I want to make very clear that I&#8217;m a fan of Rails and think that it is an incredibly useful framework for building certain applications.
I think the same is true of ASP.NET MVC. I&#8217;ve used and use both. However, I don&#8217;t think that means these are the best approach for tackling HTTP.</p>

<p>Chad&#8217;s post was very good. I agree with almost all of his points. In particular, I think he hit several very important points, the biggest of which was his emphatic quote:</p>

<blockquote><p>INHERITANCE IS FAIL FOR MOST DESIGNS, BUT NEVER MORE SO THAN IN WEB/MVC FRAMEWORKS!</p><footer><strong>Chad Myers</strong> <cite><a href='http://lostechies.com/chadmyers/sweet-sweet-vindication/'>lostechies.com/chadmyers/&hellip;</a></cite></footer></blockquote>


<p>Then from his list of criteria for a &#8220;perfect&#8221; web framework:</p>

<ul>
<li><strong>Completely compositional</strong>: 100% agree</li>
<li><strong>[Resource]-based</strong>: I take a slightly different direction here. We talk about &#8220;models&#8221;, but if you are really thinking about HTTP, you should be thinking in terms
of resources. They are similar in many ways, notably in the sorts of &#8220;behaviors&#8221; (in FubuMVC terms) that should be composed with the &#8220;model.&#8221;
Honestly, it&#8217;s the &#8220;model&#8221; term itself that seems totally overloaded or at least at the wrong layer when talking about a framework.
If you have a model, you&#8217;re probably really dealing with something more like <acronym title="Domain Driven Design">DDD</acronym> than the HTTP application layer.</li>
<li><strong>Not have any notion of controllers</strong>: Agree. In MVC-style frameworks, they are sort of necessary, but if you break away from MVC, you&#8217;ll find there are better alternatives.</li>
<li><strong>Action-based</strong>: I&#8217;m all about using functions, or delegates, as <code>'Request -&gt; 'Response</code> handlers. I also agree that these should generally be kept simple,
relying on compositional helpers, middlewares, or whatever you want to call them to perform model-binding and response generation.
Granted, this is slightly different than what Chad is talking about, and I&#8217;ll cover my thoughts on this in more detail below.</li>
<li><strong>Minimized code-in-view</strong>: templates are helpful, but the ability to add a lot of logic is just asking for trouble. I really like the tags-as-code approach taken by <a href="http://websharper.com/">WebSharper</a>
and <a href="http://wingbeats.codeplex.com/">Wing Beats</a>.</li>
<li><strong>Independent of other frameworks</strong>: Definitely limit other dependencies and play nice with others.</li>
<li><strong>Testing as a first-class citizen</strong>: At least allow whatever the consumer writes to easily write real unit tests. Generally, the only reason you can&#8217;t do this is related to hosting,
so make sure the hosting model is not necessary to test the application.</li>
</ul>


<p>Okay, so I obviously skipped some items. I don&#8217;t think the other items are bad; I just don&#8217;t think they are necessary for a &#8220;perfect&#8221; web framework.</p>

<ul>
<li><strong>Total adherence to principles</strong>: This sounds really good. I don&#8217;t disagree, really, but exactly which principles? Principles sometimes change.
Some make sense in one approach to software development and are sort of non-issues in others. Look at the description of <a href="http://moiraesoftware.com/?p=434">SOLID and its relevance to F#</a>.
You&#8217;ll note that many of the principles are sort of non-issues.</li>
<li><strong>Statically typed</strong>: I don&#8217;t really see this as a requirement. HTTP is inherently dynamic. You could build a useful, fairly complex HTTP application using only
dictionaries. Reliance upon type serialization is misguided. How do you generate accurate Atom or HTML from a static type? You don&#8217;t. You need a template or
some other custom output. At the same time, I have grown to like static type-checking, espeically in F#, and F# 3.0&#8217;s Type Providers prove you can do a lot,
even <a href="http://fsharp3sample.codeplex.com/SourceControl/changeset/view/8670#195470">type check regular expressions</a>. I just don&#8217;t see this as a strict requirement.</li>
<li><strong>Based on IoC</strong>: I love IoC in C# applications. I can&#8217;t imagine life without it. However, I&#8217;ve found that I don&#8217;t even think about IoC when writing F#
applications. It&#8217;s just not a concern. Higher-order functions, computation expressions, and other functional-style approaches generally render IoC a non-issue.
So again, I don&#8217;t really see this as a requirement but a case of &#8220;use the right tool for the job.&#8221;</li>
<li><strong>Mostly model-based conventional routing</strong>: This is a totally fine solution. I take issue with having any single prescription for routing.
There are so many ways to handle this, and in the end it doesn&#8217;t matter. If you stick to a resource-oriented approach, which perhaps is the goal Chad is getting at, then your routing should
be pretty straightforward and simple. One thing many routers miss is the connection between different methods assigned to a single uri.
So far as I know, <a href="http://openrasta.com/">OpenRasta</a> and <a href="http://wcf.codeplex.com/">Web Api</a> are the only frameworks that return the appropriate
HTTP status codes for missing methods on an uri or unmatched Accept header, among other things. FubuMVC may allow this through a convention.</li>
<li><strong>One Model In, One Model Out</strong>: When using MVC, I generally like this approach. However, I again don&#8217;t see this as a requirement.
I&#8217;m not convinced a model is always necessary. Again, HTTP is quite dynamic, and it&#8217;s sometimes easier to work directly with a request
or pull out several different &#8220;objects&#8221; from a request to help generate a response. Though perhaps <code>'Request</code> and <code>'Response</code> are models and the point is moot. :)</li>
</ul>


<p>Now for the biggest divergence: I generally prefer to be explicit rather than lean on conventions.
In C#, I typically go for conventions because of the amount of noise required by the C# syntax.
With F#, I&#8217;m able to be explicit without suffering syntax noise overload. The same is true for many dyanmic languages
like Ruby and Python. So I disagree with both the <strong>Conventional top-to-bottom</strong> and <strong>Zero touch</strong> points. Again, I&#8217;m not fully opposed,
but I definitely don&#8217;t see these as requirements at the framework level. Sure, include it as an option, especially if, as in FubuMVC, you
can redefine the conventions to suit your needs. This could just mean use the right tool for the job, or it could mean you should take a
simpler approach and build your own conventions as wrapper functions.</p>

<p>If you think this sounds like a prescription to write a lot more code, I&#8217;ll show a comparison:</p>

<div><script src='https://gist.github.com/1542861.js'></script>
<noscript><pre><code></code></pre></noscript></div>


<p>Two extra lines (in this instance) and it&#8217;s likely with a more complex example you wouldn&#8217;t see much of a difference in terms of line count.
I doubt this is true with C#, so don&#8217;t take this as a statement that this is the &#8220;one, true way.&#8221; I like conventions when using C#, just as
I like IoC in C#.</p>

<p>In any case, definitely check out <a href="http://mvc.fubu-projet.org/">FubuMVC</a> as an alternative to MVC. There&#8217;s a lot to like, and the FubuMVC team has done an incredible job
building a terrific platform. I&#8217;ll try to highlight a few others in the upcoming weeks, but while you&#8217;re looking at Fubu, also checkout
<a href="http://openrasta.com/">OpenRasta</a> and <a href="http://servicestack.net/">ServiceStack</a>.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Type Systems are Asserts]]></title>
    <link href="http://wizardsofsmart.net/status/type-systems-are-asserts/"/>
    <updated>2011-10-31T10:37:30-05:00</updated>
    <id>http://wizardsofsmart.net/status/type-systems-are-asserts</id>
    <content type="html"><![CDATA[<p>I started reading <a href="http://www.amazon.com/gp/product/1430219483/ref=as_li_ss_tl?ie=UTF8&amp;amp;tag=panesofglass-20&amp;amp;linkCode=as2&amp;amp;camp=217145&amp;amp;creative=399369&amp;amp;creativeASIN=1430219483"><em>Coders at Work</em></a>
last week, and the interviews with Simon Peyton-Jones and Peter Norvig reaped an idea that
<a href="http://docs.python.org/library/doctest.html">doctest</a>, <a href="http://disnetdev.com/contracts.coffee/">contracts.coffee</a>,
and <a href="http://panesofglass.github.com/focco/">focco</a> sowed and cultivated. What’s the idea?
<a href="http://en.wikipedia.org/wiki/Type_system">Type systems</a> are nothing more than a formal
implementation of a half-baked program proving system.</p>

<p>This is a slight over-generalization. I want to stress that I don’t think type systems are bad,
whether static or dynamic. I’ve just suddenly realized that, should you extend a type system
with tools to define pre- and post-variants and invariants, as well as performance or probability
requirements, as some unit tests do, you end up with a very nice assertion mechanism that could
replace all the different tools currently used in programming.</p>

<p>As a means of testing out this idea, I’ve started investigating the <a href="http://www.lively-kernel.org/">Lively Kernel</a>
and want to see what might happen should I add a contracts.coffee layer with a mechanism for
validating the program upon saving changes to a script.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[OOP to me means only messaging local retention...]]></title>
    <link href="http://wizardsofsmart.net/status/oop-to-me-means-only-messaging-local/"/>
    <updated>2011-10-10T23:38:30-05:00</updated>
    <id>http://wizardsofsmart.net/status/oop-to-me-means-only-messaging-local</id>
    <content type="html"><![CDATA[<blockquote><p>OOP to me means only messaging, local retention and protection and hiding of state-process, and extreme late-binding of all things. It can be done in Smalltalk and in LISP.</p><footer><strong>Dr. Alan Kay</strong> <cite><a href='http://userpage.fu-berlin.de/~ram/pub/pub_jf47ht81Ht/doc_kay_oop_en'>userpage.fu-berlin.de/~ram/pub/&hellip;</a></cite></footer></blockquote>



]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Iteratee in F# - Part 1]]></title>
    <link href="http://wizardsofsmart.net/post/iteratee-in-f/"/>
    <updated>2011-10-10T12:00:59-05:00</updated>
    <id>http://wizardsofsmart.net/post/iteratee-in-f</id>
    <content type="html"><![CDATA[<p>I&#8217;ve been playing with <a href="http://okmij.org/ftp/Streams.html">Iteratees</a> lately in my work with
<a href="http://twitter.com/#!/7sharp9">Dave</a> on <a href="https://github.com/fractureio/fracture">fracture-io</a>.</p>

<p>The <code>Iteratee</code> module used in this post is part of the <a href="http://github.com/fsharp/fsharpx">FSharpx</a>
library and provides a set of types and functions for building compositional, input processing components.</p>

<h2>A fold, by any other name</h2>

<p>A common scenario for I/O processing is parsing an HTTP request message. Granted, most will rely on ASP.NET, HttpListener, or WCF to do this for them. However, HTTP request parsing has a lot of interesting elements that are useful for demonstrating problem areas in inefficient resource usage using other techniques. For our running sample, we&#8217;ll focus on parsing the headers of the following HTTP request message:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>let httpRequest : byte [] = @"GET /some/uri HTTP/1.1
</span><span class='line'>Accept:text/html,application/xhtml+xml,application/xml
</span><span class='line'>Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
</span><span class='line'>Accept-Encoding:gzip,deflate,sdch
</span><span class='line'>Accept-Language:en-US,en;q=0.8
</span><span class='line'>Cache-Control:max-age=0
</span><span class='line'>Connection:keep-alive
</span><span class='line'>Host:stackoverflow.com
</span><span class='line'>If-Modified-Since:Sun, 25 Sep 2011 20:55:29 GMT
</span><span class='line'>Referer:http://www.bing.com/search?setmkt=en-US&q=don't+use+IEnumerable%3Cbyte%3E
</span><span class='line'>User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.4 (KHTML, like Gecko) Chrome/16.0.889.0 Safari/535.4
</span><span class='line'>
</span><span class='line'>&lt;!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01//EN"" ""http://www.w3.org/TR/html4/strict.dtd"">
</span><span class='line'>&lt;html>
</span><span class='line'>&lt;head>
</span><span class='line'>...
</span><span class='line'>&lt;/head>
</span><span class='line'>&lt;body>
</span><span class='line'>...
</span><span class='line'>&lt;/body>
</span><span class='line'>&lt;/html>"B</span></code></pre></td></tr></table></div></figure>


<p>When parsing an HTTP request message, we most likely want to return not just a list of strings but something more descriptive, such as an abstract syntax tree represented as a F# discriminated union. A perfect candidate for taking in our request message above and producing the desired result is <a href="http://msdn.microsoft.com/en-us/library/ee353471.aspx"><code>Seq.fold</code></a>.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>val fold : ('State -> 'a -> 'State) -> 'State -> seq&lt;'a> -> 'State</span></code></pre></td></tr></table></div></figure>


<p>The left fold is a very useful function. It equivalent to the <a href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.aggregate.aspx"><code>Enumerable.Aggregate</code></a> extension method in LINQ. This function takes in a state transformation function, an initial seed value, and a sequence of data, and produces a final state value incrementally.</p>

<p>Looks like we&#8217;re done here. However, there are still problems with stopping here:</p>

<h3>Composition</h3>

<p>You can certainly use function composition to generate an appropriate state incrementing function, but you would still have the problem of being able to pause to delay selecting the appropriate message body processor.</p>

<h3>Early termination</h3>

<p>Suppose you really only ever want just the message headers. How would you stop processing to free your resources as quickly as possible? Forget it. Fold is going to keep going until it runs out of chunks. Even if you have your fold function stop updating the state after the headers are complete, you won&#8217;t get a result until the entire data stream has been processed.</p>

<h2>Iteratees</h2>

<p>The iteratee itself is a data consumer. It consumes data in chunks until it has either consumed enough data to produce a result or receives an EOF.</p>

<p>An iteratee is based on the <code>fold</code> operator with two differences:</p>

<ol>
<li><p>The iteratee may complete its processing early by returning a Done state. The iteratee may return the unused portion of any chunk it was passed in its Done state. This should not be confused with the rest of the stream not yet provided by the enumerator.</p></li>
<li><p>The iteratee does not pull data but receives chunks of data from an &#8220;enumerator&#8221;. It returns a continuation to receive and process the next chunk. This means that an iteratee may be paused at any time, either by neglecting to pass it any additional data or by passing an Empty chunk.</p></li>
</ol>


<h2>Inspiration</h2>

<p>For those interested in reading more, there are any number of articles and examples. Here are a few I&#8217;ve referenced quite frequently:</p>

<ul>
<li><a href="http://okmij.org/ftp/Haskell/Iteratee/IterateeIO-talk-notes.pdf">Iteratee IO</a></li>
<li><a href="https://john-millikin.com/software/enumerator/">enumerator package for Haskell</a></li>
<li><a href="http://www.yesodweb.com/book/enumerator">Yesod Book - Enumerator package</a></li>
<li><a href="http://apocalisp.wordpress.com/2010/10/17/scalaz-tutorial-enumeration-based-io-with-iteratees/">Scalaz Tutorial: Enumeration-Based I/O with Iteratees</a></li>
</ul>


<p>The Scalaz version arguably comes closest to the F# implementation, but I have generally based my implementations on the Haskell source. I&#8217;ve got two implementations currently, a version based on the <a href="http://hackage.haskell.org/package/enumerator">enumerator package</a>, and a <a href="http://en.wikipedia.org/wiki/Continuation-passing_style">continuation-passing style</a> version based on the <a href="http://hackage.haskell.org/package/iteratee">iteratee package</a>.</p>

<p>The iteratee is composed of one of two states, either a done state with a result and the remainder of the data stream, or a continue state containing a continuation to continue processing.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>type Iteratee&lt;'el, 'a> =
</span><span class='line'>    | Done -> 'a * Stream&lt;'el>
</span><span class='line'>    | Continue -> (Stream&lt;'el> -> Iteratee&lt;'el, 'a>)</span></code></pre></td></tr></table></div></figure>


<p>The <code>Stream</code> type used here is not <code>System.IO.Stream</code> but yet another discriminated union to represent different stream chunk states:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>type Stream&lt;'el> =
</span><span class='line'>    | Chunk -> 'el  // A chunk of data
</span><span class='line'>    | Empty         // An empty chunk represents a pause and can be used as a transition in compositions
</span><span class='line'>    | EOF           // Denotes that no chunks remain</span></code></pre></td></tr></table></div></figure>


<h3>Some Iteratees</h3>

<p>The following are some sample iteratees using the List&lt;&#8217;a> type in F#. While not the most efficient, they are easy to express concisely and are thus better for illustrating the use of iteratees.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
<span class='line-number'>31</span>
<span class='line-number'>32</span>
<span class='line-number'>33</span>
<span class='line-number'>34</span>
<span class='line-number'>35</span>
<span class='line-number'>36</span>
<span class='line-number'>37</span>
<span class='line-number'>38</span>
<span class='line-number'>39</span>
<span class='line-number'>40</span>
<span class='line-number'>41</span>
<span class='line-number'>42</span>
<span class='line-number'>43</span>
<span class='line-number'>44</span>
<span class='line-number'>45</span>
<span class='line-number'>46</span>
<span class='line-number'>47</span>
<span class='line-number'>48</span>
<span class='line-number'>49</span>
<span class='line-number'>50</span>
<span class='line-number'>51</span>
<span class='line-number'>52</span>
<span class='line-number'>53</span>
<span class='line-number'>54</span>
<span class='line-number'>55</span>
<span class='line-number'>56</span>
<span class='line-number'>57</span>
<span class='line-number'>58</span>
<span class='line-number'>59</span>
<span class='line-number'>60</span>
<span class='line-number'>61</span>
<span class='line-number'>62</span>
<span class='line-number'>63</span>
<span class='line-number'>64</span>
<span class='line-number'>65</span>
<span class='line-number'>66</span>
<span class='line-number'>67</span>
<span class='line-number'>68</span>
<span class='line-number'>69</span>
<span class='line-number'>70</span>
<span class='line-number'>71</span>
<span class='line-number'>72</span>
<span class='line-number'>73</span>
<span class='line-number'>74</span>
<span class='line-number'>75</span>
<span class='line-number'>76</span>
<span class='line-number'>77</span>
<span class='line-number'>78</span>
<span class='line-number'>79</span>
<span class='line-number'>80</span>
<span class='line-number'>81</span>
<span class='line-number'>82</span>
<span class='line-number'>83</span>
<span class='line-number'>84</span>
<span class='line-number'>85</span>
<span class='line-number'>86</span>
<span class='line-number'>87</span>
<span class='line-number'>88</span>
<span class='line-number'>89</span>
<span class='line-number'>90</span>
<span class='line-number'>91</span>
<span class='line-number'>92</span>
<span class='line-number'>93</span>
<span class='line-number'>94</span>
<span class='line-number'>95</span>
<span class='line-number'>96</span>
<span class='line-number'>97</span>
<span class='line-number'>98</span>
<span class='line-number'>99</span>
<span class='line-number'>100</span>
<span class='line-number'>101</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>let length&lt;'a> : Iteratee&lt;'a list, int> =
</span><span class='line'>    let rec step n = function
</span><span class='line'>        | Empty | Chunk [] -> Continue (step n)
</span><span class='line'>        | Chunk x -> Continue (step (n + x.Length))
</span><span class='line'>        | EOF -> Done(n, EOF)
</span><span class='line'>    in Continue (step 0)
</span><span class='line'>
</span><span class='line'>let peek&lt;'a> : Iteratee&lt;'a list, 'a option> =
</span><span class='line'>    let rec inner =
</span><span class='line'>        let rec step = function
</span><span class='line'>            | Empty | Chunk ([]:'a list) -> inner
</span><span class='line'>            | Chunk(x::xs) as s -> Done(Some x, s)
</span><span class='line'>            | EOF -> Done(None, EOF)
</span><span class='line'>        Continue step
</span><span class='line'>    in inner
</span><span class='line'>
</span><span class='line'>let head&lt;'a> : Iteratee&lt;'a list, 'a option> =
</span><span class='line'>    let rec inner =
</span><span class='line'>        let rec step = function
</span><span class='line'>            | Empty | Chunk ([]:'a list) -> inner
</span><span class='line'>            | Chunk(x::xs) -> Done(Some x, Chunk xs)
</span><span class='line'>            | EOF -> Done(None, EOF)
</span><span class='line'>        Continue step
</span><span class='line'>    in inner
</span><span class='line'>
</span><span class='line'>let drop n =
</span><span class='line'>    let rec step n = function
</span><span class='line'>        | Empty | Chunk [] -> Continue &lt;| step n
</span><span class='line'>        | Chunk str ->
</span><span class='line'>            if str.Length &lt; n then
</span><span class='line'>                Continue &lt;| step (n - str.Length)
</span><span class='line'>            else let extra = List.skip n str in Done((), Chunk extra)
</span><span class='line'>        | EOF -> Done((), EOF)
</span><span class='line'>    in if n &lt;= 0 then empty&lt;_> else Continue (step n)
</span><span class='line'>
</span><span class='line'>let private dropWithPredicate pred listOp =
</span><span class='line'>    let rec step = function
</span><span class='line'>        | Empty | Chunk [] -> Continue step
</span><span class='line'>        | Chunk x ->
</span><span class='line'>            match listOp pred x with
</span><span class='line'>            | [] -> Continue step
</span><span class='line'>            | x' -> Done((), Chunk x')
</span><span class='line'>        | EOF as s -> Done((), s)
</span><span class='line'>    in Continue step
</span><span class='line'>
</span><span class='line'>let dropWhile pred = dropWithPredicate pred List.skipWhile
</span><span class='line'>let dropUntil pred = dropWithPredicate pred List.skipUntil
</span><span class='line'>
</span><span class='line'>let take n =
</span><span class='line'>    let rec step before n = function
</span><span class='line'>        | Empty | Chunk [] -> Continue &lt;| step before n
</span><span class='line'>        | Chunk str ->
</span><span class='line'>            if str.Length &lt; n then
</span><span class='line'>                Continue &lt;| step (before @ str) (n - str.Length)
</span><span class='line'>            else let str', extra = List.splitAt n str in Done(before @ str', Chunk extra)
</span><span class='line'>        | EOF -> Done(before, EOF)
</span><span class='line'>    in if n &lt;= 0 then Done([], Empty) else Continue (step [] n)
</span><span class='line'>
</span><span class='line'>let private takeWithPredicate (pred:'a -> bool) listOp =
</span><span class='line'>    let rec step before = function
</span><span class='line'>        | Empty | Chunk [] -> Continue (step before)
</span><span class='line'>        | Chunk str ->
</span><span class='line'>            match listOp pred str with
</span><span class='line'>            | str', [] -> Continue (step (before @ str'))
</span><span class='line'>            | str', extra -> Done(before @ str', Chunk extra)
</span><span class='line'>        | EOF -> Done(before, EOF)
</span><span class='line'>    in Continue (step [])
</span><span class='line'>
</span><span class='line'>let takeWhile pred = takeWithPredicate pred List.span
</span><span class='line'>let takeUntil pred = takeWithPredicate pred List.split
</span><span class='line'>
</span><span class='line'>let heads str =
</span><span class='line'>    let rec loop count str =
</span><span class='line'>        match count, str with
</span><span class='line'>        | (count, []) -> Done(count, EOF)
</span><span class='line'>        | (count, str) -> Continue (step count str)
</span><span class='line'>    and step count str s =
</span><span class='line'>        match str, s with
</span><span class='line'>        | str, Empty -> loop count str
</span><span class='line'>        | str, (Chunk []) -> loop count str
</span><span class='line'>        | c::t, (Chunk (c'::t')) ->
</span><span class='line'>            if c = c' then step (count + 1) t (Chunk t') 
</span><span class='line'>            else Done(count, Chunk (c'::t'))
</span><span class='line'>        | _, s -> Done(count, s)
</span><span class='line'>    loop 0 str
</span><span class='line'>
</span><span class='line'>// readLines clearly shows the composition allowed by iteratees.
</span><span class='line'>// Note the use of the heads and takeUntil combinators.
</span><span class='line'>let readLines =
</span><span class='line'>    let toString chars = String(Array.ofList chars)
</span><span class='line'>    let newlines = ['\r';'\n']
</span><span class='line'>    let newline = ['\n']
</span><span class='line'>    let isNewline c = c = '\r' || c = '\n'
</span><span class='line'>    let terminators = heads newlines >>= fun n -> if n = 0 then heads newline else Done(n, Empty)
</span><span class='line'>    let rec lines acc = takeUntil isNewline >>= fun l -> terminators >>= check acc l
</span><span class='line'>    and check acc l count =
</span><span class='line'>        match l, count with
</span><span class='line'>        | _, 0 -> Done(Choice1Of2 (List.rev acc |> List.map toString), Chunk l)
</span><span class='line'>        | [], _ -> Done(Choice2Of2 (List.rev acc |> List.map toString), EOF)
</span><span class='line'>        | l, _ -> lines (l::acc)
</span><span class='line'>    lines []</span></code></pre></td></tr></table></div></figure>


<h2>Enumerators</h2>

<p>Enumerators feed data into iteratees, advancing their state until they complete.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
<span class='line-number'>31</span>
<span class='line-number'>32</span>
<span class='line-number'>33</span>
<span class='line-number'>34</span>
<span class='line-number'>35</span>
<span class='line-number'>36</span>
<span class='line-number'>37</span>
<span class='line-number'>38</span>
<span class='line-number'>39</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>// Feed the EOF chunk to the iteratee in order to force the result.
</span><span class='line'>let rec enumEOF = function 
</span><span class='line'>    | Done(x,_) -> Done(x, EOF)
</span><span class='line'>    | Continue k ->
</span><span class='line'>        match k EOF with
</span><span class='line'>        | Continue _ -> failwith "enumEOF: divergent iteratee"
</span><span class='line'>        | i -> enumEOF i
</span><span class='line'>
</span><span class='line'>// Run the iteratee and either return the result or throw an exception for a divergent iteratee.
</span><span class='line'>let run i =
</span><span class='line'>    match enumEOF i with
</span><span class='line'>    | Done(x,_) -> x
</span><span class='line'>    | Continue _ -> failwith "run: divergent iteratee"
</span><span class='line'>
</span><span class='line'>// Feed the data stream to the iteratee as a single chunk.
</span><span class='line'>// This is useful for testing but not conserving memory.
</span><span class='line'>// val enumeratePure1Chunk :: 'a list -> Enumerator&lt;'a list,'b>
</span><span class='line'>let enumeratePure1Chunk str i =
</span><span class='line'>    match str, i with 
</span><span class='line'>    | [], _ -> i
</span><span class='line'>    | _, Done(_,_) -> i
</span><span class='line'>    | _::_, Continue k -> k (Chunk str)
</span><span class='line'>
</span><span class='line'>// Feed data to the iteratee in chunks of size n.
</span><span class='line'>// val enumeratePureNChunk :: 'a list -> int -> Enumerator&lt;'a list,'b>
</span><span class='line'>let rec enumeratePureNChunk n str i =
</span><span class='line'>    match str, i with
</span><span class='line'>    | [], _ -> i
</span><span class='line'>    | _, Done(_,_) -> i
</span><span class='line'>    | _::_, Continue k ->
</span><span class='line'>        let x, xs = List.splitAt n str in enumeratePureNChunk n xs (k (Chunk x))
</span><span class='line'>
</span><span class='line'>// Feed data to the iteratee one value at a time.
</span><span class='line'>//val enumerate :: 'a list -> Enumerator&lt;'a list,'b>
</span><span class='line'>let rec enumerate str i = 
</span><span class='line'>    match str, i with
</span><span class='line'>    | [], _ -> i
</span><span class='line'>    | _, Done(_,_) -> i
</span><span class='line'>    | x::xs, Continue k -> enumerate xs (k (Chunk [x]))</span></code></pre></td></tr></table></div></figure>


<h2>Reading an HTML Request by Lines</h2>

<p>Back to our earlier example of reading HTTP requests, let&#8217;s see how we might read it by lines. I&#8217;ll add a few caveats. This is not encapsulating the <code>Stream</code> well as we are using a memory stream. I could wrap this up in an <code>enumerateMemoryStream</code> function that takes all the bytes to read (which will likely happen soon). The example below is using the <code>Iteratee.Binary</code> module, not the <code>Iteratee.List</code> module.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>let runIteratee() =
</span><span class='line'>    let sw = Stopwatch.StartNew()
</span><span class='line'>    let result =
</span><span class='line'>        [ for _ in 1..10000 do
</span><span class='line'>            use stream = new MemoryStream(httpRequest)
</span><span class='line'>            yield! match enumStream 128 stream readLines |> run with
</span><span class='line'>                   | Choice1Of2 x -> x
</span><span class='line'>                   | Choice2Of2 y -> y ]
</span><span class='line'>    sw.Stop()
</span><span class='line'>    printfn "Iteratee read %d lines in %d ms" result.Length sw.ElapsedMilliseconds</span></code></pre></td></tr></table></div></figure>


<h2>So what?</h2>

<h3>System.IO.Stream-based processing</h3>

<p>The System.IO.Stream type should be familiar to anyone who has ever worked with I/O in .NET. Streams are the primary abstraction available for working with streams of data, whether over the file system (FileStream) or network protocols (NetworkStream). Streams also have a nice support structure in the form of TextReaders and TextWriters, among other, similar types.</p>

<p>Using the standard Stream processing apis, you might write something like the following:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>let rec readConsecutiveLines (reader:System.IO.StreamReader) cont =
</span><span class='line'>    if reader.EndOfStream then cont []
</span><span class='line'>    else let line = reader.ReadLine()
</span><span class='line'>         if System.String.IsNullOrEmpty(line) then cont []
</span><span class='line'>         else readConsecutiveLines reader (fun tail -> cont (line::tail))
</span><span class='line'>
</span><span class='line'>let readFromStream() =
</span><span class='line'>    let sw = System.Diagnostics.Stopwatch.StartNew()
</span><span class='line'>    let result =
</span><span class='line'>        [ for _ in 1..10000 do 
</span><span class='line'>            use stream = new System.IO.MemoryStream(httpRequest)
</span><span class='line'>            use reader = new System.IO.StreamReader(stream)
</span><span class='line'>            yield readConsecutiveLines reader id ]
</span><span class='line'>    sw.Stop()
</span><span class='line'>    printfn "Stream read %d in %d ms" result.Length sw.ElapsedMilliseconds
</span><span class='line'>
</span><span class='line'>readFromStream()</span></code></pre></td></tr></table></div></figure>


<p>What might be the problems with this approach?</p>

<h4>Blocking the current thread</h4>

<p>This is a synchronous use of reading from a Stream. In fact, <code>StreamReader</code> can only be used in a synchronous fashion. There are no methods that even offer the Asynchronous Programming Model (APM). For that, you&#8217;ll need to read from the <code>Stream</code> in chunks and find the line breaks yourself. We&#8217;ll get to more on this in a few minutes.</p>

<h4>Poor composition</h4>

<p>First off, the sample above is performing side effects throughout, and side-effects don&#8217;t compose. You might suggest using standard function composition to create a complete message parser, but what if you don&#8217;t know ahead of time what type of request body you&#8217;ll receive? Can you pause processing to select the appropriate processor? You could certainly address this with some conditional branching, but where exactly do you tie that into your current logic? Also, the current parser breaks on lines using the StreamReader&#8217;s built in logic. If you want to do parsing on individual lines, where would you tie in that logic?</p>

<h4>Memory consumption</h4>

<p>In this example, we are not taking any care about our memory use. To that end, you might argue that we should just use <code>StreamReader.ReadToEnd()</code> and then break up the string using a compositional parser like <a href="http://http://www.quanttec.com/fparsec/">FParsec</a>. If we don&#8217;t care about careful use of memory, that&#8217;s actually quite a good idea. However, in most network I/O situations &#8211; such as writing high-performance servers &#8211; you really want to control your memory use very carefully. <code>StreamReader</code> does allow you to specify the chunk size, so it&#8217;s not a complete case against using <code>StreamReader</code>, which is why this is a last-place argument. And of course, you can certainly go after <code>Stream.Read()</code> directly.</p>

<h3>IEnumerable-based processing</h3>

<p>How can we add better compositionality and refrain from blocking the thread? One way others have solved this problem is through the use of iterators. A common example can be found on <a href="http://stackoverflow.com/questions/2630359/convert-stream-to-ienumerable-if-possible-when-keeping-laziness">Stack Overflow</a>. Iterators allow you to publish a lazy stream of data, either one element at a time or in chunks, and through LINQ or F#&#8217;s <code>Seq</code> module, chain together processors for the data.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>// Read the stream byte by byte
</span><span class='line'>let readStreamByByte (stream: System.IO.Stream) =
</span><span class='line'>    seq { while true do
</span><span class='line'>            let x = stream.ReadByte()
</span><span class='line'>            if (int x) &lt; 0 then ()
</span><span class='line'>            else yield x }
</span><span class='line'>
</span><span class='line'>// Read the stream by chunks
</span><span class='line'>let readStreamByChunk chunkSize (stream: System.IO.Stream) =
</span><span class='line'>    let buffer = Array.zeroCreate&lt;byte> chunkSize
</span><span class='line'>    seq { while true do
</span><span class='line'>            let bytesRead = stream.Read(buffer, 0, chunkSize)
</span><span class='line'>            if bytesRead = 0 then ()
</span><span class='line'>            else yield buffer }
</span><span class='line'>
</span><span class='line'>// When you are sure you want text by lines
</span><span class='line'>let readStreamByLines (reader: System.IO.StreamReader) =
</span><span class='line'>    seq { while not reader.EndOfStream do
</span><span class='line'>            yield reader.ReadLine() }</span></code></pre></td></tr></table></div></figure>


<p>Three options are presented. In each, I&#8217;m using a <code>Stream</code> or <code>StreamReader</code>, but you could just as easily replace those with a <code>byte[]</code>, <code>ArraySegment&lt;byte&gt;</code>, or <code>SocketAsyncEventArgs</code>. What could be wrong with these options?</p>

<h4>Lazy, therefore resource contentious</h4>

<p>Iterators are pull-based, so you&#8217;ll only retrieve a chunk when requested. This sounds pretty good for your processing code, but it&#8217;s not a very good situation for your sockets. If you have data coming in, you want to get it moved out as quickly as possible to free up your allocated threads and pinned memory buffers for more incoming or outgoing traffic.</p>

<h4>Lazy, therefore non-deterministic</h4>

<p>Each of these items is lazy; therefore, it&#8217;s impossible to know when you can free up resources. Who owns the <code>Stream</code> or <code>StreamReader</code> passed into each method? When is it safe to free the resource? If used immediately within a function, you may be fine, but you&#8217;d also be just as well off if you used a <code>list</code> or <code>array</code> comprehension and blocked until all bytes were read. (The one possible exception might be when using a <a href="http://tomasp.net/blog/csharp-async.aspx">co-routine style async pattern</a>.)</p>

<h2>Summary</h2>

<p>Iteratees are able to resolve a number of issues related to general stream processing, as well as either lazy, e.g. seq<_>- or Async<_>-based, non-determinism. I&#8217;m sure you are wondering why I didn&#8217;t dive deeper in explaining the iteratees above. In the next part, we&#8217;ll explore a more idiomatic .NET solution for creating iteratees. We&#8217;ll then decompose the iteratees above and cover each in more detail. In the meantime, please checkout <a href="http://github.com/fsharp/fsharpx">FSharpx</a> for additional information.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[I'm working on a few seemingly unrelated posts...]]></title>
    <link href="http://wizardsofsmart.net/status/im-working-on-a-few-seemingly-unrelated-posts/"/>
    <updated>2011-07-19T14:26:30-05:00</updated>
    <id>http://wizardsofsmart.net/status/im-working-on-a-few-seemingly-unrelated-posts</id>
    <content type="html"><![CDATA[<p>I&#8217;m working on a few, seemingly unrelated posts:</p>

<ol>
<li>Iteratees in F# and their use in creating a chunk-driven parser</li>
<li>HTTP as the command line interface (CLI) for the web</li>
</ol>


<p>Stay-tuned</p>
]]></content>
  </entry>
  
</feed>
