<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom">
 
  <title>bvanderveen.com</title>
  <link href="http://bvanderveen.com/"/>
  <link type="application/atom+xml" rel="self" href="http://bvanderveen.com/atom.xml"/>
  <updated>2012-02-20T16:37:56-08:00</updated>
  <id>http://bvanderveen.com/</id>
  <author>
    <name>Benjamin van der Veen</name>
    <email>b@bvanderveen.com</email>
  </author>

  
  <entry>
    <id>http://bvanderveen.com/a/oop</id>
    <link type="text/html" rel="alternate" href="http://bvanderveen.com/a/oop"/>
    <title><code>this</code> Is Object-Oriented Programming</title>
    <updated>2012-02-08T00:00:00-08:00</updated>
    <author>
      <name>Benjamin van der Veen</name>
      <uri>http://bvanderveen.com/</uri>
    </author>
    <content type="html">&lt;p&gt;A method is a function whose first argument is &lt;code&gt;this&lt;/code&gt;. Methods hanging from &lt;code&gt;this&lt;/code&gt; are functions with &lt;code&gt;this&lt;/code&gt; a curried into them. &lt;code&gt;this&lt;/code&gt; contains data which is sometimes unneeded by the function into which it is curried. The information that &lt;code&gt;this&lt;/code&gt; conveys is mutable, and could be in any state.&lt;/p&gt;

&lt;p&gt;In programming, we make functions which operate on vectors of high-level datatypes. Perhaps the old-beards wanted objects so they could more easily operate on structs, being as they are the highest of high-level C data types. C programs tend to contain functions that operate on structs, and they&amp;#8217;re often grouped by the type of their first argument. We don&amp;#8217;t have to squint hard to see a simple class-based object system.&lt;/p&gt;

&lt;p&gt;Now, it&amp;#8217;s so easy to add fields and methods to objects. We don&amp;#8217;t have to type out all those typedefs and pointer dereferences and allocations and deallocations and header files. We have ninjas maneuvering heroically in our codebases. The gravity of our C structs does not imbue our classes.&lt;/p&gt;

&lt;p&gt;Testing a method involves more than just passing arguments to it and checking to see if its return value is correct; it is necessary to prepare &lt;code&gt;this&lt;/code&gt; before testing a method and verify the state of &lt;code&gt;this&lt;/code&gt; afterwards. The widely-adopted convention of keeping &lt;code&gt;this&lt;/code&gt; private to its methods makes this difficult–since the test cannot directly read or mutate &lt;code&gt;this&lt;/code&gt;, the object&amp;#8217;s other methods must be used to set up &lt;code&gt;this&lt;/code&gt; before the test, and used again after the test to ensure that &lt;code&gt;this&lt;/code&gt; has been mutated as expected. No longer is a single function under test; the whole set of functions—the object&amp;#8217;s behavior—is under test.&lt;/p&gt;

&lt;p&gt;Writing object-oriented code requires constant vigilance. Think twice about adding or modifying an instance variable. Every method on an object should depend on every field on the object. Make a clear distinction between what is absolutely necessary and what can be calculated. Ensure that every callee can be, in whatever way is most idiomatic, curried into its caller.&lt;/p&gt;</content>
  </entry>
  
  <entry>
    <id>http://bvanderveen.com/a/dot-net-open-source-does-not-beget-open-source</id>
    <link type="text/html" rel="alternate" href="http://bvanderveen.com/a/dot-net-open-source-does-not-beget-open-source"/>
    <title>In .NET, open source does not beget open source</title>
    <updated>2012-01-09T00:00:00-08:00</updated>
    <author>
      <name>Benjamin van der Veen</name>
      <uri>http://bvanderveen.com/</uri>
    </author>
    <content type="html">&lt;p&gt;Ruby, Python, Perl, Node, and Clojure all have, to varying degrees, a unified story for defining a project, translating its source code into runnable code, running a test suite, building distributable packages, and resolving and installing a project or package&amp;#8217;s dependencies. These stories just work across all supported platforms.&lt;/p&gt;

&lt;h3 id='setting_up_a_crossplatform_open_source_net_project_is_nontrivial'&gt;Setting up a cross-platform open source .NET project is non-trivial.&lt;/h3&gt;

&lt;p&gt;.NET open source developers jump through crazy hoops to try to get their projects to a point where anyone can check out the code from source control, build, and test the software on both .NET and Mono. What follows is a description of how I approached this task. It was painful to devise this solution and it continues to be painful to maintain.&lt;/p&gt;

&lt;h3 id='step_1_build'&gt;Step 1: Build&lt;/h3&gt;

&lt;p&gt;We want to build our source code into .DLLs. We&amp;#8217;ve got MSBuild, and Mono maintains it&amp;#8217;s own quirky clone of MSBuild, called xbuild. They both read in &lt;code&gt;.sln&lt;/code&gt; files, which are totally opaque and cannot be generated by hand, and &lt;code&gt;.csproj&lt;/code&gt; files, which are XML, but hey they&amp;#8217;re hand-editable. Okay. Ignore for a second that MonoDevelop and Visual Studio will fight over the formatting of those files, stomp on each other changes, and add garbage that&amp;#8217;s meaningless to the other. A VS- or MD-generated .csproj will be default import some target definitions called Microsoft.CSharp.targets. Uh oh, what&amp;#8217;s that? Where does that live on my system? What does it do? What package do I have to install to get that?&lt;/p&gt;

&lt;p&gt;Now we&amp;#8217;re in IDE-vs-IDE-vs-source-control hell, just so we can get a build running with two separate implementations of an XML-based project specification. But it&amp;#8217;s okay, it&amp;#8217;s cool. Let&amp;#8217;s assume we&amp;#8217;ve got that figured out and we&amp;#8217;ve got a cross-platform source-code-on-disk to DLLs-on-disk transformation. With the caveat that we&amp;#8217;re using the &lt;code&gt;msbuild&lt;/code&gt; command on Windows and &lt;code&gt;xbuild&lt;/code&gt; everywhere else.&lt;/p&gt;

&lt;h3 id='step_2_test'&gt;Step 2: Test&lt;/h3&gt;

&lt;p&gt;Now I&amp;#8217;m ready to run tests. How am I supposed to do that again? NUnit? XUnit? Something else? What&amp;#8217;s the difference between all of those? Does Microsoft have their own test framework/runner? Is there a Mono clone?&lt;/p&gt;

&lt;p&gt;Okay, I picked a test framework and runner. It doesn&amp;#8217;t matter which one because they&amp;#8217;re all the same. Now my code has a dependency on the DLL that defines the test framework. Well, I don&amp;#8217;t want to include that DLL in source control because checking binaries into source control is a no-no. I guess I&amp;#8217;ll just tell my contributors that they need to have TestFrameworkX-versionY.Z installed in the GAC to hack, and I&amp;#8217;ll just bite the bullet and field the inevitable build problems and complaints about a GAC dependency on the mailing list.&lt;/p&gt;

&lt;p&gt;Okay so I&amp;#8217;m building my tests (and all my contributors are too). Now I want to run them. Hopefully I picked something that&amp;#8217;s portable between .NET and Mono and I can easily run those tests on both platforms. Hopefully myself and my contributors can have a great test debugging experience whether we&amp;#8217;re using MonoDevelop or Visual Studio. Hopefully.&lt;/p&gt;

&lt;h3 id='step_3_repeat'&gt;Step 3: Repeat&lt;/h3&gt;

&lt;p&gt;I can build my code and I can run tests. Sweet! Now I want to set up continuous integration so I can have nightly builds and maybe some benchmarks to track the performance of my codebase over time. I&amp;#8217;d like the system to email my devs if they check in broken code. It want to do automated builds on both .NET and Mono to ensure that my codebase works on both.&lt;/p&gt;

&lt;p&gt;So I set about writing a build script that my CI system can run. Hm. I guess I could write an MSBuild file, but do I really want to maintain an XML build file? Will it be able to everything I need? Will I run into platform-dependent hiccups?&lt;/p&gt;

&lt;p&gt;Oh hey, &lt;a href='http://rake.rubyforge.org/'&gt;Rake&lt;/a&gt; is pretty nice, it&amp;#8217;s well-supported on both Windows and Unix, and someone put together a nice suite of &lt;a href='http://albacorebuild.net/'&gt;.NET-specific Rake tasks&lt;/a&gt;. Okay, I write a Ruby script to build my .NET projects. Pretty nice! I have separate commands for &lt;code&gt;msbuild&lt;/code&gt; and &lt;code&gt;xbuild&lt;/code&gt; to build the &lt;code&gt;.csproj&lt;/code&gt; files that my IDE understands, but hey, just an implementation detail, right?&lt;/p&gt;

&lt;p&gt;I also want to test that the Mono-compiled DLLs work on .NET and vice-versa. Gonna have to add some plumbing for that…&lt;/p&gt;

&lt;h3 id='step_4_ship'&gt;Step 4: Ship&lt;/h3&gt;

&lt;p&gt;I&amp;#8217;ve got nightly builds that are tested on both .NET and Mono, so I have a pretty solid codebase! Okay, let&amp;#8217;s get it into the hands of users as easily as possible. How are users getting my code these days? Should I tell them to check out and build the source with my Ruby script? What if they build from their IDE, I guess I should make sure that story works too. But ideally I should also ship binaries so users don&amp;#8217;t have to compile the project themselves&lt;/p&gt;

&lt;p&gt;Oh hey, NuGet sounds like pretty hot way to distribute binaries! Let&amp;#8217;s investigate it since it&amp;#8217;s all new and fancy. Maybe I can use this to resolve my dependency on the test framework DLL while I&amp;#8217;m at it. Okay, now I&amp;#8217;ve changed my Ruby build script to use NuGet to go download the test framework package before it builds my tests. Ah crap, NuGet blows up on Mono. Well, guess that test framework dependency stays in the GAC, and I must change my Rake script so it only uses NuGet to create the NuGet package for my project if it&amp;#8217;s running on Windows.&lt;/p&gt;

&lt;p&gt;Ah dang, you know, this also means that only Windows user are going to be able to use my project&amp;#8217;s NuGet package. I&amp;#8217;ll have to make my Ruby build script generate a zip file containing my project&amp;#8217;s DLLs. Doing it in Ruby is a heck of a lot easier than using the ZIP task in MSBuild and I don&amp;#8217;t have to worry about cross-platform issues.&lt;/p&gt;

&lt;p&gt;So, my .NET users can use Visual Studio and NuGet to take a dependency on my project, and my Mono users can have the ZIP file.&lt;/p&gt;

&lt;h3 id='step_5_go_forth_and_innovate'&gt;Step 5: Go forth and innovate!&lt;/h3&gt;

&lt;p&gt;Not so fast. Nancy, FubuMVC, Kayak, and Gate all use Rake to perform their builds, and as far as I recall those Rake scripts all branch on whether the current platform is Mono or .NET to accomplish that task. We are all using slightly different set-ups, and there&amp;#8217;s a ton of duplication of effort.&lt;/p&gt;

&lt;p&gt;If any of our users want to create an open source project that depends on our open source project, they&amp;#8217;re going to have to figure out and reimplement everything described above. The tooling to allow developers to rapidly create, distribute, and collaborate on portable modules doesn&amp;#8217;t exist in the .NET ecosystem.&lt;/p&gt;

&lt;h3 id='open_source_does_not_beget_more_open_source_in_net_because_the_barriers_to_standing_on_each_other_shoulders_are_so_high'&gt;Open source does not beget more open source in .NET, because the barriers to standing on each other shoulders are so high.&lt;/h3&gt;

&lt;p&gt;These are not unsolvable problems, but as far as I can tell, no one in the community has both resources and incentive to solve them.&lt;/p&gt;</content>
  </entry>
  
  <entry>
    <id>http://bvanderveen.com/a/sequence-uitableview</id>
    <link type="text/html" rel="alternate" href="http://bvanderveen.com/a/sequence-uitableview"/>
    <title>Sequence, UITableView</title>
    <updated>2011-12-19T00:00:00-08:00</updated>
    <author>
      <name>Benjamin van der Veen</name>
      <uri>http://bvanderveen.com/</uri>
    </author>
    <content type="html">&lt;p&gt;A great usecase for &lt;a href='https://github.com/bvanderveen/Sequence'&gt;Sequence&lt;/a&gt; is to declaratively construct content for &lt;code&gt;UITableView&lt;/code&gt;. As the user scrolls the table view, it pulls row data from a &lt;code&gt;UITableViewDataSource&lt;/code&gt; for the row visible on the screen. In this post, I discuss how Sequence supports this usecase and demonstrate how to use Sequence for this purpose.&lt;/p&gt;

&lt;h1 id='the_seeking_problem'&gt;The seeking problem&lt;/h1&gt;

&lt;p&gt;Our &lt;a href='/a/sequence-update'&gt;implementation of &lt;code&gt;itemAtIndex:&lt;/code&gt;&lt;/a&gt; supports short-circuit partial materialization of the sequence, but it doesn&amp;#8217;t help us if we&amp;#8217;re seeking to arbitary positions within the sequence. Suppose we had a table view with 1,000,000 rows of content represented by a sequence. If we call &lt;code&gt;itemAtIndex:&lt;/code&gt; on that sequence to retrieve row information while we&amp;#8217;re scrolling around the bottom of that list, we are calling &lt;code&gt;itemAtIndex:&lt;/code&gt; with an argument of ~1,000,000 every few frames of animation. Our implementation of &lt;code&gt;itemAtIndex:&lt;/code&gt; runs in O(n) time, so our table view animation grinds to a halt.&lt;/p&gt;

&lt;p&gt;The best way to seek within a sequence is if you can jump to an easily-calculated offset. Arrays are great for this—you take a pointer to the start of the array, add the product of the desired index and the array element width, and you&amp;#8217;ve calculated a pointer to the item at that index in O(1) time.&lt;/p&gt;

&lt;p&gt;In order to support our table view scenario, we&amp;#8217;ll make a time-space trade-off—we&amp;#8217;ll copy the values of the sequence into a contiguous array, so we can easily seek to arbitrary positions within our array. We can do this by calling &lt;code&gt;array&lt;/code&gt; on a sequence.&lt;/p&gt;

&lt;h2 id='table_view'&gt;Table view&lt;/h2&gt;

&lt;p&gt;Let&amp;#8217;s take a look at an abbreviated controller which specifies its contents in a declarative fashion. First, let&amp;#8217;s introduce a construct which represents the content and behavior of a table row:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// an object which represents a single row of table content
@interface TableItem : NSObject {
    UITableViewCell *(^cell)();
    void (^action)();
}

// returns a cell to display the row
@property (nonatomic, copy) UITableViewCell *(^cell)(); 

// returns an action to be called when the row is selected
@property (nonatomic, copy) void (^action)(); 

@end&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now, a trivial table view implementation using that construct:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@implementation SequenceTableController

- (id)init {

    ...

        self.content = [[[[Seq rangeWithStart:1 end:500] // a sequence of numbers, 1..500
        filter: ^ BOOL (id i) { return [i intValue] % 2 == 0 }] // filter out the odd numbers
        map:^ id (id n) { // return a TableItem to represent the row
            NSString *s = [n description]; // turn the NSNumber into a string
            TableItem *item = [[TableItem new] autorelease];
            item.cell = [[^ id () { return [self cellWithLabelText:s]; } copy] autorelease];
            item.action = [[^ void () { [self alertText:s]; } copy] autorelease];
            return item;
        }] array]; // materialize the sequence into an array

    ...

}

...

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return content.length;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TableItem *item = [content objectAtIndex:indexPath.row];
    return item.cell();
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    TableItem *item = [content objectAtIndex:indexPath.row];
    item.action();
}

@end&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Not too bad. I&amp;#8217;m imagining all the ways I could use this to avoid ever implementing &lt;code&gt;UITableViewDelegate&lt;/code&gt; or &lt;code&gt;UITableViewDataSource&lt;/code&gt; again.&lt;/p&gt;

&lt;p&gt;Check out the &lt;a href='https://github.com/bvanderveen/sequence-tableview-example'&gt;full source code&lt;/a&gt; on GitHub.&lt;/p&gt;
&lt;!--





I optimized other functions with that knowledge. Now, `any:` and `all:` can short-circuit before materializing the entire sequence.



I also added a `+[Seq rangeWithStart:end:]` which allows easy creation of `NSNumber` sequences, and a bit more documentation to [Sequence.h](https://github.com/bvanderveen/Sequence/blob/master/Sequence/Sequence.h).
--&gt;</content>
  </entry>
  
  <entry>
    <id>http://bvanderveen.com/a/sequence-push-pull</id>
    <link type="text/html" rel="alternate" href="http://bvanderveen.com/a/sequence-push-pull"/>
    <title>Sequence, push, pull</title>
    <updated>2011-12-18T00:00:00-08:00</updated>
    <author>
      <name>Benjamin van der Veen</name>
      <uri>http://bvanderveen.com/</uri>
    </author>
    <content type="html">&lt;p&gt;When I &lt;a href='/a/sequence-preview'&gt;wrote last week&lt;/a&gt; about &lt;a href='https://github.com/bvanderveen/Sequence'&gt;Sequence&lt;/a&gt;, I was not satisfied with the implementation of operations like &lt;code&gt;itemAtIndex:&lt;/code&gt;, &lt;code&gt;any:&lt;/code&gt;, or &lt;code&gt;all:&lt;/code&gt;. These operations fully materialized the entire sequence, but technically didn&amp;#8217;t need to do so. This was because I hadn&amp;#8217;t decided whether the canonical representation of a sequence should be push-style (items &lt;em&gt;returned by&lt;/em&gt; producer to consumer) or pull-style (items &lt;em&gt;passed to&lt;/em&gt; consumer by producer), and because the implementations of those operations were agnostic to whether the sequence was a push- or pull-form, they couldn&amp;#8217;t provide partial materialization of the sequence.&lt;/p&gt;

&lt;p&gt;Consider &lt;code&gt;itemAtIndex:&lt;/code&gt;. To support retrieval of a single item from a sequence by index, the code performing the look-up needs to materialize a sequence up until the requested index, but does not need to materialize it any further to provide the correct value. This partial materialization can be accomplished provided the consumer of sequence values can give some of indication to the producer of sequence values instructing the latter to abort.&lt;/p&gt;

&lt;p&gt;This could be done with a pull-style sequence if the value-receiving consumer function returned a &lt;code&gt;BOOL&lt;/code&gt; indicating if it wanted more. This strikes me as a bit more conceptually tricky than the equivalent solution for the pull-style sequence form: the consumer simply stops calling the value-returning producer function when it no longer wants values.&lt;/p&gt;

&lt;h2 id='settled'&gt;Settled.&lt;/h2&gt;

&lt;p&gt;I decided to go ahead implementing &lt;code&gt;itemAtIndex:&lt;/code&gt; using a pull-style form. It looks like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;- (id)itemAtIndex:(NSUInteger)index {
    id (^next)() = impl(); 
    id item = nil;

    // iterates over items
    for (NSUInteger i = 0; (item = next()); i++) {
        if (i == index)
            return item;
    }
    return nil;
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here, we have an &lt;code&gt;impl&lt;/code&gt; function which returns an &lt;code&gt;id (^)()&lt;/code&gt; block called &lt;code&gt;next&lt;/code&gt;. That block is called &lt;code&gt;index&lt;/code&gt; times to get the corresponding element. If the the &lt;code&gt;next&lt;/code&gt; function returns nil, the sequence has ended, and the result of &lt;code&gt;itemAtIndex:&lt;/code&gt; is &lt;code&gt;nil&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Other operations which can short-circuit work similarly:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;- (BOOL)any:(BOOL(^)(id))predicate {
    id item = nil;
    
    for (id (^next)() = impl(); (item = next());)
        if (predicate(item))
            return YES;
    
    return NO;
}

- (BOOL)all:(BOOL(^)(id))predicate {    
    id item = nil;
    BOOL evaluatedItem = NO;

    for (id (^next)() = impl(); (item = next());) {
        evaluatedItem = YES;
        if (!predicate(item))
            return NO;
    }
    
    return evaluatedItem;
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In both these cases, the &lt;code&gt;impl&lt;/code&gt; function is called at the start of the operation to retrieve the item-producing function. That function is called until the result of the operation can be determined.&lt;/p&gt;</content>
  </entry>
  
  <entry>
    <id>http://bvanderveen.com/a/node-does-io</id>
    <link type="text/html" rel="alternate" href="http://bvanderveen.com/a/node-does-io"/>
    <title>Node does IO.</title>
    <updated>2011-12-15T00:00:00-08:00</updated>
    <author>
      <name>Benjamin van der Veen</name>
      <uri>http://bvanderveen.com/</uri>
    </author>
    <content type="html">&lt;p&gt;Consider these few lines from &lt;a href='http://mmcgrana.github.com/2011/09/clojurescript-nodejs.html'&gt;Mark McGranaghan&amp;#8217;s post &lt;em&gt;ClojureScript and Node.js&lt;/em&gt;&lt;/a&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(defn handler [_ res]
  (.writeHead res 200 (.strobj {&amp;quot;Content-Type&amp;quot; &amp;quot;text/plain&amp;quot;}))
  (.end res &amp;quot;Hello World!\n&amp;quot;))&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here is the equivalent JavaScript:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;handler = function (_, res) {
    res.writeHead(200, { &amp;quot;Content-Type&amp;quot; : &amp;quot;text/plain&amp;quot; });
    res.end(&amp;quot;Hello World!\n&amp;quot;)
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is a Node.js HTTP request handler. When a request comes in, this &lt;code&gt;handler&lt;/code&gt; function is called. It writes an HTTP response header, sends a bit of body, and calls it a day. Nothing fancy.&lt;/p&gt;

&lt;p&gt;The variable &lt;code&gt;res&lt;/code&gt; is unnecessary. This code doesn&amp;#8217;t care about &lt;code&gt;res&lt;/code&gt;-the-object; that&amp;#8217;s just syntactical noise. What this code actually cares about is &lt;code&gt;writeHead&lt;/code&gt; and &lt;code&gt;end&lt;/code&gt;, the behaviors &lt;code&gt;res&lt;/code&gt;-the-object provides.&lt;/p&gt;

&lt;p&gt;The devils and angels bicker:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;That isn&amp;#8217;t fair, because what we have here is a writer pattern, which necessarily implies state—both &lt;code&gt;writeHead&lt;/code&gt; and &lt;code&gt;end&lt;/code&gt; return void. There is IO going on here, and functional programs don&amp;#8217;t do IO! We need OOP!&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;or,&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Implement a writer monad! Then abstract that idea it so the request handler returns a data structure which represents the response! This parallels the request data structure nicely and it&amp;#8217;s so beautiful this way.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Who cares. Node does IO. Abstract it, that&amp;#8217;s what it&amp;#8217;s there for.&lt;/p&gt;</content>
  </entry>
  
  <entry>
    <id>http://bvanderveen.com/a/goodbye-net</id>
    <link type="text/html" rel="alternate" href="http://bvanderveen.com/a/goodbye-net"/>
    <title>Goodbye, .NET</title>
    <updated>2011-12-11T00:00:00-08:00</updated>
    <author>
      <name>Benjamin van der Veen</name>
      <uri>http://bvanderveen.com/</uri>
    </author>
    <content type="html">&lt;p&gt;I&amp;#8217;ve been trying not to write this blog post for months, rage-quitting .NET being as it is almost a running joke in the web development community. I hope this isn&amp;#8217;t a rage-quit. The fact is that today I can no longer reason away my misgivings about the situation in which I&amp;#8217;ve found myself. Today I say goodbye to .NET.&lt;/p&gt;

&lt;p&gt;I&amp;#8217;ve met a number of awesome people during this journey, many of them extraordinarily talented engineers and forward-thinking, creative, and intelligent people. I am very glad to have had to opportunity to work with and learn from you. Keep working to improve your tools, whatever they may be.&lt;/p&gt;
&lt;!-- I acknowledge that much of what has colored my feeling for the community is of my own creation. If I think no one cares about my projects, it's because I haven't done a good job of marketing them. If I think progress is being hindered by people being contrary or due to lack of understanding, it's because I haven't made sufficient effort to engage them on a personal level, explain things more effectively, or explicitly seek consensus. If I think the technology around which the community is built is a dead-end, it's because I have failed to see and show others a coherent path from where we are to where we ought to be. --&gt;
&lt;p&gt;I&amp;#8217;ll spare this post my conspiracy theories. The bottom line is that .NET is not a technology that anyone uses for Getting Shit Done in my world. For me it was a toy. I mastered a lot of advanced topics whilst playing with .NET. But I have to be honest with myself: the .NET platform doesn&amp;#8217;t pay me, and it no longer aligns with my personal creative goals. I would be a fool to spend another minute working with it.&lt;/p&gt;

&lt;p&gt;I&amp;#8217;ve seen how mixing up personnel in any project or organization can be a very positive thing, and I hope that my departure benefits the projects with which I was involved. Best of luck to everyone!&lt;/p&gt;
&lt;!--
.NET is a tough platform for open source. I can say unequivocally that this is due to the style of Microsoft's stewardship of the platform. To be fair, they've made steps to embrace open source by contributing to open source projects, releasing source code for select Microsoft products, and making attempts to improve the open-source development story with tools such as NuGet. However, most of these projects have met with failure—they invariably dictate a few terms which make the whole effort unworkable for Real Open Source. We've heard the stories of Codeplex projects that don't accept contributions, NuGet fail-hell on various platforms, and the like.

The exception to this seems to be Microsoft's involvement with the Node.JS project. My understanding is that they contributed some engineering to libuv, the low-level IO library that underlies Node.JS and accounts for the differences between operating systems and allows Node to run anywhere. To the web development community at large I say: look at Node.JS, for it is your future. If your platform is not Node-like, it will be, and if it won't be, it will disappear. 

Someone at Microsoft knows this as well, and that person has some power, thus Node runs on Windows. It is my hunch that this person has more allegiance to Windows than they do to .NET. 

In my view, a software development toolkit is not a product. Windows is a product. Consumers experience Windows. Developers write software for Windows so consumers can experience their software while they experience Windows. If Microsoft wants more Windows developers, they rationally allocate resources to making a great software development toolkit for Windows. 

The respective goals of the groups at Microsoft which develop .NET and Windows are famously misaligned. .NET is a second-class citizen on Windows. 



Compared to technologies like HTML, CSS, JavaScript, and Node, .NET has no future on Windows. If .NET does have a future in the enterprise—well, that's cool, but: 1) the projects I've worked on for .NET (Kayak, a web server, and OWIN, WSGI or Rack for .NET) by definition have no applicability for liability-shy enterprises and 2) 
--&gt;</content>
  </entry>
  
  <entry>
    <id>http://bvanderveen.com/a/how-to-run-mono-on-heroku</id>
    <link type="text/html" rel="alternate" href="http://bvanderveen.com/a/how-to-run-mono-on-heroku"/>
    <title>How to run Mono on Heroku</title>
    <updated>2011-12-10T00:00:00-08:00</updated>
    <author>
      <name>Benjamin van der Veen</name>
      <uri>http://bvanderveen.com/</uri>
    </author>
    <content type="html">&lt;p&gt;What follows is an account of how I got Mono running under Heroku.&lt;/p&gt;

&lt;h2 id='part_1__compiling_mono'&gt;Part 1 – Compiling Mono&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;Get an account on Heroku.&lt;/p&gt;
&lt;/li&gt;

&lt;li&gt;
&lt;p&gt;Install the Heroku Toolbelt and follow the quickstart instructions.&lt;/p&gt;
&lt;/li&gt;

&lt;li&gt;
&lt;p&gt;Install vulcan. Make sure you&amp;#8217;re using the latest Ruby.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;gem install vulcan&lt;/code&gt;&lt;/p&gt;
&lt;/li&gt;

&lt;li&gt;
&lt;p&gt;Create a Vulcan build server on Heroku.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;vulcan create mono-build&lt;/code&gt;&lt;/p&gt;
&lt;/li&gt;

&lt;li&gt;
&lt;p&gt;Vulcan needs a CouchDB instance to stuff code into. It&amp;#8217;s hard-coded to use Cloudant, which is a free CouchDB provider. Sign up for an account and configure the URL of your database in your Heroku environment variables.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;heroku config:add CLOUDANT_URL=https://USERNAME:PASSWORD@USERNAME.cloudant.com --app mono-build&lt;/code&gt;&lt;/p&gt;
&lt;/li&gt;

&lt;li&gt;
&lt;p&gt;Downloaded the Mono sources. I used the tarball but a clone of the Git repo will work too (you might want to check out a specific release tag).&lt;/p&gt;
&lt;/li&gt;

&lt;li&gt;
&lt;p&gt;Decide how you want to build Mono. I settled on this:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;./configure --with-moonlight=no --enable-nls=no&lt;/code&gt;&lt;/p&gt;
&lt;/li&gt;

&lt;li&gt;
&lt;p&gt;Now we use Vulcan to build Mono on Heroku&amp;#8217;s cloud. Important: you must tell Vulcan where the build artifacts are going to end up using the &lt;code&gt;-p&lt;/code&gt; flag so that it can archive them and make them available for download. This location corresponds to the &lt;code&gt;--prefix&lt;/code&gt; flag passed to the configure script. So make sure those match:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;vulcan build -s ~/code/mono/mono-2.10.7/ -p /tmp/my-mono-build-output -c &amp;quot;./configure --with-moonlight=no --enable-nls=no --prefix=/tmp/my-mono-build-output &amp;amp;&amp;amp; make install&amp;quot;&lt;/code&gt;&lt;/p&gt;
&lt;/li&gt;

&lt;li&gt;
&lt;p&gt;Go drink a beer (or two) whilst the beast is compiled.&lt;/p&gt;
&lt;/li&gt;

&lt;li&gt;
&lt;p&gt;You should have the build artifacts (which were deposited into the prefix dir by the &lt;code&gt;make install&lt;/code&gt; command on Heroku) downloaded to your local system at &lt;code&gt;/tmp/mono-2.10.7.tgz&lt;/code&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id='part_2__make_a_heroku_buildpack_for_mono'&gt;Part 2 – Make a Heroku buildpack for Mono.&lt;/h2&gt;</content>
  </entry>
  
  <entry>
    <id>http://bvanderveen.com/a/sequence-preview</id>
    <link type="text/html" rel="alternate" href="http://bvanderveen.com/a/sequence-preview"/>
    <title>Sequence: a preview</title>
    <updated>2011-12-05T00:00:00-08:00</updated>
    <author>
      <name>Benjamin van der Veen</name>
      <uri>http://bvanderveen.com/</uri>
    </author>
    <content type="html">&lt;p&gt;I&amp;#8217;m cooking up a utility library for Objective-C called &lt;a href='https://github.com/bvanderveen/Sequence'&gt;Sequence&lt;/a&gt;. It allows you to manipulate sequences of Objective-C objects using functional constructs such as &lt;code&gt;map&lt;/code&gt;, &lt;code&gt;reduce&lt;/code&gt;, &lt;code&gt;filter&lt;/code&gt;, and the like. Check out &lt;a href='https://github.com/bvanderveen/Sequence/blob/master/Sequence/Sequence.h'&gt;Sequence.h&lt;/a&gt; for the full list of supported operations.&lt;/p&gt;

&lt;h2 id='how_to_use_it'&gt;How to use it&lt;/h2&gt;

&lt;p&gt;Sequence declares category methods on &lt;code&gt;NSObject&lt;/code&gt;. When you call one of these methods on a collection object such as &lt;code&gt;NSArray&lt;/code&gt;, &lt;code&gt;NSSet&lt;/code&gt;, or &lt;code&gt;NSDictionary&lt;/code&gt;, those are treated like sequences. If you call one of the methods on a non-collection object such as &lt;code&gt;NSNumber&lt;/code&gt; or &lt;code&gt;NSNull&lt;/code&gt;, it is treated like a single-element sequence containing that object.&lt;/p&gt;

&lt;h4 id='example_map'&gt;Example: map&lt;/h4&gt;

&lt;pre&gt;&lt;code&gt;NSArray *input = [NSArray arrayWithObjects:@&amp;quot;a&amp;quot;, @&amp;quot;b&amp;quot;, @&amp;quot;c&amp;quot;, nil];

// all sequence-returning methods return a sequence typed as id
id mapped = [input map:^ id (id i) { return [i stringByAppendingString:i]; }];

// to materialize a sequence into an array, send it the -[ array] message.
NSArray *output = [mapped array]; // contains @&amp;quot;aa&amp;quot;, @&amp;quot;bb&amp;quot;, @&amp;quot;cc&amp;quot;&lt;/code&gt;&lt;/pre&gt;

&lt;h4 id='example_reduce'&gt;Example: reduce&lt;/h4&gt;

&lt;pre&gt;&lt;code&gt;NSArray *input = [NSArray arrayWithObjects:@&amp;quot;a&amp;quot;, @&amp;quot;b&amp;quot;, @&amp;quot;c&amp;quot;, nil];
NSString *output = [input reduce:
	^ id (id acc, id i) { return [acc stringByAppendingString:i]; } seed:@&amp;quot;&amp;quot;];
// output is @&amp;quot;abc&amp;quot;&lt;/code&gt;&lt;/pre&gt;

&lt;h4 id='example_any'&gt;Example: any&lt;/h4&gt;

&lt;pre&gt;&lt;code&gt;NSArray *input = [NSArray arrayWithObjects:[NSNull null], @&amp;quot;c&amp;quot;, [NSNumber numberWithInt:0], nil];
BOOL containsString = [input any:^ BOOL (id i) { return [i isKindOfClass:[NSString class]]; }];
// containsString is YES&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id='how_it_works'&gt;How it works&lt;/h2&gt;

&lt;p&gt;The implementation works with sequences of form &lt;code&gt;(item -&amp;gt; unit) -&amp;gt; unit&lt;/code&gt; (called &lt;code&gt;PushSeq&lt;/code&gt;) and &lt;code&gt;unit -&amp;gt; (unit -&amp;gt; item)&lt;/code&gt; (called &lt;code&gt;PullSeq&lt;/code&gt;). &lt;code&gt;PullSeq&lt;/code&gt; ends by nil-termination, just like &lt;code&gt;-[NSEnumerator nextObject]&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;For my first go at it, I made a conscious decision to keep most of the implementation agnostic of which sequence form is used. The consequence of this is that operations like &lt;code&gt;any&lt;/code&gt;, &lt;code&gt;all&lt;/code&gt;, &lt;code&gt;itemAtIndex&lt;/code&gt;, etc. can&amp;#8217;t &amp;#8220;short-circuit&amp;#8221; (return before materializing the whole collection) because their implementation can&amp;#8217;t control how many items are enumerated.&lt;/p&gt;

&lt;h2 id='caveats'&gt;Caveats&lt;/h2&gt;

&lt;p&gt;Operations that could short-circuit currently do not. This is a problem, for example, if you were use this to implement &lt;code&gt;UITableViewDelegate&lt;/code&gt; or &lt;code&gt;UITableViewDataSource&lt;/code&gt;—you wouldn&amp;#8217;t want to have an intermediate array or two being allocated for every call to &lt;code&gt;cellForRowAtIndexPath:&lt;/code&gt; when you only want to query a single item out of a sequence.&lt;/p&gt;

&lt;p&gt;I&amp;#8217;m still thinking about how to best rectify that. My goal is to allow users to define complex declarative structures and query them without allocating intermediate storage beyond the heap objects that make up the query itself.&lt;/p&gt;

&lt;p&gt;As a next step, I would like to figure out how to both call and implement &lt;code&gt;NSFastEnumeration&lt;/code&gt;. It&amp;#8217;s rather obtuse and &lt;a href='http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/NSFastEnumeration_protocol/Reference/NSFastEnumeration.html'&gt;the docs&lt;/a&gt; are terse and highly general, but I&amp;#8217;ve a hunch that Sequence could benefit from interacting closely with &lt;code&gt;NSFastEnumeration&lt;/code&gt;.&lt;/p&gt;</content>
  </entry>
  
  <entry>
    <id>http://bvanderveen.com/a/offline-2011-11</id>
    <link type="text/html" rel="alternate" href="http://bvanderveen.com/a/offline-2011-11"/>
    <title>Offline this week</title>
    <updated>2011-11-21T00:00:00-08:00</updated>
    <author>
      <name>Benjamin van der Veen</name>
      <uri>http://bvanderveen.com/</uri>
    </author>
    <content type="html">&lt;p&gt;I will be taking a break from the internet over the Thanksgiving holiday. I&amp;#8217;ll resume correspondence next week.&lt;/p&gt;</content>
  </entry>
  
  <entry>
    <id>http://bvanderveen.com/a/testing-is-not-a-substitute-for-good-design</id>
    <link type="text/html" rel="alternate" href="http://bvanderveen.com/a/testing-is-not-a-substitute-for-good-design"/>
    <title>Testing is not a substitute for good design.</title>
    <updated>2011-11-17T00:00:00-08:00</updated>
    <author>
      <name>Benjamin van der Veen</name>
      <uri>http://bvanderveen.com/</uri>
    </author>
    <content type="html"></content>
  </entry>
  
  <entry>
    <id>http://bvanderveen.com/a/on-the-compiler</id>
    <link type="text/html" rel="alternate" href="http://bvanderveen.com/a/on-the-compiler"/>
    <title>On the compiler</title>
    <updated>2011-11-06T00:00:00-07:00</updated>
    <author>
      <name>Benjamin van der Veen</name>
      <uri>http://bvanderveen.com/</uri>
    </author>
    <content type="html">&lt;p&gt;In every language that I&amp;#8217;ve used, writing code is a war against the compiler or interpreter or the language grammar or whatever. It&amp;#8217;s the thing allows you to talk to a CPU. The compiler is what stands between your intent and what the computer actually ends up doing. It is your enemy.&lt;/p&gt;

&lt;p&gt;In the future, we won&amp;#8217;t have compilers. We&amp;#8217;ll have Siri.&lt;/p&gt;</content>
  </entry>
  
  <entry>
    <id>http://bvanderveen.com/a/new-gate-developments</id>
    <link type="text/html" rel="alternate" href="http://bvanderveen.com/a/new-gate-developments"/>
    <title>New Gate Developments</title>
    <updated>2011-11-06T00:00:00-07:00</updated>
    <author>
      <name>Benjamin van der Veen</name>
      <uri>http://bvanderveen.com/</uri>
    </author>
    <content type="html">&lt;p&gt;Writing Gate middleware is so damn easy. You just write some test case method names which, in plain English, describe the intent of the test. Then, you fill out the implementation of the tests. Then, you implement the middleware itself. It&amp;#8217;s so damn easy. You just write out the implementation. You don&amp;#8217;t even have to think. I don&amp;#8217;t know why I didn&amp;#8217;t do this ages ago.&lt;/p&gt;

&lt;p&gt;Actually, I do, but that&amp;#8217;s a story for another time.&lt;/p&gt;

&lt;p&gt;I&amp;#8217;ve written some &lt;a href='https://github.com/owin/gate/tree/master/src/Gate.Middleware'&gt;middleware&lt;/a&gt;. I hate the word middleware.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;HTTP Basic Authentication&lt;/li&gt;

&lt;li&gt;Method Override&lt;/li&gt;

&lt;li&gt;Content Length&lt;/li&gt;

&lt;li&gt;Chunked Response&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Those were built with two primitives: Predicate and Transform.&lt;/p&gt;

&lt;p&gt;I want to make these others modules:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Header dictionary fixer-upper thing, ensures mutability and perhaps normalizes case.&lt;/li&gt;

&lt;li&gt;Handle X-Sendfile&lt;/li&gt;

&lt;li&gt;Static file server/directory index&lt;/li&gt;

&lt;li&gt;Digest auth&lt;/li&gt;

&lt;li&gt;Multipart form parsing + files&lt;/li&gt;

&lt;li&gt;Caching/304/ETag&lt;/li&gt;

&lt;li&gt;Deflate/Gzip&lt;/li&gt;

&lt;li&gt;Lint (to verify OWIN compliance)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;These already exist in Gate/Gate.Helpers and I want to move them to Gate.Middleware:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;ContentType&lt;/li&gt;

&lt;li&gt;RewindableBody&lt;/li&gt;

&lt;li&gt;ShowExceptions&lt;/li&gt;

&lt;li&gt;Map&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Stuff that could exist but which hella exists way far out of the scope of Gate:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Session&lt;/li&gt;

&lt;li&gt;Logging&lt;/li&gt;

&lt;li&gt;Perhaps some kind of Compiler-as-a-service source reloading sort of thing which would probably be hosting dependent but I&amp;#8217;m not sure.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I&amp;#8217;m basically ripping these ideas straight off of Rack, but the foundation is compatible with both event-loop thread models like that of Node and Nginx and traditional thread-per-connection models like IIS and Apache.&lt;/p&gt;

&lt;p&gt;What other sorts of server stuff would you like to see implemented?&lt;/p&gt;</content>
  </entry>
  
  <entry>
    <id>http://bvanderveen.com/a/btd</id>
    <link type="text/html" rel="alternate" href="http://bvanderveen.com/a/btd"/>
    <title>Bank Transfer Day</title>
    <updated>2011-11-06T00:00:00-07:00</updated>
    <author>
      <name>Benjamin van der Veen</name>
      <uri>http://bvanderveen.com/</uri>
    </author>
    <content type="html">&lt;p&gt;I spoke with bravado of walking into Chase and demanding that they dispense an amount of cash to me equal to the amount of money contained within my account. As I drove past the branch, there was one woman standing on the corner with a sing that said &amp;#8220;Stop funding corporate greed, withdraw your funds.&amp;#8221; I went to roll my window down and shout at her with my support, but I had a plastic fork in my hand, which I was holding afer having puchase a big-size Whole Bowl (vegan style), and was unable to simultaneously make a left turn and roll down my window and shout all in one fluid motion.&lt;/p&gt;

&lt;p&gt;Needless to say, I failed to actually go to the bank and transfer my funds.&lt;/p&gt;

&lt;p&gt;But, I wrote some middleware.&lt;/p&gt;</content>
  </entry>
  
  <entry>
    <id>http://bvanderveen.com/a/on-jobs</id>
    <link type="text/html" rel="alternate" href="http://bvanderveen.com/a/on-jobs"/>
    <title>On jobs</title>
    <updated>2011-10-09T00:00:00-07:00</updated>
    <author>
      <name>Benjamin van der Veen</name>
      <uri>http://bvanderveen.com/</uri>
    </author>
    <content type="html">&lt;p&gt;I&amp;#8217;ve been doing poorly at my resolution to start doing more interesting things. I was out of town on business for a week and a half, and since then I&amp;#8217;ve been very busy getting ready for user testing of my project at work.&lt;/p&gt;

&lt;p&gt;In lieu of finding time or motivation or headspace to do visceral arty things, I am redoubling my efforts to make sure that the job I work at is a worthwhile pursuit. If I&amp;#8217;m going to spend a third of my time at my job, I better be working on an awesome project.&lt;/p&gt;

&lt;p&gt;I&amp;#8217;m over coding. It&amp;#8217;s a solved problem. Anything can be cross-compiled to anything else and then JITed or statically precompiled or whatever you insist is the flavor of the week. No problem. I want to operate in the domain of the bigger picture.&lt;/p&gt;

&lt;p&gt;The days following the passing of Steve Jobs were interesting. I see now that I must act immediately.&lt;/p&gt;
&lt;!--
The project I'm doing at work is pretty cool, but it's definitely getting to the point where it's less exciting and more tedious. This is just the nature of iOS projects. For the first half of the project you make a large amount of visible progress, but then there is a stage of small, incremental changes and invisible bug fixing and refactoring. These apps difficult to test in an automated fashion; and developing them is a constant hack-compile-manually-test loop. Working in Objective-C and Cocoa requires constant refactoring; you can't write 10 lines of code without moving 15 others and generating another 10 worth of boilerplate.--&gt;</content>
  </entry>
  
  <entry>
    <id>http://bvanderveen.com/a/on-engagement</id>
    <link type="text/html" rel="alternate" href="http://bvanderveen.com/a/on-engagement"/>
    <title>On engagement</title>
    <updated>2011-09-15T00:00:00-07:00</updated>
    <author>
      <name>Benjamin van der Veen</name>
      <uri>http://bvanderveen.com/</uri>
    </author>
    <content type="html">&lt;p&gt;I&amp;#8217;ve been experimenting with a secret Twitter account with the privacy setting enabled. The idea was that I could tweet about things I might not want to have associated with my professional reputation or software community persona.&lt;/p&gt;

&lt;p&gt;In practice, I don&amp;#8217;t feel more at liberty to make spur-of-the-moment, drunken, revealing, profane, arty, or otherwise inappropriate tweets to my private followers than to my public followers. It started as an attempt to be more spontaneous, edgy, and entertaining, but has led me back to the same interactions I was trying to shake off: at best boring, and more often awkward, self-conscious, and anxious.&lt;/p&gt;

&lt;p&gt;Google+ explicitly attempts to solve the different-subject-matter-for-different-contacts problem, but somehow it falls short of that goal. There are a lot of problems with Google+, most of which have been discussed in more depth and at greater length on Google+ itself than I will discuss here. But I will say this: the format is rather boring. You post, a few people might +1 and someone might even attempt witty banter, which inevitably becomes awkward and peeters out.&lt;/p&gt;

&lt;p&gt;We&amp;#8217;re left with the same problem we&amp;#8217;ve been having: we desire to communicate a message, and do so through the channels to which we&amp;#8217;ve become accustomed, and expect to get some utility out of having done so. Perhaps there is the momentary gratification of having received a notification of engagement from a contact, and we strive to keep up the volley for as long as it suits us.&lt;/p&gt;

&lt;p&gt;This ad-hoc usage social media is naïve and mundane. We should take a more measured approach to engaging these channels and work to communicate a coherent message with a specific goal in mind. For me, the secret Twitter represents a fragmentation of personal goals—my public and private accounts both represent me, but choosing to engage one or the other ends up being an arbitrary decision made in the moment, and neither representation is improved.&lt;/p&gt;

&lt;p&gt;My public Twitter account has value because it provides a somewhat coherent message about specific topic—I have about 350 followers, which have come very organically through my engagement with the open source software community. I&amp;#8217;ve met some awesome people and had amazing experiences as a direct result of engagement through Twitter.&lt;/p&gt;

&lt;p&gt;I can see that there is value to be created through that channel, but on the other hand, both my public Twitter persona and the projects with which I&amp;#8217;ve built it seem to have reached a certain maxima in terms of audience and mindshare, despite a large investments of time and energy on my part. There are myriad technical, organizational, historical, and social reasons why this might be the case, but it&amp;#8217;s clear to me that I&amp;#8217;m not optimally managing the time and energy I devote to my public persona and projects.&lt;/p&gt;

&lt;p&gt;With this in mind, and with the help of my &lt;a href='/a/been-offline'&gt;Comcast-imposed&lt;/a&gt; exile from the internet, I am actively re-evaluating my method of engagement by seeking out collaborations, affectations, and technologies through subterfuge, appropriation, obscenity, and other classical methods of research.&lt;/p&gt;</content>
  </entry>
  
  <entry>
    <id>http://bvanderveen.com/a/been-offline</id>
    <link type="text/html" rel="alternate" href="http://bvanderveen.com/a/been-offline"/>
    <title>Been offline</title>
    <updated>2011-09-14T00:00:00-07:00</updated>
    <author>
      <name>Benjamin van der Veen</name>
      <uri>http://bvanderveen.com/</uri>
    </author>
    <content type="html">&lt;p&gt;I&amp;#8217;ve been offline for the past few weeks. I moved to a new place at the end of August, and haven&amp;#8217;t had the internet connection set up yet. I got round to calling Comcast a week ago. They made me sign a contract but can&amp;#8217;t seem to give me a date for the installation. It&amp;#8217;s pretty rad.&lt;/p&gt;

&lt;p&gt;I&amp;#8217;ve got lots of project ideas on my mind for the winter. I need to work on something with a visceral quality. I currently deal in the realm of abstractions perhaps more than I ought to.&lt;/p&gt;

&lt;p&gt;I need collaborators. All this going it alone I&amp;#8217;ve been doing seems insane. It would be easiest for me to break out of this habit in the context of an art project and/or business. To that end I am actively recruiting:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;engineers and creatives&lt;/li&gt;

&lt;li&gt;beautiful people&lt;/li&gt;

&lt;li&gt;strategic partners&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Hip-hop provides a model for this endeavor. The hip-hop industry makes awesome, visceral stuff that people love, and they get rich as hell doing it. They have a mind for the whole picture—creative, business, marketing, cross-promotion, everything. They&amp;#8217;re not about to starve. They sell out before they even start.&lt;/p&gt;

&lt;p&gt;Step one: buy an MPC.&lt;/p&gt;</content>
  </entry>
  
  <entry>
    <id>http://bvanderveen.com/a/gate-0.1.4</id>
    <link type="text/html" rel="alternate" href="http://bvanderveen.com/a/gate-0.1.4"/>
    <title>Gate 0.1.4 Released</title>
    <updated>2011-08-19T00:00:00-07:00</updated>
    <author>
      <name>Benjamin van der Veen</name>
      <uri>http://bvanderveen.com/</uri>
    </author>
    <content type="html">&lt;p&gt;&lt;a href='http://nuget.org/List/Packages/gate'&gt;Gate 0.1.4&lt;/a&gt; is on NuGet. This release addresses an issue pointed out and tracked down by &lt;a href='http://majimenezp.posterous.com/'&gt;Miguel Jimenez&lt;/a&gt;&amp;#8212;thanks Miguel!&lt;/p&gt;

&lt;h2 id='gate_014'&gt;Gate 0.1.4&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;When using the RescheduleCallbacks middleware, the request body onNext callback gets a properly rescheduled continuation if and only if the wrapping app (i.e., Kayak hosting) provides a non-null continuation.&lt;/li&gt;
&lt;/ul&gt;</content>
  </entry>
  
  <entry>
    <id>http://bvanderveen.com/a/gate-0.1.2-kayak-0.7.2</id>
    <link type="text/html" rel="alternate" href="http://bvanderveen.com/a/gate-0.1.2-kayak-0.7.2"/>
    <title>Gate 0.1.2, Kayak 0.7.2</title>
    <updated>2011-08-15T00:00:00-07:00</updated>
    <author>
      <name>Benjamin van der Veen</name>
      <uri>http://bvanderveen.com/</uri>
    </author>
    <content type="html">&lt;p&gt;There are some new releases of &lt;a href='http://nuget.org/list/packages/gate'&gt;Gate&lt;/a&gt; and &lt;a href='http://nuget.org/list/packages/kayak'&gt;Kayak&lt;/a&gt; up on NuGet this week. The Gate release is a bug-fix release that addresses a few items that showed up since the first bits of Kayak/Gate/Nancy stack went out. The Kayak release adds some new APIs for getting request information and drops the explicit HttpMachine dependency.&lt;/p&gt;

&lt;h2 id='gate_012'&gt;Gate 0.1.2&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Environment class no longer deep-copies the dictionary passed to its constructor, it simply wraps it (Louis DeJardin)&lt;/li&gt;

&lt;li&gt;Fixed missing dependency in Gate.Wcf and Gate.AspNet packages.&lt;/li&gt;

&lt;li&gt;Fixed missing query string OWIN environment variable in Gate.Kayak&lt;/li&gt;

&lt;li&gt;Fixed method, path, and request header OWIN environment variables in Gate.Kayak to never be null.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Many thanks to &lt;a href='https://github.com/robhorvathpca'&gt;Rob Horvath&lt;/a&gt; and &lt;a href='http://hocke.blogspot.com/'&gt;Håkan Canberger&lt;/a&gt; for spotting these bugs!&lt;/p&gt;

&lt;h2 id='kayak_072'&gt;Kayak 0.7.2&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;HttpMachine is no longer a dependency; the HttpMachine source is compiled directly into the Kayak DLL.&lt;/li&gt;

&lt;li&gt;Added &lt;code&gt;Path&lt;/code&gt;, &lt;code&gt;QueryString&lt;/code&gt; and &lt;code&gt;Fragment&lt;/code&gt; fields to &lt;code&gt;HttpRequestHead&lt;/code&gt; struct&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Again, the best way to start using Nancy on Kayak is to create a new console application project, and pull in the &lt;a href='http://nuget.org/list/packages/nancy.hosting.owin'&gt;Nancy.Hosting.Owin&lt;/a&gt; and &lt;a href='http://nuget.org/list/packages/gate.kayak'&gt;Gate.Kayak&lt;/a&gt; NuGet packages. These two packages will bring all the necessary dependencies with them and you can get started. See the &lt;a href='http://bvanderveen.com/a/gate-0.1.0'&gt;Gate 0.1.0 release post&lt;/a&gt; for details.&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;&lt;strong&gt;Update:&lt;/strong&gt; Many thanks to &lt;a href='http://majimenezp.posterous.com/'&gt;Miguel Jimenez&lt;/a&gt; for quickly spotting a bug when using Gate 0.1.2 with Kayak and Razor. I&amp;#8217;ve just pushed 0.1.3 to address the issue.&lt;/p&gt;

&lt;h2 id='gate_013'&gt;Gate 0.1.3&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;RescheduleCallbacks middleware re-buffers response data before posting it to the scheduler so that the writing thread does not stomp previously written data in-flight.&lt;/li&gt;
&lt;/ul&gt;</content>
  </entry>
  
  <entry>
    <id>http://bvanderveen.com/a/gate-0.1.0</id>
    <link type="text/html" rel="alternate" href="http://bvanderveen.com/a/gate-0.1.0"/>
    <title>Gate 0.1.0 Released</title>
    <updated>2011-08-04T00:00:00-07:00</updated>
    <author>
      <name>Benjamin van der Veen</name>
      <uri>http://bvanderveen.com/</uri>
    </author>
    <content type="html">&lt;p&gt;Today I&amp;#8217;m very pleased to announce that Gate is available on NuGet.&lt;/p&gt;

&lt;p&gt;&lt;a href='http://nuget.org/List/Packages/Gate'&gt;Gate&lt;/a&gt; is a utility for locating, manufacturing, and hosting OWIN web applications. Hosting adapters are available for &lt;a href='http://nuget.org/List/Packages/Gate.Kayak'&gt;Kayak&lt;/a&gt;, &lt;a href='http://nuget.org/List/Packages/Gate.AspNet'&gt;ASP.NET&lt;/a&gt;, and &lt;a href='http://nuget.org/List/Packages/Gate.Wcf'&gt;WCF&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;Make an OWIN application with Nancy and Kayak&lt;/h2&gt;
&lt;p&gt;Nancy currently ships a NuGet package which provides OWIN support, so we&amp;#8217;ll make a simple demo of running Nancy on Kayak. We&amp;#8217;ll need to pull in the Kayak, Gate, and Nancy packages, as well as two adapter packages to glue them all together: Gate.Kayak and Nancy.Hosting.Owin.&lt;/p&gt;

&lt;p&gt;Start by creating a new console application project. Grab the aforementioned NuGet packages&amp;#8212;the easiest thing to do would be to pull in Gate.Kayak since that will bring Gate and Kayak with it, then Nancy.Hosting.Owin, which will bring Nancy along.&lt;/p&gt;

&lt;p&gt;Then, punch these codes into your terminal:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;using System;
using System.Net;
using Gate;
using Gate.Kayak;
using Kayak;
using Nancy.Hosting.Owin;
using Nancy;

namespace KayakGateNancyDemo
{
    public class Program
    {
        // plain-ol&amp;#39; entry point.
        public static void Main(string[] args)
        {
            var ep = new IPEndPoint(IPAddress.Any, 5500);
            Console.WriteLine(&amp;quot;Listening on &amp;quot; + ep);
            KayakGate.Start(new SchedulerDelegate(), ep, Startup.Configuration);
        }
    }

    public class Startup
    {
        // called automatically when Kayak starts up.
        public static void Configuration(IAppBuilder builder)
        {
            // we&amp;#39;ll create a very simple pipeline:

            builder
                // insert a middleware between Kayak and Nancy
                // to ensure Kayak objects are only accessed 
                // on Kayak&amp;#39;s worker thread.
                .RescheduleCallbacks()

                // cap off the pipeline with Nancy
                .RunNancy();
        }
    }

    public class SchedulerDelegate : ISchedulerDelegate
    {
        public void OnException(IScheduler scheduler, Exception e)
        {
            // called whenever an exception occurs on Kayak&amp;#39;s event loop.
            // this is good place for logging. here&amp;#39;s a start:
            Console.WriteLine(&amp;quot;Exception on scheduler&amp;quot;);
            Console.Out.WriteStackTrace(e);
        }

        public void OnStop(IScheduler scheduler)
        {
            // called when Kayak&amp;#39;s run loop is about to exit.
            // this is a good place for doing clean-up or other chores.
            Console.WriteLine(&amp;quot;Scheduler is stopping.&amp;quot;);
        }
    }

    // Your Nancy application.
    // Check out Nancy&amp;#39;s docs for more info on how it works.
    public class MyNancyModule : NancyModule
    {
        public MyNancyModule()
        {
            Get[&amp;quot;/&amp;quot;] = x =&amp;gt;
            {
                return &amp;quot;This is the root.&amp;quot;;
            };
        }
    }

    // a bit of sugar for running Nancy ;)
    public static class NancyExtensions
    {
        public static IAppBuilder RunNancy(this IAppBuilder builder)
        {
            return builder.Run(Delegates.ToDelegate(new NancyOwinHost().ProcessRequest));
        }
    }
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;KayakGate.Start&lt;/code&gt; method invokes the &lt;code&gt;Startup.Configuration&lt;/code&gt; method, uses the user-configured &lt;code&gt;IAppBuilder&lt;/code&gt; instance to manufacture an OWIN application delegate, and hosts it on port &lt;code&gt;5500&lt;/code&gt;. Visit &lt;code&gt;http://localhost:5500&lt;/code&gt; in your web browser and bask in the glory.&lt;/p&gt;

&lt;p&gt;With this bit of boilerplate, it should be possible to use Kayak to host almost any application developed with Nancy.&lt;/p&gt;

&lt;p&gt;Voilà, a completely open source .NET web application stack using an open interface brought to you by hackers in the community. Have fun, and let us know your thoughts on the &lt;a href='http://groups.google.com/group/net-http-abstractions'&gt;.NET HTTP Abstractions&lt;/a&gt; list.&lt;/p&gt;</content>
  </entry>
  
  <entry>
    <id>http://bvanderveen.com/a/kayak-0.7.1</id>
    <link type="text/html" rel="alternate" href="http://bvanderveen.com/a/kayak-0.7.1"/>
    <title>Kayak 0.7.1 Released</title>
    <updated>2011-08-01T00:00:00-07:00</updated>
    <author>
      <name>Benjamin van der Veen</name>
      <uri>http://bvanderveen.com/</uri>
    </author>
    <content type="html">&lt;p&gt;Last weekend, I met &lt;a href='http://drusellers.com'&gt;Dru Sellers&lt;/a&gt; at &lt;a href='http://monospace.us'&gt;Monospace&lt;/a&gt;. At some point, I complained to him that my projects didn&amp;#8217;t have proper cross-platform build scripts because blah blah blah. He called me a whiny baby and kicked me in the balls.&lt;/p&gt;

&lt;p&gt;Kayak 0.7.1 is out this evening. It is available on &lt;a href='http://nuget.org/List/Packages/Kayak'&gt;NuGet&lt;/a&gt;. This is mostly a bugfix release, but it&amp;#8217;s a rather significant milestone for me because for the first time, Kayak has a proper build script. Many thanks to Dru for inflicting such acute abuse, and also to the FubuMVC and Nancy guys&amp;#8212;I got quite a bit of, er, inspiration from &lt;a href='https://github.com/DarthFubuMVC/fubumvc/blob/master/rakefile.rb'&gt;FubuMVC&amp;#8217;s build script&lt;/a&gt; and &lt;a href='https://github.com/NancyFx/Nancy/blob/master/rakefile.rb'&gt;Nancy&amp;#8217;s build script&lt;/a&gt;. Thanks also to &lt;a href='http://http://twitter.com/derickbailey'&gt;Derick Bailey&lt;/a&gt; for his work on &lt;a href='http://albacorebuild.net/'&gt;Albacore&lt;/a&gt; without which none of this would be possible.&lt;/p&gt;

&lt;p&gt;Anyway, the changes:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Turns out a proper 100-continue response is prefixed with &amp;#8220;HTTP/1.1&amp;#8221;. So I added that.&lt;/li&gt;

&lt;li&gt;&lt;code&gt;BeginConnect&lt;/code&gt; seems to be a pile of fail on Mono 2.10. Work-around by invoking the synchronous &lt;code&gt;Connect&lt;/code&gt; method on the thread pool.&lt;/li&gt;

&lt;li&gt;Rake-based build script!&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you have problems, challenge me to a game of roshambo on the &lt;a href='http://groups.google.com/group/kayak-http'&gt;Kayak Google Group&lt;/a&gt;.&lt;/p&gt;</content>
  </entry>
  
  <entry>
    <id>http://bvanderveen.com/a/kayak-0.7.0</id>
    <link type="text/html" rel="alternate" href="http://bvanderveen.com/a/kayak-0.7.0"/>
    <title>Kayak 0.7.0 Released</title>
    <updated>2011-07-20T00:00:00-07:00</updated>
    <author>
      <name>Benjamin van der Veen</name>
      <uri>http://bvanderveen.com/</uri>
    </author>
    <content type="html">&lt;p&gt;I just pushed &lt;a href='http://nuget.org/List/Packages/Kayak'&gt;Kayak 0.7.0&lt;/a&gt; up to NuGet. Here&amp;#8217;s what changed:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Support for 100-continue. This will speed up most PUT and POST requests quite a bit since clients won&amp;#8217;t wait for the &lt;code&gt;100 Continue&lt;/code&gt; status (usually about 200ms) before sending the body anyway.&lt;/li&gt;

&lt;li&gt;&lt;code&gt;IHttpRequestDelegate&lt;/code&gt; implementations will get &lt;code&gt;null&lt;/code&gt; for the request body producer if the request headers do not contain &lt;code&gt;Content-Length&lt;/code&gt; or &lt;code&gt;Transfer-Encoding: chunked&lt;/code&gt;.&lt;/li&gt;

&lt;li&gt;Implementations of &lt;code&gt;IScheduler&lt;/code&gt;, &lt;code&gt;IServer&lt;/code&gt;, and &lt;code&gt;ISocket&lt;/code&gt; are now private and cannot be directly instantiated using the &lt;code&gt;new&lt;/code&gt; operator. Use &lt;code&gt;KayakScheduler.Factory&lt;/code&gt;, &lt;code&gt;KayakServer.Factory&lt;/code&gt;, and &lt;code&gt;KayakSocket.Factory&lt;/code&gt; instead.&lt;/li&gt;

&lt;li&gt;Fixed a &lt;strike&gt;typo&lt;/strike&gt; bug in socket implementation so that if &lt;code&gt;BeginReceive&lt;/code&gt; synchronously throws an exception the error-on-read logic is invoked (previously error-on-write logic was invoked).&lt;/li&gt;

&lt;li&gt;Several small optimizations to socket implementation.&lt;/li&gt;

&lt;li&gt;Improved test coverage of HTTP transaction logic.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;As always, play around, stress it, and report your experiences to the &lt;a href='http://groups.google.com/group/kayak-http'&gt;Kayak Google Group&lt;/a&gt;.&lt;/p&gt;</content>
  </entry>
  
  <entry>
    <id>http://bvanderveen.com/a/how-are-you-managing-test-permutations</id>
    <link type="text/html" rel="alternate" href="http://bvanderveen.com/a/how-are-you-managing-test-permutations"/>
    <title>How Are You Managing Test Permutations?</title>
    <updated>2011-05-17T00:00:00-07:00</updated>
    <author>
      <name>Benjamin van der Veen</name>
      <uri>http://bvanderveen.com/</uri>
    </author>
    <content type="html">&lt;p&gt;I’m going to bite the bullet and admit that I’m rather new to the whole unit-testing thing. For a long time, I didn’t see the point in doing it, but it will suffice to say that I have recognized the err of my ways.&lt;/p&gt;

&lt;p&gt;It turns out that writing good, pretty tests is an art form and is every bit as difficult and subtle as writing good, pretty code. In every introduction to unit testing I’ve ever read on the internet, the author gives the whole philosophical run down about testing, which is nice. Then, he provides an example where he tests that a function can add two and two. As a long-time coder trying to learn about unit testing, this is completely useless to me.&lt;/p&gt;

&lt;p&gt;Today, I’m testing a rather complicated bit of code in Kayak. It exposes a number of functions which can be called at lot of different times and in different orders, and it calls out to a number of functions a lot of different times and in different orders.&lt;/p&gt;
&lt;img src='/res/img/managing-testing-permutations-kayak-response-delegate-tests.png' /&gt;
&lt;p&gt;Here, I’ve modeled just three areas which can differ. They’re broken right now because I’m attempting to be “disciplined” and write the tests first as much as possible. I’ve got some very verbose method names to describe what exactly the test is doing. Each dimension of variation is separated with a double-underscore, and each variation on a dimension must be combined with all the other variations of the other dimensions. So far, each area of variation has only two possible scenarios, so each time a new permutation is added, I’ve doubled the number of tests. (Save for a trivial base case, which is green.)&lt;/p&gt;

&lt;p&gt;But I’m not done writing tests. There are three or four more dimensions that can vary, which, if my math is right, means I’m going to end up with 8-16x as many tests as above. Factor in error conditions and I&amp;#8217;m looking at possibly over 100 20-line tests for a component that&amp;#8217;s about 100 lines long.&lt;/p&gt;

&lt;p&gt;If I ever change the interface for that component, I’m going to have a lot of refactoring to do. And If I ever decide that the job that component performs doesn’t solve the over-arching problem in a very good way, and I want to solve the problem in a different way, I throw out not just 100 lines of code, but almost 2000.&lt;/p&gt;

&lt;p&gt;No one ever talks about this aspect of testing. To me, it seems dishonest not to test at this level of granularity. So my question is, how would you manage this sort of thing? Would you write and maintain all of these tests by hand? Do you automate the permutations? If so, how? Or do you just fudge it, tweaking your system-under-test in the debugger under real-world-ish use-cases until it stops crashing?&lt;/p&gt;</content>
  </entry>
  
  <entry>
    <id>http://bvanderveen.com/a/owin-as-csharp-interfaces</id>
    <link type="text/html" rel="alternate" href="http://bvanderveen.com/a/owin-as-csharp-interfaces"/>
    <title>OWIN as C# Interfaces</title>
    <updated>2011-03-17T00:00:00-07:00</updated>
    <author>
      <name>Benjamin van der Veen</name>
      <uri>http://bvanderveen.com/</uri>
    </author>
    <content type="html">&lt;p&gt;There’s been some talk about the apparent complexity of the OWIN signature, due to the fact that the signature is expressed in the spec as a nested delegate structure. I’ll admit it looks a bit hairy at first blush.&lt;/p&gt;

&lt;p&gt;Consider this excerpt from the specification:&lt;/p&gt;
&lt;blockquote&gt;
In this document, the C# Action/Func syntax is used to notate the delegate structure. However, the delegate structure could be equivalently represented with F# native functions, CLR interfaces, or named delegates. This is by design; when implementing OWIN, choose a delegate representation that works for you and your stack.
&lt;/blockquote&gt;
&lt;p&gt;I thought it might be instructive to demonstrate how one could leverage this property of OWIN to create an equivalent structure expressed using C# interfaces.&lt;/p&gt;
&lt;h2&gt;Break it down&lt;/h2&gt;
&lt;p&gt;Let’s start with the &lt;a href='http://owin.org/spec.html#EnvironmentDictionary'&gt;environment dictionary&lt;/a&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public interface IRequest : IDictionary&amp;lt;string, object&amp;gt;
{
    string Method { get; set; }
    string Path { get; set; }
    string PathBase { get; set; }
    string QueryString { get; set; }
    IDictionary&amp;lt;string, string&amp;gt; Headers { get; set; }
    IProducer&amp;lt;ArraySegment&amp;lt;byte&amp;gt;&amp;gt; Body { get; set; }
    string Scheme { get; set; }
    string Version { get; set; }
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is just a helper that adds strongly-typed properties for each of the environment items the spec defines.&lt;/p&gt;

&lt;p&gt;Next, take a look at the &lt;a href='http://owin.org/spec.html#ApplicationDelegate'&gt;application delegate&lt;/a&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Action&amp;lt;
    // env
    IDictionary&amp;lt;string, object&amp;gt;, 

    // response callback
    Action&amp;lt;
        string, // response status, e.g., &amp;quot;200 OK&amp;quot;
        IDictionary&amp;lt;string, string&amp;gt;, // response headers
        [a body delegate] // response body, represented by a body delegate
    &amp;gt;, 

    // error callback
    Action&amp;lt;Exception&amp;gt;
&amp;gt;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This delegate becomes the following interface:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public interface IApplication
{
    void Call(IRequest env, IResponse response);
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here, we&amp;#8217;ve replaced the environment dictionary with our strongly-typed request helper, and the response and error callbacks with an interface which holds those two functions:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public interface IResponse
{
    void OnComplete(string status, IDictionary&amp;lt;string, string&amp;gt; headers, IProducer&amp;lt;ArraySegment&amp;lt;byte&amp;gt;&amp;gt; body);
    void OnError(Exception e);
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now for the &lt;a href='http://owin.org/spec.html#BodyDelegate'&gt;body delegate&lt;/a&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Func&amp;lt;

    // on next
    Func&amp;lt;
        ArraySegment&amp;lt;byte&amp;gt;, // data
        Action, // continuation
        bool // will invoke continuation
    &amp;gt;,

    // on error
    Action&amp;lt;Exception&amp;gt;,

    // on complete
    Action,

    // cancel 
    Action 
&amp;gt;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is a function which takes three functions as arguments and returns another function. Just like we did for the response and error callbacks of the application delegate, we&amp;#8217;re going to group these three arguments into an interface.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public interface IProducer&amp;lt;T&amp;gt;
{
    Action Subscribe(IConsumer&amp;lt;T&amp;gt; consumer);
}

public interface IConsumer&amp;lt;T&amp;gt;
{
    bool OnNext(T next, Action continuation);
    void OnError(Exception e);
    void OnComplete();
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Voil&amp;#224;, OWIN as C# interfaces.&lt;/p&gt;
&lt;h2&gt;Why not just use interfaces?&lt;/h2&gt;
&lt;p&gt;We designed OWIN so that it could be expressed as function signatures because we didn&amp;#8217;t want to introduce concrete types and ship an &lt;code&gt;Owin.dll&lt;/code&gt; assembly. Further, we didn&amp;#8217;t want to be biased towards any particular CLR language.&lt;/p&gt;

&lt;p&gt;If you want to implement an OWIN stack entirely in F#, use &lt;code&gt;FSharpFunc&lt;/code&gt; rather than &lt;code&gt;Action&lt;/code&gt; and &lt;code&gt;Func&lt;/code&gt;. If you&amp;#8217;re a big fan of the C# &lt;code&gt;delegate&lt;/code&gt; keyword, use named delegates. It’s your stack, it’s up to you. By following the OWIN call structure, you can trivially interoperate with other OWIN-aware components.&lt;/p&gt;

&lt;p&gt;A neat side-effect of this is that OWIN could be implemented in a straight-forward manner even in non-CLR languages. A Python version is left as an exercise to the reader.&lt;/p&gt;</content>
  </entry>
  
  <entry>
    <id>http://bvanderveen.com/a/smwebrequest</id>
    <link type="text/html" rel="alternate" href="http://bvanderveen.com/a/smwebrequest"/>
    <title>SMWebRequest</title>
    <updated>2011-03-14T00:00:00-07:00</updated>
    <author>
      <name>Benjamin van der Veen</name>
      <uri>http://bvanderveen.com/</uri>
    </author>
    <content type="html">&lt;p&gt;A couple of weeks ago, &lt;a href='http://nfarina.com'&gt;Nick Farina&lt;/a&gt; emailed to tell me he was going to post a bit of code I cooked up at &lt;a href='http://spotlightmobile.com'&gt;Spotlight Mobile&lt;/a&gt; to GitHub: none other than the venerable &lt;a href='http://github.com/nfarina/webrequest'&gt;&lt;code&gt;SMWebRequest&lt;/code&gt;&lt;/a&gt;, an iOS/Mac class for talking to HTTP servers.&lt;/p&gt;

&lt;p&gt;I am very excited that this is now open-source. For data sets which fit in memory—which covers approximately 100% of API calls made by modern iOS apps—this is the best HTTP request class there is. Short, sweet, and gets the job done with less code and complexity than the others.&lt;/p&gt;

&lt;p&gt;I wrote &lt;a href='https://github.com/bvanderveen/webrequest/tree/master/SampleProject'&gt;a simple Hacker News reader&lt;/a&gt; to demonstrate using the class and how it lends itself to a clean model-controller architecture in an iOS app. Nick has &lt;a href='http://nfarina.com/post/3776625971/webrequest'&gt;a great write-up of &lt;code&gt;SMWebRequest&lt;/code&gt;&lt;/a&gt; which covers the motivation for the class and gives an overview of the features.&lt;/p&gt;</content>
  </entry>
  
  <entry>
    <id>http://bvanderveen.com/a/owin-buffering-async</id>
    <link type="text/html" rel="alternate" href="http://bvanderveen.com/a/owin-buffering-async"/>
    <title>Thoughts on OWIN, Buffering, and Async</title>
    <updated>2011-02-02T00:00:00-08:00</updated>
    <author>
      <name>Benjamin van der Veen</name>
      <uri>http://bvanderveen.com/</uri>
    </author>
    <content type="html">&lt;p&gt;Early on, we decided that OWIN should be an asynchronous interface. There are many possible approaches to this design goal, and ultimately it is important that whatever we come up with accommodates performant host implementations across platforms, and provides application and framework developers a sane programming model which takes advantage of upcoming and current “first-class” async features of C# and F#.&lt;/p&gt;

&lt;h3 id='buffering_streaming_data'&gt;Buffering Streaming Data&lt;/h3&gt;

&lt;p&gt;Consider the situation where data is coming at an application from a backend server faster than the client connected to the OWIN host can receive it—perhaps as when streaming data from a backend service to a mobile device. At some point, the OWIN host streaming data to the client will need to communicate to the OWIN app which is providing the data to the host that it ought to back off, to slow down the rate at which it provides data to the host. Of course, this means that the app will need to communicate this to the backend service.&lt;/p&gt;

&lt;p&gt;Ultimately, the app is talking to the backend service over TCP, and it can slow down the data coming over the connection by temporarily ceasing to send TCP ACK packets to the backend service to which it is connected. Once the slow client empties the OWIN host&amp;#8217;s outgoing buffer, and the host then must communicate to the OWIN app that it ought to resume sending ACK packets to the backend service, thereby triggering the service to send more data. I refer to this concept as “back-pressure”. Back-pressure is key to prevent the hosts outgoing buffers from growing indefinitely as the backend service puts data in faster than the slow client takes it out. Of course, this problem can work in the opposite direction: a client connected to an OWIN host might be sending data faster than the app can deal with it.&lt;/p&gt;

&lt;p&gt;This buffering problem adds a special twist to the basic goal of making an interface whereby a producer can huck data at a consumer. The consumer of the data must be able to somehow apply back-pressure to the producer—to communicate that it should “back off”.&lt;/p&gt;

&lt;p&gt;In our discussions, we have identified two primary approaches to implementing an asynchronous interface. What follows is a discussion of each mechanism and how back-pressure could be implemented within it.&lt;/p&gt;

&lt;h3 id='the_pull_approach'&gt;The Pull Approach&lt;/h3&gt;

&lt;p&gt;In this model, calling code asks that a value be retrieved or an operation be carried out, and later, that code is called back (by way of an interface or delegate) with a means of accessing the return value (or exception) of the operation. The callback is guaranteed to be invoked exactly once, with one value.&lt;/p&gt;

&lt;p&gt;The compiler takes care of the details, and what results is a construct which mirrors a traditional function—the user calls a function with some arguments, gets a single value back, and his code continues where it left off. This form of async is a readily grok-able conceptual model.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;async void ShuttleData()
{
	while (true)
	{
		var data = await inputSocket.Read();

		if (data.Count == 0)
		{
			inputSocket.Close();
			outputSocket.Close();
			return;
		}

		await outputSocket.Write(data);
	}
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The back-pressure mechanism is implicit, just like in a traditional synchronous model. The incoming data is (for all intents and purposes) not “ACK’d” until the user reads the input socket. Thus, until the intervening write operation succeeds and read is called again, no more data is read into user-space. The outgoing write mechanism can wait to return until its buffer has been emptied, thereby providing back-pressure by delaying further reads.&lt;/p&gt;

&lt;p&gt;In .NET, the designers of C# and F# first took the old Win32 APIs and wrapped the .NET APM patterns in the BCL, then later designed the Task Parallel Library, and now they’re working on C# 5’s async/await syntax; F#’s async syntax is equivalent and available today. These language features make using this “pull” model very easy.&lt;/p&gt;

&lt;h3 id='the_push_approach'&gt;The Push Approach&lt;/h3&gt;

&lt;p&gt;This approach more closely mirrors that of the Reactive Framework. For an example implementation, we look to Node. Node’s approach to asynchronicity is different the pull model—the user must wire up callbacks and deal with incoming values passed to the callbacks “immediately”. The callbacks cannot block on IO; this is enforced by the APIs exposed by the Node libraries to user code.&lt;/p&gt;

&lt;p&gt;In Node, whenever you write outgoing data using a &lt;code&gt;write&lt;/code&gt; function, it may be copied into to the kernel’s outgoing network buffer immediately, or placed into a user-space buffer to be sent later. The write function returns immediately. If the user-space buffer is larger than some configured maximum, the write operation will return false, otherwise true.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;inputSocket.on(&amp;quot;data&amp;quot;, function (data) {
	if (data.length == 0)
	{
		inputSocket.close();
		outputSocket.close();
	}
	else if (outputSocket.write(data) === false)
		inputSocket.pause();
});
outputSocket.on(&amp;quot;drain&amp;quot;, function () {
	inputSocket.resume();
});&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Based on this flag, the user can apply back-pressure to the source of the data by “pausing” it. Later, the outgoing buffer will fire a “drain” event, informing the user that the size of the user-space buffer has fallen to a configured minimum and that data may be added to it without causing undue memory pressure in the process. In response to this “drain” event, the user “resumes” the incoming data source, and continues to push data to the client with the &lt;code&gt;write&lt;/code&gt; function, perhaps until it returns false again.&lt;/p&gt;

&lt;p&gt;Because JavaScript lacks the expressive power of C# and F# (which will, with the release of C# 5, both have first-class asynchronous programming primitives), Node has to introduce these additional “pause” and “resume” functions.&lt;/p&gt;

&lt;h3 id='why_im_leaning_toward_the_pull_approach'&gt;Why I’m Leaning Toward the Pull Approach&lt;/h3&gt;

&lt;p&gt;It may be possible to construct some an adapter from a push-style interface into a pull-style interface, and it may be the case that a push-style interface is the way to go for OWIN. But ultimately, it is important that OWIN&amp;#8217;s asynchronous interface be easy and intuitive to use with the asynchronous language features provided be C# and F#, and these language features map cleanly onto a pull-style interface.&lt;/p&gt;</content>
  </entry>
  
  <entry>
    <id>http://bvanderveen.com/a/async-with-rx-and-the-tpl-part-3</id>
    <link type="text/html" rel="alternate" href="http://bvanderveen.com/a/async-with-rx-and-the-tpl-part-3"/>
    <title>Asynchronous Programming with the Reactive Framework and the Task Parallel Library — Part 3</title>
    <updated>2011-01-02T00:00:00-08:00</updated>
    <author>
      <name>Benjamin van der Veen</name>
      <uri>http://bvanderveen.com/</uri>
    </author>
    <content type="html">&lt;p&gt;&lt;em&gt;Note: This is the last in a series of three articles exploring differences between Rx and the TPL. The series assumes familiarity with the .NET &lt;a href='http://msdn.microsoft.com/en-us/library/2e08f6yc(v=vs.71).aspx'&gt;Asynchronous Programming Model&lt;/a&gt; (APM).&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;em&gt;&lt;a href='/a/async-with-rx-and-the-tpl-part-1'&gt;Part 1: Wrapping APM Operations&lt;/a&gt;&lt;/em&gt;&lt;/li&gt;

&lt;li&gt;&lt;em&gt;&lt;a href='/a/async-with-rx-and-the-tpl-part-2'&gt;Part 2: Implementing APM Operations&lt;/a&gt;&lt;/em&gt;&lt;/li&gt;

&lt;li&gt;&lt;em&gt;Part 3: Schedulers&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;As you may imagine, threading is very important to asynchronous programming. Where are all those callbacks coming from? What thread are they executed on and when? The answers to these questions are determined by a mechanism called a scheduler.&lt;/p&gt;

&lt;h2 id='a_scheduler'&gt;A scheduler?&lt;/h2&gt;

&lt;p&gt;Both the Reactive Framework and the Task Parallel Library define their own concept of a scheduler. A scheduler is like a gatekeeper to the CPU. Schedulers expose a method which allows outside code to provide a piece of work which should be performed. In many scheduler implementations, the piece of work is put into a queue, and the scheduler performs the work at some point in the future. The thread on which the work is performed and when is decided by the scheduler, and is important to consider if you’re writing a program with a user interface, or if you’re writing a server which manages special worker threads.&lt;/p&gt;

&lt;h2 id='scheduling_in_rx'&gt;Scheduling in Rx&lt;/h2&gt;

&lt;p&gt;In the Reactive Framework, there are three places where the calling thread is important: the call to &lt;code&gt;IObservable.Subscribe&lt;/code&gt;, the call to the &lt;code&gt;Dispose&lt;/code&gt; method of the &lt;code&gt;IDisposable&lt;/code&gt; returned by &lt;code&gt;IObservable.Subscribe&lt;/code&gt;, and the calls to the methods of &lt;code&gt;IObserver&lt;/code&gt;. Because a subscription or a disposal of a subscription may cause the observable to start or stop doing something, its important to consider what thread those calls are coming in on when implementing an observable. Similarly, when subscribing to an observable, you need to be sure about the thread on which your observer is notified by the observable.&lt;/p&gt;

&lt;p&gt;The Reactive Framework defines an interface called &lt;code&gt;IScheduler&lt;/code&gt;, which allows consumers of the interface to provide an &lt;code&gt;Action&lt;/code&gt; which should be invoked by the scheduler instance.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public interface IScheduler
{
    IDisposable Schedule(Action action);
    IDisposable Schedule(Action action, TimeSpan dueTime);
    DateTimeOffset Now { get; }
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The Reactive Framework provides two extension methods for working with schedulers, both defined on &lt;code&gt;IObservable&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public static class Observable
{
    public static IObservable&amp;lt;TSource&amp;gt; ObserveOn&amp;lt;TSource&amp;gt;(this IObservable&amp;lt;TSource&amp;gt; source, IScheduler scheduler);
    public static IObservable&amp;lt;TSource&amp;gt; SubscribeOn&amp;lt;TSource&amp;gt;(this IObservable&amp;lt;TSource&amp;gt; source, IScheduler scheduler);
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;SubscribeOn&lt;/code&gt; returns an observable which, when subscribed to or unsubscribed from, causes subscription to and unsubscription from the source observable to occur as scheduled by the scheduler. Essentially, it creates and returns a proxy observable which, rather than immediately performing the actions, delegates them to the given scheduler.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;ObserverOn&lt;/code&gt; method does the same for notifications. It creates and returns a proxy observable which simply forwards subscription to the source observable, but whenever the source observable yields a value, an exception, or completes, the proxy schedules an action on the scheduler which in turn invokes the appropriate callback on any observer which subscribes to the proxy observable. The effect is that when you subscribe to the resulting observable, you will always get callbacks on a thread determined by the scheduler you provided to &lt;code&gt;ObserverOn&lt;/code&gt;.&lt;/p&gt;

&lt;h2 id='scheduling_in_the_tpl'&gt;Scheduling in the TPL&lt;/h2&gt;

&lt;p&gt;Since the TPL is all about running user delegates, it provides a mechanism to easily configure the thread on which those delegates are run.&lt;/p&gt;

&lt;p&gt;The scheduler interface in the TPL is an abstract class called &lt;code&gt;TaskScheduler&lt;/code&gt;. The fact that it is an abstract class makes it a bit more difficult to sum up neatly in the same way that the Reactive Framework’s &lt;code&gt;IScheduler&lt;/code&gt; interface, but it largely performs the same function—it accepts work in the form of &lt;code&gt;Task&lt;/code&gt; instances, and eventually performs that work.&lt;/p&gt;

&lt;p&gt;To control the execution of tasks, several APIs in the TPL accept a &lt;code&gt;TaskScheduler&lt;/code&gt; as an argument. The most important and commonly used ones are &lt;code&gt;Task.ContinueWith&lt;/code&gt;, &lt;code&gt;Task.Start&lt;/code&gt;, and &lt;code&gt;TaskFactory.StartNew&lt;/code&gt;. The behavior of &lt;code&gt;Task.Start&lt;/code&gt;, and &lt;code&gt;TaskFactory.StartNew&lt;/code&gt; can be considered equivalent—&lt;code&gt;TaskFactory.StartNew&lt;/code&gt; just saves you from having to allocate a new &lt;code&gt;Task&lt;/code&gt; yourself and then call the &lt;code&gt;Start&lt;/code&gt; method on it.&lt;/p&gt;

&lt;p&gt;All of these APIs create a new &lt;code&gt;Task&lt;/code&gt;, and a &lt;code&gt;TaskScheduler&lt;/code&gt; may be provided to control the execution of the newly-created task. If a &lt;code&gt;TaskScheduler&lt;/code&gt; is not provided, the TPL will execute the task on the current &lt;code&gt;TaskScheduler&lt;/code&gt;. The current scheduler is available through the static method &lt;code&gt;TaskScheduler.Current&lt;/code&gt;. In the context of an executing &lt;code&gt;Task&lt;/code&gt;, the current scheduler is, as you might expect, the &lt;code&gt;TaskScheduler&lt;/code&gt; which is executing the current task. Outside the context of an executing task, the current &lt;code&gt;TaskScheduler&lt;/code&gt; is the default &lt;code&gt;TaskScheduler&lt;/code&gt;, which queues tasks for execution on the thread pool.&lt;/p&gt;

&lt;p&gt;When completing a task using &lt;code&gt;TaskCompletionSource&lt;/code&gt;, the thread which calls &lt;code&gt;SetResult&lt;/code&gt; or &lt;code&gt;SetException&lt;/code&gt; does not matter. Any tasks consequent to the &lt;code&gt;Task&lt;/code&gt; managed by &lt;code&gt;TaskCompletionSource&lt;/code&gt; will execute on the scheduler provided to the call to &lt;code&gt;ContinueWith&lt;/code&gt; which created the consequent task.&lt;/p&gt;

&lt;h2 id='what_does_it_all_mean'&gt;What does it all mean?&lt;/h2&gt;

&lt;p&gt;For most users of these frameworks, schedulers are a relatively opaque mechanism which addresses threading concerns. For example, if you’re writing a program with a GUI, all you have to do when you want to perform a background operation is make sure it is performed on a scheduler which works in the background. When you want to retrieve the results of that operation, just make sure that the callbacks which receive the results are performed on a scheduler which runs on the UI thread.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;void RxButton_Click(...) 
{            
    Observable.Create&amp;lt;Unit&amp;gt;(o =&amp;gt; {
        try
        {
            longRunningOperation();
        }
        catch (Exception e)
        {
            o.OnError(e);
        }
        o.OnCompleted();
        return () =&amp;gt; { }; // no-op disposable
    })
    .SubscribeOn(Scheduler.ThreadPool) // subscribe operation will kick off on a thread pool thread
    .ObserveOn(Scheduler.Dispatcher) // results will come in on the UI thread
    .Subscribe(
        _ =&amp;gt; { }, 
        e =&amp;gt; Console.WriteLine(&amp;quot;Got error.&amp;quot;), 
        () =&amp;gt; Console.WriteLine(&amp;quot;Success! Back on UI thread.&amp;quot;));
}

void TplButton_Click(...)
{
    var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();

    var task = new Task.Factory.StartNew(() =&amp;gt; longRunningOperation());
    task.ContinueWith(t =&amp;gt; {
         if (t.IsFaulted) Console.WriteLine(&amp;quot;Got error.&amp;quot;);
         else Console.WriteLine(&amp;quot;Success! Back on UI thread.&amp;quot;); 
    }, uiScheduler);
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;An important difference between the TPL and Rx is that tasks are usually passed around already-started, so stringing up callbacks with &lt;code&gt;ContinueWith&lt;/code&gt; happens after the task has already started and possibly already completed. With Rx, observables can be created but are generally not active until callbacks are provided through a subscription.&lt;/p&gt;

&lt;p&gt;In the previous articles, we saw that the asynchronous mechanisms of the TPL, Rx, and the APM pattern have been roughly equivalent; that it is possible to implement adapters between all of them. However, the APM doesn&amp;#8217;t provide any explicit concept of a scheduler. The thread on which the callback from an APM operation is called is up to the implementor of the operation. Most APM operations provided by the .NET BCL invoke their callbacks on thread pool threads, and in the callback you must manually marshal the result or exception of the APM End method using the &lt;code&gt;SynchronizationContext&lt;/code&gt; class or a similar mechanism. Both the TPL and Rx make this much easier to do by providing a scheduling mechanism and exposing APIs which allow the user to easily provide a scheduler to indicate what thread should be used to perform work.&lt;/p&gt;</content>
  </entry>
  
  <entry>
    <id>http://bvanderveen.com/a/async-with-rx-and-the-tpl-part-2</id>
    <link type="text/html" rel="alternate" href="http://bvanderveen.com/a/async-with-rx-and-the-tpl-part-2"/>
    <title>Asynchronous Programming with the Reactive Framework and the Task Parallel Library — Part 2</title>
    <updated>2010-12-24T00:00:00-08:00</updated>
    <author>
      <name>Benjamin van der Veen</name>
      <uri>http://bvanderveen.com/</uri>
    </author>
    <content type="html">&lt;p&gt;&lt;em&gt;Note: This is the second in a series of three articles exploring differences between Rx and the TPL. The series assumes familiarity with the .NET &lt;a href='http://msdn.microsoft.com/en-us/library/2e08f6yc(v=vs.71).aspx'&gt;Asynchronous Programming Model&lt;/a&gt; (APM).&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;em&gt;&lt;a href='/a/async-with-rx-and-the-tpl-part-1'&gt;Part 1: Wrapping APM Operations&lt;/a&gt;&lt;/em&gt;&lt;/li&gt;

&lt;li&gt;&lt;em&gt;Part 2: Implementing APM Operations&lt;/em&gt;&lt;/li&gt;

&lt;li&gt;&lt;em&gt;&lt;a href='/a/async-with-rx-and-the-tpl-part-3'&gt;Part 3: Schedulers&lt;/a&gt;&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In the Part 1, we discussed how to wrap APM asynchronous operations in &lt;code&gt;Task&amp;lt;T&amp;gt;&lt;/code&gt; and &lt;code&gt;IObservable&amp;lt;T&amp;gt;&lt;/code&gt;. In this article we’ll take a look at doing the opposite: how to implement an APM-style asynchronous operation using the Task Parallel Library and the Reactive Framework. The first draft of the OWIN specification defined APM operations for invoking a web application and reading the body of an HTTP request. Because Kayak had used both Rx and the TPL for all of its internal asynchronous logic, I needed to be able to expose that asynchronous logic as an APM operation in order to implement the spec.&lt;/p&gt;

&lt;h2 id='a_bit_about_'&gt;A Bit About &lt;code&gt;IAsyncResult&lt;/code&gt;&lt;/h2&gt;

&lt;p&gt;One of the nastiest things about implementing the APM pattern is the need to implement &lt;code&gt;IAsyncResult&lt;/code&gt;. The idea behind &lt;code&gt;IAsyncResult&lt;/code&gt; is that it should provide code that initiates an APM operation information about the identity and state of the operation. A full discussion of &lt;code&gt;IAsyncResult&lt;/code&gt; is beyond the scope of this article, but it will suffice to say that in modern C#, &lt;code&gt;IAsyncResult&lt;/code&gt; is little more than an opaque token used to obtain the result of an asynchronous operation from an APM End method.&lt;/p&gt;

&lt;p&gt;Quite curiously and very unfortunately, the .NET BCL did not historically provide an implementation of &lt;code&gt;IAsyncResult&lt;/code&gt;. For our APM pattern implementation using the Reactive Framework, we will use the implementation of &lt;code&gt;IAsyncResult&lt;/code&gt; described in &lt;a href='http://msdn.microsoft.com/en-us/magazine/cc163467.aspx'&gt;this MSDN Magazine article&lt;/a&gt; by Jeffrey Richter.&lt;/p&gt;

&lt;h2 id='implementing_the_apm_pattern_with_the_reactive_framework'&gt;Implementing the APM Pattern with the Reactive Framework&lt;/h2&gt;

&lt;p&gt;We will create a simple wrapper class that adapts a &lt;code&gt;Func&amp;lt;TArg, IObservable&amp;lt;TResult&amp;gt;&amp;gt;&lt;/code&gt; delegate into an APM pattern Begin/End pair. When the APM Begin method is called, our wrapper will call the delegate to retrieve an observable which represents the asynchronous operation. When the observable yields a result or a value, our wrapper class will invoke the &lt;code&gt;AsyncCallback&lt;/code&gt;, and the wrapper’s APM End method will provide that result or value.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class RxAsyncOperation&amp;lt;TArg, TResult&amp;gt; 
{
    Func&amp;lt;TArg, IObservable&amp;lt;TResult&amp;gt;&amp;gt; operation;
    IDisposable disposable;

    public RxAsyncOperation(Func&amp;lt;TArg, IObservable&amp;lt;TResult&amp;gt;&amp;gt; operation)
    {
        this.operation = operation;
    }

    public IAsyncResult BeginInvoke(TArg arg, AsyncCallback callback, object state)
    {
        AsyncResult&amp;lt;TResult&amp;gt; asyncResult = new AsyncResult&amp;lt;TResult&amp;gt;(callback, state);
        disposable = operation(arg).Subscribe(
            // the boolean arguments to SetAsCompleted indicate whether the operation 
            // completed synchronously. IObservable doesn&amp;#39;t relay that information,
            // so we assume false.
            r =&amp;gt;
            {
                UnsubscribeIfPossible();
                asyncResult.SetAsCompleted(r, false);
            },
            e =&amp;gt;
            {
                UnsubscribeIfPossible();
                asyncResult.SetAsCompleted(e, false);
            },
            () =&amp;gt; { });

        // if the operation completed during the call to subscribe, we won&amp;#39;t have 
        // unsubscribed yet, so do it now.
        if (asyncResult.IsCompleted)
            UnsubscribeIfPossible();

        return asyncResult;
    }

    public TResult EndInvoke(IAsyncResult asyncResult)
    {
        // the AsyncResult&amp;lt;T&amp;gt; implementation takes care of waiting and throwing exceptions for us.
        return ((AsyncResult&amp;lt;TResult&amp;gt;)asyncResult).EndInvoke();
    }

    void UnsubscribeIfPossible()
    {
        if (disposable != null)
        {
            disposable.Dispose();
            disposable = null;
        }
    }
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In the APM Begin method, we first construct an instance of &lt;code&gt;AsyncResult&amp;lt;T&amp;gt;&lt;/code&gt;, the implementation of &lt;code&gt;IAsyncResult&lt;/code&gt; we’re using. We provide the APM &lt;code&gt;AsyncCallback&lt;/code&gt; and state object to the constructor of the &lt;code&gt;AsyncResult&amp;lt;T&amp;gt;&lt;/code&gt;—it will take care of invoking the &lt;code&gt;AsyncCallback&lt;/code&gt; for us.&lt;/p&gt;

&lt;p&gt;Next, we invoke the delegate to retrieve an observable, and subscribe to that observable. Notice that we are keeping a reference to the &lt;code&gt;IDisposable&lt;/code&gt; returned by the &lt;code&gt;Subscribe&lt;/code&gt; method of the observable. This is necessary because after the observable yields a value or an exception, we need to unsubscribe from it—inform it that we no longer want to receive notifications. This is accomplished by calling the &lt;code&gt;Dispose&lt;/code&gt; method of the &lt;code&gt;IDisposable&lt;/code&gt; object returned from the &lt;code&gt;Subscribe&lt;/code&gt; method of the observable.&lt;/p&gt;

&lt;p&gt;In the &lt;code&gt;OnNext&lt;/code&gt; and &lt;code&gt;OnError&lt;/code&gt; callbacks, the first thing we do is unsubscribe from the observable to prevent further callbacks. It’s important to note that an observable may yield a value or an exception before &lt;code&gt;Subscribe&lt;/code&gt; returns, which means that it’s possible that the observable callbacks might get called before the value of the &lt;code&gt;disposable&lt;/code&gt; instance variable has set! Thus, unsubscribing from the observable might not be possible from within the &lt;code&gt;OnNext&lt;/code&gt; and &lt;code&gt;OnError&lt;/code&gt; callbacks. For this reason, after the &lt;code&gt;Subscribe&lt;/code&gt; method returns, we check to see if the operation has already completed, and if so, attempt again to unsubscribe.&lt;/p&gt;

&lt;p&gt;After unsubscribing in the &lt;code&gt;OnNext&lt;/code&gt; and &lt;code&gt;OnError&lt;/code&gt; callbacks, we inform the &lt;code&gt;AsyncResult&amp;lt;T&amp;gt;&lt;/code&gt; implementation that the operation has completed with a value or error by calling the &lt;code&gt;SetAsCompleted&lt;/code&gt; method. In response to &lt;code&gt;SetAsCompleted&lt;/code&gt;, the &lt;code&gt;AsyncResult&amp;lt;T&amp;gt;&lt;/code&gt; object will call the &lt;code&gt;AsyncCallback&lt;/code&gt; we provided to its constructor, and the &lt;code&gt;IsCompleted&lt;/code&gt; property of the will &lt;code&gt;AsyncResult&lt;/code&gt; become true.&lt;/p&gt;

&lt;p&gt;The final step in the implementation of the APM Begin method is to return the &lt;code&gt;IAsyncResult&lt;/code&gt; instance.&lt;/p&gt;

&lt;p&gt;The implementation of the APM End method is fairly trivial. Its job is to wait for the operation to complete, and return the result of the APM operation, or, if the operation resulted in an exception, re-throw that exception. Fortunately, the &lt;code&gt;AsyncResult&amp;lt;T&amp;gt;&lt;/code&gt; class takes care of all of this for us with its &lt;code&gt;EndInvoke&lt;/code&gt; method.&lt;/p&gt;

&lt;h2 id='implementing_the_apm_pattern_with_the_task_parallel_library'&gt;Implementing the APM Pattern with the Task Parallel Library&lt;/h2&gt;

&lt;p&gt;It is quite a bit simpler to implement the APM pattern with the TPL due to one convenient fact: &lt;code&gt;Task&amp;lt;T&amp;gt;&lt;/code&gt; implements the &lt;code&gt;IAsyncResult&lt;/code&gt; interface! In this example, we’re going to make a wrapper class which is very similar to the one we created for the Rx example—it will adapt a &lt;code&gt;Func&amp;lt;TArg, Task&amp;lt;TResult&amp;gt;&amp;gt;&lt;/code&gt; delegate to an APM operation. When the APM Begin method is called, our wrapper will call the delegate to obtain a &lt;code&gt;Task&amp;lt;T&amp;gt;&lt;/code&gt; which represents the operation, and when the operation completes, our wrapper will invoke the &lt;code&gt;AsyncCallback&lt;/code&gt; delegate provided by the user, and the APM End method will provide the result value or exception.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class TplAsyncOperation&amp;lt;TArg, TResult&amp;gt;
{
    Func&amp;lt;TArg, Task&amp;lt;TResult&amp;gt;&amp;gt; operation;

    public TplAsyncOperation(Func&amp;lt;TArg, Task&amp;lt;TResult&amp;gt;&amp;gt; operation)
    {
        this.operation = operation;
    }

    public IAsyncResult BeginInvoke(TArg arg, AsyncCallback callback, object state)
    {
        var task = operation(arg);
        task.ContinueWith(_ =&amp;gt; callback(task));
        return task;
    }

    public TResult EndInvoke(IAsyncResult result)
    {
        return ((Task&amp;lt;TResult&amp;gt;)result).Result;
    }
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As you can see, the TPL version is quite a bit simpler than the Rx version! We simply retrieve the underlying &lt;code&gt;Task&amp;lt;T&amp;gt;&lt;/code&gt;, register a callback to be notified of its completion using &lt;code&gt;ContinueWith&lt;/code&gt;, and return the &lt;code&gt;Task&amp;lt;T&amp;gt;&lt;/code&gt;! When that task completes, the delegate we provided to &lt;code&gt;ContinueWith&lt;/code&gt; is invoked, which in turn invokes the &lt;code&gt;AsyncCallback&lt;/code&gt; provided by the client code.&lt;/p&gt;

&lt;p&gt;Like the implementation of &lt;code&gt;AsyncResult.EndInvoke&lt;/code&gt; which we used for the Rx example, the implementation of &lt;code&gt;Task&amp;lt;T&amp;gt;.Result&lt;/code&gt; takes care of waiting and throwing exceptions for us, so we can just return that value, and everything will work as expected.&lt;/p&gt;

&lt;h2 id='a_winner'&gt;A winner?&lt;/h2&gt;

&lt;p&gt;The TPL version of the code for wrapping and implementing the APM pattern is much shorter and sweeter than the equivalent Rx code. This is not to say that the TPL is superior to the Reactive Framework, but it is clear that the TPL onto the APM pattern more cleanly than does the Reactive Framework. Both the APM and TPL share single-value-or-exception semantics, with only the producer side defining when a value will be produced; the semantics of the Reactive Framework are more general, allowing many-values-maybe-one-exception, with either the producer or consumer choosing when how many values are transmitted and when transmission should start or stop.&lt;/p&gt;

&lt;p&gt;In the previous article, we wrapped APM operations with the Task Parallel Library and the Reactive Framework; this time, we’ve gone the other way and wrapped the Task Parallel Library and the Reactive Framework with APM operations. The complete &lt;a href='https://gist.github.com/754691'&gt;source code for this article&lt;/a&gt; is available in a Gist. In the &lt;a href='/a/async-with-rx-and-the-tpl-part-3'&gt;next&lt;/a&gt; article, we will consider threading and the how-when-where of asynchronous callbacks in both the TPL and Rx.&lt;/p&gt;</content>
  </entry>
  
  <entry>
    <id>http://bvanderveen.com/a/async-with-rx-and-the-tpl-part-1</id>
    <link type="text/html" rel="alternate" href="http://bvanderveen.com/a/async-with-rx-and-the-tpl-part-1"/>
    <title>Asynchronous Programming with the Reactive Framework and the Task Parallel Library — Part 1</title>
    <updated>2010-12-21T00:00:00-08:00</updated>
    <author>
      <name>Benjamin van der Veen</name>
      <uri>http://bvanderveen.com/</uri>
    </author>
    <content type="html">&lt;p&gt;&lt;em&gt;Note: This is the first in a series of three articles exploring differences between Rx and the TPL. The series assumes familiarity with the .NET &lt;a href='http://msdn.microsoft.com/en-us/library/2e08f6yc(v=vs.71).aspx'&gt;Asynchronous Programming Model&lt;/a&gt; (APM).&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;em&gt;Part 1: Wrapping APM Operations&lt;/em&gt;&lt;/li&gt;

&lt;li&gt;&lt;em&gt;&lt;a href='/a/async-with-rx-and-the-tpl-part-2'&gt;Part 2: Implementing APM Operations&lt;/a&gt;&lt;/em&gt;&lt;/li&gt;

&lt;li&gt;&lt;em&gt;&lt;a href='/a/async-with-rx-and-the-tpl-part-3'&gt;Part 3: Schedulers&lt;/a&gt;&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;On the &lt;a href='http://groups.google.com/group/net-http-abstractions'&gt;.NET HTTP Abstractions&lt;/a&gt; list we decided early on that we wanted to allow &lt;a href='http://owin.github.org'&gt;OWIN&lt;/a&gt; applications to provide some sort of asynchronous primitive through the response enumerable. The rationale is that sometimes an OWIN host might attempt to enumerate the next item in the enumerable sequence, but the application might not be ready to provide the item immediately. We considered the options .NET had built-in: &lt;code&gt;IObservable&amp;lt;T&amp;gt;&lt;/code&gt; (the &lt;a href='http://msdn.microsoft.com/en-us/devlabs/ee794896'&gt;Reactive Framework&lt;/a&gt;) and &lt;code&gt;Task&amp;lt;T&amp;gt;&lt;/code&gt; (the &lt;a href='http://msdn.microsoft.com/en-us/library/dd460717.aspx'&gt;Task Parallel Library&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;I had already built Kayak around the Reactive Framework, and I was pretty happy with that mechanism. The one perceived drawback was that an observable could contain multiple values, but everywhere I used it throughout my system, it was axiomatically required that every observable yield a single value and complete, or yield an exception. The fact that this wasn’t enforced by the compiler nagged at me.&lt;/p&gt;

&lt;p&gt;I was leaning toward &lt;code&gt;Task&amp;lt;T&amp;gt;&lt;/code&gt; for OWIN because, by definition, it yields a single value or an exception. However, I hadn’t played with the Task Parallel Library yet, so I didn’t press the issue too hard initially. Last week, I spent some time familiarizing myself with the Task Parallel Library by porting Kayak’s asynchronous architecture from the Reactive Framework to the TPL.&lt;/p&gt;

&lt;h2 id='a_brief_introduction_to_the_reactive_framework'&gt;A Brief Introduction to the Reactive Framework&lt;/h2&gt;

&lt;p&gt;In the Reactive Framework, there are two primary interfaces: &lt;code&gt;IObservable&amp;lt;T&amp;gt;&lt;/code&gt; and &lt;code&gt;IObserver&amp;lt;T&amp;gt;&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public interface IObservable&amp;lt;T&amp;gt;
{
    IDisposable Subscribe(IObserver&amp;lt;T&amp;gt; observer);
}

public interface IObserver&amp;lt;T&amp;gt;
{
    void OnNext(T value);
    void OnException(Exception e);
    void OnCompleted();
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;IObservable&amp;lt;T&amp;gt;&lt;/code&gt; defines a single &lt;code&gt;Subscribe&lt;/code&gt; method which takes an &lt;code&gt;IObserver&amp;lt;T&amp;gt;&lt;/code&gt;. After &lt;code&gt;Subscribe&lt;/code&gt; is called, the observable may call the methods of the observer with values and exceptions at some point in the future. The &lt;code&gt;Subscribe&lt;/code&gt; method returns an &lt;code&gt;IDisposable&lt;/code&gt; which, when disposed, informs the observable that the observer provided to &lt;code&gt;Subscribe&lt;/code&gt; is no longer interested in receiving values from the observable.&lt;/p&gt;

&lt;p&gt;Depending on the semantics of the observable, &lt;code&gt;Subscribe&lt;/code&gt; may cause the observable to “start” whatever process generates the values that make up the observable sequence—for instance, if the observable represents a TCP listener, its values would be sockets representing accepted connections. Upon a call to &lt;code&gt;Subscribe&lt;/code&gt;, the TCP listener would cause a new listening socket to be created and bound, and whenever a connection is accepted, it would call the &lt;code&gt;OnNext&lt;/code&gt; method of the observer with the socket object which represents the connection.&lt;/p&gt;

&lt;p&gt;Again, depending on the semantics of the observable, disposing the disposable returned from the &lt;code&gt;Subscribe&lt;/code&gt; method may cause the observable to “stop” doing whatever it was doing to generate values. In our TCP listener example, the listener would shut down the listening socket, preventing any more connections from being accepted.&lt;/p&gt;

&lt;h2 id='wrapping_an_apm_operation_with_'&gt;Wrapping an APM operation with &lt;code&gt;IObservable&amp;lt;T&amp;gt;&lt;/code&gt;&lt;/h2&gt;

&lt;p&gt;In the Kayak’s asynchronous architecture, I originally used &lt;code&gt;IObservable&amp;lt;T&amp;gt;&lt;/code&gt; to represent and wrap up asynchronous operations following the .NET Asynchronous Programming Model (APM) pattern. The Reactive Framework provides &lt;code&gt;Observable.FromAsyncPattern&lt;/code&gt; which creates an function which, when invoked, returns observable representing an APM operation. When an observer subscribes to this observable, the Begin method of the APM operation is invoked, and the operation is started. When it completes, the &lt;code&gt;OnNext&lt;/code&gt; method of the observer is invoked with the result of the operation. Unsubscribing from this observable has no effect, because APM operations cannot be cancelled.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public static partial class Extensions
{
    public static Func&amp;lt;IObservable&amp;lt;int&amp;gt;&amp;gt; ReadAsyncRx_FromAsync(this Stream stream, byte[] buffer, int offset, int count)
    {
        return Observable.FromAsyncPattern&amp;lt;int&amp;gt;(
            (c, s) =&amp;gt; stream.BeginRead(buffer, offset, count, c, s),
            iasr =&amp;gt; stream.EndRead(iasr));
    }
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;However, this method was not adequate for Kayak. Kayak supports a “green threaded” model, so I need to very carefully control when and on what threads Kayak code gets executed, and I achieve this by making sure that the &lt;code&gt;AsyncCallback&lt;/code&gt; of any APM operation is invoked on a special thread managed by Kayak (or more specifically, the underlying IO driver). The observables created by &lt;code&gt;FromAsyncPattern&lt;/code&gt; do not guarantee that the &lt;code&gt;OnNext&lt;/code&gt;, &lt;code&gt;OnException&lt;/code&gt;, and &lt;code&gt;OnCompleted&lt;/code&gt; methods of subscribed observers are called on the same thread on which the underlying APM calls the &lt;code&gt;AsyncCallback&lt;/code&gt; provided to it. Thus, I wrote a special observable which issued callbacks in a predictable way.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public static partial class Extensions
{
        public static IObservable&amp;lt;int&amp;gt; ReadAsyncRx_ApmObservable(this Stream stream, byte[] buffer, int offset, int count)
        {
            return new ApmObservable&amp;lt;int&amp;gt;(
                (c, s) =&amp;gt; stream.BeginRead(buffer, offset, count, c, s),
                iasr =&amp;gt; stream.EndRead(iasr));
        }

}

// Observable.FromAsyncPattern reschedules the callback on the ThreadPoolScheduler. Lame!
// We need to allow the underlying APM operation to determine what thread the callback 
// comes in on.
// 
// And so we roll our own.
public class ApmObservable&amp;lt;T&amp;gt; : IObservable&amp;lt;T&amp;gt;
{
    Func&amp;lt;AsyncCallback, object, IAsyncResult&amp;gt; begin;
    Func&amp;lt;IAsyncResult, T&amp;gt; end;

    public ApmObservable(Func&amp;lt;AsyncCallback, object, IAsyncResult&amp;gt; begin, Func&amp;lt;IAsyncResult, T&amp;gt; end)
    {
        this.begin = begin;
        this.end = end;
    }

    public IDisposable Subscribe(IObserver&amp;lt;T&amp;gt; observer)
    {
        IAsyncResult asyncResult = null;

        AsyncCallback callback = (iasr) =&amp;gt;
        {
            T value = default(T);
            try
            {
                value = end(iasr);
            }
            catch (Exception e)
            {
                observer.OnError(e);
                return;
            }
            observer.OnNext(value);
            observer.OnCompleted();
        };

        try
        {
            asyncResult = begin(callback, null);
        }
        catch (Exception e)
        {
            observer.OnError(e);
        }

        return Disposable.Empty;
    }
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Upon subscription, the asynchronous operation is initiated by a call to the APM Begin method, and an &lt;code&gt;AsyncCallback&lt;/code&gt; delegate is provided. In typical APM fashion, the implementation of the AsyncCallback calls the APM End method to retrieve the result of the operation, and catches the exception, if any. The implementation of the &lt;code&gt;AsyncCallback&lt;/code&gt; then calls the observer’s &lt;code&gt;OnNext&lt;/code&gt; method with the result of the operation followed by &lt;code&gt;OnCompleted&lt;/code&gt;, or, if the APM End method threw an exception, it calls &lt;code&gt;OnError&lt;/code&gt; with the exception. Again, because APM operations in .NET cannot be cancelled, the &lt;code&gt;IDisposable&lt;/code&gt; returned from &lt;code&gt;Subscribe&lt;/code&gt; is &lt;code&gt;Disposable.Empty&lt;/code&gt;.&lt;/p&gt;

&lt;h2 id='a_brief_introduction_to_the_task_parallel_library'&gt;A Brief Introduction to the Task Parallel Library&lt;/h2&gt;

&lt;p&gt;The core interfaces of the Reactive Framework roughly correspond to TPL classes &lt;code&gt;Task&amp;lt;T&amp;gt;&lt;/code&gt; and &lt;code&gt;TaskCompletionSource&amp;lt;T&amp;gt;&lt;/code&gt;. Task is a bit like &lt;code&gt;IObservable&amp;lt;T&amp;gt;&lt;/code&gt;, in that it, by itself, represents an asynchronous operation. &lt;code&gt;TaskCompletionSource&amp;lt;T&amp;gt;&lt;/code&gt; is a bit like &lt;code&gt;IObserver&amp;lt;T&amp;gt;&lt;/code&gt;, in that it defines &lt;code&gt;SetResult&lt;/code&gt; and &lt;code&gt;SetException&lt;/code&gt; methods which accept values and exceptions.&lt;/p&gt;

&lt;p&gt;Tasks provide values and exceptions though their &lt;code&gt;Result&lt;/code&gt; and &lt;code&gt;Exception&lt;/code&gt; properties, but these properties are a bit freaky—if the task hasn’t completed yet, these properties will block the calling thread until the task completes before returning a value. It’s a very, very rare case where this behavior is what you want—if you’re doing asynchronous programming, threads blocking is often what you’re trying to avoid in the first place! Instead, you want to get a callback when the task is completed, so that you can safely access the &lt;code&gt;Result&lt;/code&gt; or &lt;code&gt;Exception&lt;/code&gt; properties without blocking. &lt;code&gt;Task&lt;/code&gt; objects provide the &lt;code&gt;ContinueWith&lt;/code&gt; method for this purpose. There are a lot of overloads of &lt;code&gt;ContinueWith&lt;/code&gt; which introduce slight variations, but the basic idea is that it takes a delegate which is executed when the target (or in MSDN parlance, “antecedent”) task completes, and returns a new &lt;code&gt;Task&lt;/code&gt; which represents the execution of the delegate.&lt;/p&gt;

&lt;p&gt;Think about that for a second. &lt;code&gt;Task.ContinueWith&lt;/code&gt; doesn’t take a task, it creates one from a delegate. Now take a look at the constructors for &lt;code&gt;Task&lt;/code&gt;—they all take delegates and create new &lt;code&gt;Task&lt;/code&gt;s from them. If a delegate is sufficient to create a task, then one might infer that the task completes when the delegate is finished executing. So constructing a task with a delegate is just a fancy way of saying &lt;code&gt;ThreadPool.QueueUserWorkItem&lt;/code&gt;, with the added plumbing of handling a return value and any exceptions and making them available through some properties.&lt;/p&gt;

&lt;p&gt;So how can a &lt;code&gt;Task&lt;/code&gt; represent an asynchronous operation which isn’t backed by a thread pool thread, such as a read or write to or from a network socket?&lt;/p&gt;

&lt;p&gt;Enter &lt;code&gt;TaskCompletionSource&amp;lt;T&amp;gt;&lt;/code&gt;. &lt;code&gt;TaskCompletionSource&amp;lt;T&amp;gt;&lt;/code&gt; is kind of like &lt;code&gt;IObserver&amp;lt;T&amp;gt;&lt;/code&gt; and &lt;code&gt;IObservable&amp;lt;T&amp;gt;&lt;/code&gt; wrapped into a single package. (In the Reactive Framework, there is a type called &lt;code&gt;ISubject&amp;lt;T&amp;gt;&lt;/code&gt; which is just that—it implements both &lt;code&gt;IObservable&amp;lt;T&amp;gt;&lt;/code&gt; and &lt;code&gt;IObserver&amp;lt;T&amp;gt;&lt;/code&gt;). When you construct a &lt;code&gt;TaskCompletionSource&amp;lt;T&amp;gt;&lt;/code&gt;, it internally constructs a special task, accessible through the &lt;code&gt;TaskCompletionSource&lt;/code&gt;’s &lt;code&gt;Task&lt;/code&gt; property, which doesn’t require a delegate. Instead, &lt;code&gt;TaskCompletionSource&amp;lt;T&amp;gt;&lt;/code&gt; defines two methods, &lt;code&gt;SetResult&lt;/code&gt; and &lt;code&gt;SetException&lt;/code&gt;, which when called, cause the &lt;code&gt;TaskCompletionSource&lt;/code&gt;’s special &lt;code&gt;Task&lt;/code&gt; to complete with the given result or exception.&lt;/p&gt;

&lt;h2 id='wrapping_an_apm_operation_with_'&gt;Wrapping an APM operation with &lt;code&gt;Task&amp;lt;T&amp;gt;&lt;/code&gt;&lt;/h2&gt;

&lt;p&gt;I’m now using &lt;code&gt;Task&amp;lt;T&amp;gt;&lt;/code&gt; to wrap up APM operations in Kayak. The &lt;code&gt;Task&lt;/code&gt; used to represent these operations is provided by a &lt;code&gt;TaskCompletionSource&amp;lt;T&amp;gt;&lt;/code&gt;, since in Kayak, every asynchronous operation may be performing asynchronous IO somewhere and therefore cannot be expressed as a single delegate.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public static partial class Extensions
{
    public static Task&amp;lt;int&amp;gt; ReadAsyncTpl(this Stream stream, byte[] buffer, int offset, int count)
    {
        var tcs = new TaskCompletionSource&amp;lt;int&amp;gt;();

        stream.BeginRead(buffer, offset, count, iasr =&amp;gt;
        {
            try
            {
                tcs.SetResult(stream.EndRead(iasr));
            }
            catch (Exception e)
            {
                tcs.SetException(e);
            }
        }, null);

        return tcs.Task;
    }
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So the first step in wrapping up an asynchronous operation with &lt;code&gt;Task&amp;lt;T&amp;gt;&lt;/code&gt; is to construct a &lt;code&gt;TaskCompletionSource&amp;lt;T&amp;gt;&lt;/code&gt;, whose task will ultimately be returned. Next, the wrapper method invokes the APM Begin method, and provides an &lt;code&gt;AsyncCallback&lt;/code&gt; whose implementation attempts to call the APM End method. The &lt;code&gt;AsyncCallback&lt;/code&gt; implementation calls &lt;code&gt;TaskCompletionSource&amp;lt;T&amp;gt;.SetResult&lt;/code&gt; with the return value of the End method, or, if the End method throws an exception, the &lt;code&gt;AsyncCallback&lt;/code&gt; calls &lt;code&gt;TaskCompletionSource&amp;lt;T&amp;gt;.SetException&lt;/code&gt; with the exception. When either &lt;code&gt;SetResult&lt;/code&gt; or &lt;code&gt;SetException&lt;/code&gt; are called, the &lt;code&gt;TaskCompletionSource&lt;/code&gt;’s special task completes. Any threads waiting on the &lt;code&gt;Result&lt;/code&gt; or &lt;code&gt;Exception&lt;/code&gt; properties of the task will continue, and any tasks to which the &lt;code&gt;TaskCompletionSource&lt;/code&gt;’s task is antecedent (i.e., those tasks created by calling &lt;code&gt;ContinueWith&lt;/code&gt; on the special &lt;code&gt;TaskCompletionSource&lt;/code&gt; task, which is returned from this wrapper method) will be executed.&lt;/p&gt;

&lt;p&gt;The TPL does actually provide an adapter from the APM pattern out of the box in the form of the method &lt;code&gt;TaskFactory.FromAsync&lt;/code&gt;. This method is heavily overloaded, but there are two basic variations:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public Task&amp;lt;TResult&amp;gt; FromAsync&amp;lt;TResult&amp;gt;(Func&amp;lt;AsyncCallback, object, IAsyncResult&amp;gt; beginMethod, Func&amp;lt;IAsyncResult, TResult&amp;gt; endMethod, object state);
public Task&amp;lt;TResult&amp;gt; FromAsync&amp;lt;TResult&amp;gt;(IAsyncResult asyncResult, Func&amp;lt;IAsyncResult, TResult&amp;gt; endMethod);&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Our example is equivalent to the first. The second however has a markedly different behavior. Notice that it takes &lt;code&gt;IAsyncResult&lt;/code&gt; as an argument—when using this overload, the calling code must invoke the APM Begin method to provide an &lt;code&gt;IAsyncResult&lt;/code&gt;, which means the &lt;code&gt;FromAsync&lt;/code&gt; method cannot provide an &lt;code&gt;AsyncCallback&lt;/code&gt; to the begin method. Therefore, it cannot be notified asynchronously when the APM operation is completed. Instead, it must wait on the &lt;code&gt;AsyncWaitHandle&lt;/code&gt; property of the &lt;code&gt;IAsyncResult&lt;/code&gt;. Beware when using overloads of &lt;code&gt;FromAsync&lt;/code&gt; which take &lt;code&gt;IAsyncResult&lt;/code&gt;—threads waiting is rarely the behavior you want! This subtle difference has very large implications for the flow of your program.&lt;/p&gt;

&lt;h2 id='what_else'&gt;What else?&lt;/h2&gt;

&lt;p&gt;An important difference between the TPL and the Reactive Framework versions of these wrapper method is that the APM Begin method is called when the TPL wrapper method is called, whereas the Rx version defers calling the APM Begin method until the observable gets a subscription. This has important ramifications for your programs which will be covered in a subsequent article.&lt;/p&gt;

&lt;p&gt;We seen how to invoke existing APM operations using both the Reactive Framework and the Task Parallel Library. The &lt;a href='https://gist.github.com/750990'&gt;source code for these examples&lt;/a&gt; is available in a Gist.&lt;/p&gt;

&lt;p&gt;In the &lt;a href='/a/async-with-rx-and-the-tpl-part-2'&gt;next article&lt;/a&gt;, we will implement new APM operations in terms of both the Reactive Framework and the Task Parallel Library.&lt;/p&gt;</content>
  </entry>
  
  <entry>
    <id>http://bvanderveen.com/a/clojure-served-this</id>
    <link type="text/html" rel="alternate" href="http://bvanderveen.com/a/clojure-served-this"/>
    <title>Clojure Served This.</title>
    <updated>2010-12-02T00:00:00-08:00</updated>
    <author>
      <name>Benjamin van der Veen</name>
      <uri>http://bvanderveen.com/</uri>
    </author>
    <content type="html">&lt;p&gt;For 8 years I have been on a quest for the perfect website generation tool. Along the way, I got side-tracked on the web server, and in the process of writing that, I felt myself bumping up against the limits of imperative programming languages. A few weeks ago, I woke up, went to a coffee shop, and realized that I didn’t want to think about web servers for a while, and that today would be the day I finally broke down and set about learning a functional programming language. I chose Clojure largely because it seemed all new-age and hip, and I’d heard Haskell might be too scary.&lt;/p&gt;

&lt;p&gt;I figured my first project would be to make that website generation tool, so today I’m happy to put up this here fancy new &lt;a href='http://clojure.org'&gt;Clojure&lt;/a&gt;-powered web site. Very impressed with Clojure overall. The language is fun to use and the community is top-notch. There are lots of fresh open source utilities for doing all sorts of cool things with Clojure. I’ve been very happy with &lt;a href='https://github.com/mmcgrana/ring'&gt;Ring&lt;/a&gt;, &lt;a href='http://compojure.org'&gt;Compojure&lt;/a&gt;, &lt;a href='https://github.com/cgrand/enlive'&gt;Enlive&lt;/a&gt;, &lt;a href='https://github.com/the-kenny/clojure-couchdb'&gt;clojure-couchdb&lt;/a&gt;, and, in particular, &lt;a href='https://github.com/technomancy/leiningen'&gt;Leiningen&lt;/a&gt;. Leiningen is probably the single most important Clojure tool. It’s an all-in-one project generating-running-testing-packaging-dependency-managing apparatus that makes starting new Clojure projects feel very light and inviting, and basically solves all of the problems related to maintaining a nice source tree. Just put the folder on GitHub and you&amp;#8217;ve got an open source project.&lt;/p&gt;

&lt;p&gt;By far the coolest hack involved in the making of this site is the &lt;a href='http://briancarper.net/blog/415/clojure-and-markdown-and-javascript-and-java-and'&gt;Markdown support, courtesy of Brian Carper&lt;/a&gt;, which uses &lt;a href='http://www.mozilla.org/rhino/'&gt;Rhino&lt;/a&gt;, Mozilla’s JavaScript interpreter for Java, to parse Markdown with the &lt;a href='http://attacklab.net/showdown/'&gt;Showdown.js&lt;/a&gt; Markdown parser. I found this solution particularly impressive; ease of interoperability with Java a huge win for Clojure. Say what you may about its LISPy roots, I find it to be extremely pragmatic.&lt;/p&gt;

&lt;p&gt;I’ve got a feeling this website tool is going to go somewhere.&lt;/p&gt;</content>
  </entry>
  
  <entry>
    <id>http://bvanderveen.com/a/dotnet-http-abstractions</id>
    <link type="text/html" rel="alternate" href="http://bvanderveen.com/a/dotnet-http-abstractions"/>
    <title>.NET HTTP Abstractions</title>
    <updated>2010-12-01T00:00:00-08:00</updated>
    <author>
      <name>Benjamin van der Veen</name>
      <uri>http://bvanderveen.com/</uri>
    </author>
    <content type="html">&lt;p&gt;&lt;em&gt;Note: OWIN has evolved significantly since this post. Please consult the &lt;a href='http://owin.org/'&gt;latest specification&lt;/a&gt;. – bvanderveen, 6 January 2011&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;For the past few days, I’ve been furiously posting on the &lt;a href='http://groups.google.com/group/net-http-abstractions'&gt;.NET HTTP Abstractions&lt;/a&gt; Google Group, where a .NET “clone” of &lt;a href='http://wsgi.org'&gt;WSGI&lt;/a&gt; is taking shape. Although I started working on &lt;a href='http://code.google.com/p/kayak/source/browse/Kayak.Core/Interfaces.cs?&amp;amp;amp;r=ea0ccf69c33bf76352719137fb2e7c9e0d77c900'&gt;something like WSGI&lt;/a&gt; toward the end of October, I had all but given up due to perceived lack of interest. Naturally, I was very excited to see the discussion on .NET HTTP Abstractions taking shape. &lt;a href='http://twitter.com/panesofglass'&gt;Ryan Riley&lt;/a&gt;, &lt;a href='http://twitter.com/serialseb'&gt;Sebastien Lambla&lt;/a&gt;, and myself have been particularly actively hashing out the details of a new specification we’re tentatively calling Open Web Interface for .NET, or OWIN. Ryan has been keeping &lt;a href='https://github.com/panesofglass/owin'&gt;a GitHub repo&lt;/a&gt; in sync with the discussion.&lt;/p&gt;

&lt;p&gt;The interface is really nice and minimal. A few details might change, but here’s where we are now:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public interface IApplication 
{
    IAsyncResult BeginInvoke(IRequest request, 
        AsyncCallback callback, object state);
    IResponse EndInvoke(IAsyncResult result);
}

public interface IRequest 
{
    IDictionary&amp;lt;string, object&amp;gt; Items { get; }
    
    string Method { get; }
    string Uri { get; }
    IDictionary&amp;lt;string, IEnumerable&amp;lt;string&amp;gt;&amp;gt; Headers { get; }
    
    IAsyncResult BeginReadBody(byte[] buffer, int offset, int count, 
        AsyncCallback callback, object state);
    int EndReadBody(IAsyncResult result);
}

public interface IResponse
{
    string Status { get; }
    IDictionary&amp;lt;string, IEnumerable&amp;lt;string&amp;gt;&amp;gt; Headers { get; }
    IEnumerable GetBody();
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Architecturally, this is a pretty significant departure from WSGI and Rack, due to the statically-typed nature of C#. Personally, I think it’s an improvement. The request is represented explicitly by a concise interface rather than a big dictionary, and gone are the ugly CGI-style variables required to access request headers. Response objects are simply returned by applications, which is a lot cleaner than WSGI&amp;#8217;s approach, which requires applications to call &lt;code&gt;start_response&lt;/code&gt; for the header data and the return an enumerable for the body data. Additionally, the whole thing is fully asynchronous, which we’re hoping will bolster performance, and saves on some of the awkward implementation consequences of WSGI surrounding threading and response buffering.&lt;/p&gt;

&lt;p&gt;A few quick points:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Environment-specific data (probably including base path, though this is still being discussed) is stored in &lt;code&gt;IRequest.Items&lt;/code&gt;.&lt;/li&gt;

&lt;li&gt;Header dictionary values are &lt;code&gt;IEnumerable&amp;lt;string&amp;gt;&lt;/code&gt; to support headers which may appear multiple times, such as &lt;code&gt;Set-Cookie&lt;/code&gt;.&lt;/li&gt;

&lt;li&gt;The &lt;code&gt;IEnumerable&lt;/code&gt; returned by &lt;code&gt;IResponse.GetBody()&lt;/code&gt; can contain different types of objects that host implementation can handle in different ways. None of these are set in stone, but for example, a &lt;code&gt;FileInfo&lt;/code&gt; might be served using the OS’ file-sending support, or a &lt;code&gt;Task&amp;lt;byte[]&amp;gt;&lt;/code&gt; might represent an asynchronously-fetched buffer of bytes. The possibilities here are exciting.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We’ve opted to keep the interface compatible all the way back to .NET 2.0, but it wouldn&amp;#8217;t be difficult to write extensions which would make it easy to use even in something as bleeding-edge as the &lt;a href='http://msdn.microsoft.com/en-us/vstudio/async.aspx'&gt;C# Async CTP&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;In the next few days, I hope to start drafting a more formal specification as we nail down remaining details. Many thanks to everyone who has contributed to the discussion! We’ve got a hell of a lot of firepower behind this thing and I’m very excited to see where it goes.&lt;/p&gt;</content>
  </entry>
  
 
</feed>
