<?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>Circles and Crosses</title>
	<atom:link href="http://ox.no/feed" rel="self" type="application/rss+xml" />
	<link>http://ox.no</link>
	<description>Håvard Stranden's website</description>
	<lastBuildDate>Sun, 31 Jan 2010 01:09:04 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Copyable available on GitHub</title>
		<link>http://ox.no/posts/copyable-available-on-github</link>
		<comments>http://ox.no/posts/copyable-available-on-github#comments</comments>
		<pubDate>Thu, 10 Dec 2009 23:10:29 +0000</pubDate>
		<dc:creator>Håvard</dc:creator>
				<category><![CDATA[Announcements]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Technical]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[copy]]></category>
		<category><![CDATA[copyable]]></category>
		<category><![CDATA[git]]></category>
		<category><![CDATA[github]]></category>
		<category><![CDATA[open source]]></category>

		<guid isPermaLink="false">http://ox.no/?p=144</guid>
		<description><![CDATA[People actually download and use Copyable, and they tend to use it in scenarios I haven&#8217;t used it in. This results in bug reports and patch submissions. So far, these have been given to me by e-mail or by blog comment, neither of which is a particularly great way of receiving them. So after receiving [...]]]></description>
			<content:encoded><![CDATA[<p>People actually download and use Copyable, and they tend to use it in scenarios I haven&#8217;t used it in. This results in bug reports and patch submissions. So far, these have been given to me by e-mail or by blog comment, neither of which is a particularly great way of receiving them. So after receiving another one today, I finally got around to putting Copyable on <a href="http://github.com">GitHub</a>.</p>

<p>The version I put up includes several enhancements from the latest release:</p>

<ul>
<li>It uses <code>FormatterServices.GetUninitializedObject</code> and hence does not depend on a parameterless constructor or custom instance provider (but you can of course still create an instance provider if you want to control object initialization)</li>
<li>The bug with copy semantics for already visited objects submitted by Walter Oesch has been fixed</li>
<li>The bug with inherited fields found by Alex, and the patch submitted for it, has been incorporated</li>
</ul>

<p>Bleeding edge Copyable can be found at <a href="http://github.com/havard/copyable">http://github.com/havard/copyable</a>. The clone URL is <a href="git://github.com/havard/copyable.git">git://github.com/havard/copyable.git</a>. Now go fix your own bugs! Or even better, enhance the framework.</p>
]]></content:encoded>
			<wfw:commentRss>http://ox.no/posts/copyable-available-on-github/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Minimalistic MapReduce in .NET 4.0 with the new Task Parallel Library (TPL)</title>
		<link>http://ox.no/posts/minimalistic-mapreduce-in-net-4-0-with-the-new-task-parallel-library-tpl</link>
		<comments>http://ox.no/posts/minimalistic-mapreduce-in-net-4-0-with-the-new-task-parallel-library-tpl#comments</comments>
		<pubDate>Tue, 03 Nov 2009 22:58:52 +0000</pubDate>
		<dc:creator>Håvard</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Concurrency]]></category>
		<category><![CDATA[Technical]]></category>
		<category><![CDATA[.NET 4.0]]></category>
		<category><![CDATA[Parallel]]></category>
		<category><![CDATA[TPL]]></category>

		<guid isPermaLink="false">http://ox.no/?p=119</guid>
		<description><![CDATA[Among the news in .NET 4.0 are several additions by the Parallel Computing Platform Team. As I wandered through the documentation of the Task library with cloud computing and parallelism buzz in the back of my head, I got the idea of using tasks to create a minimalistic MapReduce. Here&#8217;s the result, a rather crude [...]]]></description>
			<content:encoded><![CDATA[<p>Among the news in .NET 4.0 are several additions by the <a href="http://blogs.msdn.com/pfxteam/">Parallel Computing Platform Team</a>. As I wandered through the documentation of the Task library with cloud computing and parallelism buzz in the back of my head, I got the idea of using tasks to create a minimalistic MapReduce. Here&#8217;s the result, a rather crude and simple, but efficient MapReduce for you to play with and utilize!</p>

<!-- more -->

<h2>What is MapReduce?</h2>

<p>For those of you who don&#8217;t know what MapReduce is: MapReduce is a simplified interface for parallel data processing. MapReduce was initially described by the Google engineers Jeffrey Dean and Sanjay Ghemawat in the 2004 paper titled <a href="http://labs.google.com/papers/mapreduce.html">MapReduce: Simplified data processing on large clusters</a>.</p>

<p>MapReduce processes data by splitting the processing in to a set of transformations (in functional programming, this is called the &#8220;map&#8221; function (it maps or transforms an input to an output)). The results of the transformations are then combined into a single result (in functional programming, this is called the &#8220;reduce&#8221; function (it reduces a set of values to a single value)). On a sidenote, Linq has equivalent functions, but the names are different, presumably to make them more familiar to people with SQL knowledge. In Linq, map is called <code>Select</code>, and reduce is called <code>Aggregate</code>.</p>

<p>Shortly put, to process a huge set of data, you split the data into chunks and process each chunk in parallel. This eventually creates a new set of intermediary results, which is reduced to a single result.</p>

<h2>Implementing a minimalistic MapReduce in .NET 4.0</h2>

<p>The signature of my MapReduce function is</p>

<div class="dean_ch" style="white-space: wrap;"><ol><li class="li1"><div class="de1"><span class="kw1">static</span> Task&lt;TResult&gt; Start&lt;TInput, TPartial, TResult&gt;<span class="br0">&#40;</span></div></li>
<li class="li1"><div class="de1">&nbsp; Func&lt;TInput, TPartial&gt; map, </div></li>
<li class="li1"><div class="de1">&nbsp; Func&lt;TPartial<span class="br0">&#91;</span><span class="br0">&#93;</span>, TResult&gt; reduce, </div></li>
<li class="li1"><div class="de1">&nbsp; <span class="kw1">params</span> TInput<span class="br0">&#91;</span><span class="br0">&#93;</span> inputs<span class="br0">&#41;</span>;</div></li></ol></div>

<p>In other words, to start a MapReduce run, you supply a <code>map</code> function, a <code>reduce</code> function, and a set of inputs. Each input will be turned into an intermediate result (of type <code>TPartial</code>). Inputs are transformed concurrently. When all inputs are transformed, the <code>reduce</code> function is called to transform the partial results into a final result (of type <code>TResult</code>). Cool!</p>

<p>The map part is implemented by starting a task for each supplied input using <code>Task.Factory.StartNew()</code>.</p>

<div class="dean_ch" style="white-space: wrap;"><ol><li class="li1"><div class="de1">Task.<span class="me1">Factory</span>.<span class="me1">StartNew</span><span class="br0">&#40;</span><span class="br0">&#40;</span><span class="br0">&#41;</span> =&gt; map<span class="br0">&#40;</span>input<span class="br0">&#41;</span><span class="br0">&#41;</span>;</div></li></ol></div>

<p>The reduce part is implemented as a <a href="http://en.wikipedia.org/wiki/Continuation">continuation</a> of all the map tasks, meaning that the reduce task waits for all the map tasks to complete, and then executes. This is achieved using <code>Task.Factory.ContinueWhenAll</code>.</p>

<div class="dean_ch" style="white-space: wrap;"><ol><li class="li1"><div class="de1">Task.<span class="me1">Factory</span>.<span class="me1">ContinueWhenAll</span><span class="br0">&#40;</span></div></li>
<li class="li1"><div class="de1">&nbsp; mapTasks, </div></li>
<li class="li1"><div class="de1">&nbsp; tasks =&gt; PerformReduce<span class="br0">&#40;</span>reduce, tasks<span class="br0">&#41;</span><span class="br0">&#41;</span>;</div></li></ol></div>

<p>As you can see, the implementation is minimalistic and simple, and usage is likewise.</p>

<p>Here&#8217;s a simple example using MapReduce to calculate the <a href="http://en.wikipedia.org/wiki/Root_mean_square">root mean square (MSE)</a> of a set of values:</p>

<div class="dean_ch" style="white-space: wrap;"><ol><li class="li1"><div class="de1">var task = MapReduce.<span class="me1">Start</span>&lt;int, <span class="kw4">int</span>, double&gt;<span class="br0">&#40;</span></div></li>
<li class="li1"><div class="de1">&nbsp; i =&gt; i * i,</div></li>
<li class="li1"><div class="de1">&nbsp; s =&gt; Math.<span class="me1">Sqrt</span><span class="br0">&#40;</span>s.<span class="me1">Aggregate</span><span class="br0">&#40;</span><span class="br0">&#40;</span>a, b<span class="br0">&#41;</span> =&gt; a + b<span class="br0">&#41;</span> / <span class="nu0">5</span><span class="br0">&#41;</span>,</div></li>
<li class="li1"><div class="de1">&nbsp; <span class="nu0">1</span>, <span class="nu0">2</span>, <span class="nu0">3</span>, <span class="nu0">4</span>, <span class="nu0">5</span><span class="br0">&#41;</span>;</div></li>
<li class="li2"><div class="de2"><span class="co1">// Wait for result</span></div></li>
<li class="li1"><div class="de1">task.<span class="me1">Wait</span><span class="br0">&#40;</span><span class="br0">&#41;</span>;</div></li>
<li class="li1"><div class="de1"><span class="co1">// Prints 3.3166&#8230;</span></div></li>
<li class="li1"><div class="de1">Console.<span class="me1">WriteLine</span><span class="br0">&#40;</span>task.<span class="me1">Result</span><span class="br0">&#41;</span>;</div></li></ol></div>

<p>Actual applications of MapReduce are of course far more interesting than this simple example.</p>

<h2>Applications of MapReduce</h2>

<p>MapReduce can essentially be applied to any problem where you need a number of things to be done in parallel. It can even be applied in cases where you don&#8217;t need a final result. Just return an arbitrary value as the result (or even better, implement a variant of my MapReduce which uses <code>Action&lt;T&gt;</code>).</p>

<p>A few obvious use cases:</p>

<ul>
<li>Distributed search</li>
<li>Distributed sort</li>
<li>Tokenization</li>
<li>Indexing</li>
<li>Log processing</li>
<li>Machine learning</li>
<li>General artificial intelligence</li>
<li>General data mining</li>
<li>Large scale image processing</li>
<li>&#8230;</li>
</ul>

<p>The list goes on and on, these are just a few things off the top of my head.</p>

<p>You can grab the <a href="http://ox.no/files/MapReduce.cs">source code for MapReduce here</a>. Since this is done in .NET 4.0, it requires Visual Studio 2010 Beta 2 or later.</p>

<p>As usual, play around with it, have fun, and let me know if you find it useful!</p>
]]></content:encoded>
			<wfw:commentRss>http://ox.no/posts/minimalistic-mapreduce-in-net-4-0-with-the-new-task-parallel-library-tpl/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>RSA using BouncyCastle</title>
		<link>http://ox.no/posts/rsa-using-bouncycastle</link>
		<comments>http://ox.no/posts/rsa-using-bouncycastle#comments</comments>
		<pubDate>Thu, 19 Mar 2009 06:44:51 +0000</pubDate>
		<dc:creator>Håvard</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Technical]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[decryption]]></category>
		<category><![CDATA[encryption]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[rsa]]></category>

		<guid isPermaLink="false">http://ox.no/?p=80</guid>
		<description><![CDATA[Trying to do RSA using BouncyCastle, but struggling to find your way around the API? In a previous post (see here) I pondered why the RSA implementation in System.Security.Cryptography is restricted to only the most common usage scenarios. I mentioned BouncyCastle as an alternative for those who wanted a more flexible API, but never got [...]]]></description>
			<content:encoded><![CDATA[<p>Trying to do RSA using BouncyCastle, but struggling to find your way around the API? In a previous post (see <a href="/posts/why-cripple-the-net-rsa-implementation">here</a>) I pondered why the RSA implementation in <code>System.Security.Cryptography</code> is restricted to only the most common usage scenarios. I mentioned <a href="http://bouncycastle.org">BouncyCastle</a> as an alternative for those who wanted a more flexible API, but never got around to providing examples where BouncyCastle was used. By request, this post provides usage examples by building a crude and simple, but efficient set of methods for RSA key generation, encryption, and decryption, all built on top of BouncyCastle.</p>

<!-- more -->

<p>BouncyCastle provides flexibility and control over your encryption approach, which comes at a cost. The BouncyCastle API might be a bit hard to cope with at first, but if you know encryption in general you should be able to find your way around the API without too much effort. This post will be focusing on RSA, since that was my original need, but it should be mentioned that BouncyCastle provides many other asymmetric (and symmetric) algorithms for which the usage is similar to what you find below.</p>

<h2>Creating RSA keys</h2>

<p>Creating RSA keys is a simple task. The method below lets you specify the key size in bits, and creates a key pair for you.</p>

<div class="dean_ch" style="white-space: wrap;"><ol><li class="li1"><div class="de1">&nbsp;</div></li>
<li class="li1"><div class="de1"><span class="kw1">public</span> AsymmetricCipherKeyPair GenerateKeys<span class="br0">&#40;</span><span class="kw4">int</span> keySizeInBits<span class="br0">&#41;</span></div></li>
<li class="li1"><div class="de1"><span class="br0">&#123;</span></div></li>
<li class="li1"><div class="de1">&nbsp; RsaKeyPairGenerator r = <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span class="kw3">new</span></a> RsaKeyPairGenerator<span class="br0">&#40;</span><span class="br0">&#41;</span>;</div></li>
<li class="li2"><div class="de2">&nbsp; r.<span class="me1">Init</span><span class="br0">&#40;</span><a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span class="kw3">new</span></a> KeyGenerationParameters<span class="br0">&#40;</span><a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span class="kw3">new</span></a> SecureRandom<span class="br0">&#40;</span><span class="br0">&#41;</span>,</div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; keySizeInBits<span class="br0">&#41;</span><span class="br0">&#41;</span>;</div></li>
<li class="li1"><div class="de1">&nbsp; AsymmetricCipherKeyPair keys = r.<span class="me1">GenerateKeyPair</span><span class="br0">&#40;</span><span class="br0">&#41;</span>;</div></li>
<li class="li1"><div class="de1">&nbsp; <span class="kw1">return</span> keys;</div></li>
<li class="li1"><div class="de1"><span class="br0">&#125;</span></div></li>
<li class="li2"><div class="de2">&nbsp;</div></li></ol></div>

<p>That&#8217;s all there is to it.</p>

<h2>Encryption</h2>

<p>Now that we have a key pair, we are ready to encrypt and decrypt using RSA. In the example below, we use a key (public or private) to encrypt a byte sequence. To encrypt a string, simply convert the string to a byte array using <code>Encoding.GetBytes</code>.</p>

<div class="dean_ch" style="white-space: wrap;"><ol><li class="li1"><div class="de1">&nbsp;</div></li>
<li class="li1"><div class="de1"><span class="kw1">public</span> <span class="kw4">byte</span><span class="br0">&#91;</span><span class="br0">&#93;</span> Encrypt<span class="br0">&#40;</span><span class="kw4">byte</span><span class="br0">&#91;</span><span class="br0">&#93;</span> data, AsymmetricKeyParameter key<span class="br0">&#41;</span></div></li>
<li class="li1"><div class="de1"><span class="br0">&#123;</span></div></li>
<li class="li1"><div class="de1">&nbsp; RsaEngine e = <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span class="kw3">new</span></a> RsaEngine<span class="br0">&#40;</span><span class="br0">&#41;</span>;</div></li>
<li class="li2"><div class="de2">&nbsp; e.<span class="me1">Init</span><span class="br0">&#40;</span><span class="kw1">true</span>, key<span class="br0">&#41;</span>;</div></li>
<li class="li1"><div class="de1">&nbsp;</div></li>
<li class="li1"><div class="de1">&nbsp; <span class="kw4">int</span> blockSize = e.<span class="me1">GetInputBlockSize</span><span class="br0">&#40;</span><span class="br0">&#41;</span>;</div></li>
<li class="li1"><div class="de1">&nbsp;</div></li>
<li class="li1"><div class="de1">&nbsp; List&lt;byte&gt; output = <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span class="kw3">new</span></a> List&lt;byte&gt;<span class="br0">&#40;</span><span class="br0">&#41;</span>;</div></li>
<li class="li2"><div class="de2">&nbsp;</div></li>
<li class="li1"><div class="de1">&nbsp; <span class="kw1">for</span> <span class="br0">&#40;</span><span class="kw4">int</span> chunkPosition = <span class="nu0">0</span>; chunkPosition &lt; data.<span class="me1">Length</span>; </div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; chunkPosition += blockSize<span class="br0">&#41;</span></div></li>
<li class="li1"><div class="de1">&nbsp; <span class="br0">&#123;</span></div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; <span class="kw4">int</span> chunkSize = Math.<span class="me1">Min</span><span class="br0">&#40;</span>blockSize, data.<span class="me1">Length</span> &#8211; </div></li>
<li class="li2"><div class="de2">&nbsp; &nbsp; &nbsp; <span class="br0">&#40;</span>chunkPosition * blockSize<span class="br0">&#41;</span><span class="br0">&#41;</span>;</div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; output.<span class="me1">AddRange</span><span class="br0">&#40;</span>e.<span class="me1">ProcessBlock</span><span class="br0">&#40;</span>data, chunkPosition,</div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; &nbsp; chunkSize<span class="br0">&#41;</span><span class="br0">&#41;</span>;</div></li>
<li class="li1"><div class="de1">&nbsp; <span class="br0">&#125;</span></div></li>
<li class="li1"><div class="de1">&nbsp; <span class="kw1">return</span> output.<span class="me1">ToArray</span><span class="br0">&#40;</span><span class="br0">&#41;</span>;</div></li>
<li class="li2"><div class="de2"><span class="br0">&#125;</span></div></li>
<li class="li1"><div class="de1">&nbsp;</div></li></ol></div>

<p>The approach above uses a list to gather output for the sake of simplicity. Note that the RSA engine can only process a limited block size at a time (block size depends on the key size). The approach above generalizes the RSA engine, and processes a data set of an arbitrary size.</p>

<p>The above method does not impose constraints on which key you use for encryption. Use the public key or the private key as you see fit for your solution.</p>

<h2>Decryption</h2>

<p>The <code>Decrypt</code> method is very similar to the <code>Encrypt</code> method:</p>

<div class="dean_ch" style="white-space: wrap;"><ol><li class="li1"><div class="de1">&nbsp;</div></li>
<li class="li1"><div class="de1"><span class="kw1">public</span> <span class="kw4">byte</span><span class="br0">&#91;</span><span class="br0">&#93;</span> Decrypt<span class="br0">&#40;</span><span class="kw4">byte</span><span class="br0">&#91;</span><span class="br0">&#93;</span> data, AsymmetricKeyParameter key<span class="br0">&#41;</span></div></li>
<li class="li1"><div class="de1"><span class="br0">&#123;</span></div></li>
<li class="li1"><div class="de1">&nbsp; RsaEngine e = <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span class="kw3">new</span></a> RsaEngine<span class="br0">&#40;</span><span class="br0">&#41;</span>;</div></li>
<li class="li2"><div class="de2">&nbsp; e.<span class="me1">Init</span><span class="br0">&#40;</span><span class="kw1">false</span>, key<span class="br0">&#41;</span>;</div></li>
<li class="li1"><div class="de1">&nbsp;</div></li>
<li class="li1"><div class="de1">&nbsp; <span class="kw4">int</span> blockSize = e.<span class="me1">GetInputBlockSize</span><span class="br0">&#40;</span><span class="br0">&#41;</span>;</div></li>
<li class="li1"><div class="de1">&nbsp;</div></li>
<li class="li1"><div class="de1">&nbsp; List&lt;byte&gt; output = <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span class="kw3">new</span></a> List&lt;byte&gt;<span class="br0">&#40;</span><span class="br0">&#41;</span>;</div></li>
<li class="li2"><div class="de2">&nbsp;</div></li>
<li class="li1"><div class="de1">&nbsp; <span class="kw1">for</span> <span class="br0">&#40;</span><span class="kw4">int</span> chunkPosition = <span class="nu0">0</span>; chunkPosition &lt; data.<span class="me1">Length</span>;</div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; chunkPosition += blockSize<span class="br0">&#41;</span></div></li>
<li class="li1"><div class="de1">&nbsp; <span class="br0">&#123;</span></div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; <span class="kw4">int</span> chunkSize = Math.<span class="me1">Min</span><span class="br0">&#40;</span>blockSize, data.<span class="me1">Length</span> &#8211; </div></li>
<li class="li2"><div class="de2">&nbsp; &nbsp; &nbsp; <span class="br0">&#40;</span>chunkPosition * blockSize<span class="br0">&#41;</span><span class="br0">&#41;</span>;</div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; output.<span class="me1">AddRange</span><span class="br0">&#40;</span>e.<span class="me1">ProcessBlock</span><span class="br0">&#40;</span>data, chunkPosition,</div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; &nbsp; chunkSize<span class="br0">&#41;</span><span class="br0">&#41;</span>;</div></li>
<li class="li1"><div class="de1">&nbsp; <span class="br0">&#125;</span></div></li>
<li class="li1"><div class="de1">&nbsp; <span class="kw1">return</span> output.<span class="me1">ToArray</span><span class="br0">&#40;</span><span class="br0">&#41;</span>;</div></li>
<li class="li2"><div class="de2"><span class="br0">&#125;</span></div></li>
<li class="li1"><div class="de1">&nbsp;</div></li></ol></div>

<p>Again, it&#8217;s up to you which key you choose to use. If you want to use the common approach, encrypt using a symmetric cipher, hash the data, and sign the hash with your private key using the above <code>Encrypt</code> method. If you want to use another approach like encrypting the actual data using your private key, you are free to do so.</p>

<p>I hope this post helps those of you who want to apply RSA (or any other asymmetric cipher) to more subtle cases than those supported by the .NET framework.</p>
]]></content:encoded>
			<wfw:commentRss>http://ox.no/posts/rsa-using-bouncycastle/feed</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Mocking HtmlHelper in ASP.NET MVC RC1 using Moq</title>
		<link>http://ox.no/posts/mocking-htmlhelper-in-aspnet-mvc-rc1-using-moq</link>
		<comments>http://ox.no/posts/mocking-htmlhelper-in-aspnet-mvc-rc1-using-moq#comments</comments>
		<pubDate>Sun, 08 Mar 2009 17:15:13 +0000</pubDate>
		<dc:creator>Håvard</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Technical]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[Mock]]></category>
		<category><![CDATA[Moq]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Unit Test]]></category>

		<guid isPermaLink="false">http://ox.no/?p=65</guid>
		<description><![CDATA[For those of you trying to mock HtmlHelper, but finding it difficult, here&#8217;s a mock that works in ASP.NET MVC RC1.



The ViewDataDictionary that is passed to the HtmlHelper can be empty, or made to contain the data you want for your test.

&#160;
public static HtmlHelper CreateHtmlHelper&#40;ViewDataDictionary vd&#41;
&#123;
&#160; var mockViewContext = new Mock&#60;ViewContext&#62;&#40;
&#160; &#160; new ControllerContext&#40;
&#160; &#160; [...]]]></description>
			<content:encoded><![CDATA[<p>For those of you trying to mock HtmlHelper, but finding it difficult, here&#8217;s a mock that works in ASP.NET MVC RC1.</p>

<p><span id="more-65"></span></p>

<p>The <code>ViewDataDictionary</code> that is passed to the <code>HtmlHelper</code> can be empty, or made to contain the data you want for your test.</p>

<div class="dean_ch" style="white-space: wrap;"><ol><li class="li1"><div class="de1">&nbsp;</div></li>
<li class="li1"><div class="de1"><span class="kw1">public</span> <span class="kw1">static</span> HtmlHelper CreateHtmlHelper<span class="br0">&#40;</span>ViewDataDictionary vd<span class="br0">&#41;</span></div></li>
<li class="li1"><div class="de1"><span class="br0">&#123;</span></div></li>
<li class="li1"><div class="de1">&nbsp; var mockViewContext = <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span class="kw3">new</span></a> Mock&lt;ViewContext&gt;<span class="br0">&#40;</span></div></li>
<li class="li2"><div class="de2">&nbsp; &nbsp; <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span class="kw3">new</span></a> ControllerContext<span class="br0">&#40;</span></div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; &nbsp; <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span class="kw3">new</span></a> Mock&lt;HttpContextBase&gt;<span class="br0">&#40;</span><span class="br0">&#41;</span>.<span class="kw4">Object</span>,</div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; &nbsp; <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span class="kw3">new</span></a> RouteData<span class="br0">&#40;</span><span class="br0">&#41;</span>,</div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; &nbsp; <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span class="kw3">new</span></a> Mock&lt;ControllerBase&gt;<span class="br0">&#40;</span><span class="br0">&#41;</span>.<span class="kw4">Object</span><span class="br0">&#41;</span>,</div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span class="kw3">new</span></a> Mock&lt;IView&gt;<span class="br0">&#40;</span><span class="br0">&#41;</span>.<span class="kw4">Object</span>,</div></li>
<li class="li2"><div class="de2">&nbsp; &nbsp; vd,</div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span class="kw3">new</span></a> TempDataDictionary<span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#41;</span>;</div></li>
<li class="li1"><div class="de1">&nbsp;</div></li>
<li class="li1"><div class="de1">&nbsp; var mockViewDataContainer = <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span class="kw3">new</span></a> Mock&lt;IViewDataContainer&gt;<span class="br0">&#40;</span><span class="br0">&#41;</span>;</div></li>
<li class="li1"><div class="de1">&nbsp; mockViewDataContainer.<span class="me1">Setup</span><span class="br0">&#40;</span>v =&gt; v.<span class="me1">ViewData</span><span class="br0">&#41;</span></div></li>
<li class="li2"><div class="de2">&nbsp; &nbsp; .<span class="me1">Returns</span><span class="br0">&#40;</span>vd<span class="br0">&#41;</span>;</div></li>
<li class="li1"><div class="de1">&nbsp;</div></li>
<li class="li1"><div class="de1">&nbsp; <span class="kw1">return</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span class="kw3">new</span></a> HtmlHelper<span class="br0">&#40;</span>mockViewContext.<span class="kw4">Object</span>, </div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; mockViewDataContainer.<span class="kw4">Object</span><span class="br0">&#41;</span>;</div></li>
<li class="li1"><div class="de1"><span class="br0">&#125;</span></div></li>
<li class="li2"><div class="de2">&nbsp;</div></li></ol></div>
]]></content:encoded>
			<wfw:commentRss>http://ox.no/posts/mocking-htmlhelper-in-aspnet-mvc-rc1-using-moq/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Why cripple the .NET RSA implementation?</title>
		<link>http://ox.no/posts/why-cripple-the-net-rsa-implementation</link>
		<comments>http://ox.no/posts/why-cripple-the-net-rsa-implementation#comments</comments>
		<pubDate>Thu, 04 Dec 2008 20:45:10 +0000</pubDate>
		<dc:creator>Håvard</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Technical]]></category>

		<guid isPermaLink="false">http://ox.no/?p=19</guid>
		<description><![CDATA[I just found out that RSACryptoServiceProvider, the RSA implementation in .NET, does not allow you to use a private key to encrypt data. I&#8217;m no cryptographic expert, but I do know how asymmetric key algorithms like RSA work, and that you can use a private key for encryption. That&#8217;s how signing works. But why cripple [...]]]></description>
			<content:encoded><![CDATA[<p>I just found out that <code>RSACryptoServiceProvider</code>, the RSA implementation in .NET, does not allow you to use a private key to encrypt data. I&#8217;m no cryptographic expert, but I do know how asymmetric key algorithms like RSA work, and that you can use a private key for encryption. That&#8217;s how signing works. But why cripple the implementation and limit it to just signing?</p>

<!-- more -->

<p>The rationale is in the common application of public-key cryptography, where:</p>

<ul>
<li>Encrypting with the public key ensures <em>confidentiality</em>, i.e. the process known as encryption in common tongue. Encrypting with a public key ensures that only the entity in possession of the private key can read the data.</li>
<li>Encrypting with the private key ensures <em>authenticity</em>, i.e. the process known as signing in common tongue. There is no need to encrypt the entire data stream to ensure authenticity, so the common approach is to calculate a hash of the data and sign the hash instead.</li>
</ul>

<p>To facilitate these patterns, the .NET public-key cryptography API is designed so that:</p>

<ul>
<li><code>Encrypt()</code> encrypts with a public key, <code>Decrypt()</code> requires a private key.</li>
<li><code>SignData()</code> encrypts with a private key, but since that implies a signature, one must provide a hashing algorithm and a private key. <code>VerifyData()</code> uses a public key.</li>
</ul>

<p>But I want to encrypt with my private key! Yes, this is what <code>SignData()</code> does, but it does so to just the hash calculated by the provided hashing algorithm, since that is the de-facto approach for signing, and implementing my own <code>HashAlgorithm</code> that passes in all the data is just wrong.</p>

<p>OK, these are the common uses, but why limit the API to that? There is no limitation in the RSA algorithm to my knowledge that prevents other uses than the two offered by <code>RSACryptoServiceProvider</code>. In fact, if I wanted to perform the traditional signing approach, I could just hash the data myself and encrypt it with my private key myself. Or even better, <code>SignData()</code> could be available to help me <em>for convenience</em>.</p>

<p>So, how do you apply RSA in .NET in an uncommon manner? Don&#8217;t use .NET&#8217;s cryptography API, but embrace an open source alternatives like <a href="http://bouncycastle.org">BouncyCastle</a>, which saves your day.</p>
]]></content:encoded>
			<wfw:commentRss>http://ox.no/posts/why-cripple-the-net-rsa-implementation/feed</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Strongly typed data binding in Windows Forms</title>
		<link>http://ox.no/posts/strongly-typed-data-binding-in-windows-forms</link>
		<comments>http://ox.no/posts/strongly-typed-data-binding-in-windows-forms#comments</comments>
		<pubDate>Sun, 28 Sep 2008 15:17:05 +0000</pubDate>
		<dc:creator>Håvard</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Technical]]></category>

		<guid isPermaLink="false">http://ox.no/?p=31</guid>
		<description><![CDATA[Windows Forms data binding is a great tool for model-view-style applications, where the connection between the model and its view is easily declared. However, data binding is also an error-prone and tedious process with no IntelliSense support where properties are specified as strings. Tired of the need of looking up property names when you declare [...]]]></description>
			<content:encoded><![CDATA[<p>Windows Forms data binding is a great tool for model-view-style applications, where the connection between the model and its view is easily declared. However, data binding is also an error-prone and tedious process with no IntelliSense support where properties are specified as strings. <br /><br />Tired of the need of looking up property names when you declare data bindings? Sick of mistyping a property name when you bind and not discovering the mistake until you run your application? Have a look at Strongbind.</p>

<!-- more -->

<h2>Strongbind vs traditional data binding</h2>

<p>Traditional data binding is typically declared like this:</p>

<div class="dean_ch" style="white-space: wrap;"><ol><li class="li1"><div class="de1"><span class="co1">// Assume we have a binding source with </span></div></li>
<li class="li1"><div class="de1"><span class="co1">// a description, and a text box</span></div></li>
<li class="li1"><div class="de1"><span class="co1">// This binds the Text property of the text </span></div></li>
<li class="li1"><div class="de1"><span class="co1">// box to the Description property of the source</span></div></li>
<li class="li2"><div class="de2">textBox.<span class="me1">DataBindings</span>.<span class="me1">Add</span><span class="br0">&#40;</span><span class="st0">&quot;Text&quot;</span>, bindingSource, </div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; <span class="st0">&quot;Description&quot;</span><span class="br0">&#41;</span>;</div></li></ol></div>

<p>Obviously, many errors can arise from this declaration: Your control may not have a <code>Text</code> property, or you might have spelled it wrong. The same goes the <code>Description</code> property of your source.</p>

<p>The same declaration in Strongbind is written as follows:</p>

<div class="dean_ch" style="white-space: wrap;"><ol><li class="li1"><div class="de1"><span class="kw1">using</span><span class="br0">&#40;</span>BindingScope scope = <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span class="kw3">new</span></a> BindingScope<span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#41;</span></div></li>
<li class="li1"><div class="de1"><span class="br0">&#123;</span></div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; <span class="co1">// Create bindables</span></div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; IBusinessObject bindableSource = </div></li>
<li class="li2"><div class="de2">&nbsp; &nbsp; &nbsp; &nbsp; scope.<span class="me1">CreateSource</span><span class="br0">&#40;</span>bindingSource<span class="br0">&#41;</span>;</div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; TextBox bindableTarget = </div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; scope.<span class="me1">CreateTarget</span><span class="br0">&#40;</span>textBox<span class="br0">&#41;</span>;</div></li>
<li class="li1"><div class="de1">&nbsp;</div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; <span class="co1">// Declare bindings</span></div></li>
<li class="li2"><div class="de2">&nbsp; &nbsp; Binder.<span class="me1">Bind</span><span class="br0">&#40;</span>bindableSource.<span class="me1">Description</span><span class="br0">&#41;</span></div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; .<span class="me1">To</span><span class="br0">&#40;</span>bindableTarget.<span class="me1">Text</span><span class="br0">&#41;</span>;</div></li>
<li class="li1"><div class="de1"><span class="br0">&#125;</span></div></li></ol></div>

<p>As you probably understand, the risk of mistyping is removed, and we get IntelliSense support out of the box.</p>

<h2>Behind the scenes of Strongbind</h2>

<p>To achieve this strongly typed data binding, Strongbind uses a technique known as proxying. Strongbind dynamically generates a proxy for your business object and your control, and uses the proxies to intercept the calls to the property getters during runtime to declare the data binding. Hence, you need to declare a bindable source and bindable target first to create the proxies, and then use these proxies during the binding declaration. You will get a runtime error if you try to use your real objects when declaring data bindings.</p>

<h2>Limitations of Strongbind</h2>

<p>Although Strongbind makes data binding a far more declarative process, the library does have its limitations.</p>

<p>Controls containing ActiveX components are not supported. If the control containing an ActiveX component is a custom control created by you, you can get around it by declaring an interface for
the control and specifying that as the type to use when declaring your binding source:</p>

<div class="dean_ch" style="white-space: wrap;"><ol><li class="li1"><div class="de1"><span class="co1">// The control interface </span></div></li>
<li class="li1"><div class="de1"><span class="co1">// (must inherit IBindableComponent)</span></div></li>
<li class="li1"><div class="de1"><span class="kw1">public</span> <span class="kw4">interface</span> IBindableAXControl </div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; : IBindableComponent </div></li>
<li class="li2"><div class="de2"><span class="br0">&#123;</span></div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; <span class="kw4">string</span> Text <span class="br0">&#123;</span> get; set; <span class="br0">&#125;</span></div></li>
<li class="li1"><div class="de1"><span class="br0">&#125;</span></div></li>
<li class="li1"><div class="de1">&nbsp;</div></li>
<li class="li1"><div class="de1"><span class="co1">// Declare the binding target this way within a </span></div></li>
<li class="li2"><div class="de2"><span class="co1">// binding scope</span></div></li>
<li class="li1"><div class="de1">IBindableAXControl source = </div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp;scope.<span class="me1">CreateTarget</span>&lt;IBindableAXControl&gt;<span class="br0">&#40;</span>control<span class="br0">&#41;</span>;</div></li></ol></div>

<p>Also, binding to concrete binding sources with non-virtual properties is not supported. Again, the recommended workaround is to create an interface for your binding source and use that when declaring the data bindings. (You always want to create these interfaces, since decoupling your objects&#8217; interfaces from their implementation is recommended for testability, maintainability, and is generally A Good Thing(tm).)</p>

<div class="dean_ch" style="white-space: wrap;"><ol><li class="li1"><div class="de1"><span class="co1">// The business object interface</span></div></li>
<li class="li1"><div class="de1"><span class="kw1">public</span> <span class="kw4">interface</span> IBusinessObject</div></li>
<li class="li1"><div class="de1"><span class="br0">&#123;</span></div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; <span class="kw4">string</span> Description <span class="br0">&#123;</span> get; set; <span class="br0">&#125;</span></div></li>
<li class="li2"><div class="de2"><span class="br0">&#125;</span></div></li>
<li class="li1"><div class="de1">&nbsp;</div></li>
<li class="li1"><div class="de1"><span class="co1">// Declare the binding source this way within a </span></div></li>
<li class="li1"><div class="de1"><span class="co1">// binding scope</span></div></li>
<li class="li1"><div class="de1">IBusinessObject bindableSource = </div></li>
<li class="li2"><div class="de2">&nbsp; &nbsp; scope.<span class="me1">CreateSource</span>&lt;IBusinessObject&gt;<span class="br0">&#40;</span>source<span class="br0">&#41;</span>;</div></li></ol></div>

<p>Apart from these two issues, which can be worked around in most cases, Strongbind should work flawlessly. If it does not, <a href="http://code.google.com/p/strongbind/issues/">I would be happy to know</a>.</p>

<h2>Where do I get it?</h2>

<p><a href="http://strongbind.googlecode.com">Strongbind is an open source project</a> hosted at <a href="http://googlecode.com">Google Code</a>. To get the latest version, <a href="http://code.google.com/p/strongbind/source/checkout">check out the code from its repository</a>.</p>

<p>Strongbind is still in an early development stage, so no releases have been created yet. I still encourage you to check out and start using the library as soon as possible, though. A beta will be released as soon as I feel comfortable doing it.</p>

<p>If you want to contribute to Strongbind, I would be happy to welcome you. Visit http://strongbind.googlecode.com for instructions.</p>

<p>Bind away!</p>
]]></content:encoded>
			<wfw:commentRss>http://ox.no/posts/strongly-typed-data-binding-in-windows-forms/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>AJAST &#8211; Cross-domain REST calls using JSON injection</title>
		<link>http://ox.no/posts/ajast-cross-domain-rest-calls-using-json-injection</link>
		<comments>http://ox.no/posts/ajast-cross-domain-rest-calls-using-json-injection#comments</comments>
		<pubDate>Mon, 24 Mar 2008 22:48:32 +0000</pubDate>
		<dc:creator>Håvard</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Technical]]></category>
		<category><![CDATA[AJAST]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[REST]]></category>

		<guid isPermaLink="false">http://ox.no/posts/ajast-cross-domain-rest-calls-using-javascript-injection</guid>
		<description><![CDATA[The typical (and original AJAX) approach to calling web services asynchronously from a browser uses the XMLHTTPRequest object to request data asynchronously. However, as most of you probably already know, requests made using this object are restricted to the same domain as the script they originate from. This means that in order to request data [...]]]></description>
			<content:encoded><![CDATA[<p>The typical (and original AJAX) approach to calling web services asynchronously from a browser uses the <code>XMLHTTPRequest</code> object to request data asynchronously. However, as most of you probably already know, requests made using this object are restricted to the same domain as the script they originate from. This means that in order to request data from services like Google Maps, Flickr, etc. you need to implement a server-side proxy on your domain to use the <code>XMLHTTPRequest</code> object. But what if you want to stay on the client side? Enter JSON injection.</p>

<p>JSON injection, or actually script tag injection, is a rather common technique that circumvents the <code>XMLHTTPRequest</code> limitation by dynamically injecting script tags into the calling page. A script tag can have any domain as its source, which means that cross-domain calls are possible. The technique is also referred to as JSON callbacks, although it really is not limited to JSON payloads. The technique is also referred to as JSONP, although <a href="http://ajaxian.com/archives/jsonp-json-with-padding">the original JSONP</a> is a bit more extensive than just callbacks using script injection.</p>

<p>It really is a neat technique without a cool term. JSONP is a term for a superset of JSON injection. A more precise term than JSON injection would be Javascript injection, but that&#8217;s already used to describe vulnerabilities in web pages where malicious Javascript code is injected through e.g. links from external sites. I hereby propose the term <b>AJAST</b> &#8211; <b>A</b>synchronous <b>J</b>avascript <b>A</b>nd <b>S</b>cript <b>T</b>ags. At least it&#8217;ll be the name of my implementation. If it doesn&#8217;t catch on for anything but that, we&#8217;ll even be a bit more confused than we already are. Now, what do we require to do AJAST?</p>

<h3>AJAST requirements</h3>

<p>The requirements an AJAST request lays on the server-side are the following:</p>

<ol>
<li>The server must provide its services through HTTP GET requests.</li>
<li>The client must be able to supply the name of a callback function that the response will be wrapped in.</li>
<li>The server is expected to provide a response on the form <code>callback(payload)</code>, where <code>callback</code> is the name of the callback function supplied by the client, and <code>payload</code> is the payload returned by the server. The payload can be XML, JSON, or any other form of data that the Javascript callback function can accept as a single argument.</li>
</ol>

<p>These requirements are already fulfilled by many REST services, but they are still hard to use in an AJAST fashion due to client side challenges. The two main requirements for an AJAST library are:</p>

<ol>
<li>Complete handling of requests. Nothing more than a URL and a callback should be needed to create a request.</li>
<li>Timeouts is a show stopper for AJAST. With script injection, it is difficult to know if a call completes, and from an AJAST usage perspective it is essentially impossible to create a decent solution without knowing if requests complete or not.</li>
</ol>

<p>Security is another obvious challenge, although in my view it is a challenge for the Internet in general rather than AJAST in particular. Developers creating cross-domain applications should be aware of the security risks involved, and take measures to prevent security breaches accordingly. There is no silver bullet.</p>

<p>Although several examples for implementing an AJAST request are found around the web, I found no fully functional stand-alone implementations. Dan Theurer&#8217;s <a href="http://www.theurer.cc/blog/2005/12/15/web-services-json-dump-your-proxy/">article on script requests</a> provides code that can be used to create an implementation, but leaves the timeout problem unsolved. Toolkits such as <a href="http://dojotoolkit.org">Dojo</a> also implement variations on the approach using IFrame requests, but they are a lot more hairy, and I really don&#8217;t want a framework (or parts of it) bloating the web site I am creating just to be able to do AJAST. I want a library that can perform just the task that I want it to perform, and perform it well.</p>

<h3>An AJAST library</h3>

<p>So, I decided to create my own AJAST library, <a href="http://ox.no/files/ox.ajast.js">OX.AJAST</a>, complete with the following features:</p>

<ul>
<li><b>A fully encapsulated mechanism for making AJAST calls</b><br />You simply supply a URL, the name of the callback parameter that will be appended to the URL, and a callback function.</li>
<li><b>Support for timeouts</b><br />Remote requests can of course time out, and time outs need to be handled. Apart from the obvious security challenges involved with using AJAST (note that I&#8217;m not saying they&#8217;re defects, they&#8217;re challenges for us developers to handle) , this is the hardest challenge for AJAST requests. Without the ability of specifying timeouts, we&#8217;re essentially in the dark with regards to whether or not a request will complete. OX.AJAST neatly supports timeouts by wrapping the supplied callbacks, putting on a timer, and checking for completion when the timer times out.</li>
<li><b>Guarantee that the callback function will be called</b><br />Whatever happens, and as a direct consequence of the timeout support, the library <em>guarantees</em> that the callback function will be called. For this reason, the callback function must accept two arguments, the first a boolean indicating if the request succeeded or not, the other a string containing the response from the call. If the first argument is false, the call may have timed out or failed.</li>
</ul>

<h3>Using the AJAST call function</h3>

<p>There are two ways of using OX.AJAST. The simplest is to use the <code>call</code> function.</p>

<div class="dean_ch" style="white-space: wrap;"><ol><li class="li1"><div class="de1"> &nbsp;<span class="co1">// Create a function that will be called when the AJAST request completes</span></div></li>
<li class="li1"><div class="de1">&nbsp; <span class="kw2">function</span> callCompleted<span class="br0">&#40;</span>success, data<span class="br0">&#41;</span></div></li>
<li class="li1"><div class="de1">&nbsp; <span class="br0">&#123;</span></div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; <span class="kw1">if</span><span class="br0">&#40;</span>!success<span class="br0">&#41;</span></div></li>
<li class="li2"><div class="de2">&nbsp; &nbsp; &nbsp; <span class="kw3">alert</span><span class="br0">&#40;</span><span class="st0">&#8216;Fail&#8217;</span><span class="br0">&#41;</span>;</div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; <span class="kw1">else</span></div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; &nbsp; <span class="kw3">alert</span><span class="br0">&#40;</span><span class="st0">&#8216;Received: &#8216;</span> + data<span class="br0">&#41;</span>;</div></li>
<li class="li1"><div class="de1">&nbsp; <span class="br0">&#125;</span></div></li>
<li class="li1"><div class="de1">&nbsp; <span class="co1">// Call a service</span></div></li>
<li class="li2"><div class="de2">&nbsp; OX.<span class="me1">AJAST</span>.<span class="me1">call</span><span class="br0">&#40;</span></div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; <span class="st0">&#8216;http://xampl.com/rest?arg=foo&#8217;</span>, </div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; <span class="st0">&#8216;callback&#8217;</span>, </div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; callCompleted<span class="br0">&#41;</span>;</div></li></ol></div>

<p>The <code>call</code> function will execute the request by appending <code>&amp;callback=wrapper</code> to the URL and injecting a <code>&lt;script&gt;</code> tag with the final URL as the <code>src</code> attribute. This will add a call to the DOM as soon as the data is received, which the browser will execute.</p>

<p>The function called from the injected script tag is a wrapper around the <code>callCompleted</code> function provided to the <code>call</code> function. The wrapper function is created by the <code>call</code> function, and handles timeouts and deletion of the script tag after the <code>callCompleted</code> function completes. As mentioned, by using this wrapper, the AJAST library can guarantee that <code>callCompleted</code> will be called, which significantly eases the handling of asynchronous calls for users of the library.</p>

<p>The function also allows you to specify how long the request will wait for a response before it times out. The default timeout is 5 seconds. Finally, you can pass an argument specifying if you want the response to be automatically decoded from JSON before it is passed to your callback function.</p>

<div class="dean_ch" style="white-space: wrap;"><ol><li class="li1"><div class="de1"><span class="co1">// Call with a 10 second timeout, decode JSON response</span></div></li>
<li class="li1"><div class="de1">OX.<span class="me1">AJAST</span>.<span class="me1">call</span><span class="br0">&#40;</span></div></li>
<li class="li1"><div class="de1">&nbsp; <span class="st0">&#8216;http://xampl.com/rest?arg=foo&#8217;</span>, </div></li>
<li class="li1"><div class="de1">&nbsp; <span class="st0">&#8216;callback&#8217;</span>, </div></li>
<li class="li2"><div class="de2">&nbsp; callCompleted, </div></li>
<li class="li1"><div class="de1">&nbsp; <span class="nu0">10000</span>, </div></li>
<li class="li1"><div class="de1">&nbsp; <span class="kw2">true</span><span class="br0">&#41;</span>;</div></li></ol></div>

<p>As stated above, all callback functions must be on the form <code>callbackfunction(success, data){}</code>, where <code>success</code> indicates whether or not the asynchronous call succeeded, and <code>data</code> is any data that was received from the call. It is also important to note that <code>data</code> may be undefined, but <code>success</code> will always be <code>true</code> or <code>false</code>.</p>

<h3>Using the AJAST broker</h3>

<p>The AJAST broker encapsulates a common pattern for REST requests using HTTP GET. Many RESTful services found online typically use some kind of root URL of the form <code>http://xampl.com/rest</code> as the base URL for all their REST services. The query string determines which service is requested, as well as the arguments for the service.</p>

<p>For the services that follow this pattern, the AJAST library provides a <code>Broker</code> class that encapsulates the process of calling the REST services.</p>

<p>The example below shows how the request from the first example can be made using the broker.</p>

<div class="dean_ch" style="white-space: wrap;"><ol><li class="li1"><div class="de1"><span class="co1">// Create a broker object</span></div></li>
<li class="li1"><div class="de1"><span class="kw2">var</span> broker = <span class="kw2">new</span> OX.<span class="me1">AJAST</span>.<span class="me1">Broker</span><span class="br0">&#40;</span></div></li>
<li class="li1"><div class="de1">&nbsp; <span class="st0">&#8216;http://xampl.com/rest&#8217;</span>, </div></li>
<li class="li1"><div class="de1">&nbsp; <span class="st0">&#8216;callback&#8217;</span></div></li>
<li class="li2"><div class="de2"><span class="br0">&#41;</span>;</div></li>
<li class="li1"><div class="de1"><span class="co1">// Perform the same call using the broker</span></div></li>
<li class="li1"><div class="de1">broker.<span class="me1">call</span><span class="br0">&#40;</span><span class="br0">&#123;</span>arg: <span class="st0">&#8216;foo&#8217;</span><span class="br0">&#125;</span>, callCompleted<span class="br0">&#41;</span>;</div></li></ol></div>

<p>The broker also supports the specification of a timeout limit, automated JSON decoding, and also provides the option of passing a set of default arguments that will be passed with every request, such as a Flickr API key.</p>

<div class="dean_ch" style="white-space: wrap;"><ol><li class="li1"><div class="de1"><span class="co1">// Create a broker object</span></div></li>
<li class="li1"><div class="de1"><span class="kw2">var</span> broker = <span class="kw2">new</span> OX.<span class="me1">AJAST</span>.<span class="me1">Broker</span><span class="br0">&#40;</span></div></li>
<li class="li1"><div class="de1">&nbsp; <span class="st0">&#8216;http://xampl.com/rest&#8217;</span>, </div></li>
<li class="li1"><div class="de1">&nbsp; <span class="st0">&#8216;callback&#8217;</span>, </div></li>
<li class="li2"><div class="de2">&nbsp; <span class="kw2">true</span>, <span class="co1">// Decode JSON response</span></div></li>
<li class="li1"><div class="de1">&nbsp; <span class="nu0">10000</span>, <span class="co1">// Timeout in ms</span></div></li>
<li class="li1"><div class="de1">&nbsp; <span class="br0">&#123;</span>APIKey : <span class="st0">&#8216;123&#8242;</span><span class="br0">&#125;</span> <span class="co1">// Default parameters</span></div></li>
<li class="li1"><div class="de1"><span class="br0">&#41;</span>;</div></li></ol></div>

<p>Now let&#8217;s do something useful with it.</p>

<h3>A real example: Flickr using AJAST</h3>

<p>To keep the example as simple as possible, we&#8217;ll create the functions necessary for a page which fetches the most recent photos from <a href="http://flickr.com">Flickr</a>.</p>

<p>Luckily, Flickr supports REST and JSON callbacks in a lovely manner, so we&#8217;ll use the broker for our calls.</p>

<div class="dean_ch" style="white-space: wrap;"><ol><li class="li1"><div class="de1"><span class="kw2">function</span> flickrGetRecent<span class="br0">&#40;</span><span class="br0">&#41;</span></div></li>
<li class="li1"><div class="de1"><span class="br0">&#123;</span></div></li>
<li class="li1"><div class="de1">&nbsp; <span class="co1">// Create &nbsp;a broker</span></div></li>
<li class="li1"><div class="de1">&nbsp; <span class="kw2">var</span> broker = <span class="kw2">new</span> OX.<span class="me1">AJAST</span>.<span class="me1">Broker</span><span class="br0">&#40;</span></div></li>
<li class="li2"><div class="de2">&nbsp; &nbsp; <span class="st0">&#8216;http://api.flickr.com/services/rest/&#8217;</span>, </div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; <span class="st0">&#8216;jsoncallback&#8217;</span>, </div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; <span class="kw2">true</span>, </div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; <span class="nu0">10000</span>,</div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; <span class="br0">&#123;</span>api_key: <span class="st0">&#8216;YourVeryOwnFlickrApiKey&#8217;</span>, </div></li>
<li class="li2"><div class="de2">&nbsp; &nbsp; &nbsp; format: <span class="st0">&#8216;json&#8217;</span><span class="br0">&#125;</span><span class="br0">&#41;</span>;</div></li>
<li class="li1"><div class="de1">&nbsp;</div></li>
<li class="li1"><div class="de1">&nbsp; <span class="co1">// Perform the call</span></div></li>
<li class="li1"><div class="de1">&nbsp; broker.<span class="me1">call</span><span class="br0">&#40;</span></div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; <span class="br0">&#123;</span>method: <span class="st0">&#8216;flickr.photos.getRecent&#8217;</span><span class="br0">&#125;</span>, </div></li>
<li class="li2"><div class="de2">&nbsp; &nbsp; recentFetched<span class="br0">&#41;</span>;</div></li>
<li class="li1"><div class="de1"><span class="br0">&#125;</span></div></li>
<li class="li1"><div class="de1">&nbsp;</div></li></ol></div>

<p>We&#8217;ve told the broker to call a function named <code>recentFetched</code> when the recent photos have been fetched, so let&#8217;s implement that as well. To keep the example simple, we&#8217;ll just append the photos to the body of the document.</p>

<div class="dean_ch" style="white-space: wrap;"><ol><li class="li1"><div class="de1"><span class="kw2">function</span> recentFetched<span class="br0">&#40;</span>success, rsp<span class="br0">&#41;</span></div></li>
<li class="li1"><div class="de1"><span class="br0">&#123;</span></div></li>
<li class="li1"><div class="de1">&nbsp; <span class="co1">// Check for failure</span></div></li>
<li class="li1"><div class="de1">&nbsp; <span class="kw1">if</span><span class="br0">&#40;</span>!success || !rsp || rsp.<span class="me1">stat</span> != <span class="st0">&#8216;ok&#8217;</span><span class="br0">&#41;</span></div></li>
<li class="li2"><div class="de2">&nbsp; <span class="br0">&#123;</span></div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; <span class="kw3">alert</span><span class="br0">&#40;</span><span class="st0">&#8216;Call failed&#8217;</span><span class="br0">&#41;</span>;</div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; <span class="kw1">return</span>;</div></li>
<li class="li1"><div class="de1">&nbsp; <span class="br0">&#125;</span></div></li>
<li class="li1"><div class="de1">&nbsp;</div></li>
<li class="li2"><div class="de2">&nbsp; <span class="co1">// For each photo&#8230; &nbsp;</span></div></li>
<li class="li1"><div class="de1">&nbsp; <span class="kw1">for</span><span class="br0">&#40;</span>i <span class="kw1">in</span> rsp.<span class="me1">photos</span>.<span class="me1">photo</span><span class="br0">&#41;</span></div></li>
<li class="li1"><div class="de1">&nbsp; <span class="br0">&#123;</span></div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; photo = rsp.<span class="me1">photos</span>.<span class="me1">photo</span><span class="br0">&#91;</span>i<span class="br0">&#93;</span>;</div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; </div></li>
<li class="li2"><div class="de2">&nbsp; &nbsp; <span class="co1">// Create an img element</span></div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; img = document.<span class="me1">createElement</span><span class="br0">&#40;</span><span class="st0">&#8216;img&#8217;</span><span class="br0">&#41;</span>;</div></li>
<li class="li1"><div class="de1">&nbsp;</div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; <span class="co1">// Set its source to a valid Flickr URL</span></div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; img.<span class="me1">setAttribute</span><span class="br0">&#40;</span><span class="st0">&#8217;src&#8217;</span>, </div></li>
<li class="li2"><div class="de2">&nbsp; &nbsp; &nbsp; <span class="st0">&#8216;http://farm&#8217;</span> + <span class="br0">&#40;</span>photo.<span class="me1">farm</span> || <span class="nu0">1</span><span class="br0">&#41;</span> + </div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; &nbsp; <span class="st0">&#8216;.static.flickr.com/&#8217;</span> + photo.<span class="me1">server</span> + </div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; &nbsp; <span class="st0">&#8216;/&#8217;</span> + photo.<span class="me1">id</span> + <span class="st0">&#8216;_&#8217;</span> + photo.<span class="me1">secret</span> + <span class="st0">&#8216;_t.jpg&#8217;</span><span class="br0">&#41;</span>;</div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; </div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; <span class="co1">// Append the element</span></div></li>
<li class="li2"><div class="de2">&nbsp; &nbsp; document.<span class="me1">body</span>.<span class="me1">appendChild</span><span class="br0">&#40;</span>img<span class="br0">&#41;</span>;</div></li>
<li class="li1"><div class="de1">&nbsp; <span class="br0">&#125;</span></div></li>
<li class="li1"><div class="de1"><span class="br0">&#125;</span></div></li></ol></div>

<p>Now we just have to call flickrGetRecent from somewhere in a document, and the most recent photos will be appended to the document. A full example can be seen <a href="http://ox.no/files/flickr.html">here</a>. Note that you will need a <a href="http://www.flickr.com/services/api/">Flickr API key</a> to test it.</p>

<p>As you can see, the OX.AJAST library is really easy to use, and enables you to do pure client-side REST service calls across domain boundaries with hardly any effort. I hope you find it useful. Drop a comment if you have problems or suggestions, or if you create improvements to it. Now <a href="http://ox.no/files/ox.ajast.js" title="The OX AJAST library">start using AJAST</a>!</p>
]]></content:encoded>
			<wfw:commentRss>http://ox.no/posts/ajast-cross-domain-rest-calls-using-json-injection/feed</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Object-Relational Mappings Considered Harmful</title>
		<link>http://ox.no/posts/object-relational-mappings-considered-harmful</link>
		<comments>http://ox.no/posts/object-relational-mappings-considered-harmful#comments</comments>
		<pubDate>Tue, 04 Mar 2008 22:48:25 +0000</pubDate>
		<dc:creator>Håvard</dc:creator>
				<category><![CDATA[Software Design]]></category>
		<category><![CDATA[Technical]]></category>
		<category><![CDATA[Database]]></category>
		<category><![CDATA[LINQ]]></category>

		<guid isPermaLink="false">http://ox.no/posts/object-relational-mappings-considered-harmful</guid>
		<description><![CDATA[Creating an Object-Relational Mapping (ORM) has become the de facto way of handling persistence in the object-oriented programming paradigm. Almost all systems require some form of persistent state, and relational databases have become the de facto place to put that state. Relational databases are proven, scale well, and organize data in a tabular manner suitable [...]]]></description>
			<content:encoded><![CDATA[<p>Creating an Object-Relational Mapping (ORM) has become the de facto way of handling persistence in the object-oriented programming paradigm. Almost all systems require some form of persistent state, and relational databases have become the de facto place to put that state. Relational databases are proven, scale well, and organize data in a tabular manner suitable for many of the real world problems that we try to solve, so they are an obvious choice. Choosing them, however, means we have a new problem at our hands, known as the <a href="http://en.wikipedia.org/wiki/Object-Relational_impedance_mismatch" title="The Object-Relational Impedance Mismatch">object-relational impedance mismatch</a>.</p>

<!-- more -->

<p>The problem is that a relational database is not suited for storing an object-oriented model. An object is almost always a non-scalar value, meaning that it won&#8217;t fit well in a table row. Hence, we have to create a schema suitable for persisting our objects to a set of tables. This schema will be different for each type of object we have, so it&#8217;s a rather tedious task, but it solves the problem.</p>

<p>As always, we developers tend to dislike repetitive tasks, so we try to simplify and automate the extra work involved with creating an ORM. This has led to various design patterns such as DAO, and in recent years a set of fully automated ORM tools such as <a href="http://hibernate.org/" title="Hibernate">Hibernate (Java)</a>, <a href="http://nhibernate.org" title="NHibernate">NHibernate (.NET)</a>, <a href="http://sqlalchemy.org" title="SQLAlchemy">SQLAlchemy (Python)</a>, and <a href="http://propel.phpdb.org/" title="Propel">Propel (PHP)</a> have become very popular. These tools offer a highly transparent solution to the ORM problem, at the addition of a cost that varies heavily with the nature of the ORM problem. Still, their presence moves us closer and closer to a solution &#8211; we are creating an abstraction that fully encapsulates the difference between a relational database as our storage for persistent objects, and the objects themselves. Hopefully, we will soon be able to create an ORM that induces a linear or perhaps even constant cost on our solution, regardless of the nature of the problem we are trying to solve.</p>

<p>But wait. The real problem we are trying to solve is how to persist the state of our objects, remember? The database is indeed a store, and hence a candidate solution, but using it introduces an impedance mismatch, which is another problem we need to solve. It really is like trying to fit a square block in a round hole.</p>

<p>Let&#8217;s stop trying to solve the wrong problem of creating an ORM, and start finding a solution to our initial and real problem of persisting our objects. Recent innovations such as <a href="http://en.wikipedia.org/wiki/Language_Integrated_Query">LINQ</a> has taken us a step in the right direction by making persistence an integral part of the language, but we&#8217;re still a long way from automated persistence for our objects. I am certain, though, that moving focus away from the challenges of an ORM and on to the challenge of persistence in general will take us further.</p>

<p>Let&#8217;s do that.</p>

<p>(And I&#8217;m sorry for reusing <a href="http://www.u.arizona.edu/~rubinson/copyright_violations/Go_To_Considered_Harmful.html" title="Go To Statement Considered Harmful">Dijkstra&#8217;s</a> already <a href="http://meyerweb.com/eric/comment/chech.html" title="Considered Harmful Essays Considered Harmful">overused</a> phrase.)</p>
]]></content:encoded>
			<wfw:commentRss>http://ox.no/posts/object-relational-mappings-considered-harmful/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Extension methods for copying or cloning objects</title>
		<link>http://ox.no/posts/extension-methods-for-copying-or-cloning-objects</link>
		<comments>http://ox.no/posts/extension-methods-for-copying-or-cloning-objects#comments</comments>
		<pubDate>Thu, 10 Jan 2008 19:23:32 +0000</pubDate>
		<dc:creator>Håvard</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Technical]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[clone]]></category>
		<category><![CDATA[copy]]></category>
		<category><![CDATA[copyable]]></category>
		<category><![CDATA[open source]]></category>

		<guid isPermaLink="false">http://ox.no/posts/extension-methods-for-copying-or-cloning-objects</guid>
		<description><![CDATA[C# 3.0 includes a new feature known as extension methods, and fiddling with it triggered the idea of creating a mechanism for copying or cloning (virtually) any .NET object or graph of objects. The manifestation of that idea has become a rather decent little framework for copying objects. It performs a deep copy as automatically [...]]]></description>
			<content:encoded><![CDATA[<p>C# 3.0 includes a new feature known as extension methods, and fiddling with it triggered the idea of creating a mechanism for copying or cloning (virtually) any .NET object or graph of objects. The manifestation of that idea has become a rather decent little framework for copying objects. It performs a deep copy as automatically as it possibly can, and provides mechanisms to easily solve many of the cases which cannot be covered automatically. It is great for copying your custom object hierarchies, and saves you the pain of a solution like implementing <code>ICloneable</code> for an entire hierarchy of objects. Click <a href="http://ox.no/software/copyable" title="The Copyable framework">here</a> to grab it now, and read on for a presentation.<!-- more --></p>

<p>Let&#8217;s start off with a few words on extension methods. They are best explained through an example. Let&#8217;s say we want to be able to calculate area given size. Wouldn&#8217;t it be nice to be able to add <code>GetArea</code> to the already existing <code>Size</code> class? Well, let&#8217;s do so!</p>

<div class="dean_ch" style="white-space: wrap;"><ol><li class="li1"><div class="de1"><span class="kw1">public</span> <span class="kw1">static</span> <span class="kw4">class</span> ExtensionMethods</div></li>
<li class="li1"><div class="de1"><span class="br0">&#123;</span></div></li>
<li class="li1"><div class="de1">&nbsp; <span class="kw1">public</span> <span class="kw1">static</span> <span class="kw4">int</span> GetArea<span class="br0">&#40;</span><span class="kw1">this</span> Size size<span class="br0">&#41;</span></div></li>
<li class="li1"><div class="de1">&nbsp; <span class="br0">&#123;</span></div></li>
<li class="li2"><div class="de2">&nbsp; &nbsp; <span class="kw1">return</span> size.<span class="me1">Width</span> * size.<span class="me1">Height</span>;</div></li>
<li class="li1"><div class="de1">&nbsp; <span class="br0">&#125;</span></div></li>
<li class="li1"><div class="de1"><span class="br0">&#125;</span></div></li></ol></div>

<p>As you can see, the new syntax simply allows you to tell the compiler that the <code>this</code> of this method is a <code>Size</code>. This means that the method is an extension of the <code>Size</code> class.</p>

<p>As mentioned, I had the idea of extending the very base of the C# class hierarchy (<code>System.Object</code>) with a method for copying or cloning &#8220;any&#8221; object. Obviously, the method cannot automatically copy <em>any</em> object, since it cannot possibly know how to construct an object from an arbitrary class. Hence, a small framework needed to be created. The goals were to:</p>

<ul>
<li>Enable copying of <em>many</em> objects automatically.</li>
<li>Enable copying of virtually <em>any</em> object with very little effort.</li>
<li>Automate and hide away as much as possible (The <a href="http://en.wikipedia.org/wiki/KISS_principle" title="The KISS Principle">KISS</a> Principle).</li>
</ul>

<p>The result is Copyable (pun intended). <!-- more --></p>

<h2>The Copyable framework</h2>

<p>Copyable is a small framework for copying (or cloning, if you will) objects. The straightforward way of using it is to just reference the assembly it&#8217;s in from your project, and start copying!</p>

<div class="dean_ch" style="white-space: wrap;"><ol><li class="li1"><div class="de1">SomeType instance = <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span class="kw3">new</span></a> SomeType<span class="br0">&#40;</span><span class="br0">&#41;</span>;</div></li>
<li class="li1"><div class="de1"><span class="co1">// &#8230;do lots of stuff to the object&#8230;</span></div></li>
<li class="li1"><div class="de1">SomeType copy = instance.<span class="me1">Copy</span><span class="br0">&#40;</span><span class="br0">&#41;</span>; <span class="co1">// Create a deep copy</span></div></li></ol></div>

<p>The instance <code>copy</code> is now a deep copy of <code>instance</code>, no matter how complex the object graph for <code>instance</code> is. The relations in the <code>copy</code> graph is the same as in <code>instance</code>, but all objects in the <code>copy</code> object graph are copies of those in <code>instance</code>.</p>



<p>For the automated copy to work, though, one of the following statements must hold for <code>instance</code>:</p>

<ul>
<li>Its type must have a parameterless constructor, or</li>
<li>It must be a <code>Copyable</code>, or</li>
<li>It must have an <code>IInstanceProvider</code> registered for its type.</li>
</ul>

<p>Besides the <code>Copy</code> method, The <code>Copyable</code> class and <code>IInstanceProvider</code> interface are the two major building blocks of the Copyable framework. Each of these blocks enable copying of objects that cannot automatically be copied.</p>

<h2>The Copyable base class</h2>

<p><code>Copyable</code> is an abstract base class for objects that can be copied. To create a copyable class, you simply subclass <code>Copyable</code> and call its constructor with the arguments of your constructor.</p>

<div class="dean_ch" style="white-space: wrap;"><ol><li class="li1"><div class="de1"><span class="kw4">class</span> MyClass : Copyable</div></li>
<li class="li1"><div class="de1"><span class="br0">&#123;</span></div></li>
<li class="li1"><div class="de1">&nbsp; <span class="kw1">public</span> MyClass<span class="br0">&#40;</span><span class="kw4">int</span> a, <span class="kw4">double</span> b, <span class="kw4">string</span> c<span class="br0">&#41;</span></div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; : <span class="kw1">base</span><span class="br0">&#40;</span>a, b, c<span class="br0">&#41;</span></div></li>
<li class="li2"><div class="de2">&nbsp; <span class="br0">&#123;</span></div></li>
<li class="li1"><div class="de1">&nbsp; <span class="br0">&#125;</span></div></li>
<li class="li1"><div class="de1"><span class="br0">&#125;</span></div></li></ol></div>

<p>This code above makes <code>MyClass</code> a copyable class. Note that if <code>MyClass</code> had had a parameterless constructor, subclassing <code>Copyable</code> would not be necessary.</p>

<p><code>MyClass</code> can now be copied just like the previous example.</p>

<div class="dean_ch" style="white-space: wrap;"><ol><li class="li1"><div class="de1">MyClass a = <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span class="kw3">new</span></a> MyClass<span class="br0">&#40;</span><span class="nu0">1</span>, <span class="nu0">2.0</span>, <span class="st0">&quot;3&quot;</span><span class="br0">&#41;</span>;</div></li>
<li class="li1"><div class="de1">MyClass b = a.<span class="me1">Copy</span><span class="br0">&#40;</span><span class="br0">&#41;</span>;</div></li></ol></div>

<p>The introduction of the <code>Copyable</code> base class solves many problems, but not all. Let&#8217;s say you wanted to copy a <code>System.Drawing.SolidBrush</code>. This class does not have a parameterless constructor, which means it cannot be copied &#8220;automatically&#8221; by the framework. Also, you cannot alter it so that it subclasses <code>Copyable</code>. So, what do you do? You create an instance provider.</p>

<h2>The IInstanceProvider interface</h2>

<p>An instance provider is defined by the interface <code>IInstanceProvider</code>. As the name clearly states, the implementation is a provider of instances. One instance provider can provide instances of one given type. The Copyable framework automatically detects <code>IInstanceProvider</code> implementations in all assembies in its application domain, so all you need to do to create a working instance provider is to define it. No registration or other additional operations are required. To simplify the implementation of instance providers and the <code>IInstanceProvider</code> interface, an abstract class <code>InstanceProvider</code> is included in the framework.</p>

<div class="dean_ch" style="white-space: wrap;"><ol><li class="li1"><div class="de1"><span class="kw1">public</span> <span class="kw4">class</span> SolidBrushProvider </div></li>
<li class="li1"><div class="de1">&nbsp; : InstanceProvider&lt;SolidBrush&gt;</div></li>
<li class="li1"><div class="de1"><span class="br0">&#123;</span></div></li>
<li class="li1"><div class="de1">&nbsp; <span class="kw1">public</span> <span class="kw1">override</span> SolidBrush CreateTypedCopy<span class="br0">&#40;</span>SolidBrush s<span class="br0">&#41;</span></div></li>
<li class="li2"><div class="de2">&nbsp; <span class="br0">&#123;</span></div></li>
<li class="li1"><div class="de1">&nbsp; &nbsp; <span class="kw1">return</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span class="kw3">new</span></a> SolidBrush<span class="br0">&#40;</span>s.<span class="me1">Color</span><span class="br0">&#41;</span>;</div></li>
<li class="li1"><div class="de1">&nbsp; <span class="br0">&#125;</span></div></li>
<li class="li1"><div class="de1"><span class="br0">&#125;</span></div></li></ol></div>

<p>This implementation will be used automatically by the Copyable framework. <strong>NOTE: To be usable, the instance provider MUST have a parameterless constructor.</strong></p>

<p>The instance provider pattern does not solve the case where you want different initial states for your SolidBrush instances depending on which context you use them for copying. For those cases, an overload of <code>Copy()</code> exists which takes an already created instance as an argument. This argument will become the copy.</p>

<div class="dean_ch" style="white-space: wrap;"><ol><li class="li1"><div class="de1">SolidBrush instance = <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span class="kw3">new</span></a> SolidBrush<span class="br0">&#40;</span>Color.<span class="me1">Red</span><span class="br0">&#41;</span>;</div></li>
<li class="li1"><div class="de1">instance.<span class="me1">Color</span> = Color.<span class="me1">Black</span>;</div></li>
<li class="li1"><div class="de1">SolidBrush copy = <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span class="kw3">new</span></a> SolidBrush<span class="br0">&#40;</span>Color.<span class="me1">Red</span><span class="br0">&#41;</span>;</div></li>
<li class="li1"><div class="de1">instance.<span class="me1">Copy</span><span class="br0">&#40;</span>copy<span class="br0">&#41;</span>; <span class="co1">// Create a deep copy</span></div></li></ol></div>

<p>In this example, <code>copy</code> is now of the color <code>Color.Black</code>.</p>

<h2>Limitations and pitfalls</h2>

<p>Although this solution works in most cases, it&#8217;s not a silver bullet. Be aware when you copy classes that hold unmanaged resources such as handles. If these classes are designed on the premise that their resources are exclusive to them, they will manage them as they see fit. Imagine if you copied a class which holds a handle, disposed one of the instances, and continued using the copy. The handle will (probably) be freed by the original instance, and the copy will generate an access violation by attempting reading or writing freed memory.</p>

<p>That&#8217;s it! The Copyable framework can be downloaded from <a href="http://ox.no/software/copyable" title="The Copyable framework">here</a>. For those interested in reading more on extension methods, For additional information, MSDN provides an excellent explanation in the <a href="http://msdn2.microsoft.com/en-us/library/bb383977.aspx" title="Extension methods in C# 3.0">C# Programming Guide</a>, and Scott Guthrie has an introduction article <a href="http://weblogs.asp.net/scottgu/archive/2007/03/13/new-orcas-language-feature-extension-methods.aspx" title="Scott Guthrie on extension methods">here</a>.</p>

<p>Enjoy Copyable, and please let me know if you find it useful or come across any problems with it.</p>

<p><strong>UPDATE 2009-12-11:</strong> Due to popular demand, I have made the source code for Copyable available under the MIT license. The source can be downloaded <a href="http://ox.no/software/copyable" title="The Copyable framework">here</a>.</p>

<p><strong>UPDATE 2010-01-31:</strong> The requirement of parameterless constructors has been removed in the latest version of Copyable available on GitHug. A new release will follow soon.</p>
]]></content:encoded>
			<wfw:commentRss>http://ox.no/posts/extension-methods-for-copying-or-cloning-objects/feed</wfw:commentRss>
		<slash:comments>37</slash:comments>
		</item>
		<item>
		<title>Five advices on implementing a cache</title>
		<link>http://ox.no/posts/five-advices-on-implementing-a-cache</link>
		<comments>http://ox.no/posts/five-advices-on-implementing-a-cache#comments</comments>
		<pubDate>Thu, 25 Oct 2007 20:57:35 +0000</pubDate>
		<dc:creator>Håvard</dc:creator>
				<category><![CDATA[Software Design]]></category>
		<category><![CDATA[Technical]]></category>
		<category><![CDATA[Database]]></category>

		<guid isPermaLink="false">http://ox.no/posts/five-advices-on-implementing-a-cache</guid>
		<description><![CDATA[I&#8217;ve spent the last few days at work implementing a cache in the data access layer (DAL) of one of our services. The cache works great, and speeds up our service very much in some cases, and somewhat in all cases. I&#8217;ve implemented caches before, and experienced many of the difficulties that arise when introducing [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve spent the last few days at work implementing a cache in the data access layer (DAL) of one of our services. The cache works great, and speeds up our service very much in some cases, and somewhat in all cases. I&#8217;ve implemented caches before, and experienced many of the difficulties that arise when introducing a cache. It always seems rather easy, and always has unwanted side effects. The general advice is of course not to do it (and the advice from the database guys are always not to do it), but here are my five best advices on what you should consider if you decide to do it.</p>

<!-- more -->

<p><strong>1. Make sure the cache is transparent.</strong></p>

<p>The system shall not in any way notice that there is a cache handing objects to it instead of the database, nor should the introduction of a cache require changes in any layers above the layer where the cache resides. If you decide that changes are required, be aware that you are making changes to code that does work, and that re-verifying its behavior is a hard and expensive task.</p>

<p><strong>2. If your system is transactional, make sure that the lifetime and mutability of objects in your cache matches your transaction isolation level.</strong></p>

<p>The obvious solution for a cache in a transactional system is a cache that lives per transaction, but this is not guaranteed to work. As an example, let&#8217;s say that transaction 1 reads some data and starts operating on them. Meanwhile, transaction 2 reads, alters, and commits some data that partially or fully depends on the data read by transaction 1. After the commit, transaction 1 reads some other data that depend on the new data committed by transaction 1. In this case, a cache in transaction 1 alters the system behavior if a too low isolation level is used (the alteration is most likely correct, but does not need to be, and it most certainly changes the behavior nonetheless) (see <a href="http://en.wikipedia.org/wiki/Isolation_(computer_science)" title="Transaction isolation">this Wikipedia page</a> for an explanation of transaction isolation levels). Be aware of your isolation level, and know also that the default isolation level is different from RDBMS to RDBMS. As an example, MySQL uses repeatable read as the default isolation level, while MS SQL Server uses read committed. With an isolation level less than repeatable read, a cache with any mutable data in it is essentially useless.</p>



<p><strong>3. Use the cache for immutable data as much as possible.</strong></p>

<p>Also, use the cache for mutable data as little as possible, since this significantly increases the difficulty of the cache implementation, and with it the risk of errors.</p>

<p><strong>4. Give the objects in the cache an as short lifetime as possible.</strong></p>

<p>When implementing a cache, you want the objects in your cache to live as long as possible, since accessing the cache is much faster than accessing the database. Well, think about this: A cache with objects that live forever is actually a replacement for your database, which is not what you want to achieve. To avoid an implementation that is difficult, hard to verify, and unnecessary complex, make objects live as short as possible, while maintaining an increase in speed.</p>

<p><strong>5. Be absolutely certain that the keys you use in your cache identify objects uniquely and unambiguously.</strong></p>

<p>This sounds obvious, but with complex object hierarchies and caching of different parts of the hierarchy at different levels, it suddenly becomes very hard. In general, cache either the top-most or the lower-most objects in your hierarchy. The choice of an approach depends on how you access your data. The best way to decide which approach to take is to do a thorough analysis of your data and the objects that represent them, how you access these objects, how you use them, and in which cases you are most likely to gain speed by introducing a cache.</p>
]]></content:encoded>
			<wfw:commentRss>http://ox.no/posts/five-advices-on-implementing-a-cache/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
