<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Ad hoc Geek</title>
	<atom:link href="http://www.adhocgeek.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.adhocgeek.com</link>
	<description>Approaching geekery in an ad hoc and improvisational manner.</description>
	<lastBuildDate>Thu, 19 Aug 2010 15:26:56 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.5</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>An animated, Reuters-style ticker in WPF</title>
		<link>http://www.adhocgeek.com/2010/08/an-animated-reuters-style-ticker-in-wpf/</link>
		<comments>http://www.adhocgeek.com/2010/08/an-animated-reuters-style-ticker-in-wpf/#comments</comments>
		<pubDate>Thu, 19 Aug 2010 15:26:56 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Geek]]></category>
		<category><![CDATA[Animation]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.adhocgeek.com/?p=169</guid>
		<description><![CDATA[I just need to get this out onto the blog for posterity, as it were.
This is a class that derives from StackPanel and Implements a Reuters style ticker behaviour with its children. Anything you add to the Children collection will be ticked from left to right.
The only issue with it so far is that adding [...]]]></description>
			<content:encoded><![CDATA[<p>I just need to get this out onto the blog for posterity, as it were.</p>
<p>This is a class that derives from StackPanel and Implements a Reuters style ticker behaviour with its children. Anything you add to the Children collection will be ticked from left to right.</p>
<p>The only issue with it so far is that adding something to the Children collection makes it initially show up on the left (intialised to coordinates (0,0)). This could probably be solved by adding something like an AnimatedChildren collection, and only adding to the Children collection when the animation is initiated?</p>
<p>This is hugely untidy at the moment, but it does work after a fashion. I don&#8217;t in any way claim this is the right way to do this or that any of this is best practice <img src='http://www.adhocgeek.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> MyPanel <span style="color: #008000;">:</span> Canvas
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">private</span> Timer _timer <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Timer<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">500</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF;">public</span> MyPanel<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        LayoutUpdated <span style="color: #008000;">+=</span> <span style="color: #008000;">new</span> EventHandler<span style="color: #000000;">&#40;</span>MyPanel_LayoutUpdated<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        _timer.<span style="color: #0000FF;">Elapsed</span> <span style="color: #008000;">+=</span> <span style="color: #008000;">new</span> ElapsedEventHandler<span style="color: #000000;">&#40;</span>_timer_Elapsed<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        _timer.<span style="color: #0000FF;">Start</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">void</span>  _timer_Elapsed<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> sender, ElapsedEventArgs e<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        Dispatcher.<span style="color: #0000FF;">BeginInvoke</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> Func<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">object</span><span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>RunNextAnimation<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #FF0000;">object</span> RunNextAnimation<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>storyBoardQueue.<span style="color: #0000FF;">Count</span> <span style="color: #008000;">==</span> <span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span> <span style="color: #0600FF;">return</span> null<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">//check the last animated child</span>
        <span style="color: #008080; font-style: italic;">//if there is space, begin the animation of the next child.</span>
        <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>lastAnimated <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            var sb <span style="color: #008000;">=</span> storyBoardQueue.<span style="color: #0000FF;">Dequeue</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            var child <span style="color: #008000;">=</span> childQueue.<span style="color: #0000FF;">Dequeue</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            animatingChildQueue.<span style="color: #0000FF;">Enqueue</span><span style="color: #000000;">&#40;</span>child<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            animatingStoryBoardQueue.<span style="color: #0000FF;">Enqueue</span><span style="color: #000000;">&#40;</span>sb<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            sb.<span style="color: #0000FF;">Begin</span><span style="color: #000000;">&#40;</span>child, <span style="color: #0600FF;">true</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            lastAnimated <span style="color: #008000;">=</span> child<span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
        <span style="color: #0600FF;">else</span>
        <span style="color: #000000;">&#123;</span>
            var x <span style="color: #008000;">=</span> lastAnimated.<span style="color: #0000FF;">RenderTransform</span>.<span style="color: #0000FF;">Value</span>.<span style="color: #0000FF;">OffsetX</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>x <span style="color: #008000;">+</span> lastAnimated.<span style="color: #0000FF;">ActualWidth</span> <span style="color: #008000;">&lt;</span> ActualWidth <span style="color: #008000;">-</span> <span style="color: #FF0000;">10</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                var sb <span style="color: #008000;">=</span> storyBoardQueue.<span style="color: #0000FF;">Dequeue</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                var child <span style="color: #008000;">=</span> childQueue.<span style="color: #0000FF;">Dequeue</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                animatingChildQueue.<span style="color: #0000FF;">Enqueue</span><span style="color: #000000;">&#40;</span>child<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                animatingStoryBoardQueue.<span style="color: #0000FF;">Enqueue</span><span style="color: #000000;">&#40;</span>sb<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                sb.<span style="color: #0000FF;">Begin</span><span style="color: #000000;">&#40;</span>child, <span style="color: #0600FF;">true</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                lastAnimated <span style="color: #008000;">=</span> child<span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
        <span style="color: #0600FF;">return</span> null<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">void</span> MyPanel_LayoutUpdated<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> sender, EventArgs e<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">foreach</span><span style="color: #000000;">&#40;</span>var child <span style="color: #0600FF;">in</span> Children<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>animatedChildren.<span style="color: #0000FF;">Contains</span><span style="color: #000000;">&#40;</span>child <span style="color: #0600FF;">as</span> FrameworkElement<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> continue<span style="color: #008000;">;</span>
            AnimateChild<span style="color: #000000;">&#40;</span>child <span style="color: #0600FF;">as</span> FrameworkElement<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">//just to keep track of things we've created storyboards/translations for</span>
    <span style="color: #0600FF;">private</span> List<span style="color: #008000;">&lt;</span>FrameworkElement<span style="color: #008000;">&gt;</span> animatedChildren <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> List<span style="color: #008000;">&lt;</span>FrameworkElement<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">private</span> Queue<span style="color: #008000;">&lt;</span>Storyboard<span style="color: #008000;">&gt;</span> storyBoardQueue <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Queue<span style="color: #008000;">&lt;</span>Storyboard<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF;">private</span> Queue<span style="color: #008000;">&lt;</span>FrameworkElement<span style="color: #008000;">&gt;</span> childQueue <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Queue<span style="color: #008000;">&lt;</span>FrameworkElement<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">private</span> FrameworkElement lastAnimated<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">private</span> Queue<span style="color: #008000;">&lt;</span>Storyboard<span style="color: #008000;">&gt;</span> animatingStoryBoardQueue <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Queue<span style="color: #008000;">&lt;</span>Storyboard<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF;">private</span> Queue<span style="color: #008000;">&lt;</span>FrameworkElement<span style="color: #008000;">&gt;</span> animatingChildQueue <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Queue<span style="color: #008000;">&lt;</span>FrameworkElement<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> AnimateChild<span style="color: #000000;">&#40;</span>FrameworkElement child<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>child <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span> return<span style="color: #008000;">;</span>
&nbsp;
        NameScope.<span style="color: #0000FF;">SetNameScope</span><span style="color: #000000;">&#40;</span>child, <span style="color: #008000;">new</span> NameScope<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        var anim <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> DoubleAnimation
                   <span style="color: #000000;">&#123;</span>
                       From <span style="color: #008000;">=</span> ActualWidth,
                       To <span style="color: #008000;">=</span> <span style="color: #008000;">-</span><span style="color: #FF0000;">100</span>,
                       By <span style="color: #008000;">=</span> <span style="color: #008000;">-</span><span style="color: #FF0000;">5</span>,
                       Duration <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Duration<span style="color: #000000;">&#40;</span>TimeSpan.<span style="color: #0000FF;">FromSeconds</span><span style="color: #000000;">&#40;</span>ActualWidth<span style="color: #008000;">/</span><span style="color: #FF0000;">40</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>,
                   <span style="color: #000000;">&#125;</span><span style="color: #008000;">;</span>
&nbsp;
        var transform <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> TranslateTransform<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        child.<span style="color: #0000FF;">RegisterName</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;translate&quot;</span>, transform<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        child.<span style="color: #0000FF;">RenderTransform</span> <span style="color: #008000;">=</span> transform<span style="color: #008000;">;</span>
        Storyboard.<span style="color: #0000FF;">SetTargetName</span><span style="color: #000000;">&#40;</span>anim, <span style="color: #666666;">&quot;translate&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        Storyboard.<span style="color: #0000FF;">SetTargetProperty</span><span style="color: #000000;">&#40;</span>anim, <span style="color: #008000;">new</span> PropertyPath<span style="color: #000000;">&#40;</span>TranslateTransform.<span style="color: #0000FF;">XProperty</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        var myStoryBoard <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Storyboard<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        myStoryBoard.<span style="color: #0000FF;">Children</span>.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>anim<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        myStoryBoard.<span style="color: #0000FF;">Completed</span> <span style="color: #008000;">+=</span> myStoryBoard_Completed<span style="color: #008000;">;</span>
        storyBoardQueue.<span style="color: #0000FF;">Enqueue</span><span style="color: #000000;">&#40;</span>myStoryBoard<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        childQueue.<span style="color: #0000FF;">Enqueue</span><span style="color: #000000;">&#40;</span>child<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        animatedChildren.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>child<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">void</span>  myStoryBoard_Completed<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> sender, EventArgs e<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        storyBoardQueue.<span style="color: #0000FF;">Enqueue</span><span style="color: #000000;">&#40;</span>animatingStoryBoardQueue.<span style="color: #0000FF;">Dequeue</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        childQueue.<span style="color: #0000FF;">Enqueue</span><span style="color: #000000;">&#40;</span>animatingChildQueue.<span style="color: #0000FF;">Dequeue</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://www.adhocgeek.com/2010/08/an-animated-reuters-style-ticker-in-wpf/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Uploading large files with ASP.NET</title>
		<link>http://www.adhocgeek.com/2009/10/uploading-large-files-with-asp-net/</link>
		<comments>http://www.adhocgeek.com/2009/10/uploading-large-files-with-asp-net/#comments</comments>
		<pubDate>Tue, 20 Oct 2009 11:29:49 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Geek]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[byte stream processing]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[IHttpModule]]></category>
		<category><![CDATA[Large File Uploads]]></category>

		<guid isPermaLink="false">http://www.adhocgeek.com/?p=158</guid>
		<description><![CDATA[I&#8217;ve recently had a need for users of an intranet application to upload comparatively large text files (1-200MB) to a web server. There are only a couple of ways I can think of to get around the limits imposed by IIS and ASP.NET without writing code : train the users to upload smaller files which [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve recently had a need for users of an intranet application to upload comparatively large text files (1-200MB) to a web server. There are only a couple of ways I can think of to get around the limits imposed by IIS and ASP.NET without writing code : train the users to upload smaller files which could be concatenated at the server, or allow the users to &#8220;upload&#8221; from a network share which the server has access to. These are obviously inelegant solutions, and after a little research I&#8217;ve found that the necessary code to enable large uploads yourself is surprisingly easy to write.</p>
<p><a href="http://weblogs.asp.net/jgalloway/default.aspx">Jon Galloway</a> has written a useful article which gives a more complete and eloquent view of the ASP.NET large file upload problem than I have time for <a href="http://weblogs.asp.net/jgalloway/archive/2008/01/08/large-file-uploads-in-asp-net.aspx">here</a>. Particularly of interest is the discussion he links to, titled <a href="http://forums.asp.net/t/55127.aspx?PageIndex=1">&#8220;HttpHandler or HttpModule for file upload, large files, progress indicator?&#8221;</a>. I&#8217;ve adapted or rewritten some of the suggested code from there for my solution. I&#8217;m particularly indebted to <a href="http://forums.asp.net/members/TravisWhidden.aspx">Travis Whidden</a> whose code is much more complete than mine (it handles multiple files, for a start). Part of the reason I ended up rewriting it is because I didn&#8217;t think this solution handled a particular edge case, but I also needed to understand what it was doing, and the best way for me to do that was rewrite from scratch (this took me about a day of thinking, poking around and testing &#8211; I don&#8217;t claim to be a fast learner <img src='http://www.adhocgeek.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>
<p>Essentially the code consists of two classes, UploadModule and RequestProcessor, along with some minor changes in the web.config file :</p>
<h3>UploadModule</h3>
<p>In order to intercept the HttpRequest and deal with it in a stream-wise fashion, we have to implement an IHttpModule :</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Diagnostics</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Text</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Web</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Reflection</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF;">namespace</span> MyIntranetSite
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> UploadModule <span style="color: #008000;">:</span> IHttpModule
    <span style="color: #000000;">&#123;</span>
        <span style="color: #008080;">#region IHttpModule Members</span>
&nbsp;
        <span style="color: #0600FF;">void</span> IHttpModule.<span style="color: #0000FF;">Dispose</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">void</span> IHttpModule.<span style="color: #0000FF;">Init</span><span style="color: #000000;">&#40;</span>HttpApplication context<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            context.<span style="color: #0000FF;">BeginRequest</span> <span style="color: #008000;">+=</span> <span style="color: #008000;">new</span> EventHandler<span style="color: #000000;">&#40;</span>context_BeginRequest<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">void</span>  context_BeginRequest<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> sender, EventArgs e<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            HttpApplication application <span style="color: #008000;">=</span> <span style="color: #000000;">&#40;</span>HttpApplication<span style="color: #000000;">&#41;</span> sender<span style="color: #008000;">;</span>
            HttpContext context <span style="color: #008000;">=</span> application.<span style="color: #0000FF;">Context</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>context.<span style="color: #0000FF;">Request</span>.<span style="color: #0000FF;">ContentType</span>.<span style="color: #0000FF;">IndexOf</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;multipart/form-data&quot;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">==</span> <span style="color: #008000;">-</span><span style="color: #FF0000;">1</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #008080; font-style: italic;">//Not our bag, baby.</span>
                return<span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
&nbsp;
            <span style="color: #0600FF;">try</span>
            <span style="color: #000000;">&#123;</span>
                HttpWorkerRequest workerRequest <span style="color: #008000;">=</span> <span style="color: #000000;">&#40;</span>HttpWorkerRequest<span style="color: #000000;">&#41;</span> context.<span style="color: #0000FF;">GetType</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">GetProperty</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;WorkerRequest&quot;</span>, BindingFlags.<span style="color: #0000FF;">Instance</span> <span style="color: #008000;">|</span> BindingFlags.<span style="color: #0000FF;">NonPublic</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">GetValue</span><span style="color: #000000;">&#40;</span>context, <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>workerRequest.<span style="color: #0000FF;">HasEntityBody</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
                <span style="color: #000000;">&#123;</span>
                    <span style="color: #FF0000;">long</span> defaultBuffer <span style="color: #008000;">=</span> <span style="color: #FF0000;">500000</span><span style="color: #008000;">;</span> 
                    <span style="color: #FF0000;">long</span> contentLength <span style="color: #008000;">=</span> <span style="color: #FF0000;">long</span>.<span style="color: #0000FF;">Parse</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span>workerRequest.<span style="color: #0000FF;">GetKnownRequestHeader</span><span style="color: #000000;">&#40;</span>HttpWorkerRequest.<span style="color: #0000FF;">HeaderContentLength</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
                    <span style="color: #FF0000;">byte</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> preloadedBufferData <span style="color: #008000;">=</span> workerRequest.<span style="color: #0000FF;">GetPreloadedEntityBody</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                    RequestProcessor rp <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> RequestProcessor<span style="color: #000000;">&#40;</span>contentLength<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                    rp.<span style="color: #0000FF;">ReadBuffer</span><span style="color: #000000;">&#40;</span><span style="color: #0600FF;">ref</span> preloadedBufferData<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
                    <span style="color: #FF0000;">long</span> remaining <span style="color: #008000;">=</span> contentLength <span style="color: #008000;">-</span> preloadedBufferData.<span style="color: #0000FF;">Length</span><span style="color: #008000;">;</span>
                    <span style="color: #FF0000;">byte</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> bufferData<span style="color: #008000;">;</span>
                    <span style="color: #0600FF;">while</span> <span style="color: #000000;">&#40;</span>remaining <span style="color: #008000;">&gt;</span> <span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span>
                    <span style="color: #000000;">&#123;</span>
                        bufferData <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #FF0000;">byte</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#40;</span>remaining <span style="color: #008000;">&gt;</span> defaultBuffer<span style="color: #000000;">&#41;</span><span style="color: #008000;">?</span> defaultBuffer <span style="color: #008000;">:</span> remaining<span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span>
                        remaining <span style="color: #008000;">-=</span> bufferData.<span style="color: #0000FF;">Length</span><span style="color: #008000;">;</span>
                        workerRequest.<span style="color: #0000FF;">ReadEntityBody</span><span style="color: #000000;">&#40;</span>bufferData, bufferData.<span style="color: #0000FF;">Length</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                        rp.<span style="color: #0000FF;">ReadBuffer</span><span style="color: #000000;">&#40;</span><span style="color: #0600FF;">ref</span> bufferData<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                    <span style="color: #000000;">&#125;</span>
                <span style="color: #000000;">&#125;</span>
            <span style="color: #000000;">&#125;</span>
            <span style="color: #0600FF;">catch</span><span style="color: #000000;">&#40;</span>Exception ex<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                EventLog.<span style="color: #0000FF;">WriteEntry</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Custom ASP.NET Upload Module&quot;</span>, ex.<span style="color: #0000FF;">Message</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
&nbsp;
            context.<span style="color: #0000FF;">Response</span>.<span style="color: #0000FF;">Redirect</span><span style="color: #000000;">&#40;</span>context.<span style="color: #0000FF;">Request</span>.<span style="color: #0000FF;">RawUrl</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080;">#endregion</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>This handles ALL &#8220;multipart/form-data&#8221; requests at the moment. You would probably want to check the url of the request and match it against a list of expected pages, otherwise all of your web requests (that is, every postback) would get processed by this module, and much of your code would be bypassed!</p>
<h3>RequestProcessor</h3>
<p>This class takes a series of byte array buffers and parses them for a start and end pattern. Hopefully, I&#8217;ve commented my code well enough for it to be read and understood. However, I should say that this only deals with single file uploads at the moment and expects to be able to write to &#8220;C:\temp\&#8221;. It would be possible to improve the code to handle multiple files and making the upload directory configurable would be fairly trivial, but I think it&#8217;s more useful as a learning tool if I keep it simple for now.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Diagnostics</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Collections.Generic</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.IO</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Text</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF;">namespace</span> MyIntranetSite
<span style="color: #000000;">&#123;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">//</span>
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// Takes byte[] chunks from an HTTP request and processes them looking for (currently) the first file.</span>
    <span style="color: #008080; font-style: italic;">/// Each file will be wrapped by the lines :</span>
    <span style="color: #008080; font-style: italic;">/// (start) &quot;Content-Type: [some content type]\r\n&quot;</span>
    <span style="color: #008080; font-style: italic;">/// (end) &quot;-----------------------------[a form post ID]\r\n\r\n&quot; </span>
    <span style="color: #008080; font-style: italic;">///       (that's 29 &quot;-&quot;s followed by a number, followed by 2 * carriage return + newline</span>
    <span style="color: #008080; font-style: italic;">/// </span>
    <span style="color: #008080; font-style: italic;">/// Problems arise because the start and end patterns could span two buffers.</span>
    <span style="color: #008080; font-style: italic;">/// This means we can't write from the latest buffer - we have to always be writing from the previous buffer,</span>
    <span style="color: #008080; font-style: italic;">/// since we can never know if the latest buffer (assuming there are more bytes to read) contains the start of the</span>
    <span style="color: #008080; font-style: italic;">/// end pattern, but not all of it.</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> RequestProcessor <span style="color: #008000;">:</span> IDisposable 
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">long</span> Length <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> <span style="color: #0600FF;">private</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">long</span> BytesRead <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> <span style="color: #0600FF;">private</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
        <span style="color: #0600FF;">public</span> List<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span><span style="color: #008000;">&gt;</span> FinishedFiles <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> List<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span><span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #0600FF;">private</span> BufferChunk previous<span style="color: #008000;">;</span>
        <span style="color: #0600FF;">private</span> <span style="color: #FF0000;">bool</span> _startFound <span style="color: #008000;">=</span> false<span style="color: #008000;">;</span>
        <span style="color: #0600FF;">private</span> <span style="color: #FF0000;">bool</span> _endFound <span style="color: #008000;">=</span> false<span style="color: #008000;">;</span>
        <span style="color: #0600FF;">private</span> List<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">byte</span><span style="color: #008000;">&gt;</span> startPatternBegin<span style="color: #008000;">;</span>
        <span style="color: #0600FF;">private</span> List<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">byte</span><span style="color: #008000;">&gt;</span> startPatternEnd<span style="color: #008000;">;</span>
        <span style="color: #0600FF;">private</span> List<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">byte</span><span style="color: #008000;">&gt;</span> endPattern<span style="color: #008000;">;</span>
        <span style="color: #0600FF;">private</span> FileStream currentFileStream<span style="color: #008000;">;</span>
        <span style="color: #0600FF;">private</span> <span style="color: #FF0000;">string</span> currentFileName <span style="color: #008000;">=</span> Guid.<span style="color: #0000FF;">NewGuid</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;.bin&quot;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> RequestProcessor<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">long</span> length<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            Length <span style="color: #008000;">=</span> length<span style="color: #008000;">;</span>
            BytesRead <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
            startPatternBegin <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> List<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">byte</span><span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>Encoding.<span style="color: #0000FF;">UTF8</span>.<span style="color: #0000FF;">GetBytes</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Content-Type: &quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            startPatternEnd <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> List<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">byte</span><span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>Encoding.<span style="color: #0000FF;">UTF8</span>.<span style="color: #0000FF;">GetBytes</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;<span style="color: #008080; font-weight: bold;">\r</span><span style="color: #008080; font-weight: bold;">\n</span><span style="color: #008080; font-weight: bold;">\r</span><span style="color: #008080; font-weight: bold;">\n</span>&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> ReadBuffer<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">ref</span> <span style="color: #FF0000;">byte</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> buffer<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_endFound<span style="color: #000000;">&#41;</span> return<span style="color: #008000;">;</span>
&nbsp;
            BufferChunk current <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> BufferChunk<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">ref</span> buffer<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>previous <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #008080; font-style: italic;">//first buffer chunk</span>
                <span style="color: #008080; font-style: italic;">//the first line of this will give the form content separator, which is also the endPattern</span>
                <span style="color: #FF0000;">int</span> i <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
                endPattern <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> List<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">byte</span><span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                <span style="color: #0600FF;">while</span> <span style="color: #000000;">&#40;</span>current.<span style="color: #0000FF;">Data</span><span style="color: #000000;">&#91;</span>i<span style="color: #000000;">&#93;</span> <span style="color: #008000;">!=</span> Encoding.<span style="color: #0000FF;">UTF8</span>.<span style="color: #0000FF;">GetBytes</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;<span style="color: #008080; font-weight: bold;">\r</span>&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#91;</span><span style="color: #FF0000;">0</span><span style="color: #000000;">&#93;</span><span style="color: #000000;">&#41;</span>
                <span style="color: #000000;">&#123;</span>
                    endPattern.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>current.<span style="color: #0000FF;">Data</span><span style="color: #000000;">&#91;</span>i<span style="color: #000000;">&#93;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                    i<span style="color: #008000;">++;</span>
                <span style="color: #000000;">&#125;</span>
            <span style="color: #000000;">&#125;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">//Merge the previous and current buffers</span>
            List<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">byte</span><span style="color: #008000;">&gt;</span> mergedBuffers <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> List<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">byte</span><span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>previous <span style="color: #008000;">!=</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span> mergedBuffers.<span style="color: #0000FF;">AddRange</span><span style="color: #000000;">&#40;</span>previous.<span style="color: #0000FF;">Data</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            mergedBuffers.<span style="color: #0000FF;">AddRange</span><span style="color: #000000;">&#40;</span>current.<span style="color: #0000FF;">Data</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #008000;">!</span>_startFound<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #008080; font-style: italic;">//Look for start pattern in the current buffer.</span>
                <span style="color: #008080; font-style: italic;">//It could span this buffer and the one before (in which case the start point is in THIS buffer)</span>
                <span style="color: #008080; font-style: italic;">//or it could span this buffer and the next (in which case the start point is in the NEXT buffer)</span>
                <span style="color: #008080; font-style: italic;">//The latter case has to be checked when the next buffer comes in.</span>
&nbsp;
                <span style="color: #FF0000;">int</span> startBegin<span style="color: #008000;">;</span>
                <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span>startBegin <span style="color: #008000;">=</span> FindBytePattern<span style="color: #000000;">&#40;</span>mergedBuffers, startPatternBegin, <span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">!=</span> <span style="color: #008000;">-</span><span style="color: #FF0000;">1</span><span style="color: #000000;">&#41;</span>
                <span style="color: #000000;">&#123;</span>
                    <span style="color: #008080; font-style: italic;">//found a content-type declaration, look for the end of that line :</span>
                    <span style="color: #FF0000;">int</span> startEnd<span style="color: #008000;">;</span>
                    <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span>startEnd <span style="color: #008000;">=</span> FindBytePattern<span style="color: #000000;">&#40;</span>mergedBuffers, startPatternEnd, startBegin <span style="color: #008000;">+</span> startPatternBegin.<span style="color: #0000FF;">Count</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">!=</span> <span style="color: #008000;">-</span><span style="color: #FF0000;">1</span><span style="color: #000000;">&#41;</span>
                    <span style="color: #000000;">&#123;</span>
                        <span style="color: #008080; font-style: italic;">//found the end of the line</span>
                        <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>startEnd <span style="color: #008000;">+</span> startPatternEnd.<span style="color: #0000FF;">Count</span> <span style="color: #008000;">&lt;</span> mergedBuffers.<span style="color: #0000FF;">Count</span> <span style="color: #008000;">-</span> <span style="color: #FF0000;">1</span><span style="color: #000000;">&#41;</span>
                        <span style="color: #000000;">&#123;</span>
                            <span style="color: #FF0000;">int</span> startByte <span style="color: #008000;">=</span> startEnd <span style="color: #008000;">+</span> startPatternEnd.<span style="color: #0000FF;">Count</span><span style="color: #008000;">;</span>
                            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>previous <span style="color: #008000;">!=</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
                            <span style="color: #000000;">&#123;</span>
                                current.<span style="color: #0000FF;">Start</span> <span style="color: #008000;">=</span> startByte <span style="color: #008000;">-</span> previous.<span style="color: #0000FF;">Data</span>.<span style="color: #0000FF;">Count</span><span style="color: #008000;">;</span>
                            <span style="color: #000000;">&#125;</span>
                            <span style="color: #0600FF;">else</span>
                            <span style="color: #000000;">&#123;</span>
                                current.<span style="color: #0000FF;">Start</span> <span style="color: #008000;">=</span> startByte<span style="color: #008000;">;</span>
                            <span style="color: #000000;">&#125;</span>
                            _startFound <span style="color: #008000;">=</span> true<span style="color: #008000;">;</span>
                        <span style="color: #000000;">&#125;</span>
                        <span style="color: #008080; font-style: italic;">// else the start byte is in the next buffer.</span>
                    <span style="color: #000000;">&#125;</span>
                <span style="color: #000000;">&#125;</span>
&nbsp;
                <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #008000;">!</span>_startFound<span style="color: #000000;">&#41;</span> current.<span style="color: #0000FF;">Start</span> <span style="color: #008000;">=</span> current.<span style="color: #0000FF;">Data</span>.<span style="color: #0000FF;">Count</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
&nbsp;
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_startFound <span style="color: #008000;">&amp;&amp;</span> <span style="color: #008000;">!</span>_endFound<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #008080; font-style: italic;">//Look for the end pattern in the current buffer</span>
                <span style="color: #008080; font-style: italic;">//As with the start it could span beginning (in which case the last byte is in the PREVIOUS buffer)</span>
                <span style="color: #008080; font-style: italic;">//Or it could span the end (in which case the last byte is in THIS buffer)</span>
                <span style="color: #008080; font-style: italic;">//The latter case has to be checked when the next buffer comes in.</span>
&nbsp;
                <span style="color: #FF0000;">int</span> endBegin<span style="color: #008000;">;</span>
                <span style="color: #FF0000;">int</span> searchStart <span style="color: #008000;">=</span> previous <span style="color: #008000;">!=</span> <span style="color: #0600FF;">null</span><span style="color: #008000;">?</span> previous.<span style="color: #0000FF;">Start</span> <span style="color: #008000;">:</span> current.<span style="color: #0000FF;">Start</span><span style="color: #008000;">;</span>
                <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span>endBegin <span style="color: #008000;">=</span> FindBytePattern<span style="color: #000000;">&#40;</span>mergedBuffers, endPattern, searchStart<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">!=</span> <span style="color: #008000;">-</span><span style="color: #FF0000;">1</span><span style="color: #000000;">&#41;</span>
                <span style="color: #000000;">&#123;</span>
                    <span style="color: #FF0000;">int</span> endByte <span style="color: #008000;">=</span> endBegin <span style="color: #008000;">-</span> <span style="color: #FF0000;">1</span><span style="color: #008000;">;</span>
                    <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>previous <span style="color: #008000;">!=</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
                    <span style="color: #000000;">&#123;</span>
                        <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>endByte <span style="color: #008000;">&lt;</span> previous.<span style="color: #0000FF;">Data</span>.<span style="color: #0000FF;">Count</span><span style="color: #000000;">&#41;</span>
                            previous.<span style="color: #0000FF;">End</span> <span style="color: #008000;">=</span> endByte<span style="color: #008000;">;</span>
                        <span style="color: #0600FF;">else</span>
                            current.<span style="color: #0000FF;">End</span> <span style="color: #008000;">=</span> endByte <span style="color: #008000;">-</span> previous.<span style="color: #0000FF;">Data</span>.<span style="color: #0000FF;">Count</span><span style="color: #008000;">;</span>
                    <span style="color: #000000;">&#125;</span>
                    <span style="color: #0600FF;">else</span>
                    <span style="color: #000000;">&#123;</span>
                        current.<span style="color: #0000FF;">End</span> <span style="color: #008000;">=</span> endByte<span style="color: #008000;">;</span>
                    <span style="color: #000000;">&#125;</span>
                    _endFound <span style="color: #008000;">=</span> true<span style="color: #008000;">;</span>
                <span style="color: #000000;">&#125;</span>
                <span style="color: #008080; font-style: italic;">// else the end byte is in the next buffer.</span>
&nbsp;
                <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #008000;">!</span>_endFound <span style="color: #008000;">&amp;&amp;</span> previous <span style="color: #008000;">!=</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span> previous.<span style="color: #0000FF;">End</span> <span style="color: #008000;">=</span> previous.<span style="color: #0000FF;">Data</span>.<span style="color: #0000FF;">Count</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
            BytesRead <span style="color: #008000;">+=</span> current.<span style="color: #0000FF;">Data</span>.<span style="color: #0000FF;">Count</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">//FILE CREATION</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>previous <span style="color: #008000;">!=</span> <span style="color: #0600FF;">null</span> <span style="color: #008000;">&amp;&amp;</span> _startFound <span style="color: #008000;">&amp;&amp;</span> previous.<span style="color: #0000FF;">WriteBytes</span> <span style="color: #008000;">&gt;</span> <span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #008080; font-style: italic;">//Write out the previous buffer from Start to End</span>
                <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>currentFileStream <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
                <span style="color: #000000;">&#123;</span>
                    currentFileStream <span style="color: #008000;">=</span> File.<span style="color: #0000FF;">OpenWrite</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">@&quot;C:\temp\&quot;</span> <span style="color: #008000;">+</span> currentFileName<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                <span style="color: #000000;">&#125;</span>
                currentFileStream.<span style="color: #0000FF;">Write</span><span style="color: #000000;">&#40;</span>previous.<span style="color: #0000FF;">Data</span>.<span style="color: #0000FF;">ToArray</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>, previous.<span style="color: #0000FF;">Start</span>, previous.<span style="color: #0000FF;">WriteBytes</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
&nbsp;
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_startFound <span style="color: #008000;">&amp;&amp;</span> _endFound <span style="color: #008000;">||</span> BytesRead <span style="color: #008000;">==</span> Length<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #008080; font-style: italic;">//Write out the current buffer from Start to End</span>
                <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>currentFileStream <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
                <span style="color: #000000;">&#123;</span>
                    currentFileStream <span style="color: #008000;">=</span> File.<span style="color: #0000FF;">OpenWrite</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">@&quot;C:\temp\&quot;</span> <span style="color: #008000;">+</span> currentFileName<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                <span style="color: #000000;">&#125;</span>
                currentFileStream.<span style="color: #0000FF;">Write</span><span style="color: #000000;">&#40;</span>current.<span style="color: #0000FF;">Data</span>.<span style="color: #0000FF;">ToArray</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>, current.<span style="color: #0000FF;">Start</span>, current.<span style="color: #0000FF;">WriteBytes</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                currentFileStream.<span style="color: #0000FF;">Close</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                currentFileStream.<span style="color: #0000FF;">Dispose</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
&nbsp;
            previous <span style="color: #008000;">=</span> current<span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">int</span> FindBytePattern<span style="color: #000000;">&#40;</span>List<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">byte</span><span style="color: #008000;">&gt;</span> container, List<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">byte</span><span style="color: #008000;">&gt;</span> pattern, <span style="color: #FF0000;">int</span> startIndex<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #FF0000;">int</span> i, position<span style="color: #008000;">;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>pattern.<span style="color: #0000FF;">Count</span> <span style="color: #008000;">&gt;</span> container.<span style="color: #0000FF;">Count</span> <span style="color: #008000;">-</span> startIndex<span style="color: #000000;">&#41;</span> <span style="color: #0600FF;">return</span> <span style="color: #008000;">-</span><span style="color: #FF0000;">1</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span>position <span style="color: #008000;">=</span> startIndex<span style="color: #008000;">;</span> position <span style="color: #008000;">&lt;</span> container.<span style="color: #0000FF;">Count</span><span style="color: #008000;">;</span> position<span style="color: #008000;">++</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>container<span style="color: #000000;">&#91;</span>position<span style="color: #000000;">&#93;</span> <span style="color: #008000;">==</span> pattern<span style="color: #000000;">&#91;</span><span style="color: #FF0000;">0</span><span style="color: #000000;">&#93;</span><span style="color: #000000;">&#41;</span>
                <span style="color: #000000;">&#123;</span>
                    <span style="color: #0600FF;">for</span><span style="color: #000000;">&#40;</span>i <span style="color: #008000;">=</span> <span style="color: #FF0000;">1</span><span style="color: #008000;">;</span> i <span style="color: #008000;">&lt;</span> pattern.<span style="color: #0000FF;">Count</span><span style="color: #008000;">;</span> i<span style="color: #008000;">++</span><span style="color: #000000;">&#41;</span>
                    <span style="color: #000000;">&#123;</span>
                        <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>position <span style="color: #008000;">+</span> i <span style="color: #008000;">==</span> container.<span style="color: #0000FF;">Count</span> <span style="color: #008000;">||</span> pattern<span style="color: #000000;">&#91;</span>i<span style="color: #000000;">&#93;</span> <span style="color: #008000;">!=</span> container<span style="color: #000000;">&#91;</span>position <span style="color: #008000;">+</span> i<span style="color: #000000;">&#93;</span><span style="color: #000000;">&#41;</span> break<span style="color: #008000;">;</span>
                    <span style="color: #000000;">&#125;</span>
                    <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>i <span style="color: #008000;">==</span> pattern.<span style="color: #0000FF;">Count</span><span style="color: #000000;">&#41;</span> <span style="color: #0600FF;">return</span> position<span style="color: #008000;">;</span>
                <span style="color: #000000;">&#125;</span>
            <span style="color: #000000;">&#125;</span>
&nbsp;
            <span style="color: #0600FF;">return</span> <span style="color: #008000;">-</span><span style="color: #FF0000;">1</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080;">#region IDisposable Members</span>
&nbsp;
        <span style="color: #0600FF;">void</span> IDisposable.<span style="color: #0000FF;">Dispose</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>currentFileStream <span style="color: #008000;">!=</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                currentFileStream.<span style="color: #0000FF;">Close</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                currentFileStream.<span style="color: #0000FF;">Dispose</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080;">#endregion</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> BufferChunk
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">public</span> List<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">byte</span><span style="color: #008000;">&gt;</span> Data<span style="color: #008000;">;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> Start<span style="color: #008000;">;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> End<span style="color: #008000;">;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> WriteBytes <span style="color: #000000;">&#123;</span> get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> End <span style="color: #008000;">-</span> Start<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span> <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> BufferChunk<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">ref</span> <span style="color: #FF0000;">byte</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> buffer<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            Data <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> List<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">byte</span><span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>buffer<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            Start <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
            End <span style="color: #008000;">=</span> Data.<span style="color: #0000FF;">Count</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>These files can sit within your web project or in a separate assembly if you want. Personally I&#8217;d rather have them sitting with the web project since that makes them more straightforward to debug and more obvious as to where they belong.</p>
<h3>Web.Config changes</h3>
<p>This is almost laughably trivial :</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;httpModules<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;add</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;UploadModule&quot;</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;MyIntranetSite.UploadModule&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/httpModules<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>And that&#8217;s it! There&#8217;s obviously a lot more that could be done (such as the progress indicator Travis incorporated), but this seems like a decent start to me.</p>
<p>Ideally, ASP.NET 3.0(?) and IIS 7.0 would address this kind of problem once and for all, but I&#8217;m not holding my breath. I also suspect a lot of businesses will remain on IE6.0, IIS 5/6 and ASP.NET 2.0 for another few years, so this approach will remain relevant a little while longer.</p>
<h3>Update (a warning)</h3>
<p>It&#8217;s entirely possible that the parser will bomb out with some kind of error on occasion. If this happens when the number of bytes left to process is greater than the ASP.NET maxRequestLength (or the IIS request length) then the site will (seemingly) silently fail and you&#8217;ll get the dreaded &#8220;Connection was reset&#8221; error page!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.adhocgeek.com/2009/10/uploading-large-files-with-asp-net/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Enumerating Users with LDAP</title>
		<link>http://www.adhocgeek.com/2009/10/enumerating-users-with-ldap/</link>
		<comments>http://www.adhocgeek.com/2009/10/enumerating-users-with-ldap/#comments</comments>
		<pubDate>Fri, 09 Oct 2009 10:25:20 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Geek]]></category>
		<category><![CDATA[Active Directory]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[LDAP]]></category>
		<category><![CDATA[Starting Blocks]]></category>

		<guid isPermaLink="false">http://www.adhocgeek.com/?p=153</guid>
		<description><![CDATA[I&#8217;m sure there are lots of other tutorials, blog posts and actual documentation telling you how to do this, and this probably goes for a lot of the things I&#8217;ll post here, but this blog isn&#8217;t necessarily for other people. I&#8217;m beginning to realise that a lot of the code I post here is simply [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m sure there are lots of other tutorials, blog posts and actual documentation telling you how to do this, and this probably goes for a lot of the things I&#8217;ll post here, but this blog isn&#8217;t necessarily for other people. I&#8217;m beginning to realise that a lot of the code I post here is simply for my own benefit, and if it happens to coincide with the needs of someone else, that&#8217;s fine.</p>
<p>Anyway, I&#8217;m currently on-site again so I don&#8217;t have a lot of time to play and post snippets, but the LDAP code I was toying with this morning struck me as something I might want to revisit at some point in the future. It&#8217;s not exactly rocket science, but I often find that a short piece of working code can be an essential starting point when embarking on the understanding of a complex new library (for example, knowing that the technology is called LDAP and even understanding what that means, doesn&#8217;t tell you which .NET assemblies you should be investigating).</p>
<p>The following code is a C# console application which simply enumerates the users that the current account has access to know about in the given domain. An administrator running this should see everyone, but a lowly user with minimal rights may see only themselves (or possibly nothing at all!).</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Collections.Generic</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.DirectoryServices</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF;">namespace</span> ADTest
<span style="color: #000000;">&#123;</span>
  <span style="color: #FF0000;">class</span> Program
  <span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Main<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> args<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
      DirectoryEntry entry <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> DirectoryEntry<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;LDAP://FM&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
      DirectorySearcher search <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> DirectorySearcher<span style="color: #000000;">&#40;</span>entry<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span> 
      search.<span style="color: #0000FF;">Filter</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;(&amp;(objectClass=user)(objectCategory=person))&quot;</span><span style="color: #008000;">;</span>
      SearchResultCollection src <span style="color: #008000;">=</span> search.<span style="color: #0000FF;">FindAll</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
      Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span>src.<span style="color: #0000FF;">Count</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
      <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>SearchResult sr <span style="color: #0600FF;">in</span> src<span style="color: #000000;">&#41;</span>
      <span style="color: #000000;">&#123;</span>
        List<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span><span style="color: #008000;">&gt;</span> props <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> List<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span><span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> propName <span style="color: #0600FF;">in</span> sr.<span style="color: #0000FF;">Properties</span>.<span style="color: #0000FF;">PropertyNames</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
          props.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>propName <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;=[&quot;</span> <span style="color: #008000;">+</span> sr.<span style="color: #0000FF;">Properties</span><span style="color: #000000;">&#91;</span>propName<span style="color: #000000;">&#93;</span> <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;]&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">String</span>.<span style="color: #0000FF;">Join</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;, &quot;</span>, props.<span style="color: #0000FF;">ToArray</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;<span style="color: #008080; font-weight: bold;">\n</span>&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
      <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
  <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>This immediately gives me something to play with, it tells me I should investigate <strong>System.DirectoryServices</strong>, it tells me something about the way active directory search results are organised, and it tells me there is a curious filter syntax to investigate&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.adhocgeek.com/2009/10/enumerating-users-with-ldap/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Binomial Option Pricing with Alchemy</title>
		<link>http://www.adhocgeek.com/2009/09/binomial-option-pricing-with-alchemy/</link>
		<comments>http://www.adhocgeek.com/2009/09/binomial-option-pricing-with-alchemy/#comments</comments>
		<pubDate>Thu, 17 Sep 2009 14:30:47 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Geek]]></category>
		<category><![CDATA[actionscript]]></category>
		<category><![CDATA[alchemy]]></category>
		<category><![CDATA[algorithms]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[financial engineering]]></category>
		<category><![CDATA[mathematics]]></category>
		<category><![CDATA[option pricing]]></category>

		<guid isPermaLink="false">http://www.adhocgeek.com/?p=146</guid>
		<description><![CDATA[Yet another version of the binomial option pricing algorithm (sorry), but this time I&#8217;m using Alchemy!
I have to admit to not entirely understanding how Alchemy works, but I understand enough C to write a simple pricer in it. Here&#8217;s the relevant C-code (which is, in part, copied from Mike Chambers&#8217; stringecho.c sample) :

#include &#60;stdlib.h&#62;
#include &#60;stdio.h&#62;
#include [...]]]></description>
			<content:encoded><![CDATA[<p>Yet another version of the binomial option pricing algorithm (sorry), but this time I&#8217;m using <a href="http://labs.adobe.com/wiki/index.php/Alchemy">Alchemy</a>!</p>
<p>I have to admit to not entirely understanding how Alchemy works, but I understand enough C to write a simple pricer in it. Here&#8217;s the relevant C-code (which is, in part, copied from <a href="http://www.mikechambers.com/blog/">Mike Chambers&#8217;</a> stringecho.c sample) :</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &lt;stdlib.h&gt;</span>
<span style="color: #339933;">#include &lt;stdio.h&gt;</span>
<span style="color: #339933;">#include &lt;math.h&gt;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Header file for AS3 interop APIs</span>
<span style="color: #339933;">#include &quot;AS3.h&quot;</span>
&nbsp;
<span style="color: #993333;">static</span> AS3_Val getPrice<span style="color: #009900;">&#40;</span><span style="color: #993333;">void</span><span style="color: #339933;">*</span> self<span style="color: #339933;">,</span> AS3_Val args<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">double</span> N<span style="color: #339933;">,</span> T<span style="color: #339933;">,</span> S<span style="color: #339933;">,</span> K<span style="color: #339933;">,</span> v<span style="color: #339933;">,</span> r<span style="color: #339933;">,</span> price<span style="color: #339933;">;</span>
    AS3_ArrayValue<span style="color: #009900;">&#40;</span> args<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;DoubleType, DoubleType, DoubleType, DoubleType, DoubleType, DoubleType&quot;</span><span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>N<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>T<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>S<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>K<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>v<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>r<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #993333;">double</span> dt <span style="color: #339933;">=</span> T<span style="color: #339933;">/</span>N<span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//one time step</span>
&nbsp;
    <span style="color: #993333;">double</span> u <span style="color: #339933;">=</span> <span style="color: #0000dd;">1</span> <span style="color: #339933;">+</span> v<span style="color: #339933;">*</span>sqrt<span style="color: #009900;">&#40;</span>dt<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//up-tick</span>
    <span style="color: #993333;">double</span> d <span style="color: #339933;">=</span> <span style="color: #0000dd;">1</span> <span style="color: #339933;">-</span> v<span style="color: #339933;">*</span>sqrt<span style="color: #009900;">&#40;</span>dt<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//down-tick</span>
    <span style="color: #993333;">double</span> p <span style="color: #339933;">=</span> <span style="color:#800080;">0.5</span> <span style="color: #339933;">+</span> r<span style="color: #339933;">*</span>sqrt<span style="color: #009900;">&#40;</span>dt<span style="color: #009900;">&#41;</span><span style="color: #339933;">/</span><span style="color: #009900;">&#40;</span><span style="color: #0000dd;">2</span><span style="color: #339933;">*</span>v<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//risk-neutral probability of up-tick</span>
    <span style="color: #993333;">double</span> df <span style="color: #339933;">=</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">/</span><span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #339933;">+</span>r<span style="color: #339933;">*</span>dt<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//discount factor over 1 time step, dt</span>
&nbsp;
    <span style="color: #993333;">double</span><span style="color: #339933;">*</span> optionValues <span style="color: #339933;">=</span> malloc<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>N<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">*</span> <span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">double</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">//populate the tree (for N-steps there will be N+1 values)</span>
    <span style="color: #993333;">int</span> i<span style="color: #339933;">,</span> j<span style="color: #339933;">;</span>
    <span style="color: #993333;">double</span> ST<span style="color: #339933;">;</span>
    <span style="color: #b1b100;">for</span> <span style="color: #009900;">&#40;</span>i<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> N<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> 
    <span style="color: #009900;">&#123;</span>
        ST <span style="color: #339933;">=</span> S <span style="color: #339933;">*</span> pow<span style="color: #009900;">&#40;</span>u<span style="color: #339933;">,</span> i<span style="color: #009900;">&#41;</span> <span style="color: #339933;">*</span> pow<span style="color: #009900;">&#40;</span>d<span style="color: #339933;">,</span> N<span style="color: #339933;">-</span>i<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        optionValues<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>ST <span style="color: #339933;">&gt;</span> K<span style="color: #009900;">&#41;</span><span style="color: #339933;">?</span> ST <span style="color: #339933;">-</span> K <span style="color: #339933;">:</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">//now work backwards to get expected </span>
    <span style="color: #666666; font-style: italic;">//option value at each previous stage</span>
    <span style="color: #b1b100;">for</span> <span style="color: #009900;">&#40;</span>i<span style="color: #339933;">=</span>N<span style="color: #339933;">;</span> i <span style="color: #339933;">&gt;=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i<span style="color: #339933;">--</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>j<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> j<span style="color: #339933;">&lt;</span>i<span style="color: #339933;">;</span> j<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            optionValues<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>p<span style="color: #339933;">*</span>optionValues<span style="color: #009900;">&#91;</span>j<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">+</span> <span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #339933;">-</span>p<span style="color: #009900;">&#41;</span><span style="color: #339933;">*</span>optionValues<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">*</span>df<span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    price <span style="color: #339933;">=</span> optionValues<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
    free<span style="color: #009900;">&#40;</span>optionValues<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">return</span> AS3_Number<span style="color: #009900;">&#40;</span>price<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">//define the methods exposed to ActionScript</span>
    <span style="color: #666666; font-style: italic;">//typed as an ActionScript Function instance</span>
    AS3_Val getPriceMethod <span style="color: #339933;">=</span> AS3_Function<span style="color: #009900;">&#40;</span> NULL<span style="color: #339933;">,</span> getPrice <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// construct an object that holds references to the functions</span>
    AS3_Val result <span style="color: #339933;">=</span> AS3_Object<span style="color: #009900;">&#40;</span> <span style="color: #ff0000;">&quot;getPrice: AS3ValType&quot;</span><span style="color: #339933;">,</span> getPriceMethod <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// Release</span>
    AS3_Release<span style="color: #009900;">&#40;</span> getPriceMethod <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// notify that we initialized -- THIS DOES NOT RETURN!</span>
    AS3_LibInit<span style="color: #009900;">&#40;</span> result <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// should never get here!</span>
    <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>It&#8217;s been a long time since I used C in anger though, so it&#8217;s entirely possible I&#8217;m using malloc and free badly here! If so, please let me know.</p>
<p>Using the compile SWC in a flex project is incredibly simple, here&#8217;s the relevant exerpt :</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #0066CC;">import</span> cmodule.<span style="color: #006600;">binomial_pricer</span>.<span style="color: #006600;">CLibInit</span>;
&nbsp;
<span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">function</span> calc_Click<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
<span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">var</span> <span style="color: #0066CC;">start</span>:<span style="color: #0066CC;">Number</span> = <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #0066CC;">Date</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #0066CC;">time</span>;
    <span style="color: #000000; font-weight: bold;">var</span> result:<span style="color: #0066CC;">Number</span>;
    <span style="color: #000000; font-weight: bold;">var</span> loader:CLibInit = <span style="color: #000000; font-weight: bold;">new</span> CLibInit<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #000000; font-weight: bold;">var</span> lib:<span style="color: #0066CC;">Object</span> = loader.<span style="color: #006600;">init</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">var</span> i:<span style="color: #0066CC;">int</span>=<span style="color: #cc66cc;">0</span>; i <span style="color: #66cc66;">&lt;</span> repetitions.<span style="color: #006600;">value</span>; i++<span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#123;</span>
        result = lib.<span style="color: #006600;">getPrice</span><span style="color: #66cc66;">&#40;</span>    steps.<span style="color: #006600;">value</span>, 
                            timeToExpiry.<span style="color: #006600;">value</span>, 
                            spot.<span style="color: #006600;">value</span>,
                            strike.<span style="color: #006600;">value</span>,
                            volatility.<span style="color: #006600;">value</span>,
                            <span style="color: #0066CC;">rate</span>.<span style="color: #006600;">value</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>                                
    price.<span style="color: #0066CC;">text</span> = result.<span style="color: #0066CC;">toString</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;            
    <span style="color: #000000; font-weight: bold;">var</span> <span style="color: #0066CC;">end</span>:<span style="color: #0066CC;">Number</span> = <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #0066CC;">Date</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #0066CC;">time</span>;
    averageTime.<span style="color: #0066CC;">text</span> = <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span>end-<span style="color: #0066CC;">start</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">/</span>repetitions.<span style="color: #006600;">value</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #0066CC;">toString</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> + <span style="color: #ff0000;">&quot;ms&quot;</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>And the finished result, which is about 8x (!) faster than the pixel bender version (on my machine at least) :</p>
<p><object width="400" height="360" data="/flash/AlchemyBinomialPricer/AlchemyBinomialPricer.swf" type="application/x-shockwave-flash"><param name="name" value="AlchemyBinomialPricer" /><param name="bgcolor" value="#ffffff" /><param name="align" value="middle" /><param name="src" value="/flash/AlchemyBinomialPricer/AlchemyBinomialPricer.swf" /><param name="quality" value="high" /></object></p>
]]></content:encoded>
			<wfw:commentRss>http://www.adhocgeek.com/2009/09/binomial-option-pricing-with-alchemy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Binomial Option Pricing with Pixel Bender</title>
		<link>http://www.adhocgeek.com/2009/09/binomial-option-pricing-with-pixel-bender/</link>
		<comments>http://www.adhocgeek.com/2009/09/binomial-option-pricing-with-pixel-bender/#comments</comments>
		<pubDate>Tue, 15 Sep 2009 11:13:03 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Geek]]></category>
		<category><![CDATA[actionscript]]></category>
		<category><![CDATA[algorithms]]></category>
		<category><![CDATA[financial engineering]]></category>
		<category><![CDATA[flash]]></category>
		<category><![CDATA[mathematics]]></category>
		<category><![CDATA[option pricing]]></category>
		<category><![CDATA[pixel bender]]></category>

		<guid isPermaLink="false">http://www.adhocgeek.com/?p=134</guid>
		<description><![CDATA[Pixel Bender has been around for a little while now and it&#8217;s a very cool idea, promising incredible speed improvements by allowing developers to make the most of multi-core processors and GPUs. It seems as though it was designed primarily for Adobe image manipulation software, but, since images are just arrays of bytes it can [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://labs.adobe.com/technologies/pixelbender/">Pixel Bender</a> has been around for a little while now and it&#8217;s a very cool idea, promising incredible speed improvements by allowing developers to make the most of multi-core processors and GPUs. It seems as though it was designed primarily for Adobe image manipulation software, but, since images are just arrays of bytes it can also be used to speed up any parallelisable code you might have within Flash.</p>
<h3>A fast intro to Pixel Bender</h3>
<p>The main unit of operation in pixel bender is the kernel. Generally, each kernel will take a source image and calculate the value of a single pixel in the output image. i.e. for every pixel in your source image, a single kernel instance will be run which can use that whole image to calculate the value of a single pixel (although you won&#8217;t usually want it to look at the whole image &#8211; the less dependent it is on other pixels, the faster it can run).</p>
<p>The kernel language is intended to be fast and as such is fairly simplistic. A simple kernel which converts every pixel in the source image to black would be written as follows :</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>languageVersion <span style="color: #339933;">:</span> <span style="color:#800080;">1.0</span><span style="color: #339933;">;&gt;</span>
&nbsp;
kernel Gothify
<span style="color: #339933;">&lt;</span>   namespace <span style="color: #339933;">:</span> <span style="color: #ff0000;">&quot;com.example&quot;</span><span style="color: #339933;">;</span>
    vendor <span style="color: #339933;">:</span> <span style="color: #ff0000;">&quot;Example.com&quot;</span><span style="color: #339933;">;</span>
    version <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    description <span style="color: #339933;">:</span> <span style="color: #ff0000;">&quot;Fills every pixel in the source image with black&quot;</span><span style="color: #339933;">;</span>
<span style="color: #339933;">&gt;</span>
<span style="color: #009900;">&#123;</span>        
    input image4 source<span style="color: #339933;">;</span>
    output pixel4 result<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #993333;">void</span> evaluatePixel<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        result <span style="color: #339933;">=</span> pixel4<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">0</span><span style="color: #339933;">,</span><span style="color: #0000dd;">0</span><span style="color: #339933;">,</span><span style="color: #0000dd;">0</span><span style="color: #339933;">,</span><span style="color:#800080;">1.0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>The developer&#8217;s guide says to use pixel4(0,0,0,0), but since the last value is the alpha channel, that just ends up with a <em>transparent</em> black image. It also doesn&#8217;t include the input image4, and while this may do something in photoshop, it&#8217;s not going to give you any output in the pixel bender IDE.</p>
<p>Now, an image is basically just an array of pixels, and, within pixel bender, a 4-channel pixel (a pixel4 type) is just a vector of floats. We can use <em>any</em> values within a pixel4, limited only by the bounds of a standard float size. So, we could change the evaluatePixel function above to the following and it wouldn&#8217;t make any difference to the output image :</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">void</span> evaluatePixel<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    result <span style="color: #339933;">=</span> pixel4<span style="color: #009900;">&#40;</span><span style="color: #339933;">-</span><span style="color:#800080;">1500.67</span><span style="color: #339933;">,-</span><span style="color:#800080;">45.0</span><span style="color: #339933;">,-</span><span style="color:#800080;">32.333</span><span style="color: #339933;">,</span><span style="color:#800080;">515.47</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>It&#8217;s only the values between 0.0 and 1.0 that can change the output colour, anything above 1.0 is at maximum and anything below 0.0 is at minimum. This means we can use pixel bender to operate on any array of floating point values as long as we&#8217;re happy for it to operate on pixel sized chunks of data in isolation (the pixel bender graph language does allow chaining of kernels, but this isn&#8217;t available to us in the flash player, so I&#8217;m going to ignore it for now).</p>
<h3>Parallelising the Binomial Option Pricing Algorithm</h3>
<p>There&#8217;s a short, fairly readable paper <a href="http://saahpc.ncsa.illinois.edu/papers/Ganesan_paper.pdf">here</a> [Ganesan, Chamberlain, Buhler] which gives some ideas for how to parallelise the algorithm. I&#8217;m only going to implement the scheme which is probably best illustrated by their fig. 2. This requires me to pass to each kernel the input image (array of option values at time T), the risk-neutral probability of an up-tick and the discount factor over one time step.<br />
I&#8217;ll then have to call the resulting kernel (or array of kernels, depending on how you think of it), N-1 times to get the final option price.</p>
<p>The kernel I wrote ended up like this :</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>languageVersion <span style="color: #339933;">:</span> <span style="color:#800080;">1.0</span><span style="color: #339933;">;&gt;</span>
&nbsp;
kernel BinomialOptionPricer
<span style="color: #339933;">&lt;</span>   namespace <span style="color: #339933;">:</span> <span style="color: #ff0000;">&quot;com.adhocgeek&quot;</span><span style="color: #339933;">;</span>
    vendor <span style="color: #339933;">:</span> <span style="color: #ff0000;">&quot;Ad hoc Geek&quot;</span><span style="color: #339933;">;</span>
    version <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    description <span style="color: #339933;">:</span> <span style="color: #ff0000;">&quot;Calculates the one step binomial option price&quot;</span><span style="color: #339933;">;</span>
<span style="color: #339933;">&gt;</span>
<span style="color: #009900;">&#123;</span>
    input image3 src<span style="color: #339933;">;</span>
    output pixel3 dst<span style="color: #339933;">;</span>
&nbsp;
    parameter <span style="color: #993333;">float</span> p<span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//risk-neutral probability of an up-tick</span>
    parameter <span style="color: #993333;">float</span> df<span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//discount factor over one time step</span>
&nbsp;
    <span style="color: #993333;">void</span> evaluatePixel<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        pixel3 down <span style="color: #339933;">=</span> sampleNearest<span style="color: #009900;">&#40;</span>src<span style="color: #339933;">,</span> outCoord<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        pixel3 up <span style="color: #339933;">=</span> sampleNearest<span style="color: #009900;">&#40;</span>src<span style="color: #339933;">,</span> outCoord<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> float2<span style="color: #009900;">&#40;</span><span style="color:#800080;">1.0</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #993333;">float</span> V <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>p<span style="color: #339933;">*</span>up.<span style="color: #202020;">x</span> <span style="color: #339933;">+</span> <span style="color: #009900;">&#40;</span><span style="color:#800080;">1.0</span><span style="color: #339933;">-</span>p<span style="color: #009900;">&#41;</span><span style="color: #339933;">*</span>down.<span style="color: #202020;">x</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">*</span>df<span style="color: #339933;">;</span>
&nbsp;
        dst <span style="color: #339933;">=</span> pixel3<span style="color: #009900;">&#40;</span>V<span style="color: #339933;">,</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<h3>Using the Pixel Bender Filter in Actionscript</h3>
<p>This is actually incredibly easy. Flash 10 gives us a new class called the <a href="http://help.adobe.com/en_US/AS3LCR/Flash_10.0/flash/display/Shader.html">Shader</a> which represents a Pixel Bender kernel. You can use this with the new ShaderJob class to trigger a set of kernel operations on any vector or byte array that you&#8217;ve created. I&#8217;m not going to try and write a tutorial, so here&#8217;s the final actionscript code I wrote (you should notice it&#8217;s quite similar to the previous version):</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #66cc66;">&#91;</span>Embed<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;BinomialOptionPricer.pbj&quot;</span>, mimeType=<span style="color: #ff0000;">&quot;application/octet-stream&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#93;</span>
<span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">var</span> BinomialOptionPricer:<span style="color: #000000; font-weight: bold;">Class</span>;
&nbsp;
<span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">function</span> getPrice<span style="color: #66cc66;">&#40;</span>  N:<span style="color: #0066CC;">Number</span>, <span style="color: #808080; font-style: italic;">//Number of steps</span>
                                    T:<span style="color: #0066CC;">Number</span>, <span style="color: #808080; font-style: italic;">//Time to expiry (in years)</span>
                                    S:<span style="color: #0066CC;">Number</span>, <span style="color: #808080; font-style: italic;">//Spot price of underlying</span>
                                    K:<span style="color: #0066CC;">Number</span>, <span style="color: #808080; font-style: italic;">//Option strike</span>
                                    v:<span style="color: #0066CC;">Number</span>, <span style="color: #808080; font-style: italic;">//Volatility of underlying</span>
                                    r:<span style="color: #0066CC;">Number</span>, <span style="color: #808080; font-style: italic;">//risk-free rate</span>
                                    NUMOPTIONS:<span style="color: #0066CC;">Number</span> 
                                 <span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">Number</span>
<span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">var</span> dt:<span style="color: #0066CC;">Number</span> = T<span style="color: #66cc66;">/</span>N; <span style="color: #808080; font-style: italic;">//one time step</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">var</span> u:<span style="color: #0066CC;">Number</span> = <span style="color: #cc66cc;">1</span> + v<span style="color: #66cc66;">*</span><span style="color: #0066CC;">Math</span>.<span style="color: #0066CC;">sqrt</span><span style="color: #66cc66;">&#40;</span>dt<span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">//up-tick</span>
    <span style="color: #000000; font-weight: bold;">var</span> d:<span style="color: #0066CC;">Number</span> = <span style="color: #cc66cc;">1</span> - v<span style="color: #66cc66;">*</span><span style="color: #0066CC;">Math</span>.<span style="color: #0066CC;">sqrt</span><span style="color: #66cc66;">&#40;</span>dt<span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">//down-tick</span>
    <span style="color: #000000; font-weight: bold;">var</span> p:<span style="color: #0066CC;">Number</span> = <span style="color: #cc66cc;">0.5</span> + r<span style="color: #66cc66;">*</span><span style="color: #0066CC;">Math</span>.<span style="color: #0066CC;">sqrt</span><span style="color: #66cc66;">&#40;</span>dt<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">/</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">2</span><span style="color: #66cc66;">*</span>v<span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">//risk-neutral prob. of up-tick</span>
    <span style="color: #000000; font-weight: bold;">var</span> df:<span style="color: #0066CC;">Number</span> = <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">/</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span>+r<span style="color: #66cc66;">*</span>dt<span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">//discount factor over 1 time step, dt</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">var</span> optionValues:Vector.<span style="color: #66cc66;">&lt;</span>Number<span style="color: #66cc66;">&gt;</span> = <span style="color: #000000; font-weight: bold;">new</span> Vector.<span style="color: #66cc66;">&lt;</span>Number<span style="color: #66cc66;">&gt;</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
    <span style="color: #808080; font-style: italic;">//Populate the fake pixels array </span>
    <span style="color: #000000; font-weight: bold;">var</span> i:<span style="color: #0066CC;">int</span>, j:<span style="color: #0066CC;">int</span>, ST:<span style="color: #0066CC;">Number</span>;
    <span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span>j=<span style="color: #cc66cc;">0</span>; j <span style="color: #66cc66;">&lt;</span> NUMOPTIONS; j++<span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#123;</span>
        <span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span>i=<span style="color: #cc66cc;">0</span>; i <span style="color: #66cc66;">&lt;</span> N+<span style="color: #cc66cc;">1</span>; i++<span style="color: #66cc66;">&#41;</span> 
        <span style="color: #66cc66;">&#123;</span>
            ST = spot.<span style="color: #006600;">value</span> <span style="color: #66cc66;">*</span> <span style="color: #0066CC;">Math</span>.<span style="color: #0066CC;">pow</span><span style="color: #66cc66;">&#40;</span>u, i<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">*</span> <span style="color: #0066CC;">Math</span>.<span style="color: #0066CC;">pow</span><span style="color: #66cc66;">&#40;</span>d, N-i<span style="color: #66cc66;">&#41;</span>;
            optionValues.<span style="color: #0066CC;">push</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span>ST <span style="color: #66cc66;">&gt;</span> K<span style="color: #66cc66;">&#41;</span>? ST - K : <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>;
            optionValues.<span style="color: #0066CC;">push</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>;
            optionValues.<span style="color: #0066CC;">push</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>;
        <span style="color: #66cc66;">&#125;</span>
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
&nbsp;
    <span style="color: #808080; font-style: italic;">//work backwards to get expected option value at each previous stage</span>
    <span style="color: #000000; font-weight: bold;">var</span> sj:ShaderJob;
    <span style="color: #000000; font-weight: bold;">var</span> shader:Shader = <span style="color: #000000; font-weight: bold;">new</span> Shader<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> BinomialOptionPricer<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> as ByteArray<span style="color: #66cc66;">&#41;</span>;
    shader.<span style="color: #0066CC;">data</span>.<span style="color: #006600;">src</span>.<span style="color: #006600;">input</span> = optionValues;
    shader.<span style="color: #0066CC;">data</span>.<span style="color: #006600;">src</span>.<span style="color: #0066CC;">height</span> = NUMOPTIONS;
    shader.<span style="color: #0066CC;">data</span>.<span style="color: #006600;">p</span>.<span style="color: #006600;">value</span> = <span style="color: #66cc66;">&#91;</span>p<span style="color: #66cc66;">&#93;</span>;
    shader.<span style="color: #0066CC;">data</span>.<span style="color: #006600;">df</span>.<span style="color: #006600;">value</span> = <span style="color: #66cc66;">&#91;</span>df<span style="color: #66cc66;">&#93;</span>;
    <span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span>i=N; i <span style="color: #66cc66;">&gt;</span> <span style="color: #cc66cc;">0</span>; i--<span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#123;</span>
        shader.<span style="color: #0066CC;">data</span>.<span style="color: #006600;">src</span>.<span style="color: #0066CC;">width</span> = i+<span style="color: #cc66cc;">1</span>;
        sj = <span style="color: #000000; font-weight: bold;">new</span> ShaderJob<span style="color: #66cc66;">&#40;</span>shader, optionValues, i+<span style="color: #cc66cc;">1</span>, NUMOPTIONS<span style="color: #66cc66;">&#41;</span>;
        sj.<span style="color: #0066CC;">start</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">true</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #b1b100;">return</span> optionValues<span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#93;</span>; 
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>Points to note are where I&#8217;ve embedded the kernel in the actionscript itself and where I&#8217;ve added the ability to run the calculation multiple times in parallel (simulating running the calculation for many different options at once). Each line in the source &#8220;image&#8221; represents a different option (although they&#8217;re all using the same source data at the moment).</p>
<p>Here (if you have Flash Player 10 installed) is the resulting swf (view source enabled, of course) :</p>
<p><object width="400" height="360" data="/flash/PixelBenderPricer/PBBinomialPricer.swf" type="application/x-shockwave-flash"><param name="name" value="PBBinomialPricer" /><param name="bgcolor" value="#ffffff" /><param name="align" value="middle" /><param name="src" value="/flash/PixelBenderPricer/PBBinomialPricer.swf" /><param name="quality" value="high" /></object></p>
<p>It&#8217;s slightly faster than the straight actionscript version, but not by a great deal, where it really shines is in calculating multiple options at once. There&#8217;s an interesting non-linear relationship between the number of lines in the source &#8220;image&#8221; and the speed of this particular algorithm. I might graph it at some point&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.adhocgeek.com/2009/09/binomial-option-pricing-with-pixel-bender/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Binomial Option Pricing in Actionscript</title>
		<link>http://www.adhocgeek.com/2009/09/binomial-option-pricing-in-actionscript/</link>
		<comments>http://www.adhocgeek.com/2009/09/binomial-option-pricing-in-actionscript/#comments</comments>
		<pubDate>Wed, 09 Sep 2009 12:20:33 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Geek]]></category>
		<category><![CDATA[actionscript]]></category>
		<category><![CDATA[algorithms]]></category>
		<category><![CDATA[financial engineering]]></category>
		<category><![CDATA[mathematics]]></category>

		<guid isPermaLink="false">http://www.adhocgeek.com/?p=125</guid>
		<description><![CDATA[The binomial option pricing model is one of the simplest pricing models to understand and code. I&#8217;m not going to go into an explanation of the model itself, as that would take more time than I&#8217;m willing to expend, however I think it&#8217;s always useful to have example code lying around and I&#8217;m quite happy [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://en.wikipedia.org/wiki/Binomial_options_pricing_model">binomial option pricing model</a> is one of the simplest pricing models to understand and code. I&#8217;m not going to go into an explanation of the model itself, as that would take more time than I&#8217;m willing to expend, however I think it&#8217;s always useful to have example code lying around and I&#8217;m quite happy for some of it to lie around on my website.</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">function</span> getPrice<span style="color: #66cc66;">&#40;</span>  N:<span style="color: #0066CC;">Number</span>, <span style="color: #808080; font-style: italic;">//Number of steps</span>
                            T:<span style="color: #0066CC;">Number</span>, <span style="color: #808080; font-style: italic;">//Time to expiry (in years)</span>
                            S:<span style="color: #0066CC;">Number</span>, <span style="color: #808080; font-style: italic;">//Spot price of underlying</span>
                            K:<span style="color: #0066CC;">Number</span>, <span style="color: #808080; font-style: italic;">//Option strike</span>
                            v:<span style="color: #0066CC;">Number</span>, <span style="color: #808080; font-style: italic;">//Volatility of underlying</span>
                            r:<span style="color: #0066CC;">Number</span> <span style="color: #808080; font-style: italic;">//risk-free rate </span>
                         <span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">Number</span>
<span style="color: #66cc66;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">var</span> dt:<span style="color: #0066CC;">Number</span> = T<span style="color: #66cc66;">/</span>N; <span style="color: #808080; font-style: italic;">//one time step</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">var</span> u:<span style="color: #0066CC;">Number</span> = <span style="color: #cc66cc;">1</span> + v<span style="color: #66cc66;">*</span><span style="color: #0066CC;">Math</span>.<span style="color: #0066CC;">sqrt</span><span style="color: #66cc66;">&#40;</span>dt<span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">//up-tick</span>
    <span style="color: #000000; font-weight: bold;">var</span> d:<span style="color: #0066CC;">Number</span> = <span style="color: #cc66cc;">1</span> - v<span style="color: #66cc66;">*</span><span style="color: #0066CC;">Math</span>.<span style="color: #0066CC;">sqrt</span><span style="color: #66cc66;">&#40;</span>dt<span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">//down-tick</span>
    <span style="color: #000000; font-weight: bold;">var</span> p:<span style="color: #0066CC;">Number</span> = <span style="color: #cc66cc;">0.5</span> + r<span style="color: #66cc66;">*</span><span style="color: #0066CC;">Math</span>.<span style="color: #0066CC;">sqrt</span><span style="color: #66cc66;">&#40;</span>dt<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">/</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">2</span><span style="color: #66cc66;">*</span>v<span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">//risk-neutral prob. of up-tick</span>
    <span style="color: #000000; font-weight: bold;">var</span> df:<span style="color: #0066CC;">Number</span> = <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">/</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span>+r<span style="color: #66cc66;">*</span>dt<span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">//discount factor over 1 time step, dt</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">var</span> optionValues:<span style="color: #0066CC;">Array</span> = <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #0066CC;">Array</span><span style="color: #66cc66;">&#40;</span>N+<span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
    <span style="color: #808080; font-style: italic;">//populate the tree (for N-steps there will be N+1 values)</span>
    <span style="color: #000000; font-weight: bold;">var</span> i:<span style="color: #0066CC;">int</span>, j:<span style="color: #0066CC;">int</span>, ST:<span style="color: #0066CC;">Number</span>;
    <span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span>i=<span style="color: #cc66cc;">0</span>; i <span style="color: #66cc66;">&lt;</span> N+<span style="color: #cc66cc;">1</span>; i++<span style="color: #66cc66;">&#41;</span> 
    <span style="color: #66cc66;">&#123;</span>
        ST = spot.<span style="color: #006600;">value</span> <span style="color: #66cc66;">*</span> <span style="color: #0066CC;">Math</span>.<span style="color: #0066CC;">pow</span><span style="color: #66cc66;">&#40;</span>u, i<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">*</span> <span style="color: #0066CC;">Math</span>.<span style="color: #0066CC;">pow</span><span style="color: #66cc66;">&#40;</span>d, N-i<span style="color: #66cc66;">&#41;</span>;
        optionValues<span style="color: #66cc66;">&#91;</span>i<span style="color: #66cc66;">&#93;</span> = <span style="color: #66cc66;">&#40;</span>ST <span style="color: #66cc66;">&gt;</span> K<span style="color: #66cc66;">&#41;</span>? ST - K : <span style="color: #cc66cc;">0</span>;
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">//now work backwards to get expected option value at each previous stage</span>
    <span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span>i=N; i <span style="color: #66cc66;">&gt;</span>= <span style="color: #cc66cc;">0</span>; i--<span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#123;</span>
        <span style="color: #b1b100;">for</span><span style="color: #66cc66;">&#40;</span>j=<span style="color: #cc66cc;">0</span>; j<span style="color: #66cc66;">&lt;</span>i; j++<span style="color: #66cc66;">&#41;</span>
        <span style="color: #66cc66;">&#123;</span>
            optionValues<span style="color: #66cc66;">&#91;</span>j<span style="color: #66cc66;">&#93;</span> = <span style="color: #66cc66;">&#40;</span>p<span style="color: #66cc66;">*</span>optionValues<span style="color: #66cc66;">&#91;</span>j+<span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#93;</span> + <span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span>-p<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">*</span>optionValues<span style="color: #66cc66;">&#91;</span>j<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">*</span>df;
        <span style="color: #66cc66;">&#125;</span>
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #b1b100;">return</span> optionValues<span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#93;</span>; 
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>What I&#8217;ve written is slightly different from some of the examples you might see (though exactly what Wikipedia suggests) &#8211; I don&#8217;t bother building up an array of stock prices since each value in the final array can be calculated with a simple formula. This means that I&#8217;ve removed a couple of loops from the calculation and (roughly) halved the execution time. I&#8217;m also assuming that we&#8217;re pricing a vanilla call option and that the risk-free rate is discretely compounded, though it would be fairly trivial to replace the call payoff function ((ST > K)? ST &#8211; K : 0) with any kind of external payoff function and to replace the discrete discount factor with a continuous one (1+rt becomes e<sup>rT</sup>, essentially). In the end, with enough time steps, these kinds of changes make only a little difference though.</p>
<p>Have a play :</p>
<p><object width="400" height="360" data="/flash/BinomialOptionPricer/OptionPricer.swf" type="application/x-shockwave-flash"><param name="name" value="OptionPricer" /><param name="bgcolor" value="#ffffff" /><param name="align" value="middle" /><param name="src" value="/flash/BinomialOptionPricer/OptionPricer.swf" /><param name="quality" value="high" /></object></p>
<p>And for comparison, here&#8217;s a Black-Scholes pricer :</p>
<p><object width="400" height="360" data="/flash/BlackScholesPricer/BlackScholesPricer.swf" type="application/x-shockwave-flash"><param name="name" value="BlackScholes" /><param name="bgcolor" value="#ffffff" /><param name="align" value="middle" /><param name="src" value="/flash/BlackScholesPricer/BlackScholes.swf" /><param name="quality" value="high" /></object></p>
]]></content:encoded>
			<wfw:commentRss>http://www.adhocgeek.com/2009/09/binomial-option-pricing-in-actionscript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>VAR, COVAR and COREL in Actionscript</title>
		<link>http://www.adhocgeek.com/2009/08/var-covar-and-corel-in-actionscript/</link>
		<comments>http://www.adhocgeek.com/2009/08/var-covar-and-corel-in-actionscript/#comments</comments>
		<pubDate>Fri, 28 Aug 2009 11:07:13 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Geek]]></category>
		<category><![CDATA[actionscript]]></category>
		<category><![CDATA[covariance]]></category>
		<category><![CDATA[mathematics]]></category>
		<category><![CDATA[statistics]]></category>

		<guid isPermaLink="false">http://www.adhocgeek.com/?p=119</guid>
		<description><![CDATA[Someone was asking whether or not it&#8217;s possible to call Excel functions from a Flex project because they needed to use VAR, COVAR and COREL. The short answer is, of course, no (at least not to my knowledge, and, even if it were possible, I don&#8217;t think it&#8217;s something you really want to encourage). A [...]]]></description>
			<content:encoded><![CDATA[<p>Someone was asking whether or not it&#8217;s possible to call Excel functions from a Flex project because they needed to use VAR, COVAR and COREL. The short answer is, of course, no (at least not to my knowledge, and, even if it were possible, I don&#8217;t think it&#8217;s something you really want to encourage). A better answer would explain that these functions aren&#8217;t especially complex and that an Actionscript implementation is fairly straightforward. The wikipedia page on <a href="http://en.wikipedia.org/wiki/Covariance">covariance</a> is a little daunting if you&#8217;ve never really thought about what these functions entail (or have forgotten), but essentially it boils down to this :</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">function</span> corel<span style="color: #66cc66;">&#40;</span>X:<span style="color: #0066CC;">Array</span>, Y:<span style="color: #0066CC;">Array</span><span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">Number</span>
<span style="color: #66cc66;">&#123;</span>
    <span style="color: #808080; font-style: italic;">//correlation coeff between two random variables X and Y is defined as :</span>
    <span style="color: #808080; font-style: italic;">//correlation(X,Y) = covar(X,Y)/(sqrt(Var(X)) * sqrt(Var(Y)))</span>
    <span style="color: #808080; font-style: italic;">//</span>
    <span style="color: #808080; font-style: italic;">//var(X) = covar(X,X);</span>
    <span style="color: #808080; font-style: italic;">//covar(X,Y) = E((X-xm)(Y-ym)); where xm, ym are the population means.</span>
    <span style="color: #b1b100;">return</span> covar<span style="color: #66cc66;">&#40;</span>X, Y<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">/</span><span style="color: #0066CC;">Math</span>.<span style="color: #0066CC;">sqrt</span><span style="color: #66cc66;">&#40;</span>covar<span style="color: #66cc66;">&#40;</span>X, X<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">*</span> covar<span style="color: #66cc66;">&#40;</span>Y, Y<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">function</span> covar<span style="color: #66cc66;">&#40;</span>X:<span style="color: #0066CC;">Array</span>, Y:<span style="color: #0066CC;">Array</span><span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">Number</span>
<span style="color: #66cc66;">&#123;</span>
    <span style="color: #808080; font-style: italic;">//Sample covariance is Sum((X-xm)(Y-ym))/n-1</span>
    <span style="color: #808080; font-style: italic;">//where n is the sample size and xm &amp; ym are sample means.</span>
    <span style="color: #808080; font-style: italic;">//I'll assume that X and Y are the same size...</span>
    <span style="color: #000000; font-weight: bold;">var</span> total:<span style="color: #0066CC;">Number</span> = <span style="color: #cc66cc;">0</span>;
    <span style="color: #000000; font-weight: bold;">var</span> xm:<span style="color: #0066CC;">Number</span> = average<span style="color: #66cc66;">&#40;</span>X<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #000000; font-weight: bold;">var</span> ym:<span style="color: #0066CC;">Number</span> = <span style="color: #66cc66;">&#40;</span>X == Y<span style="color: #66cc66;">&#41;</span>? xm : average<span style="color: #66cc66;">&#40;</span>Y<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">var</span> i:<span style="color: #0066CC;">int</span>=<span style="color: #cc66cc;">0</span>; i<span style="color: #66cc66;">&lt;</span>X.<span style="color: #0066CC;">length</span>; i++<span style="color: #66cc66;">&#41;</span>
        total += <span style="color: #66cc66;">&#40;</span>X<span style="color: #66cc66;">&#91;</span>i<span style="color: #66cc66;">&#93;</span>-xm<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">*</span><span style="color: #66cc66;">&#40;</span>Y<span style="color: #66cc66;">&#91;</span>i<span style="color: #66cc66;">&#93;</span>-ym<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #b1b100;">return</span> total<span style="color: #66cc66;">/</span><span style="color: #66cc66;">&#40;</span>X.<span style="color: #0066CC;">length</span> - <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span>; 
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">function</span> average<span style="color: #66cc66;">&#40;</span>X:<span style="color: #0066CC;">Array</span><span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">Number</span>
<span style="color: #66cc66;">&#123;</span>
    <span style="color: #808080; font-style: italic;">//Sample mean or average = Sum(X)/(sample size)</span>
    <span style="color: #000000; font-weight: bold;">var</span> total:<span style="color: #0066CC;">Number</span> = <span style="color: #cc66cc;">0</span>;
    <span style="color: #b1b100;">for</span> each<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">var</span> x:<span style="color: #0066CC;">Number</span> <span style="color: #b1b100;">in</span> X<span style="color: #66cc66;">&#41;</span>
        total += x;
    <span style="color: #b1b100;">return</span> total<span style="color: #66cc66;">/</span>X.<span style="color: #0066CC;">length</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>Of course, it&#8217;s not quite that simple &#8211; my covar won&#8217;t return the same value as COVAR in Excel, because Excel uses the biased estimator (i.e. it divides by n rather than (n-1)), but this cancels out when calculating the correlation coefficient, and correcting covar to the biased estimator is trivial (multply by (n-1)/n). Personally, I think Excel is wrong for defaulting to the biased estimator for COVAR, especially since VAR uses the unbiased one (and, as I&#8217;ve written in the comments, VAR(X)=COVAR(X,X)).</p>
]]></content:encoded>
			<wfw:commentRss>http://www.adhocgeek.com/2009/08/var-covar-and-corel-in-actionscript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Playing with IDataReader and SqlBulkCopy</title>
		<link>http://www.adhocgeek.com/2009/08/playing-with-idatareader-and-sqlbulkcopy/</link>
		<comments>http://www.adhocgeek.com/2009/08/playing-with-idatareader-and-sqlbulkcopy/#comments</comments>
		<pubDate>Tue, 25 Aug 2009 13:57:14 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Geek]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[IDataReader]]></category>
		<category><![CDATA[sql]]></category>
		<category><![CDATA[SqlBulkCopy]]></category>

		<guid isPermaLink="false">http://www.adhocgeek.com/?p=108</guid>
		<description><![CDATA[For importing huge amounts of data into SQL Server, there&#8217;s really nothing quite like SqlBulkCopy. I&#8217;ve recently had a need to manipulate a (roughly) 330,000 line CSV file and import the results of that manipulation into a single table. Doing this record by record can take minutes, but with SqlBulkCopy, importing that many records can [...]]]></description>
			<content:encoded><![CDATA[<p>For importing huge amounts of data into SQL Server, there&#8217;s really nothing quite like <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx">SqlBulkCopy</a>. I&#8217;ve recently had a need to manipulate a (roughly) 330,000 line CSV file and import the results of that manipulation into a single table. Doing this record by record can take <em>minutes</em>, but with <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx">SqlBulkCopy</a>, importing that many records can be done in about 4 seconds on my development machine (and it&#8217;s definitely not the fastest PC in the world).</p>
<p><strong>Out of Memory</strong></p>
<p>Originally I was reading in the file, manipulating the data and writing out another CSV file I could use with DTS. However, <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.writetoserver.aspx">SqlBulkCopy.WriteToServer</a> doesn&#8217;t take a CSV file directly, it only takes either a <a href="http://msdn.microsoft.com/en-us/library/system.data.datatable.aspx">DataTable</a>, <a href="http://msdn.microsoft.com/en-us/library/system.data.datarow.aspx">DataRow</a>[] or <a href="http://msdn.microsoft.com/en-us/library/system.data.idatareader.aspx">IDataReader</a>, so at first, while writing out the CSV file I was also building up a <a href="http://msdn.microsoft.com/en-us/library/system.data.datatable.aspx">DataTable</a> to pass to it. For a file like mine of only a few hundred thousand records, it wasn&#8217;t a big problem to build that <a href="http://msdn.microsoft.com/en-us/library/system.data.datatable.aspx">DataTable</a> in memory &#8211; it was only taking a few hundred MB &#8211; but it occurred to me that there could be a problem if the number of records increased modestly to a million or so. In fact, with a file of only 4 million records, I&#8217;d probably be looking at a <a href="http://msdn.microsoft.com/en-us/library/system.outofmemoryexception.aspx">System.OutOfMemoryException</a>.</p>
<p><strong>IDataReader</strong></p>
<p>The solution to this problem is to write a class which implements <a href="http://msdn.microsoft.com/en-us/library/system.data.idatareader.aspx">IDataReader</a> and pass this to SqlBulkCopy. There are <a href="http://www.google.co.uk/search?hl=en&#038;q=CSVDataReader+C%23">a few implementations out there already</a>, but I couldn&#8217;t find anything both free and in C#. I didn&#8217;t look terribly hard though, and I was curious to try writing a basic implementation myself just to see how difficult it would be.<br />
It turns out it&#8217;s not very difficult at all, it depends on how much effort you want to put in. For a simple spike like this I just wanted to see how long it took to implement enough of IDataReader for SqlBulkCopy to work so I could then see how much memory was being used. This is (part of) what I ended up with :</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> CSVDataReader <span style="color: #008000;">:</span> IDataReader
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">private</span> StreamReader stream<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">private</span> Dictionary<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span>, <span style="color: #FF0000;">int</span><span style="color: #008000;">&gt;</span> columnsByName <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Dictionary<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span>,<span style="color: #FF0000;">int</span><span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF;">private</span> Dictionary<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">int</span>, <span style="color: #FF0000;">string</span><span style="color: #008000;">&gt;</span> columnsByOrdinal <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Dictionary<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">int</span>,<span style="color: #FF0000;">string</span><span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF;">private</span> <span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> currentRow<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">private</span> <span style="color: #FF0000;">bool</span> _isClosed <span style="color: #008000;">=</span> true<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> CSVDataReader<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> fileName<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #008000;">!</span>File.<span style="color: #0000FF;">Exists</span><span style="color: #000000;">&#40;</span>fileName<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
            <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> Exception<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;File [&quot;</span> <span style="color: #008000;">+</span> fileName <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;] does not exist.&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">stream</span> <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> StreamReader<span style="color: #000000;">&#40;</span>fileName<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> headers <span style="color: #008000;">=</span> stream.<span style="color: #0000FF;">ReadLine</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Split</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">','</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> i<span style="color: #008000;">=</span><span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> i <span style="color: #008000;">&lt;</span> headers.<span style="color: #0000FF;">Length</span><span style="color: #008000;">;</span> i<span style="color: #008000;">++</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            columnsByName.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>headers<span style="color: #000000;">&#91;</span>i<span style="color: #000000;">&#93;</span>, i<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            columnsByOrdinal.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>i, headers<span style="color: #000000;">&#91;</span>i<span style="color: #000000;">&#93;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        _isClosed <span style="color: #008000;">=</span> false<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Close<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>stream <span style="color: #008000;">!=</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span> stream.<span style="color: #0000FF;">Close</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        _isClosed <span style="color: #008000;">=</span> true<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> FieldCount
    <span style="color: #000000;">&#123;</span>
        get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> columnsByName.<span style="color: #0000FF;">Count</span><span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// This is the main function that does the work - it reads in the next line of data and parses the values into ordinals.</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// &lt;returns&gt;A value indicating whether the EOF was reached or not.&lt;/returns&gt;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">bool</span> Read<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>stream <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span> <span style="color: #0600FF;">return</span> false<span style="color: #008000;">;</span>
        <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>stream.<span style="color: #0000FF;">EndOfStream</span><span style="color: #000000;">&#41;</span> <span style="color: #0600FF;">return</span> false<span style="color: #008000;">;</span>
&nbsp;
        currentRow <span style="color: #008000;">=</span> stream.<span style="color: #0000FF;">ReadLine</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Split</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">','</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">return</span> true<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">object</span> GetValue<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> i<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">return</span> currentRow<span style="color: #000000;">&#91;</span>i<span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> GetName<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> i<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">return</span> columnsByOrdinal<span style="color: #000000;">&#91;</span>i<span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> GetOrdinal<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> name<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">return</span> columnsByName<span style="color: #000000;">&#91;</span>name<span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">//Other IDataReader methods/properties here, but all throwing not implemented exceptions.</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>It turns out you only need to implement these few properties and methods for SqlBulkCopy (I&#8217;m not even sure you need implement this much). Once I had this, it was a mere four lines to import the CSV file into SQL Server :</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">SqlBulkCopy sbc <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> SqlBulkCopy<span style="color: #000000;">&#40;</span>mySqlConnection<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
sbc.<span style="color: #0000FF;">DestinationTableName</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;MyTable&quot;</span><span style="color: #008000;">;</span>
sbc.<span style="color: #0000FF;">BulkCopyTimeout</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">6000</span><span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">//10 Minutes</span>
sbc.<span style="color: #0000FF;">WriteToServer</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> CSVDataReader<span style="color: #000000;">&#40;</span>myFileName<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Of course, this relies on all of MyTable&#8217;s columns being of type varchar and the column headers in the CSV file need to match up with the column headers in the table, but this is supposed to be a simple spike.<br />
The first time I ran this, it was using about 12MB of memory for a 12MB file (my original 330K line file), and while this was an improvement over the 100s of MB for building the DataTable, it didn&#8217;t really tell me anything about how it might scale. So, I generated a file with about 35 million rows in it just to see what would happen. I was pleasantly surprised to find that it only used about 12MB from start to finish &#8211; this is clearly the benefit of using this DataReader model, the whole file/data structure is never in memory so we&#8217;re not generating enormous data structures to pass around.</p>
<p>If I have to do something similar to this in the future, I&#8217;ll probably tidy up this CSVDataReader and use it again. I may even implement the rest of it&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.adhocgeek.com/2009/08/playing-with-idatareader-and-sqlbulkcopy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Actionscript Date Lunacy</title>
		<link>http://www.adhocgeek.com/2009/08/actionscript-date-lunacy/</link>
		<comments>http://www.adhocgeek.com/2009/08/actionscript-date-lunacy/#comments</comments>
		<pubDate>Thu, 20 Aug 2009 14:41:31 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Geek]]></category>
		<category><![CDATA[actionscript]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[dates]]></category>
		<category><![CDATA[formatting]]></category>

		<guid isPermaLink="false">http://www.adhocgeek.com/?p=100</guid>
		<description><![CDATA[I really hate the Actionscript Date class. Mostly because of the way it deals with local time offsets. When I create a new date instance, I generally don&#8217;t care about the local time zone settings. I&#8217;ll care about them when I have to combine it with other dates, sure, but at the time I set [...]]]></description>
			<content:encoded><![CDATA[<p>I <em>really</em> hate the <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/Date.html">Actionscript Date class</a>. Mostly because of the way it deals with local time offsets. When I create a new date instance, I generally don&#8217;t care about the local time zone settings. I&#8217;ll care about them when I have to combine it with other dates, sure, but at the time I set that value I want it to <em>stay</em> that value. The AS date class thinks otherwise.</p>
<p>Say I have a number of milliseconds from epoch (1 Jan 1970) which I want to use to create a specific date so I can use a DateFormatter to output the result, then you&#8217;d think that the following would be fine :</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">var</span> myDate:<span style="color: #0066CC;">Date</span> = <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #0066CC;">Date</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1250766979000</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #000000; font-weight: bold;">var</span> df:DateFormatter = <span style="color: #000000; font-weight: bold;">new</span> DateFormatter<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
df.<span style="color: #006600;">formatString</span> = <span style="color: #ff0000;">&quot;YYYY-MM-DD JJ:NN:SS&quot;</span>;
<span style="color: #000000; font-weight: bold;">var</span> stringDate:<span style="color: #0066CC;">String</span> = df.<span style="color: #006600;">format</span><span style="color: #66cc66;">&#40;</span>myDate<span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p><small>(Let&#8217;s gloss over the batshit-insane need for a DateFormatter class and the actual formatString itself &#8211; JJ for 0-23 hour time, really?)</small></p>
<p>But no. In my area, we&#8217;re currently in daylight savings mode, so the Flash player decides that this date must be modified accordingly, and if you format it with the code above you&#8217;ll get &#8220;2009-08-20 12:16:19&#8243;, whereas it should be &#8220;2009-08-20 11:16:19&#8243; (you can try and calculate this yourself if you&#8217;re feeling particularly bored). This sounds fairly trivial to deal with until you realise that, short of writing your own DateFormatter, there&#8217;s no way to output the actual, formatted UTC date and time (ignoring the unformattable toUTCString() method).</p>
<p>To do that, you have to take this approach :</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">var</span> myDate:<span style="color: #0066CC;">Date</span> = <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #0066CC;">Date</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1250766979000</span><span style="color: #66cc66;">&#41;</span>;
myDate.<span style="color: #0066CC;">setTime</span><span style="color: #66cc66;">&#40;</span>myDate.<span style="color: #0066CC;">getTime</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> + myDate.<span style="color: #006600;">timezoneOffset</span> <span style="color: #66cc66;">*</span> <span style="color: #cc66cc;">60</span> <span style="color: #66cc66;">*</span> <span style="color: #cc66cc;">1000</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #000000; font-weight: bold;">var</span> df:DateFormatter = <span style="color: #000000; font-weight: bold;">new</span> DateFormatter<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
df.<span style="color: #006600;">formatString</span> = <span style="color: #ff0000;">&quot;YYYY-MM-DD JJ:NN:SS&quot;</span>;
<span style="color: #000000; font-weight: bold;">var</span> stringDate:<span style="color: #0066CC;">String</span> = df.<span style="color: #006600;">format</span><span style="color: #66cc66;">&#40;</span>myDate<span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>Which, to me at least, seems mental, because we haven&#8217;t really created a UTC date there &#8211; we&#8217;ve actually had to modify the milliseconds since epoch due to the local timezone settings. If I change the time settings on my computer, the output of this will still change! It&#8217;s possible I&#8217;ve lived too long in Microsoft-land, but the equivalent code in C# seems a million times better and far more predictable :</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">DateTime dat <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> DateTime<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">1970</span>, <span style="color: #FF0000;">1</span>, <span style="color: #FF0000;">1</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> TimeSpan<span style="color: #000000;">&#40;</span>12507669790000000L<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #FF0000;">string</span> stringDate <span style="color: #008000;">=</span> dat.<span style="color: #0000FF;">ToString</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;yyyy-MM-dd HH:mm:ss&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Yes, miraculously, dates can format themselves in C#! There&#8217;s no need for a superfluous DateFormatter class. The only reason this code might look a litte overinflated is that dates in C# have a wider range, so I&#8217;ve had to convert the milliseconds since Unix epoch to 10&#8217;s of nanoseconds since 0001-1-1 00:00:00.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.adhocgeek.com/2009/08/actionscript-date-lunacy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Simple IIS Scripting</title>
		<link>http://www.adhocgeek.com/2009/08/simple-iis-scripting/</link>
		<comments>http://www.adhocgeek.com/2009/08/simple-iis-scripting/#comments</comments>
		<pubDate>Tue, 18 Aug 2009 13:27:36 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Geek]]></category>
		<category><![CDATA[IIS]]></category>
		<category><![CDATA[JScript]]></category>
		<category><![CDATA[scripting]]></category>
		<category><![CDATA[windows scripting host]]></category>

		<guid isPermaLink="false">http://www.adhocgeek.com/?p=93</guid>
		<description><![CDATA[Using the Windows Scripting Host, it&#8217;s possible to write small JScript files which perform administrative tasks. I had a need for a small script to automatically create a virtual directory in IIS and link it with a particular path as part of a (very basic) deployment procedure. After a little bit (maybe 15 minutes?) of [...]]]></description>
			<content:encoded><![CDATA[<p>Using the <a href="http://en.wikipedia.org/wiki/Windows_Script_Host">Windows Scripting Host</a>, it&#8217;s possible to write small <a href="http://en.wikipedia.org/wiki/JScript">JScript</a> files which perform administrative tasks. I had a need for a small script to automatically create a virtual directory in IIS and link it with a particular path as part of a (very basic) deployment procedure. After a little bit (maybe 15 minutes?) of searching and reading, this is what I ended up with :</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> install<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> hostname	<span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;localhost&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #003366; font-weight: bold;">var</span> projectName	<span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;MyProject&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #003366; font-weight: bold;">var</span> projectDir	<span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;C:<span style="color: #000099; font-weight: bold;">\\</span>Projects<span style="color: #000099; font-weight: bold;">\\</span>MyProject&quot;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000066; font-weight: bold;">try</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #003366; font-weight: bold;">var</span> existing <span style="color: #339933;">=</span> GetObject<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;IIS://&quot;</span> <span style="color: #339933;">+</span> hostname <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;/W3SVC/1/Root/&quot;</span> <span style="color: #339933;">+</span> projectName<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        WScript.<span style="color: #660066;">Echo</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;ERROR : An application called &quot;</span> <span style="color: #339933;">+</span> projectName <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot; already exists.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">return</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span> <span style="color: #000066; font-weight: bold;">catch</span><span style="color: #009900;">&#40;</span>e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000066; font-weight: bold;">try</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #006600; font-style: italic;">//Get the root IIS application</span>
        <span style="color: #003366; font-weight: bold;">var</span> objIIS <span style="color: #339933;">=</span> GetObject<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;IIS://&quot;</span> <span style="color: #339933;">+</span> hostname <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;/W3SVC/1/Root&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #003366; font-weight: bold;">var</span> virtualDir <span style="color: #339933;">=</span> objIIS.<span style="color: #660066;">Create</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;IISWebVirtualDir&quot;</span><span style="color: #339933;">,</span> projectName<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        virtualDir.<span style="color: #660066;">AppIsolated</span>		<span style="color: #339933;">=</span> <span style="color: #CC0000;">2</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">//pooled process</span>
        virtualDir.<span style="color: #660066;">AccessScript</span> 	<span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">true</span><span style="color: #339933;">;</span>
        virtualDir.<span style="color: #660066;">AppFriendlyName</span>	<span style="color: #339933;">=</span> projectName<span style="color: #339933;">;</span>
        virtualDir.<span style="color: #660066;">Path</span> 		<span style="color: #339933;">=</span> projectDir<span style="color: #339933;">;</span>
        virtualDir.<span style="color: #660066;">AccessWrite</span>		<span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">true</span><span style="color: #339933;">;</span>
        virtualDir.<span style="color: #660066;">AccessRead</span>		<span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">true</span><span style="color: #339933;">;</span>
        virtualDir.<span style="color: #660066;">AccessExecute</span>	<span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">true</span><span style="color: #339933;">;</span>
        virtualDir.<span style="color: #660066;">AppCreate</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        virtualDir.<span style="color: #660066;">SetInfo</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        WScript.<span style="color: #660066;">Echo</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;IIS application <span style="color: #000099; font-weight: bold;">\&quot;</span>&quot;</span> <span style="color: #339933;">+</span> projectName <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;<span style="color: #000099; font-weight: bold;">\&quot;</span> created successfully.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000066; font-weight: bold;">catch</span><span style="color: #009900;">&#40;</span>e<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #003366; font-weight: bold;">var</span> msg <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;&quot;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> prop <span style="color: #000066; font-weight: bold;">in</span> e<span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            msg <span style="color: #339933;">+=</span> prop <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;:&quot;</span> <span style="color: #339933;">+</span> e<span style="color: #009900;">&#91;</span>prop<span style="color: #009900;">&#93;</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        WScript.<span style="color: #660066;">Echo</span><span style="color: #009900;">&#40;</span>msg<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
install<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Pretty simple really. The <a href="http://msdn.microsoft.com/en-us/library/at5ydy31(VS.85).aspx">WScript object</a> is the root of the WSH hierarchy and is always available, but the important type here is <a href="http://msdn.microsoft.com/en-us/library/ms524579.aspx">IISWebVirtualDir</a>.</p>
<p>It&#8217;s possible to do all kinds of things in IIS from a script, but this was all I needed. I might investigate permissions and DNS entries if the deployment gets more complicated (or more frequent).</p>
]]></content:encoded>
			<wfw:commentRss>http://www.adhocgeek.com/2009/08/simple-iis-scripting/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
