<?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>DevTalk.net</title>
	<atom:link href="http://devtalk.net/feed/" rel="self" type="application/rss+xml" />
	<link>http://devtalk.net</link>
	<description>A blog on programming and quantitative finance</description>
	<lastBuildDate>Sun, 10 Mar 2013 20:39:33 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.4.1</generator>
		<item>
		<title>Late-Night Ruminations on C++</title>
		<link>http://devtalk.net/cpp/late-night-ruminations-on-c/</link>
		<comments>http://devtalk.net/cpp/late-night-ruminations-on-c/#comments</comments>
		<pubDate>Sun, 10 Mar 2013 20:39:33 +0000</pubDate>
		<dc:creator>Dmitri Nesteruk</dc:creator>
				<category><![CDATA[Cpp]]></category>

		<guid isPermaLink="false">http://devtalk.net/?p=271</guid>
		<description><![CDATA[Way Back When I think it was in 199X when I got my first experience of &#8216;serious&#8217; programming. One day, being fed up with toying about with Delphi (it was relevant at that time, unlike now), I went out and bought one of those book+CD packages. The package included two books on Programming Windows with [...]]]></description>
			<content:encoded><![CDATA[<h3>Way Back When</h3>
<p>I think it was in 199X when I got my first experience of &lsquo;serious&rsquo; programming. One day, being fed up with toying about with Delphi (it was relevant at that time, unlike now), I went out and bought one of those book+CD packages. The package included two books on Programming Windows with Visual Studio 97, a refernce book (essentially, a very large reprint of a chunk of MSDN), and the CDs containing a trial version (the equivalent of today&rsquo;s Express) of Visual Studio. I installed it on my 166MHz 16Mb RAM machine, and I was hooked.</p>
<p>The fact that I got to actually write MFC apps was amazing. After all, MFC with all its insane macros and types such as <code>CString</code> that supplanted ordinary STL types (was there an STL back then?) were about as appropriate for learning C++ as it is appropriate to lose virginity with a horse. (Sorry, really crude example, but true.)</p>
<p>At any rate, I seem to have somehow survived MFC (without writing one single meaningful app, of course) and moved on to just writing console apps. At the moment I was trying to implement the gaming rules of AD&#038;D (2<sup>nd</sup> edition, I beleive), and I distincly remember my excitement of learning about Microsoft&rsquo;s <code>__declspec(property)</code> which, for those of you who do not know, allows one to have C#-style properties. Yes, we really had this capability ages ago (and still do).</p>
<p>However, at some point, C++ gave way first to Java, then to C#. I suppose that the real problem was the creating a good GUI app was much easier using .NET. That and the fact that C# had usable strings, memory management, and a whole host of other things. You dodn&rsquo;t have to deal with arcane things such as Boost, and even STL which <em>is</em> arcane, especially if  you consider its error messages.</p>
<h3>Recently</h3>
<p>Fast-forward a few years, and I&rsquo;ve started using C++ again. Why? Well, I think the reason I got back into it was image processing. In C#, manipulating an image is easy (the API is very intuitive and <code>System.Drawing.Bitmap</code> is nice), but the speed basically kills the effort outright. So what I did is I started using P/Invoke to basically <code>Lock()</code> all the bytes in place, send it off to a C++ DLL to process, and then return the results back in.</p>
<p>Performance increased tenfold. And sure, you can fiddle around in C# with <code>unsafe</code> and pointers, but why bother?</p>
<p>Anyways, the real issue with C++ compared to C# to me, at least, seemed to be the fact that C++ is generally superior for parallelization. That&rsquo;s why, at some point, I completely gave up on using the Microsoft compiler (which, to be fair, has improved in recent years) and focussed on using Intel Parallel Studio. The great thing about IPS is that, first, it&rsquo;s a terrific set of compiler+libraries+tools, and is a real joy to use provided you invest some time in learning how it all works; and second, the Intel compiler is available on non-Windows OSs, which helps in terms of uniformity, even if I don&rsquo;t use other OSs as much.</p>
<p>In terms of parallelization, .NET has TPL whereas C++ has</p>
<ul>
<li>
<p>PPL</p>
</li>
<li>
<p>OpenMP</p>
</li>
<li>
<p>Intel Threading Building Blocks (similar to PPL, by the way)</p>
</li>
<li>
<p>MPI</p>
</li>
</ul>
<p>Okay so maybe it&rsquo;s not fair to bring all of these into the same category, but they all serve one purpose&nbsp;&ndash; speeding up code. And they do it pretty well. I&rsquo;ve used OpenMP on a project, and this is basically &lsquo;blind parallelization&rsquo;, kind of like trusting TPL&rsquo;s <code>Parallel.For()</code> to optimize your loop for multicore.</p>
<h3>&lsquo;Modern&rsquo; C++</h3>
<p>Today&rsquo;s C++ is every bit as painful as the C++ of old. You still have to do the same menial things. In terms of what can seriously annoy a C#/Java developer, I can think of the following:</p>
<ul>
<li>
<p>Having to manage your own memory. Worse yet, there&rsquo;s lots of ambiguous ways of using all those funny <code>shared_ptr</code>, <code>unique_ptr</code> etc. containers, and it&rsquo;s nearly impossible to figure out even for experienced devs, let alone the uninitiated.</p>
</li>
<li>
<p>The lack of proper string literals as well as C++&lsquo;s inability to just bite the bullet and create <em>just</em> a compiler flag for how to treat strings has led us to the insanity of <code>char/wchar_t</code>, various BSTR implementations, as well as the fact that I need to put the letter L in front of string literals.</p>
</li>
<li>
<p>Truly insane compiler messages that Clang is supposed to be able to fix (err&hellip; I&rsquo;ll beleive it when I see it).</p>
</li>
<li>
<p>Really messed up mechanisms for declaring/initializing arrays, as well as the equally insane idea that an array is just a pointer to the first element. And don&rsquo;t get me started on multi-dimensional arrays.</p>
</li>
<li>
<p>The separation between header and implementation files results in huge amounts of wasted efforts. Personally, I try to avoid it by keeping everything in one single, huge .cpp file, but that&rsquo;s not a good idea either.</p>
</li>
</ul>
<p>On the other hand, there <em>are</em> reasons to use C++ nowadays. I&rsquo;ve mentioned parallelization briefly, but there&rsquo;s also C++ AMP, which is a way to transparently (ugh, more or less) execute C++ on a GPU. And of course, like it or not, interfacing with CUDA is a lot easier from C++ than .NET, though products are showing up all over the place that actually illustrate that it&rsquo;s possible to just transcompiler. Still, if you go looking for jobs in the GPGPU space, you&rsquo;re essentially looking at CUDA C which is, you guessed it, a C variant, so something closely related to C++.</p>
<p>Another advantage to C/C++ is that it&rsquo;s a lot easier to integrate with .NET. I won&rsquo;t talk about MC++ here, because this is a really ambigous product, but rather about P/Invoke&nbsp;&ndash; a technology that lets you transparently call C++ DLL functions right from C# (or indeed F#/VB.NET). Of course, you cannot use OOP structures from C#, but chances are you&rsquo;re just optimizing a particular algorithm and you don&rsquo;t need to import any hierarchies.</p>
<p>On the subject, there has been a few attempts to bring even OOP libraries to .NET. A good example is QuantLib which is a C++ library for quant finance (a topic very close to my heart). This library actually uses Boost for lifetime management, and of course it does use objects. Still, there are mechanisms which let you use it from .NET, though you must realize that you&rsquo;re essentially getting a second-rate product.</p>
<h3>Conclusion</h3>
<p>There is no conclusion, since these are just my ruminations on a language that has largely gone out of relevance and now remains the niche of a few specialists. That&rsquo;s not to say that it&rsquo;s fundamentally <em>bad</em>, rather that it&rsquo;s no longer something that warrants serious investment. In fact, I&rsquo;d argue that knowing CUDA C is a more valuable skill than knowing C++, unless of course you&rsquo;re job seeking in the quant space, where it&rsquo;s still considered fresh.</p>
]]></content:encoded>
			<wfw:commentRss>http://devtalk.net/cpp/late-night-ruminations-on-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>X2C &#8211; Convert Excel Spreadsheets into Executable Code</title>
		<link>http://devtalk.net/dotnet/x2c-convert-excel-spreadsheets-into-executable-code/</link>
		<comments>http://devtalk.net/dotnet/x2c-convert-excel-spreadsheets-into-executable-code/#comments</comments>
		<pubDate>Sun, 23 Sep 2012 14:19:53 +0000</pubDate>
		<dc:creator>Dmitri Nesteruk</dc:creator>
				<category><![CDATA[DotNet]]></category>
		<category><![CDATA[excel]]></category>
		<category><![CDATA[x2c]]></category>

		<guid isPermaLink="false">http://devtalk.net/?p=259</guid>
		<description><![CDATA[Introduction About a year ago, while I was putting the polish on MathSharp (a MathML-to-code converter), I had yet another idea. I observed that for computational problems, despite the usefulness of MATLAB, Mathematica and other math applications, a great many people used Excel. Excel really is convenient, and I also model things in it. But [...]]]></description>
			<content:encoded><![CDATA[<h3>Introduction</h3>
<p>About a year ago, while I was putting the polish on <a href="http://activemesa.com/mathsharp">MathSharp</a> (a MathML-to-code converter), I had yet another idea. I observed that for computational problems, despite the usefulness of MATLAB, Mathematica and other math applications, a great many people used Excel.</p>
<p>Excel really is convenient, and I also model things in it. But for executing code on &#8216;live&#8217; server systems, rather than running an Excel workbook as a server (yes, it <em>is</em> possible), people typically prefer executable code.</p>
<p>And so with that in mind, I decided to put the two together and create an Excel add-in that would let me turn Excel spreadsheets (with formulae and all) into ready-to-compile C++ code. Thus, the <a href="http://activemesa.com/x2c">X2C</a> project was born.</p>
<h3>High-Level Design</h3>
<p>How can Excel and C++ constructs be related? My approach is to define <em>mappings</em> from cells to C++ code constructs. There are 5 different types of mapping:</p>
<ul>
<li>
<p><em>Scalar</em> &mdash; a scalar maps a single cell to a variable. This means that a single <code>A1</code> cell with the value <code>42</code> can be mapped to a global field defined as <code>double A1 = 42</code>. Of course, the name is customizable, and I left an option to not set the default value if it&#8217;s not needed.</p>
</li>
<li>
<p><em>Function</em> &mdash; this corresponds to a global function. For example, if cell <code>A2</code> has a formula <code>=A1+23</code>, we generate a global function: <code>double A2() { return A1+23; }</code></p>
</li>
<li>
<p><em>Vector</em> &mdash; this is a one-dimensional array of values. This means that a selection of <code>A1:A3</code> can be mapped to a <code>double Stuff[]</code> array with 3 elements in it. If an array is subsequently used in a formula, we use the <code>[]</code> operator to extract the right element. Note that some advanced C++ is used here: for example if someone has a formula <code>=SUM(A1:A3)</code>, we cannot create a temporary variable and a <code>for</code> loop to sum things up.</p>
</li>
<li>
<p><em>Matrix</em> &mdash; this is a two-dimensional array. It works just like a 1D array but its initialization is tricker and it&#8217;s tougher to understand the iteration code in case it&#8217;s used in a formula somewhere. Also, one can take 1D slices out of a 2D matrix, which turns things really nasty.</p>
</li>
<li>
<p><em>Entity</em> &mdash; this construct basically converts a selection of scalar/function definitions into a <code>class</code>! This lets you take a chunk of a spreadsheet and organize it in a way that its constituent parts now become part of a larger, named entity. Of course, lots of tricks are needed here too, because for example, a formula might use a cell mapped to an entity, so you need to add <code>EntityName&amp;</code> to the parameters and dereference accordingly.</p>
</li>
</ul>
<p>All of these mapping are created by an Excel add-in that lets you just click a button with the cell selected and edit the mapping. It&#8217;s really as simple as that, though mappings do have different code generation options for added customization.</p>
<h3>Mathematical Issues</h3>
<p>When dealing with math, there&#8217;s lots of issues caused by mismatches between real-world-math and computational math. Here are a few examples:</p>
<ul>
<li>
<p><em>Functions with known equivalents</em> are easy: they are typically replicated by corresponding STL and Boost calls. In certain cases, though, it makes sense to create temporaries: for example, if a function uses <code>NORM.DIST</code> in many places, it makes sense to create the Boost normal distribution construct only once and then reuse it.</p>
</li>
<li>
<p><em>Functions with no equivalents and easy implementation</em> are typically done using best-available methods. For example, <code>ODD</code> and <code>EVEN</code> Excel functions require checking the last bit of an integer, so we can simply check e.g. <code>(long int)foo &amp; 1</code>.</p>
</li>
<li>
<p><em>Functions that are weird or just difficult to implement</em>, like <code>BAHTTEXT</code> for example, are completely left out: not much we can do about those.</p>
</li>
<li>
<p>Lots of <em>matrix functions</em> are meticulously implemented with cell-by-cell addressing. For example, a multiplication of two Excel matrices will be spelled out by creating real-life matrices from the data and then using Boost to perform the multiplication. The code for such a construct can look quite scary when generated, but the important thing is that it&#8217;s syntactically correct.</p>
</li>
<li>
<p><em>Inefficient operations</em> are rewritten when necessary. This includes things like repeated calculations. If you&#8217;re OK with having <code>POWER(x,3)</code> then that&#8217;s fine, but you can also get <code>x * x * x</code> or <code>MyIntPow(x, 3)</code> or even <code>_IntPow(x,3)</code> if you feel like it.</p>
</li>
</ul>
<h3>Things to Come</h3>
<p>As it stands, X2C only supports C++, and it is capable if generating C++ files that you can preview and dump to disk. There&#8217;s rudimentary operations like removal and editing of mappings, and some customization functionality already in the box.</p>
<p>The following ideas might be worth pursuing (depending on demand for the program):</p>
<ul>
<li>
<p><em>.NET support</em> is probably highest on the list. MathSharp already supports C# and F# (but not C++ &mdash; that might also happen at some point), so having at least F# in X2C would be nice. It would especially be nice to get continuous (re) compilation working for the generated code, so that the user can see immediately his model updating the code and the code being executed.</p>
</li>
<li>
<p><em>Web service</em> support is also another neat idea. Generating web server stubs isn&#8217;t exactly difficult, but would let users put up the calculations as a service and then share it accross the internet.</p>
</li>
<li>
<p><em>UI generation</em> is another <em>very</em> attractive feature, because once you get the model in a compilable state, the next thing you want to do is to is to start wiring up the UI so you can manipulate the data and observe the results. So why not generate the UI from the outset?</p>
</li>
</ul>
<p>All in all, the development of X2C really depends on two things: my own personal needs as well as how much demand there is for such a tool. Meanwhile, if I got you interested, check out the <a href="http://activemesa.com/x2c">product page</a> (I promise to update the video as soon as I can) and let me know what you think.</p>
]]></content:encoded>
			<wfw:commentRss>http://devtalk.net/dotnet/x2c-convert-excel-spreadsheets-into-executable-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Performance of String Histogram Building in C++ AMP</title>
		<link>http://devtalk.net/cppamp/performance-of-string-histogram-building-in-cpp-amp/</link>
		<comments>http://devtalk.net/cppamp/performance-of-string-histogram-building-in-cpp-amp/#comments</comments>
		<pubDate>Fri, 24 Aug 2012 20:09:50 +0000</pubDate>
		<dc:creator>Dmitri Nesteruk</dc:creator>
				<category><![CDATA[CppAmp]]></category>
		<category><![CDATA[cplusplus]]></category>
		<category><![CDATA[gpu]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://devtalk.net/?p=247</guid>
		<description><![CDATA[We all know that GPUs are excellent number crunchers. Given a large amount of data, GPUs can process numerics up to 2 orders of magnitude more efficiently than today&#8217;s multi-core CPUs. But to date, the use of GPUs has been mainly restricted exactly to this scientific/mathematical domain, without much concern to alternative uses. In this [...]]]></description>
			<content:encoded><![CDATA[<p>We all know that GPUs are excellent number crunchers. Given a large amount of data, GPUs can process numerics up to 2 orders of magnitude more efficiently than today&rsquo;s multi-core CPUs. But to date, the use of GPUs has been mainly restricted exactly to this scientific/mathematical domain, without much concern to alternative uses.</p>
<p>In this post, I want to take a look at other ways of exploiting GPUs&nbsp;&ndash; specifically, how individual strings as well as string arrays can be processed on the GPU and what kind of performance benefit we would be able to get. For the purposes of my investigations, I will be using an ATI 6800 series GPU with an ordinary Core 4 Quad. I will use ordinary C++ and C++ AMP as the technologies being compared. I will use primary Latin characters (in a range that can be displayed in a console), but in Unicode (i.e., <code>wchar_t</code>-based) strings as befits a modern framework.</p>
<p>Please note that the examples use <em>minimum optimization</em> of C++ code, i.e., common STL algorithms and approaches are used and <em>no attempt</em> is made to improve or replace basic C++ constructs. This, I beleive, constitutes a fairer test than attempting to fine-tune C++ for peak performance.</p>
<h3>Character histogram</h3>
<p>We&rsquo;ll begin with a simple case: given a rather lengthy text, how long would it take to build a histogram of all the characters present in the string? We&rsquo;ll use a special function to randomly generate strings of different sizes:</p>
<pre class="brush: cpp; title: ; notranslate">
// uses chars 32-127
void fill_string(wchar_t* chars, int count)
{
  for (int i = 0; i &lt; count; ++i)
  {
    chars[i] = 32 + rand() % 95;
  }
}
</pre>
<p>We&rsquo;ll perform the experiment on strings with length from 2 to 2<sup>24</sup> to ascertain how the algorithm performs under different conditions. First, we begin with a C++ implementation&nbsp;&ndash; without any constraints on the architecture, we&rsquo;ll use a simple <code>map</code>-based approach:</p>
<pre class="brush: cpp; title: ; notranslate">
typedef concurrent_unordered_map&lt;wchar_t,int&gt; histogram;
unique_ptr&lt;histogram&gt; cpu_histogram(wchar_t* str, size_t count)
{
  unique_ptr&lt;histogram&gt; result(new histogram);
  parallel_for((size_t)0, count, [&amp;](int i)
  {
    (*result)[str[i]]++;
  });
      
  return result;
}
</pre>
<p>The GPU function is quite a bit more complicated. First of all, there is no real way of treating elements as <code>wchar_t</code> types since C++ AMP does not recognize elements smaller than an <code>uint32_t</code>. Thus, any view over a <code>wchar_t</code> array has to use the <code>uint32_t</code> data type.</p>
<p>In order to test the histogram, I used an <a href="http://blogs.msdn.com/b/nativeconcurrency/archive/2012/01/17/histogram-using-c-amp.aspx" title="http://blogs.msdn.com/b/nativeconcurrency/archive/2012/01/17/histogram-using-c-amp.aspx">existing implementation</a> written by Daniel Moth. I won&rsquo;t replicate the code here. All I changed in Daniel&rsquo;s implementation is the definition of the data type, which I set to <code>wchar_t</code>, as well as an implementation of an alternative constructor that took actual data rather than the data size.</p>
<p>From then on, what I did is created strings of sizes 2<sup>n</sup> and filled them in with random printable characters:</p>
<pre class="brush: cpp; title: ; notranslate">
int size = sizes[i];
wchar_t* target = new wchar_t[size+1];
ZeroMemory(target, (size+1) * sizeof(wchar_t));
fill_string(target, size);
</pre>
<p>Then, I simply timed the &lsquo;cost&rsquo; of the CPU and GPU calls and averaged out results:</p>
<pre class="brush: cpp; title: ; notranslate">
aggregate = 0.0;
for (int s = 0; s &lt; 20; ++s)
{
  Timer gpuTimer;
  gpuTimer.Start();
  auto gh = gpu_histogram(target, size);
  gpuTimer.Stop();
  aggregate += gpuTimer.Elapsed();
}
wcout &lt;&lt; (aggregate / 20.0) &lt;&lt; endl;
</pre>
<h3>Measuring Performance</h3>
<p>For performance measurement I found yet another <a href="http://blogs.msdn.com/b/nativeconcurrency/archive/2011/12/28/how-to-measure-the-performance-of-c-amp-algorithms.aspx" title="http://blogs.msdn.com/b/nativeconcurrency/archive/2011/12/28/how-to-measure-the-performance-of-c-amp-algorithms.aspx">useful blog post</a> describing the steps necessary to get the measurement just right. I also used a high-res timer from <a href="http://blogs.msdn.com/b/nativeconcurrency/archive/2011/12/28/high-resolution-timer-for-c.aspx" title="http://blogs.msdn.com/b/nativeconcurrency/archive/2011/12/28/high-resolution-timer-for-c.aspx">this article</a> (isn&rsquo;t the internet wonderful?).</p>
<p>The end result is the following performance measurements from the CPU and GPU. This is from a Release build with all optimizations enabled. Each iteration was repeated 20 times with the results averaged.</p>
<p align="center"><img src="http://nesteruk.org/pix/0/e721dfcb-3276-4dff-848b-b5dfad76141c.png" alt="" style="border:0"/></p>
<p align="center"><strong>Figure 1.</strong> Comparison of GPU and CPU performance for building a string histogram. The X axis corresponds to a string of length 2<sup>x</sup>, the Y axis represents the elapsed time in milliseconds, and is binary-log-scaled.</p>
<p>It&rsquo;s clear that, up to some point, the CPU has an advantage, as the GPU is consistently paying a small but annoying start-up cost. As far as measuring the benefits, the parallel lines on the right hand side of the chart suggest a constant <strong>8&times; performance improvement</strong> when using the GPU. Performance benefits of the GPU can only be appreciated when dealing with strings with length greater than 2<sup>16</sup> (65536) characters.</p>
<h3>Conclusion</h3>
<p>This experiment is just a small performance investigation, probably full of various methodological errors and inaccuracies, but the above has certainly been benefitial in terms of figuring out that:</p>
<ul>
<li>
<p>The GPU kernel appears to have a fixed start-up cost associated with it. However, the start-up cost seems to be around 2ms, which is fairly insignificant, except maybe for things like high-frequency trading.</p>
</li>
<li>
<p>The GPU appears to have a <em>linear</em> advantage over the CPU (about 3 orders of binary magnitude), which is surprising, because I would expect non-linear divergence in the results.</p>
</li>
<li>
<p>The current approach seems to be entirely <em>unfit</em> for calculating histograms with unlimited character sets. The reason is that currently, a histogram array matches the size of all possible characters, and then there are equally many numbers of such arrays. Essentially, to make lots of arrays of size 2<sup>sizeof(wchar_t)</sup> is impossible&nbsp;&ndash; the GPU just doesn&rsquo;t have thas much memory.</p>
</li>
</ul>
<p>I&rsquo;ll certainly be playing more with C++ AMP and string processing specifically. Meanwhile, if you&rsquo;d like to get the source code for this article, you can find it <a href="http://nesteruk.org/files/GpuStringProcessing.zip" title="http://nesteruk.org/files/GpuStringProcessing.zip">here</a>. Who knows, maybe your performance measurements will be entirely different? Or maybe the algorithm won&rsquo;t even run on your machine? At any rate, let me know.&nbsp;■</p>
]]></content:encoded>
			<wfw:commentRss>http://devtalk.net/cppamp/performance-of-string-histogram-building-in-cpp-amp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ReSharper SDK Adventures Part 4 &#8211; SSR, Gutter Marks and Suppressions in Agent Mulder</title>
		<link>http://devtalk.net/resharper/resharper-sdk-adventures-4/</link>
		<comments>http://devtalk.net/resharper/resharper-sdk-adventures-4/#comments</comments>
		<pubDate>Tue, 19 Jun 2012 10:00:49 +0000</pubDate>
		<dc:creator>Dmitri Nesteruk</dc:creator>
				<category><![CDATA[ReSharper]]></category>

		<guid isPermaLink="false">http://devtalk.net/?p=235</guid>
		<description><![CDATA[In the previous three parts of the SDK Adventures we looked at some artificially created samples. Time to change all that. In this part, we&#8217;re going to take a look at some of the advanced features used by Igal Tabachnik&#8217;s (@hmemcpy) excellent Agent Mulder plugin. Brief Overview of Agent Mulder The principal idea behind Agent [...]]]></description>
			<content:encoded><![CDATA[<p>In the previous three parts of the SDK Adventures we looked at some artificially created samples. Time to change all that. In this part, we&rsquo;re going to take a look at some of the advanced features used by Igal Tabachnik&rsquo;s (<a href="http://twitter.com/hmemcpy" title="hmemcpy's posts on twitter">@hmemcpy</a>) excellent <a href="https://github.com/hmemcpy/AgentMulder" title="https://github.com/hmemcpy/AgentMulder">Agent Mulder</a> plugin.</p>
<h3>Brief Overview of Agent Mulder</h3>
<p>The principal idea behind Agent Mulder is to get ReSharper to support various IoC frameworks. To get a better appreciation for its features, take a look at the <a href="http://tv.jetbrains.net/videocontent/introducing-agent-mulder-plugin-for-resharper" title="http://tv.jetbrains.net/videocontent/introducing-agent-mulder-plugin-for-resharper">screencast</a> or, better yet, <a href="https://github.com/hmemcpy/AgentMulder/downloads" title="https://github.com/hmemcpy/AgentMulder/downloads">download the plugin</a> and try it out for yourself. But to sum things up, Agent Mulder augments ReSharper with intrinsic knowledge about the types registered in the IoC container and allows all sorts of wonderful things, such as e.g. the possibility to navigate to the point where a type is registered.</p>
<p>But seeing how our SDK adventures concern actual implementations of the various features, here&rsquo;s what we&rsquo;re going to talk about today:</p>
<ul>
<li>
<p>Programmatic use of Structural Search and Replace (SSR)</p>
</li>
<li>
<p>Use of gutter marks</p>
</li>
<li>
<p>Suppression of existing inspections</p>
</li>
</ul>
<p>All of these are fairly advanced topics, but we&rsquo;ll tread carefully and hopefully things will make sense.</p>
<h3>Programmatic SSR</h3>
<p>Structured Search and Replace is a ReSharper feature that helps people locate code based on some pattern. For example, you can go off looking for <code>$1.Foo($2)</code> where <code>$1</code> and <code>$2</code> have specific types. The <em>Replace</em> part of the SSR lets you then replace the found pattern with something else by presenting a context action.</p>
<p>So how does this work in Agent Mulder? Well, AM needs to locate places where a particular component has been registered. To do that, it creates and uses <em>search patterns</em>&nbsp;&ndash; definitions of type <code>IStructuralSearchPattern</code> which are object-orientated equivalents of what one would otherwise define in the SSR GUI. For example, here&rsquo;s the pattern for a Castle Windsor container registration:</p>
<pre class="brush: csharp; title: ; notranslate">private static readonly IStructuralSearchPattern pattern =
  new CSharpStructuralSearchPattern(&quot;$container$.Register($arguments$)&quot;,
    new ExpressionPlaceholder(&quot;container&quot;, &quot;Castle.Windsor.IWindsorContainer&quot;, false),
    new ArgumentPlaceholder(&quot;arguments&quot;, -1, -1)); // any number of arguments
</pre>
<p>The above is a simple search for <code>$container$.Register($arguments$)</code> where the first parameter has a type of <code>IWindsorContainer</code> and the second argument is actually variadic (i.e., there might be several arguments).</p>
<p>Now that we&rsquo;ve got the pattern to search with, how do we perform the search? Well, to match an expression to a pattern we need a <em>matcher</em> embodies by the <code>IStructuralMatcher</code> interface. This matcher is effectively created from the defined pattern, for example:</p>
<pre class="brush: csharp; title: ; notranslate">var matcher = pattern.CreateMatcher();
</pre>
<p>With the matcher in hand, any particular <code>ITreeNode</code> can then be matched against the pattern using a <code>QuickMatch()</code> method. This method takes the tree node as a parameter and returned a <code>bool</code> indicating whether there is, in fact, a match. Keep in mind that a matcher works on a particular in vocation, not on the entire tree. This is why Agent Mulder also tries to get the tree node as an <code>IInvocationExpression</code> and, if successful, performs a match against all its subexpressions.</p>
<h3>Gutter Marks</h3>
<p>Gutter marks are little glyphs on the left-hand side of the editing pane. They typically show various useful bits of information, such as indicating that a type inherits from another type. Gutter marks are also clickable. In the case of Agent Mulder, a gutter mark is used to indicate that a type is registered in a container.</p>
<p><img src="http://i.imgur.com/xjYrT.png" alt="" style="border:0"/></p>
<p>So what&rsquo;s a gutter mark in terms of the API? Put simply, it is a class that inherits from <code>IconGutterMark</code> and is registered with an <em>assembly-level</em> <code>RegisterHighlighter</code> attribute. There are a few things the gutter mark class has to do. First of all, it has to call the base class constructor and provide an image that it is going to display:</p>
<pre class="brush: csharp; title: ; notranslate">public ContainerGutterMark()
  : base(ImageLoader.GetImage(&quot;Hat&quot;, Assembly.GetExecutingAssembly()))
{
}
</pre>
<p>The above loads the <code>Hat.png</code> image file from the current assembly. In order for the above invocation to work, an additional assembly-level attribute is required in <code>AssemblyInfo.cs</code>:</p>
<pre class="brush: csharp; title: ; notranslate">[assembly: ImagesBase(&quot;AgentMulder.ReSharper.Plugin.Resources&quot;)]
</pre>
<p>Now, once the image is loaded, there is also the <code>IsClickable</code> property of the gutter mark class to implement. Its function is predictable: if set to <code>true</code>, the <code>OnClick()</code> function must be defined.</p>
<pre class="brush: csharp; title: ; notranslate">public override bool IsClickable
{
  get { return true; }
}
</pre>
<p>Now, before we get to clickability itself, we need to discuss the way gutter marks are actually <em>added</em> to a file because, after all, their invocation (the <code>OnClick()</code> override) depends entirely on their position relative to code.</p>
<p>The answer to this question is rather simple: gutter mark positions are actually controlled by highlightings&nbsp;&ndash; yes, the same highlightings that are used to indicate warnings, errors, and so on. This exact mechanism allows the clickable gutter mark to actually get information about its location. Here&rsquo;s how it works: the gutter mark is registered at the assembly level with an attribute similar to the following:</p>
<pre class="brush: csharp; title: ; notranslate">[assembly: RegisterHighlighter(&quot;Container Registration&quot;, 
  &quot;{B57372C1-16C3-4CB5-8B68-A0FBEFB487AD}&quot;, 
  EffectType = EffectType.GUTTER_MARK, GutterMarkType = typeof(ContainerGutterMark), 
  Layer = 2001)]
</pre>
<p>The critical parameter in the above registration is the <code>Id</code>, and in this case it has a value of <code>"Container Registration"</code>. Now, we can go ahead and create a simple highlighting with a severity of <code>INFO</code>. The critical piece of the puzzle is that the <code>AttributeId</code> parameter of the highlighting has to match the <code>Id</code> from above:</p>
<pre class="brush: csharp; title: ; notranslate">[StaticSeverityHighlighting(Severity.INFO, &quot;GutterMarks&quot;, 
  OverlapResolve = OverlapResolveKind.NONE, AttributeId = &quot;Container Registration&quot;, 
  ShowToolTipInStatusBar = false)]
public sealed class RegisteredByContainerHighlighting : IClickableGutterHighlighting
{
  // implementation here
}
</pre>
<p>But this doesn&rsquo;t answer the most difficult of questions: how does the gutter mark know where to go? It knows because the gutter mark&rsquo;s <code>OnClick()</code> override gets an <code>IHighlighter</code> as a parameter. This means that if we get a solution manager and this highlighter, we can get at the actual highlighting and invoke <em>its own</em> <code>Click()</code> method:</p>
<pre class="brush: csharp; title: ; notranslate">public override void OnClick(IHighlighter highlighter)
{
  ISolution currentSolution = Shell.Instance.GetComponent&lt;ISolutionManager&gt;().CurrentSolution;
  if (currentSolution == null)
  {
    return;
  }
  var clickable = Daemon.GetInstance(currentSolution).GetHighlighting(highlighter)
                  as IClickableGutterHighlighting;
  if (clickable != null)
  {
    clickable.OnClick();
  }
}
</pre>
<p>Put all of the above together and you get a clickable gutter mark.</p>
<h3>Suppression of Inspections</h3>
<p>If you turn on Solution-Wide Analysis (SWA), you&rsquo;ll get container-registered classes as unused, which isn&rsquo;t good because they are used, albeit in a container. Sure, you could just mark these as <code>[UsedImplicitly]</code>, but this is extra work for the developer, so Agent Mulder&rsquo;s idea is to handle this automatically.</p>
<p>How does it work? Well, one of the daemon processes in ReSharper&rsquo;s ecosystem is the <code>CollectUsagesStageProcess</code>. This process handles usage information, and conveniently enough, this component has a <code>SetElementState()</code> method that can set the &lsquo;usage state&rsquo; of a particular element (in the case of Agent Mulder, an <code>IConstructor</code>):</p>
<pre class="brush: csharp; title: ; notranslate">private void SetConstructorsState(ITypeElement typeElement, UsageState state)
{
  foreach (IConstructor constructor in typeElement.Constructors)
  {
    collectUsagesStageProcess.SetElementState(constructor, state);
  }
}
</pre>
<p>It really is that simple. Agent Mulder actually sets the usages in its daemon stage process as it goes through the files. This means that, for classes that are registered in the container, constructors are marked as used which prevents SWA from claiming that the class is unused.</p>
<h3>Conclusion</h3>
<p>I&rsquo;ve gone over most of the core aspects of Agent Mulder, leaving out perhaps just one&nbsp;&ndash; the search &amp; navigation aspect. This really warrants its own entry however, so stay tuned for more R# SDK adventures. Oh, and check out <a href="https://github.com/hmemcpy/AgentMulder" title="https://github.com/hmemcpy/AgentMulder">Agent Mulder</a> if you haven&rsquo;t done so already!</p>
]]></content:encoded>
			<wfw:commentRss>http://devtalk.net/resharper/resharper-sdk-adventures-4/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ReSharper SDK Adventures Part 3 – CSV Paste Action</title>
		<link>http://devtalk.net/resharper/resharper-sdk-adventures-3/</link>
		<comments>http://devtalk.net/resharper/resharper-sdk-adventures-3/#comments</comments>
		<pubDate>Mon, 28 May 2012 11:53:14 +0000</pubDate>
		<dc:creator>Dmitri Nesteruk</dc:creator>
				<category><![CDATA[ReSharper]]></category>

		<guid isPermaLink="false">http://devtalk.net/?p=226</guid>
		<description><![CDATA[The two previous posts have been about various ReSharper features such as analyzers and context actions. But what if you&#8217;ve got a plugin that just wants to do something without showing fancy UI and interacting with the R# ecosystem in any major way? Well, in this case, you can create something known as an action. [...]]]></description>
			<content:encoded><![CDATA[<p>The two previous posts have been about various ReSharper <em>features</em> such as analyzers and context actions. But what if you&rsquo;ve got a plugin that just wants to do something without showing fancy UI and interacting with the R# ecosystem in any major way? Well, in this case, you can create something known as an <em>action</em>.</p>
<h3>What are actions?</h3>
<p>Actions are, effectively, commands that you can invoke and your plugin can respond to. To invoke an action, you can use any number of menus as well as keyboard shortcuts. Actions are actually published as commands in Visual Studio, so binding them to a particular key is no problem.</p>
<p>For example, let&rsquo;s say we&rsquo;re working with Excel and we want to cut-and-paste data from Excel into your C# file, naturally turning the data into some easily digestible form, like e.g., an array. What we can do is define an action to handle it. An action has to implement the <code>IActionHandler</code> interface and be decorated with the <code>ActionHandler</code> attribute whose parameter takes the action&rsquo;s identifier.</p>
<pre class="brush: csharp; title: ; notranslate">
[ActionHandler(&quot;PasteCSV&quot;)]
public class PasteCSV : IActionHandler
{
  // todo
}
</pre>
<p>Now, the <code>IActionHandler</code> interface has two methods that you need to implement.</p>
<p>First, there is the <code>Update()</code> method, which determines whether our action gets executed at all. This is a great place to check, in our case, if we&rsquo;ve got the right data on the clipboard. Interestingly, when you copy a chunk of an Excel worksheet, data gets placed on the clipboard in <em>multiple formats simultaneously</em>, including a plain-text format (separated by tabs) and a CSV format (separated by commas). We&rsquo;ll go for the CSV format here. Also, we need to check that there is an editor to work with, because if there isn&rsquo;t, pasting is meaningless. Here&rsquo;s the implementation we end up with:</p>
<pre class="brush: csharp; title: ; notranslate">
public bool Update(IDataContext context, ActionPresentation presentation, DelegateUpdate nextUpdate)
{
  return Clipboard.ContainsText(TextDataFormat.CommaSeparatedValue) &amp;&amp;
    context.GetData(JetBrains.TextControl.DataContext.DataConstants.TEXT_CONTROL) != null;
}
</pre>
<p>The second method is the <code>Execute()</code> method where, as you may have guessed, execution of the action actually happens. This is where the bulk of our algorithm will reside.</p>
<h3>The Algorithm</h3>
<p>Now, we know text is in there, so let&rsquo;s think a little about the algorithm that we might want to implement when pasting things. Data can be coming in as a single row, column, or a table of multiple rows and columns. It can also be homogeneous (e.g., all numbers) or heterogeneous, mixing text and numbers.</p>
<p>Without overcomplicating things, I&rsquo;d argue that:</p>
<ul>
<li>
<p>A single row or column of numeric data can be declared as an array of fixed size.</p>
</li>
<li>
<p>A table of purely numeric data can be treated as a rectangular array.</p>
</li>
<li>
<p>Any &lsquo;mixed&rsquo; data needs to be declared as an array of <code>Tuple</code>s. The supported data types are <code>double</code>, <code>DateTime</code> or <code>string</code>, depending what parses.</p>
</li>
</ul>
<p>We therefore start by getting the clipboard data and breaking it into lines:</p>
<pre class="brush: csharp; title: ; notranslate">
var csv = Clipboard.GetText(TextDataFormat.CommaSeparatedValue);
var lines = csv.Split(new[]{Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);
</pre>
<p>We can now write a simple method checking that all data is numeric:</p>
<pre class="brush: csharp; title: ; notranslate">
public bool IsAllDataNumeric(string[] lines)
{
  double dummy;
  return lines.SelectMany(line =&gt; line.Split(','))
    .All(element =&gt; double.TryParse(element, out dummy));
}
</pre>
<p>Let&rsquo;s consider the numeric case first. If either the number of rows or columns is equal to zero, we get a 1-dimensional array; otherwise, we get a rectangular array:</p>
<pre class="brush: csharp; title: ; notranslate">
if (rows == 1 || cols == 1)
{
  sb.AppendFormat(&quot;double[] foo = {{ {0} }};&quot;,
                  rows == 1 ? lines[0] : lines.Join(&quot;,&quot;));
}
else
{
  sb.Append(&quot;double[,] foo = {&quot;).AppendLine();
  foreach (var line in lines)
    sb.AppendFormat(&quot;{{ {0} }},&quot;, line).AppendLine();
  sb.Append(&quot;};&quot;);
}
</pre>
<p>Well, that was the easy part, now the tough part. How can we guess the type of a non-numeric data item? Well, we can try parsing it for whatever data structure we want. And once we&rsquo;ve got the type, we can format things accordingly:</p>
<pre class="brush: csharp; title: ; notranslate">
public string FormatForType(string input)
{
  DateTime dt;
  double d;
  if (DateTime.TryParse(input, out dt))
    return dt.ToAssemblyCode();
  else if (double.TryParse(input, out d))
    return input;
  else return input.Quoted();
}
</pre>
<p>In the above, the <code>ToAssemblyCode()</code> extension method creates a <code>new DateTime(...)</code> declaration corresponding to the actual <code>DateTime</code> object. <code>Quoted()</code> simply puts double quotes around a string.</p>
<p>Now, if we are making an array, we can still keep implicit typing just so long as data is, roughly the same. This can cause a few hiccups: for example, is <code>123</code> a <code>double</code>? According to type conversion rules, it may as well be. But according to type inferencing rules, it&rsquo;s not, and <code>Tuple.Create(123)</code> is actually a <code>Tuple&lt;int&gt;</code> even if you&rsquo;ve got a large array where <em>some</em> elements are of type <code>double</code>. You need to be explicit about this.</p>
<p>Anyways, the implementation of <code>Tuple</code>-based algorithm for both vectors and matrices is as follows:</p>
<pre class="brush: csharp; title: ; notranslate">
if (rows == 1 || cols == 1)
{
  var data = rows == 1 ? lines[0].Split(',') : lines.ToArray();
  sb.AppendFormat(&quot;var foo = Tuple.Create({0});&quot;, data.Select(FormatForType).Join(&quot;,&quot;));
} else
{
  sb.Append(&quot;var foo = new[] {&quot;).AppendLine();
  foreach (var line in lines)
    sb.Append(&quot;Tuple.Create(&quot;).Append(line.Split(',').Select(FormatForType).Join(&quot;,&quot;)).Append(&quot;),&quot;);
  sb.Append(&quot;};&quot;);
}
</pre>
<p>And finally, we can put insert the generated text into the current document at the caret position:</p>
<pre class="brush: csharp; title: ; notranslate">
var textControl = context.GetData(JetBrains.TextControl.DataContext.DataConstants.TEXT_CONTROL);
var doc = textControl.Document;
var pos = textControl.Caret.Position;
doc.InsertText(pos.Value.ToDocOffset(), sb.ToString());
</pre>
<p>And that&rsquo;s all there really is to it.</p>
<h3>Using Actions</h3>
<p>There are two fairly obvious ways to use actions.</p>
<p>The first is to simply bind it to a shortcut. To do this, you go to <strong>Tools | Options</strong> and choose the <strong>Environment &rarr; Keyboard</strong> section:</p>
<p><img src="http://nesteruk.org/pix/0/1699c93b-650a-4a19-ac95-b08ac85bfedb.png" alt="" style="border:0"/></p>
<p>The other option is to have the action display its own menu item, either in the top menu bar or in any number of context menus for, e.g., the solution, the project, etc. In order to implement this, you need to do three things:</p>
<ul>
<li>
<p>Create in your project a file called <code>Actions.xml</code> and set its Build Action to &rdquo;Embedded Resource&ldquo;</p>
</li>
<li>
<p>Edit the file, specifying the action and the menu you want it to appear under. For example, to have our action in the top-level menu under <strong>ReSharper | Foo</strong>, you would specify the following in the XML file:</p>
<pre class="brush: csharp; title: ; notranslate">
&lt;actions&gt;
  &lt;insert group-id=&quot;ReSharper&quot; position=&quot;last&quot;&gt;
    &lt;action-group id=&quot;Foo&quot; text=&quot;Foo&quot; shared=&quot;true&quot;&gt;
      &lt;action id=&quot;PasteCSV&quot; text=&quot;Paste CSV&quot;/&gt;
    &lt;/action-group&gt;
  &lt;/insert&gt;
&lt;/actions&gt;
</pre>
<p>A more comprehensive example of places where the menu item can be added is available in the SDK.</p>
</li>
<li>
<p>Finally, you need to specify the location of the <code>Actions.xml</code> file in <code>AssemblyInfo.cs</code>, i.e., add a line similar to the following:</p>
<pre class="brush: csharp; title: ; notranslate">
[assembly: ActionsXml(&quot;Bar.Baz.Actions.xml&quot;)]
</pre>
<p>In the above, <code>Bar.Baz</code> refers to the name of the assembly you&rsquo;re working with. (We <em>are</em> referencing an embedded resource, after all.)</p>
</li>
</ul>
<h3>Conclusion</h3>
<p>Once again, I&rsquo;ve presented an example that would require a lot more rigor if it were to be deemed production-ready code. Actions are simple, but there are lots of useful things you can do with them. And in case you&rsquo;re interested, the source code for this action can be found <a href="http://pastebin.com/WvAECVfz" title="http://pastebin.com/WvAECVfz">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://devtalk.net/resharper/resharper-sdk-adventures-3/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>ReSharper SDK Adventures Part 2 &#8211; Math.Pow Improvements</title>
		<link>http://devtalk.net/resharper/resharper-sdk-adventures-2/</link>
		<comments>http://devtalk.net/resharper/resharper-sdk-adventures-2/#comments</comments>
		<pubDate>Thu, 10 May 2012 12:07:02 +0000</pubDate>
		<dc:creator>Dmitri Nesteruk</dc:creator>
				<category><![CDATA[ReSharper]]></category>

		<guid isPermaLink="false">http://devtalk.net/?p=220</guid>
		<description><![CDATA[In the first part of our SDK experiments, we implemented a way of identifying Math.Pow() calls with integer-based powers and wrote a quick-fix to correct the situation. Let us now try to improve the robustness of our code as well as increase its functionality. Checking that caller is indeed System.Math So far, we only checked [...]]]></description>
			<content:encoded><![CDATA[<p>In the <a href="http://devtalk.net/resharper/resharper-sdk-adventures-1/" title="http://devtalk.net/resharper/resharper-sdk-adventures-1/">first part</a> of our SDK experiments, we implemented a way of identifying <code>Math.Pow()</code> calls with integer-based powers and wrote a quick-fix to correct the situation. Let us now try to improve the robustness of our code as well as increase its functionality.</p>
<h3>Checking that caller is indeed System.Math</h3>
<p>So far, we only checked that the function being called is <code>Pow</code> by getting the name of the reference:</p>
<pre class="brush: csharp; title: ; notranslate">
bool functionIsCalledPow = false;
var e = element.InvokedExpression as IReferenceExpression;
if (e != null)
{
  if (e.Reference.GetName().Equals(&quot;Pow&quot;))
    functionIsCalledPow = true;
}
</pre>
<p>This means that we can easily get a false positive with something like this:</p>
<pre class="brush: csharp; title: ; notranslate">
double y = Foo.Pow(x, 2.0);
</pre>
<p>Now, to handle this situation properly, we&rsquo;re going to scrap our previous check of the name and replace it with the following:</p>
<pre class="brush: csharp; title: ; notranslate">
bool isOnMathPow = false;
var r = element.InvocationExpressionReference.Resolve();
var m = r.DeclaredElement as IMethod;
if (m != null)
{
  var parent = m.GetContainingType();
  if (parent != null)
  {
    isOnMathPow = parent.GetClrName().FullName.Equals(&quot;System.Math&quot;)
                  &amp;&amp; m.ShortName.Equals(&quot;Pow&quot;);
  }
}
</pre>
<p>There&rsquo;s quite a lot that&rsquo;s happening in the above, so let&rsquo;s go through it step-by-step:</p>
<ul>
<li>
<p>The first thing you&rsquo;ll notice is that we now use the <code>InvocationExpressionReference</code> and <code>Resolve()</code> it. This typically yields us a &lsquo;resolve result&rsquo;, but can also fail in case the method doesn&rsquo;t resolve to anything.</p>
</li>
<li>
<p>To figure out if the resolution happened correctly, we simply take the result&rsquo;s <code>DeclaredElement</code> and cast it to an <code>IMethod</code>, since <code>Math.Pow()</code> is a static method call.</p>
</li>
<li>
<p>If the result is OK, we also get the type that contains the method. If this is the right call, this should point us to the <code>System.Math</code> class.</p>
</li>
<li>
<p>To check that we do in fact have <code>System.Math</code>, we get the <code>parent</code>&rsquo;s CLR name, and from that its <code>FullName</code>, which has the full namespace prefix.</p>
</li>
<li>
<p>To check we have the right method, we simply check its name as before.</p>
</li>
</ul>
<p>The above manipulations, though complex, rid us from false positives like that <code>Foo.Pow()</code> call.</p>
<h3>Custom function handling</h3>
<p>Changing <code>Math.Pow(x, 2.0)</code> to <code>x*x</code> makes sense. So does changing <code>Math.Pow(y, 3)</code> to <code>y*y*y</code>. However, after this threshold, things get a bit ridiculous: you really don&rsquo;t want <code>z*z*z*z*z*z</code> in your code, particularly since there&rsquo;s no way to read from this that this is <code>z^6</code>. Wouldn&rsquo;t it be nice if the user could specify their custom function that we ought to use for powers, say, greater than 3?</p>
<p>Let&rsquo;s do this. First of all, we&rsquo;ll define a settings class that will house the user&rsquo;s preferences, specifically whether they want to have a custom power function, and what its name is:</p>
<pre class="brush: csharp; title: ; notranslate">
[SettingsKey(typeof(Missing), &quot;General Settings&quot;)]
public class GeneralSettings
{
  [SettingsEntry(false, &quot;Use Custom Power Function&quot;)]
  public bool UseCustomPowerFunction { get; set; }
 
  [SettingsEntry(&quot;&quot;, &quot;Custom Power Function Name&quot;)]
  public string CustomPowerFunctionName { get; set; }
}
</pre>
<p>We can now create a settings page (a user control that implements <code>IOptionsPage</code>) and bind the properties as follows:</p>
<pre class="brush: csharp; title: ; notranslate">
settings.SetBinding(this.lifetime, (GeneralSettings gs) =&gt; gs.UseCustomPowerFunction,
  WinFormsProperty.Create(this.lifetime, chUseCustomFunction, x =&gt; x.Checked, true));
settings.SetBinding(this.lifetime, (GeneralSettings gs) =&gt; gs.CustomPowerFunctionName,
  WinFormsProperty.Create(this.lifetime, tbInliningFunctionName, x =&gt; x.Text, true));
</pre>
<p>Now, we need to change our inlining fix. This is tricky. First of all, let&rsquo;s define a method that would actually get the two values given a context function:</p>
<pre class="brush: csharp; title: ; notranslate">
public Pair&lt;bool, string&gt; GetCustomFunctionSettings(Func&lt;Lifetime, DataContexts, IDataContext&gt; ctx)
{
  var ss = Shell.Instance.GetComponent&lt;ISettingsStore&gt;();
  var bs = ss.BindToContextTransient(ContextRange.Smart(ctx));
  var s = bs.GetKey&lt;GeneralSettings&gt;(SettingsOptimization.DoMeSlowly);
  return new Pair&lt;bool, string&gt;(s.UseCustomPowerFunction, s.CustomPowerFunctionName);
}
</pre>
<p>The above simply gets a settings store, binds it to a transient context that&rsquo;s based on the function we provide (more on that in a sec), reads the settings and returns them in a <code>Pair&lt;&gt;</code>.</p>
<p>The function above may be a bit tricky, but it&rsquo;s required to create a context. Typically, though, you can get the function directly from whatever code element you&rsquo;re operating on. In our case, the highlighting passed into a quick-fix has an <code>Expression</code>, so we can simply use that:</p>
<pre class="brush: csharp; title: ; notranslate">
public IntPowerInliningFix(IntPowerHighlighting highlighting)
{
  this.highlighting = highlighting;
  customNameSettings = GetCustomFunctionSettings(highlighting.Expression.ToDataContext());
}
</pre>
<p>Now that we&rsquo;ve got the settings, all that remains is to use them! The approach I&rsquo;m going to take here is to use the custom function, if available, for powers greater than 3:</p>
<pre class="brush: csharp; title: ; notranslate">
protected override Action&lt;ITextControl&gt; ExecutePsiTransaction(ISolution solution, IProgressIndicator progress)
{
  var expr = highlighting.Expression;
  var arg = expr.Arguments[0];
  var factory = CSharpElementFactory.GetInstance(expr.GetPsiModule());
  ICSharpExpression replacement;
  if (customNameSettings.First &amp;&amp; highlighting.Power &gt; 3)
  {
    var template = &quot;$0($1, &quot; + highlighting.Power + &quot;)&quot;;
    replacement = factory.CreateExpression(template, 
      customNameSettings.Second, expr.Arguments[0]);
  }
  else
  {
    replacement = factory.CreateExpression(
      Enumerable.Range(0, highlighting.Power).Select(i =&gt; &quot;$0&quot;).Join(&quot;*&quot;), arg.Value);
  }
  ModificationUtil.ReplaceChild(expr, replacement);
      
  return null;
}
</pre>
<p>Now, a user can specify a replacement function <code>Maths.IntPow</code> and have their <code>Math.Pow(x, 4.0)</code> call refactored to <code>Maths.IntPow(x, 4)</code>. Note that it&rsquo;s <code>4</code>, not <code>4.0</code>&nbsp;&mdash; we assume that the target function takes an <code>int</code> as the second parameter. Note also that in order to get <code>4</code> to appear, we cannot use the <code>$</code> notation&nbsp;&ndash; instead, we prepare the template by concatenating strings, putting the integer there manually.</p>
<h3>Code Cleanup</h3>
<p>Changing the <code>Math.Pow()</code> invocations one at a time is too slow if you&rsquo;ve got hundreds of such instances. The mechanism to perform changes <em>en masse</em> in ReSharper is called Code Cleanup and that&rsquo;s the mechanism we&rsquo;re going to use to perform changes on all <code>int</code>-bearing instances of <code>Math.Pow()</code> that are found, be it in a file, project or whole solution.</p>
<p>So let&rsquo;s start with the basics: what we need is a code cleanup module, a class that implements the <code>ICodeCleanupModule</code> interface and is decorated with <code>[CodeCleanupModule]</code>. Unfortunately, <code>ICodeCleanupModule</code> has six methods that we must implement. Some of these are similar to <code>IQuickFix</code> methods but actually serve different purposes. There&rsquo;s also the thorny issue of descriptors, so let&rsquo;s start with those.</p>
<p>A <em>descriptor</em> is basically an option of code cleanup. For example, the option of whether to change declarations to <code>var</code> is encapsulated within a descriptor. We need at least one descriptor to define whether we want to do the <code>Math.Pow()</code> replacement at all, so here goes:</p>
<pre class="brush: csharp; title: ; notranslate">
[DefaultValue(false)]
[DisplayName(&quot;Replace Math.Pow() integer calls&quot;)]
[Category(CSharpCategory)]
private class Descriptor : CodeCleanupBoolOptionDescriptor
{
  public Descriptor() : base(&quot;ReplaceMathPowIntegerCalls&quot;) {}
}
</pre>
<p>All this does is provide an option to turn the feature on or off in various code cleanup profiles. Now, this feature can be instantiated and returned from the code cleanup module:</p>
<pre class="brush: csharp; title: ; notranslate">
private static readonly Descriptor descriptor = new Descriptor();
public ICollection&lt;CodeCleanupOptionDescriptor&gt; Descriptors
{
  get { return new[] {descriptor}; }
}
</pre>
<p>Now, moving on, let&rsquo;s implement the <code>IsAvailable()</code> method. This method takes an <code>IPsiSourceFile</code> and we&rsquo;re supposed to determine whether it can be used. Well, our only restriction right now is that this has to be a C# file, so&hellip;</p>
<pre class="brush: csharp; title: ; notranslate">
public bool IsAvailable(IPsiSourceFile sourceFile)
{
  return sourceFile.GetPsiFile&lt;CSharpLanguage&gt;() != null;
}
</pre>
<p>One small thing to note is that the above causes the action to also fire in <em>injected</em> PSI, i.e., in C# that&rsquo;s part of MVC or Razor views. If you want to avoid this, we could use <code>GetNonInjectedPsiFile()</code> instead.</p>
<p>Next, let&rsquo;s go after <code>SetDefaultSetting()</code>, which determines the default value of this option depending on the code cleanup profile that&rsquo;s being used. Let&rsquo;s assume that, by default,</p>
<ul>
<li>
<p>Our feature is <strong>on</strong> in the &ldquo;Full Cleanup&rdquo; profile.</p>
</li>
<li>
<p>Our feature is <strong>off</strong> in the &ldquo;Reformat&rdquo; profile.</p>
</li>
</ul>
<p>Thus, the following implementation of <code>SetDefaultSetting()</code> communicates our preferences:</p>
<pre class="brush: csharp; title: ; notranslate">
public void SetDefaultSetting(CodeCleanupProfile profile, CodeCleanup.DefaultProfileType profileType)
{
  switch (profileType)
  {
    case CodeCleanup.DefaultProfileType.FULL:
      profile.SetSetting(descriptor, true);
      break;
    default:
      profile.SetSetting(descriptor, false);
      break;
  }
}
</pre>
<p>Now, there&rsquo;s also the <code>IsAvailableeOnSelection</code> property, which is pretty self-descriptive. You can return <code>true</code> or <code>false</code> here based on applicability; it doesn&rsquo;t matter much for our experiments.</p>
<p>Finally, we come to the meat of the problem: the <code>Process()</code> method where changes actually happen. But, annoyingly enough, this method needs to reuse our analyzer and quick-fix code. We don&rsquo;t really want to run it all again, do we? As a result, we perform the following refactorings:</p>
<ul>
<li>
<p>In <code>IntPowerProblemAnalyzer</code>, we isolate the check on the right method into a static method called <code>InvocationExpressionIsMathPowCall</code>. This function now returns two values&nbsp;&ndash; a <code>bool</code> indicating whether this is the right function, and an <code>int</code> indicating the power that is being used.</p>
</li>
<li>
<p>In <code>IntPowerInliningFix</code>, we ensure the function to acquire settings is static; we then isolate the code that performs the change into a separate (again, static) method.</p>
</li>
</ul>
<p>We can now attempt to perform the code cleanup itself. This is no mean feat, considering that previously, in our quick-fix, a lot of the plumbing was handled by the <code>BulbItemImpl</code> class that we inherited from. Let&rsquo;s do a few checks, first. Let&rsquo;s check that we&rsquo;ve got the right file and that we are allowed to do the change:</p>
<pre class="brush: csharp; title: ; notranslate">
var file = sourceFile.GetPsiFile&lt;CSharpLanguage&gt;();
if (file == null) 
  return;
 
if (!profile.GetSetting(descriptor)) 
  return;
</pre>
<p>If these checks pass, there&rsquo;s some legitimacy to doing the change. We may as well get the user settings for the quick-fix right now, because doing them every time we meet an invocation expression is a bad idea:</p>
<pre class="brush: csharp; title: ; notranslate">
var settings = IntPowerInliningFix.GetCustomFunctionSettings(sourceFile.ToDataContext());
</pre>
<p>Now, regrettably, we must <em>manually</em> set up a transaction using the <code>PsiManager</code>. We&rsquo;re going to also be using shell locks, specifically a write lock that is required to perform changes in a file. The <code>IShellLocks</code> variable can be injected into the constructor of our module:</p>
<pre class="brush: csharp; title: ; notranslate">
var settings = IntPowerInliningFix.GetCustomFunctionSettings(sourceFile.ToDataContext());
file.GetPsiServices().PsiManager.DoTransaction(() =&gt;
{
  using (shellLocks.UsingWriteLock())
  {
    // scary stuff here
  }
}, &quot;Code cleanup&quot;);
</pre>
<p>So, what exactly is happening inside the above? Well, we have to go through all <code>IInvocationExpression</code>&rsquo;s in the file recursively and, for each one that happens to be a correct <code>Math.Pow()</code> call, perform the replacement. This is where our refactorings come into play, because without them we&rsquo;d be duplicating code or creating meaningless (and quite possibly broken) instances of our analyzer or quick-fix.</p>
<p>Here&rsquo;s what the &lsquo;scary stuff&rsquo; looks like:</p>
<pre class="brush: csharp; title: ; notranslate">
var itemsToChange = new List&lt;Pair&lt;IInvocationExpression,int&gt;&gt;();
file.ProcessChildren&lt;IInvocationExpression&gt;(e =&gt;
{
  int power;
  if (IntPowerProblemAnalyzer.InvocationExpressionIsMathPowCall(e, out power))
    itemsToChange.Add(new Pair&lt;IInvocationExpression, int&gt;(e, power));
});
foreach (var e in itemsToChange)
  IntPowerInliningFix.PerformChange(e.First, settings, e.Second);
</pre>
<p>Notice how we have to cache the items before they are processed&nbsp;&mdash; this is necessary because modifying these items as they are being iterated is not safe, just as it&rsquo;s not safe to modify the loop iterator within the loop. Thus, we use a <code>List&lt;&gt;</code> to cache the items and their respective powers, and then reprocess them wholesale once the iteration has been completed.</p>
<h3>Conclusion</h3>
<p>In this post I&rsquo;ve demonstrated how to dig into the invocation&rsquo;s type name (no easy feat), how to define settings and use them. I&rsquo;ve also demonstrated how to write a code cleanup module to perform large-scale changes on the code base. You can find the source code <a href="http://pastebin.com/HQR0sumZ" title="http://pastebin.com/HQR0sumZ">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://devtalk.net/resharper/resharper-sdk-adventures-2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>ReSharper SDK Adventures Part 1 &#8211; Math.Pow Inlining</title>
		<link>http://devtalk.net/resharper/resharper-sdk-adventures-1/</link>
		<comments>http://devtalk.net/resharper/resharper-sdk-adventures-1/#comments</comments>
		<pubDate>Fri, 04 May 2012 16:30:19 +0000</pubDate>
		<dc:creator>Dmitri Nesteruk</dc:creator>
				<category><![CDATA[ReSharper]]></category>

		<guid isPermaLink="false">http://devtalk.net/?p=215</guid>
		<description><![CDATA[Seeing how the ReSharper SDK has been out for quite a while, I&#8217;d like to start a series of posts demonstrating how it can be used. And since this is the first post in a series, I&#8217;m going to explain a little about some of the practices related to plugin development, and illustrate a few [...]]]></description>
			<content:encoded><![CDATA[<p>Seeing how the <a href="http://www.jetbrains.com/resharper/download/index.html" title="http://www.jetbrains.com/resharper/download/index.html">ReSharper SDK</a> has been out for quite a while, I&rsquo;d like to start a series of posts demonstrating how it can be used. And since this is the first post in a series, I&rsquo;m going to explain a little about some of the practices related to plugin development, and illustrate a few concepts that are central to R# as a product.</p>
<h3>Problem</h3>
<p>Why does the plugin ecosystem exist in the first place? Why make the SDK? The motivation is, of course, the fact that individual features that <em>you</em> might need for your particular case aren&rsquo;t available out of the box. For example, you are aware of a particular case where code is bad and you want to somehow correct this. (SSR helps in simple cases, but the one we&rsquo;ll consider is a bit more complex.)</p>
<p>For example, the following is, arguably, bad code:</p>
<pre class="brush: csharp; title: ; notranslate">
var y = Math.Pow(x, 2.0);
</pre>
<p>The performance overhead on calculating x² this way is <em>massive</em>. The reason is that <code>Math.Pow()</code> is tuned towards floating-point powers, which means that up to some extent, it is a lot more efficient to do one of the following:</p>
<ul>
<li>
<p>Write the expression inline, i.e., <code>Math.Pow(x, 2.0)</code> &rarr; <code>x*x</code>.</p>
</li>
<li>
<p>Substitute an expression with your own implementation where the power is an integer, i.e., <code>Math.Pow(x, 2.0)</code> &rarr; <code>Maths.Pow(x, 2)</code>, where <code>Maths</code> is your own utility class and <code>Pow</code> is a function that has an integer overload.</p>
</li>
</ul>
<p>Now, the above is a problem, and I&rsquo;d like this problem to be taken care of by using ReSharper&rsquo;s extensibility mechanisms.</p>
<h3>Identifying the Structure</h3>
<p>If we are to somehow fix the above, we first need to be able to identify the &lsquo;offending&rsquo; structure. We are going to assume the simplest possible case, <code>Math.Pow(x, y)</code> where <code>x</code> is an identifier and <code>y</code> is a numeric value that happens to be an integer.</p>
<p>We should immediately be able to realize the constraints that we are putting on this model. For example, we assume that <code>x</code> is an identifier and <em>not</em>, for example, a numeric value. In fact, if it was, we could precompute the whole thing. But what if it was a constant, something like <code>Math.Pow(Math.PI, 2)</code>? Clearly, in this particular case, we wouldn&rsquo;t care whether the power was an integer or not, because in any case, the replacement would be a computed constant value.</p>
<p>So, let&rsquo;s look at a typical call, <code>Math.Pow(x, 2.0)</code>. Here&rsquo;s how to get info about it:</p>
<ol>
<li>
<p>First, fire up Visual Studio with the <code>/ReSharper.Internal</code> switch to get all the internal debug menus.</p>
</li>
<li>
<p>Make a bare-bones file that contains the <code>Math.Pow()</code> statement in it.</p>
</li>
<li>
<p>In the top-level menu, choose <strong>ReSharper | Internal | Go to PSI Viewer</strong>.</p>
</li>
</ol>
<p>What you should end up with is something like this:</p>
<p><img src="http://nesteruk.org/pix/0/76479d63-5544-40db-a32a-38f25393dce2.png" alt="" style="border:0"/></p>
<p>The PSI viewer is a really neat tool for figuring out what the code you&rsquo;re after actually is. For instance, the above basically shows us that <code>Math.Pow(x, 2.0)</code> is</p>
<ul>
<li>
<p>An <code>IInvocationExpression</code> containing</p>
</li>
</ul>
<ul>
<li>
<p>A reference expression referring to <code>Math.Pow</code></p>
</li>
<li>
<p>A list of arguments containing</p>
</li>
</ul>
<ul>
<li>
<p>A reference expression with an identifier <code>x</code></p>
</li>
<li>
<p>A literal expression with a floating-point value of 2.0</p>
</li>
</ul>
<p>And that&rsquo;s just about all we need to know&nbsp;&ndash; for now. We can now create a simple problem analyzer to look for this particular scenario.</p>
<h3>Problem Analyzer</h3>
<p>A problem analyzer is a piece of code that ReSharper can use to find out if there&rsquo;s a problem somewhere. Since we agree to consider integer-based <code>Math.Pow</code> expressions to be a performance problem, we are going to create an element problem analyzer that will help us identify it.</p>
<p>First of all, let us define a class called <code>IntPowerProblemAnalyzer</code>. This class is looking explicitly for <code>IInvocationExpression</code>s, thus it will be made to inherit from <code>ElementProblemanalyzer&lt;IInvocationExpression&gt;</code>. There&rsquo;s also some metadata at the top that we&rsquo;ll discuss in a moment.</p>
<pre class="brush: csharp; title: ; notranslate">
[ElementProblemAnalyzer(new[]{typeof(IInvocationExpression)}, 
  HighlightingTypes=new[]{typeof(IntPowerHighlighting)})]
public class IntPowerProblemAnalyzer : ElementProblemAnalyzer&lt;IInvocationExpression&gt;
{
  protected override void Run(IInvocationExpression element, 
    ElementProblemAnalyzerData data, IHighlightingConsumer consumer)
  {
    // todo :)
  }
}
</pre>
<p>Okay, so the class we have right now has to implement a single method called <code>Run()</code>. This method is important because this is where we teach the plugin to identify and highlight code that conforms to our pattern. But how to actually identify the pattern? Using the PSI viewer above, we can deduce that a <code>Math.Pow()</code> call check would consist of two parts: checking that we are calling a <code>Pow()</code> function, and checking that the arguments are correct. The first condition is checked as follows:</p>
<pre class="brush: csharp; title: ; notranslate">
bool functionIsCalledPow = false;
var e = element.InvokedExpression as IReferenceExpression;
if (e != null)
{
  if (e.Reference.GetName().Equals(&quot;Pow&quot;))
    functionIsCalledPow = true;
}
</pre>
<p>Note that we&rsquo;re not testing it was <code>Math</code> that this was called on&nbsp;&ndash; this is more complicated and a bit out-of-scope right now. The second part of the check is a little more convoluted:</p>
<pre class="brush: csharp; title: ; notranslate">
bool firstArgIsIdentifier = false;
bool secondArgIsInteger = false;
if (element.Arguments.Count == 2)
{
  firstArgIsIdentifier = element.Arguments[0].Value is IReferenceExpression;
  var secondArg = element.Arguments[1].Value as ICSharpLiteralExpression;
  if (secondArg != null &amp;&amp; (secondArg.IsConstantValue()))
  {
    double value = -1.0;
    var cv = secondArg.ConstantValue;
    if (cv.IsDouble())
      value = (double)cv.Value;
    else if (cv.IsInteger())
      value = (int) cv.Value;
    secondArgIsInteger = (value &gt; 0.0) &amp;&amp; value == Math.Floor(value);
  }
}
</pre>
<p>The above does a very basic, almost simplistic check on the structure of the code in question. Note that I&rsquo;ve greatly simplified the identification of the reference, but it will do for now. The next thing that we have to discuss is how problematic code is highlighted.</p>
<h3>Highlighting the Problem</h3>
<p>We&rsquo;ve got some code for finding the problem, but how to show it to the user? In the snippet above, we used the highlighting consumer and passed it an instance of a highlighting. So what is it?</p>
<p>A highlighting is simply a class that implements that <code>IHighlighting</code> interface and is decorated by appropriate attributes. All it does is define how a particular problem is highlighted by ReSharper. This highlighting is passed to the consumer and is also featured as part of the <code>HighlightingTypes</code> attribute parameter of the problem analyzer. We are currently using the following definition of <code>IntPowerHighlighting</code>:</p>
<pre class="brush: csharp; title: ; notranslate">
[StaticSeverityHighlighting(Severity.WARNING, CSharpLanguage.Name)]
public class IntPowerHighlighting : IHighlighting
{
  private readonly IInvocationExpression expression;
  public int Power { get; private set; }
  public IntPowerHighlighting(IInvocationExpression expression, int power)
  {
    this.expression = expression;
    Power = power;
  }
  public bool IsValid()
  {
    return expression != null &amp;&amp; expression.IsValid();
  }
  public string ToolTip { get { return &quot;Inefficient use of integer-based power&quot;; } }
  public string ErrorStripeToolTip { get { return ToolTip; } }
  public int NavigationOffsetPatch { get { return 0; } }
}
</pre>
<p>Together with the element problem analyzer, we can fire up our plugin and get a result similar to the following:</p>
<p><img src="http://nesteruk.org/pix/0/a226c5fd-2a4e-485f-bb07-c96a6d09e623.png" alt="" style="border:0"/></p>
<p>And that&rsquo;s what we wanted in the first place, but just seeing the problem isn&rsquo;t enough. How about letting the end user <em>correct</em> the problem?</p>
<h3>Quick-Fix</h3>
<p>A quick-fix is a fix associated with a highlighting. In our case, we want to let a user replace <code>Math.Pow(x,2)</code> with <code>x*x</code>, with the number of <code>x</code>&rsquo;s corresponding to the power. Note that it is entirely unreasonable beyond a certain value, typically around 2-3, so our fix will only work for these values.</p>
<p>In order to implement an inlining fix, we need to create an additional class. This class will implement the <code>IQuickFix</code> interface and decorate it with a <code>[QuickFix]</code> attribute as follows:</p>
<pre class="brush: csharp; title: ; notranslate">
[QuickFix]
public class IntPowerInliningFix : BulbItemImpl, IQuickFix
{
  private readonly IntPowerHighlighting highlighting;
  public IntPowerInliningFix(IntPowerHighlighting highlighting)
  {
    this.highlighting = highlighting;
  }
  protected override Action&lt;ITextControl&gt; ExecutePsiTransaction(ISolution solution, IProgressIndicator progress)
  {
    // todo
  }
  public override string Text
  {
    get { return &quot;Inline integer power&quot;; }
  }
  public bool IsAvailable(IUserDataHolder cache)
  {
    int power = highlighting.Power;
    return power == 2 || power == 3;
  }
}
</pre>
<p>Note how the fix is only available for powers 2 and 3. The <code>ExecutePsiTransaction()</code> method is where all interesting things occur. Specifically, this is where we actually replace the <code>Math.Pow()</code> call with an inlined multiplication. Since this is somewhat more complicated, let&rsquo;s go through this step-by-step. First of all, we need to get our argument&nbsp;&ndash; the one we&rsquo;re going to multiply a few times:</p>
<pre class="brush: csharp; title: ; notranslate">
var arg = highlighting.Expression.Arguments[0];
</pre>
<p>Now we need to create an element factory to construct the replacement expression. We use the original expression to get at the PSI module:</p>
<pre class="brush: csharp; title: ; notranslate">
var factory = CSharpElementFactory.GetInstance(highlighting.Expression.GetPsiModule());
</pre>
<p>Now, through a bit of LINQ magic, we create an expression that represents the multiplication. Essentially, we create lots of <code>$0</code>&rsquo;s separated by multiplication signs and let <code>CSharpElementFactory</code> fill them in:</p>
<pre class="brush: csharp; title: ; notranslate">
var replacement = factory.CreateExpression(
  Enumerable.Range(0, highlighting.Power).Select(i =&gt; &quot;$0&quot;).Join(&quot;*&quot;), arg.Value);
</pre>
<p>Finally, we replace the old expression with the new one:</p>
<pre class="brush: csharp; title: ; notranslate">
ModificationUtil.ReplaceChild(highlighting.Expression, replacement);
</pre>
<p>And here is what it looks like:</p>
<p><img src="http://nesteruk.org/pix/0/8b522660-0504-4865-a15a-9ef2cb066c8e.png" alt="" style="border:0"/></p>
<h3>Conclusion</h3>
<p>This demonstration is, admittedly, very simple. I&rsquo;ve taken a number of methodological shortcuts that would never be acceptable in production code, namely:</p>
<ul>
<li>
<p>Only checked that the function is called <code>Pow()</code> without verifying that it&rsquo;s part of <code>System.Math</code></p>
</li>
<li>
<p>Only did a basic check against the first argument</p>
</li>
<li>
<p>Assumed that the power is either a <code>double</code> or an <code>int</code>, whereas in reality it could be e.g., a <code>short</code></p>
</li>
<li>
<p>Didn&rsquo;t write any tests</p>
</li>
</ul>
<p>In the next part of the series we&rsquo;ll continue with this theme and take a look at how the plugin can be enhanced and its operations can be more rigorously checked. Meanwhile, check out the <a href="http://pastebin.com/mcTC41pN" title="http://pastebin.com/mcTC41pN">source code</a>. For more information on the ReSharper API, check out the <a href="http://confluence.jetbrains.net/display/ReSharper/ReSharper+6+Plugin+Development" title="http://confluence.jetbrains.net/display/ReSharper/ReSharper+6+Plugin+Development">ReSharper Plugin Development Guide</a>. Happy coding!</p>
]]></content:encoded>
			<wfw:commentRss>http://devtalk.net/resharper/resharper-sdk-adventures-1/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Realtime Programming</title>
		<link>http://devtalk.net/fsharp/realtime-programming/</link>
		<comments>http://devtalk.net/fsharp/realtime-programming/#comments</comments>
		<pubDate>Fri, 06 Apr 2012 17:39:48 +0000</pubDate>
		<dc:creator>Dmitri Nesteruk</dc:creator>
				<category><![CDATA[FSharp]]></category>

		<guid isPermaLink="false">http://devtalk.net/?p=208</guid>
		<description><![CDATA[One of the recent talks that stirred the blogosphere is the Inventing on Principle talk by Bret Victor, in which he shows how one can do programming with realtime results. What surprised me more than the talk itself was people&#8217;s reaction to the talk: I think many developers felt that what was shown was somehow [...]]]></description>
			<content:encoded><![CDATA[<p>One of the recent talks that stirred the blogosphere is the <a href="http://vimeo.com/36579366">Inventing on Principle</a> talk by Bret Victor, in which he shows how one can do programming with realtime results. What surprised me more than the talk itself was people&#8217;s reaction to the talk: I think many developers felt that what was shown was somehow new (whether technologically or ideologically).</p>
<p>I beg to differ. In fact, minus the fancy manipulation widgets, the demonstrated approach shown is already available to anyone wishing to have it.</p>
<p>The solution is to take a language that is either REPL-pliable or very quick to compile and then re-run the compiler/interpreter on every symbol change in the editor. For example, in F# we can wire up <code>FSI.EXE</code> to re-run our script on any change. This is feasible performance-wise, and, coupled with a little code to intercept the standard output/error streams, you get a complete solution for rapidly prototyping any piece of code without having to explicitly compile something, manage the project, etc.</p>
<h3>Use Cases</h3>
<p>One place where the realtime approach is useful is numerics. Now we know that tools such as Mathematica, MATLAB etc. all basically do REPL, but that&#8217;s not nearly good enough. But what you can do is simply feed a <em>whole file</em> to an application to process wholesale. Then, simply observe any result you get.</p>
<p>The great thing about this is error handling during compilation. Making a mistake and then not getting the right result is very costly when compilation takes a long time and the availability of static analysis tools is poor. As a result, this &#8216;realtime&#8217; approach really does save a lot of time and energy that would have otherwise been spent recompiling and cursing at yourself/the compiler/the universe.</p>
<p>And by the way, languages that support REPL are a lot better at outputting objects as text. For example, F# lets you write <code>printf "%A" xyz</code> where <code>xyz</code> can be a list, sequence, whatever. And it does output nicely formatted lists in a manner that, say, MATLAB easily can.</p>
<h3>Enhancements</h3>
<p>Let&#8217;s get back to F#/FSI for a moment. What&#8217;s interesting about feeding the &#8216;intermediate code state&#8217; into the interpreter (which is the same as the compiler, by the way) is that we can <em>augment</em> the code passed in by putting in additional diagnostic statements. Not in the code, but at the postprocessing stage.</p>
<p>For example, we can take all method parameters and output them to the console. Or we can find every <code>let</code> binding and output the object that&#8217;s being kept. And then, all of a sudden, all that &#8216;Inventing on Principle&#8217; magic with illustrating changes in the intermediate variables suddenly becomes possible.</p>
<h3>Conclusion</h3>
<p>The applicability of this technique largely depends on the language. However, in many languages, it&#8217;s totally reasonable to adapt this approach. In particular, compiled languages that have a scripting counterpart (e.g., D) can be more amenable to this approach, whereas slow-to-compile languages such as C++ can benefit from <em>substitution</em>, the idea being that you prototype your code using a different language entirely. (Of course, extra effort will be required to make the conversion.)</p>
<p>Moral of the story: you already have capabilities for realtime programming, you just aren&#8217;t using them.</p>
]]></content:encoded>
			<wfw:commentRss>http://devtalk.net/fsharp/realtime-programming/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Local Inversion of Control</title>
		<link>http://devtalk.net/dotnet/local-inversion-of-control/</link>
		<comments>http://devtalk.net/dotnet/local-inversion-of-control/#comments</comments>
		<pubDate>Mon, 30 Jan 2012 20:44:50 +0000</pubDate>
		<dc:creator>Dmitri Nesteruk</dc:creator>
				<category><![CDATA[DotNet]]></category>

		<guid isPermaLink="false">http://devtalk.net/?p=198</guid>
		<description><![CDATA[The term &#8216;Inversion of Control&#8217; is typically used in relation to DI/IoC frameworks. However, that same idea works at the micro scale too. I for one encounter a lot of what I could call Local Inversion of Control (LIoC) all the time, and this is what this short post is all about. Examples Let&#8217;s start [...]]]></description>
			<content:encoded><![CDATA[<p>The term &lsquo;Inversion of Control&rsquo; is typically used in relation to DI/IoC frameworks. However, that same idea works at the micro scale too. I for one encounter a lot of what I could call <strong>Local Inversion of Control</strong> (LIoC) all the time, and this is what this short post is all about.</p>
<h3>Examples</h3>
<p>Let&rsquo;s start with the simplest example. Say you want to add an item to the collection: this is typically written as</p>
<pre class="brush: csharp; title: ; notranslate">
myCollection.Add(x)
</pre>
<p>If you pause for a moment and think about the above statement and voice it in English, what you&rsquo;ll get is <em><code>myCollection</code> should add to itself item <code>x</code></em> which is very much unreadable. This is precisely the case where IoC is useful, and here&rsquo;s how: let us define an <code>AddTo()</code> extension method:</p>
<pre class="brush: csharp; title: ; notranslate">
public static T AddTo&lt;T&gt;(this T self, ICollection&lt;T&gt; collection)
{
  collection.Add(self);
  return self;
}
</pre>
<p>Now, instead of calling the <code>Add()</code> method on the collection, control is inverted, so the <code>AddTo()</code> method is called on the collection:</p>
<pre class="brush: csharp; title: ; notranslate">
var aList = new List&lt;int&gt;();
2.AddTo(aList);
</pre>
<p>Translated to English, the above now reads <em>2 should be added to <code>aList</code></em>. Makes more sense, doesn&rsquo;t it? Also, as an added bonus, the <code>AddTo()</code> operation is <em>fluent</em> because it returns the original argument. This means that a value can be added to more than one list at once, e.g.:</p>
<pre class="brush: csharp; title: ; notranslate">
2.AddTo(someList).AddTo(someOtherList);
</pre>
<p>Let&rsquo;s try something else. Suppose you want to check that a collection is empty. Typically, you&rsquo;d write</p>
<pre class="brush: csharp; title: ; notranslate">
if (myClass.Fields.Count == 0) { ... }
// or
if (!myClass.Fields.Any()) { ... }
</pre>
<p>Both of these approaches are okay, I guess, but the code reads strange. The first example says <em>if <code>myClass</code>&rsquo;s fields count is equal to zero</em> whereas the second reads <em>if not <code>myClass</code>&rsquo;s fields are any in number</em>, which is even worse.</p>
<p>So here&rsquo;s a pair of extension methods:</p>
<pre class="brush: csharp; title: ; notranslate">
public static bool HasSome&lt;TSubject, T&gt;(this TSubject subject, 
  Func&lt;TSubject, IEnumerable&lt;T&gt;&gt; propertyToCheck)
{
  return propertyToCheck(subject).Any();
}
public static bool HasNo&lt;TSubject, T&gt;(this TSubject subject, 
  Func&lt;TSubject, IEnumerable&lt;T&gt;&gt; propertyToCheck)
{
  return !HasSome(subject, propertyToCheck);
}
</pre>
<p>Now, a check for the presence of fields turns into</p>
<pre class="brush: csharp; title: ; notranslate">
if (myClass.HasNo(c =&gt; c.Fields)) {}
</pre>
<p>which reads as <em><code>myClass</code> has no fields</em>, which is precisely what we&rsquo;re checking here.</p>
<p>Okay, one more example. Say you&rsquo;re checking a string value, and you want to compare it with a set of values. This is typically represented as</p>
<pre class="brush: csharp; title: ; notranslate">
if (myOp == &quot;AND&quot; || myOp == &quot;OR&quot; || myOp == &quot;XOR&quot;) { ... }
</pre>
<p>This reads in a kind of OK, but fragmented, fashion. A much better way would be to group the variants into an array but, in C#, this just looks ugly:</p>
<pre class="brush: csharp; title: ; notranslate">
if (new[]{&quot;AND&quot;, &quot;OR&quot;, &quot;XOR&quot;}.Contains(myOp)) { ... }
</pre>
<p>This is even less semantic. What if there was an <code>IsOneOf()</code> function instead?</p>
<pre class="brush: csharp; title: ; notranslate">
public static bool IsOneOf&lt;T&gt;(this T self, params T[] variants)
{
  return variants.Contains(self);
}
</pre>
<p>Now, the above check would turn to</p>
<pre class="brush: csharp; title: ; notranslate">
if (myOp.IsOneOf(&quot;AND&quot;, &quot;OR&quot;, &quot;XOR&quot;)) { ... }
</pre>
<p>The great thing about the above approach is that the arguments are declared as <code>params T[]</code>, so we don&rsquo;t have to initialize any arrays with <code>new[]</code> before using them as a test.</p>
<h3>Summary</h3>
<p>So here&rsquo;s the basic premise of LIoC: given a function <code>f(x,y...)</code>, it may <em>in certain cases</em> be more benefitial from the semantic and usability perspectives to instead define an extension method on <code>x</code> that applies the function <code>f</code> using the argument(s) <code>y</code>.</p>
<p>Additional benefits are provided by the fact that:</p>
<ul>
<li>
<p>Extension methods may take generic arguments, thus letting you define inverted operations on groups of similar objects.</p>
</li>
<li>
<p>The <code>params</code> keyword lets your API behave in a &lsquo;variadic&rsquo; fashion by unchaining you from explicit collection initialization.</p>
</li>
<li>
<p>Additional level of expressiveness can be gained from passing in lambdas or expressions.</p>
</li>
</ul>
<p>The disadvantages of this approach are:</p>
<ul>
<li>
<p>Having to manage separate classes containing extension methods.</p>
</li>
<li>
<p>API pollution&nbsp;&mdash; any time you define an extension method on a generic type, <em>all objects</em> get an additional IntelliSense popup member.</p>
</li>
<li>
<p>Possible performance overhead&nbsp;&mdash; for example, in cases where you use a lambda instead of direct member access.</p>
</li>
</ul>
<p>I use LIoC all over the place, just like I use the <a href="http://devtalk.net/csharp/chained-null-checks-and-the-maybe-monad/" title="http://devtalk.net/csharp/chained-null-checks-and-the-maybe-monad/">Maybe monad</a>. It makes the code a lot more readable, maintainable and amenable to refactoring. ▪</p>
]]></content:encoded>
			<wfw:commentRss>http://devtalk.net/dotnet/local-inversion-of-control/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Web Mining via Phantom.js and SharpKit</title>
		<link>http://devtalk.net/dotnet/web-mining-phantomjs-sharpkit/</link>
		<comments>http://devtalk.net/dotnet/web-mining-phantomjs-sharpkit/#comments</comments>
		<pubDate>Thu, 01 Dec 2011 16:10:31 +0000</pubDate>
		<dc:creator>Dmitri Nesteruk</dc:creator>
				<category><![CDATA[DotNet]]></category>
		<category><![CDATA[phantomjs]]></category>
		<category><![CDATA[sharpkit]]></category>

		<guid isPermaLink="false">http://devtalk.net/?p=189</guid>
		<description><![CDATA[When it comes to web scraping, having a real, physical web browser is a chore. Not only is it a problem to open 10+ copies of IE, but the whole idea of showing up UI on a machine that may not have an operator to close it should things go awry is something that feels, [...]]]></description>
			<content:encoded><![CDATA[<p>When it comes to web scraping, having a real, physical web browser is a chore. Not only is it a problem to open 10+ copies of IE, but the whole idea of showing up UI on a machine that may not have an operator to close it should things go awry is something that feels, well, very <em>wrong</em> to me.</p>
<p>Unfortunately, there is no headless WebKit library for .Net and <a href="http://testerthoughts.com/2011/05/17/guest-post-net-headless-browser-options/" title="http://testerthoughts.com/2011/05/17/guest-post-net-headless-browser-options/">current approaches</a> all either have Java or JavaScript bindings or, alternatively, suggest that you <a href="http://blog.stevensanderson.com/2010/03/30/using-htmlunit-on-net-for-headless-browser-automation/" title="http://blog.stevensanderson.com/2010/03/30/using-htmlunit-on-net-for-headless-browser-automation/">use IKVM</a>. However, this got me thinking: if an IKVM-driven port works (albeit not very well, in terms of performance, at least), then how about going in the direction of JavaScript solutions such as <a href="http://phantomjs.org" title="http://phantomjs.org">Phantom.js</a>?</p>
<p><strong>And then it hit me:</strong> I&rsquo;ve already good a transcompiler called <a href="http://sharpkit.net" title="http://sharpkit.net">SharpKit</a> that knows how to translate C# to JavaScript. So what if I were to simply write my code in C#, then let Phantom.js execute it as JavaScript?</p>
<h3>What is Phantom.js, anyway?</h3>
<p>Phantom.js is a dual API: it contains both its own APIs as well as APIs exposed through the <code>webpage</code> and <code>fs</code> modules of <a href="http://wiki.commonjs.org/wiki/Modules/1.1.1" title="http://wiki.commonjs.org/wiki/Modules/1.1.1">CommonJS</a>. As a result, to get this API within SharpKit, I would have to trail through these APIs and generate corresponding C# classes and methods for them. This is actually fairly trivial&nbsp;&ndash; all I have to do is to decorate the class with <code>[JsType(JsMode.Prototype)]</code> and the methods with <code>[JsMethod/JsProperty]</code> and everything would work.</p>
<p>As you can see, it&rsquo;s impossible to redefine property names, so the C# API has lost some of its gloss. But that&rsquo;s not critical. What&rsquo;s important it that I&rsquo;ve been able to replicate the API of both the <code>phantom</code> and <code>WebPage</code> objects in C#. I didn&rsquo;t go for the CommonJS modules because it seemed that the existing features, together with the DOM and jQuery APIs provided by Sharpkit are more than enough.</p>
<h3>Trying It Out</h3>
<p>To try things out, I rewrote the Phantom pizza-searching example to use C#. Here it is, in all its glory:</p>
<pre class="brush: csharp; title: ; notranslate">
var page = new WebPage();
string url = &quot;http://lite.yelp.com/search?find_desc=pizza&amp;find_loc=94040&amp;find_submit=Search&quot;;
page.open(url, status =&gt; {
  if (status != &quot;success&quot;) console.log(&quot;Unable to access network&quot;);
  else
  {
    var result = page.evaluate(() =&gt;
    {
      var list = document.querySelectorAll(&quot;span.address&quot;);
      var pizza = new JsArray&lt;string&gt;();
      for (int i = 0; i &lt; list.length; i++)
      {
        pizza.push(list[i].innerText);
      }
      return pizza;
    });
    console.log(result.As&lt;JsArray&lt;string&gt;&gt;().join(&quot;\n&quot;));
  }
  Phantom.exit();
});
</pre>
<p>Surprisingly enough, there aren&rsquo;t that many caveats to note here. One issue I had is how to return types from methods that should, in all fairness, be made generic. In the end, I ended up deciding that it&rsquo;s better to leave the return type as <code>JsObject</code> and then using the <code>As&lt;&gt;()</code> method to cast the result to whatever I actually need. The explicit type would have to appear eventually, unless of course we went with <code>dynamic</code>&nbsp;&ndash; but then again, I don&rsquo;t know if this even possible.</p>
<p>Needless to say, the example worked out of the box, which shouldn&rsquo;t really be surprising considering that I actually peeked into the resulting JS file and saw that what was generated.</p>
<h3>Persisting Data</h3>
<p>There&rsquo;s no way getting around the fact that, with this approach, your main data mining process will be spawning an extra process for PhantomJS to do its work. Given that Phantom seems to only support the <code>fs</code> module, the expected mechanism for communication between the mining service and phantom would appear to be file storage. (This implies that progress monitoring is, effectively, impossible.)</p>
<p>At any rate, I have replicated <code>fs</code> in SharpKit, adding just enough of the methods in order to get the ball rolling. Annoyingly enough, I&rsquo;ve declared the <code>require()</code> instruction in a rather strange fashion:</p>
<pre class="brush: csharp; title: ; notranslate">
[JsType(JsMode.Prototype, Export=false, Name = &quot;require&quot;)]
public static class Require
{
  [JsMethod(Name=&quot;require&quot;, Global = true)]
  public static JsObject Module(string moduleName)
  {
    return null;
  }
}
</pre>
<p>There&rsquo;s probably a better way out there, as this approach requires me to use the <code>As&lt;&gt;()</code> method again to get the right module type. Ah well.</p>
<pre class="brush: csharp; title: ; notranslate">
// not very pretty
var fs = Require.Module(&quot;fs&quot;).As&lt;FileSystem&gt;();
</pre>
<p>Given that PhantomJS uses Qt, Python and who knows what else, it&rsquo;s hardly surprising that its file system API doesn&rsquo;t like standard Windows paths such as <code>c:\somewhere.txt</code>. Not a big deal, really, because we can just write to the current directory, read off the data by our web minder, and then delete the file when we&rsquo;re done. The file name would typically be provided as a <em>parameter</em> to the <code>phantomjs.exe</code> process (we get the parameters as a collection, remember?).</p>
<h3>It&rsquo;s All Gone Pear-Shaped</h3>
<p>Having verified that the file system calls work (somewhat), I&rsquo;ve decided to jump in and rewrite one of my WatiN-driven workflows using this new PhantomJS framework. That&rsquo;s when I hit a couple of fairly serious problems:</p>
<ul>
<li>
<p>First of all, Phantom refused to work over SSL. It took some searching to figure out that, in the latest dynamic release, the authors simply forgot to include one of the required DLLs. Luckily, that was easy to fix.</p>
</li>
<li>
<p>The next annoying thing I discovered is that doing something wrongly within Phantom basically causes your program to either hang or exit without any explanation. <strong>There is no debugging</strong> as far as I can see, which makes tracking things down impossible (compare with WatiN, where debugging is sensible).</p>
</li>
<li>
<p>The jQuery API turned out to be insufficient for the purposes of data mining. That&rsquo;s when I realized where the business value of WatiN is&nbsp;&ndash; the ability to write something like <code>browser.Forms[0].TextField(t =&gt; t.Name.StartsWith("test"))</code> is what makes WatiN a lot more usable. True, you can try to get the same result with jQuery selectors, but those typically cause <strong>silent failure</strong> and are not statically checked the wame way WatiN-based LINQ expressions are.</p>
</li>
</ul>
<p>That last bullet point is the killer, as far as I can tell. Essentially, what this means is that if I want to have a good LINQ-driven selection mechanism, I have to write my own APIs on top of jQuery to give me the collections in the format I want. Furthermore, were I to do this (and this is a fairly substantial task), there would still be a problem debugging into these collections as they are iterated and processed.</p>
<p>Well, it sure was an interesting idea. Let&rsquo;s hope there is more where that came from. Meanwhile, if you want the source code, you can <a href="https://gist.github.com/1423002" title="https://gist.github.com/1423002">get it here</a>. ▪</p>
]]></content:encoded>
			<wfw:commentRss>http://devtalk.net/dotnet/web-mining-phantomjs-sharpkit/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>A brief note on GPU programming</title>
		<link>http://devtalk.net/dotnet/brief-note-on-gpu-programming/</link>
		<comments>http://devtalk.net/dotnet/brief-note-on-gpu-programming/#comments</comments>
		<pubDate>Fri, 22 Jul 2011 21:21:44 +0000</pubDate>
		<dc:creator>Dmitri Nesteruk</dc:creator>
				<category><![CDATA[DotNet]]></category>

		<guid isPermaLink="false">http://devtalk.net/?p=185</guid>
		<description><![CDATA[A couple of years ago, I once &#8216;came up&#8217; with the idea of performing calculations faster on a graphics card. Of course, as soon as I went to the computer, it turned out that the field of GPGPU (general-purpose computation on GPUs) already existed and I hadn&#8217;t really discovered anything. Still, it was a curious [...]]]></description>
			<content:encoded><![CDATA[<p>A couple of years ago, I once &lsquo;came up&rsquo; with the idea of performing calculations faster on a graphics card. Of course, as soon as I went to the computer, it turned out that the field of GPGPU (general-purpose computation on GPUs) already existed and I hadn&rsquo;t really discovered anything. Still, it was a curious revelation.</p>
<p>At the time, in order to get a speed-up from a graphics card, you basically had to &lsquo;deceive&rsquo; it by presenting your data as a texture and letting a pixel shader &ndash; a programmable GPU component capable of determinining a pixel&rsquo;s color &ndash; perform mathematical computations on your behalf.</p>
<p>Luckily, things have improved since then. GPU manufacturers realized that their processors were far more efficient than general-purpose CPUs, albeit for a <em>certain category of tasks</em>. Of course, given that this category featured any kind of math where large quantities of data could be processed in parallel, the universal applicability has given rise to things such as CUDA. CUDA is NVidia&rsquo;s unified API for programming the graphics card &ndash; not just for graphics but also for any kind of computation where the presence of a few hundred processor cores is of benefit.</p>
<h3>Complexity abound</h3>
<p>GPU computation does come with a set of limitations. It&rsquo;s predominantly geared towards <code>float</code> data types, with <code>double</code> support appearing only now. Some of its numeric behavior is different from equivalent standards on the CPU &ndash; different in very obscure, hard-to-understand ways. But what&rsquo;s most important is that the design of an algorithm for a GPU is entirely different than for a CPU.</p>
<p>In a way, GPUs exemplify the &lsquo;multicore crisis&rsquo; &ndash; the problem where developers are in their majority not smart enough to &lsquo;grok&rsquo; the new paradigm. This is precisely why Microsoft brought out its TPL (Task Parallel Library) API &ndash; because TPL is the absolute simplification of both task-level and data-level parallelism. Suddenly, if we want to run several methods in parallel, we use <code>Parallel.Invoke</code>, if we want to process a loop in parallel, we use <code>Parallel.For/ForEach</code>, and should we perform any kind of heavy data processing, we simply inject the <code>AsParallel()</code> call into our LINQ method chain and that&rsquo;s it &ndash; our algorithm is <em>supposedly</em> made parallel, almost by magic.</p>
<p>With GPUs, none of these tricks work. The developer doesn&rsquo;t have the option of not knowing the architecture of the GPUs they code for. Also, the combined complexity of blocks, threads, streams &mdash; together with the problems related to marshalling data to &amp; from the GPU &ndash; make the task of writing GPU-specific algorithms so much harder.</p>
<h3>Simplifying things (somewhat)</h3>
<p>Now, just to be clear, there is <em>no</em> antidote to the complexity of parallel algorithms. We have some &lsquo;hacks&rsquo; for the CPU which lets us not worry about frameworks such as OpenMP, PPL/Intel TBB, but it is unlikely that a &lsquo;classical&rsquo; (CPU-specific) implementation of an algorithm can suddenly be translated to the GPU automatically. There&rsquo;s no escaping the GPU specifics.</p>
<p>On the other hand, there <em>are</em> frameworks such as Microsoft Accelerator or GPU.NET which make things more manageable by hiding the really gory bits from us. For example, GPU.NET lets you define kernels right in .Net code, which automatically takes care of the problem of marshalling data to/from the GPU by hand. Also, being a managed solution, it automatically benefits from having the support of tools such as ReSharper.</p>
<p>Personally, I see this persistent trend of <em>trascoding</em> certain languages (or their compiled form) into another representation. And if IL can be transcoded into a stream of NVidia-specific instructions, who&rsquo;s to say it cannot be transcoded to, e.g., a netlist for synthesis on an FPGA?</p>
]]></content:encoded>
			<wfw:commentRss>http://devtalk.net/dotnet/brief-note-on-gpu-programming/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>RESTful Web Conversations 3</title>
		<link>http://devtalk.net/dotnet/restful-web-conversations-3/</link>
		<comments>http://devtalk.net/dotnet/restful-web-conversations-3/#comments</comments>
		<pubDate>Thu, 26 May 2011 15:35:41 +0000</pubDate>
		<dc:creator>Dmitri Nesteruk</dc:creator>
				<category><![CDATA[DotNet]]></category>
		<category><![CDATA[rest]]></category>
		<category><![CDATA[wcf]]></category>
		<category><![CDATA[web api]]></category>
		<category><![CDATA[websharper]]></category>

		<guid isPermaLink="false">http://devtalk.net/?p=179</guid>
		<description><![CDATA[This is the final post in the series concerning my RESTful conversation framework /part 1/part 2/. This post describes my cleaning up of some loose ends in the system, and finally shows a production sample. If you cannot be bothered to read all of this, just go and see the demo, available at http://nesteruk.org/talk. Source [...]]]></description>
			<content:encoded><![CDATA[<p>This is the final post in the series concerning my RESTful conversation framework /<a href="http://devtalk.net/csharp/restful-web-conversations/" title="http://devtalk.net/csharp/restful-web-conversations/">part 1</a>/<a href="http://devtalk.net/fsharp/restful-web-conversations-2/" title="http://devtalk.net/fsharp/restful-web-conversations-2/">part 2</a>/. This post describes my cleaning up of some loose ends in the system, and finally shows a production sample.</p>
<p>If you cannot be bothered to read all of this, just go and see the demo, available at <a href="http://nesteruk.org/talk">http://nesteruk.org/talk</a>. Source code is, as always, available at <a href="https://bitbucket.org/nesteruk/restfulwebconversation">https://bitbucket.org/nesteruk/restfulwebconversation</a>.</p>
<h3>Back to JSONP</h3>
<p>So the first things I wanted to do is to get JSONP back. As it turns out, the Web API still doesn&rsquo;t have this built-in (why, I wonder?), but the <a href="http://wcf.codeplex.com" title="http://wcf.codeplex.com">project site</a> was helpful &ndash; I found <a href="http://wcf.codeplex.com/discussions/250545" title="http://wcf.codeplex.com/discussions/250545">this post</a>, which basically gave me an implementation of JSONP on a silver platter. <em>Or not.</em></p>
<p>In actual fact, things went wrong from the start because</p>
<ul>
<li>
<p>There&rsquo;s still no support for the header which accepts <em>any</em> media type (i.e., <code>Accept: */*</code>)</p>
</li>
<li>
<p>The default formatters &lsquo;take over&rsquo; whatever you do</p>
</li>
<li>
<p>The implementation I found on the CodePlex site is just plain wrong</p>
</li>
</ul>
<p>So let&rsquo;s deal with the above issues. It&rsquo;s clear that we have to define our own <code>JsonpFormatter</code>. But how do we handle the <code>*/*</code> header? The answer is that we specify a media range mapping such that an unspecified range maps onto <code>application/json</code>:</p>
<pre class="brush: csharp; title: ; notranslate">
public class JsonPFormatter : MediaTypeFormatter
{
  public JsonPFormatter()
  {
    this.AddMediaRangeMapping(new MediaTypeHeaderValue(&quot;*/*&quot;), new MediaTypeHeaderValue(&quot;application/json&quot;));
    SupportedMediaTypes.Add(new MediaTypeHeaderValue(&quot;application/json&quot;));
  }
  ...
}
</pre>
<p>The above basically ensures that:</p>
<ul>
<li>
<p>A request with <code>*/*</code> in the header will return JSON</p>
</li>
<li>
<p>A request with an accept value other than <code>*/*</code> or <code>application/json</code> will be processed by another formatter. This ensures that XML support is still there.</p>
</li>
</ul>
<p>Now, let&rsquo;s finish out the formatter. First, we determine whther we can read or write a particular type. Since there is only one type in our app, this is somewhat easy:</p>
<pre class="brush: csharp; title: ; notranslate">
protected override bool OnCanWriteType(Type type)
{
  return type == typeof (ConversationItemDTO);
}
protected override bool OnCanReadType(Type type)
{
  return false;
}
</pre>
<p>Now, we need to take care of the method that <em>writes</em> the resulting data to the stream. The original CodePlex sample made the mistake in that it assumed that a JSON request always had to be JSONP, but that&rsquo;s not correct. So, I changed it to selectively return JSON or padded JSON depending on whether the callback parameter was provided:</p>
<pre class="brush: csharp; title: ; notranslate">
...
var callback = queryString[&quot;callback&quot;];
if (callback != null)
  sb.Append(callback + &quot;(&quot; + jsonString + &quot;);&quot;);
else
  sb.Append(jsonString);
byte[] buffer = Encoding.UTF8.GetBytes(sb.ToString());
stream.Write(buffer, 0, buffer.Length);
</pre>
<p>So, given this, I hit a final problem: how to make sure that my formatter takes precedence over the default JSON formatter? After some searching, I found the solution: inserting it as the first formatter in the configuration:</p>
<pre class="brush: csharp; title: ; notranslate">
// jsonp formatter comes first!
config.Configuration.OperationHandlerFactory.Formatters.Insert(
  0, container.Resolve&lt;JsonPFormatter&gt;());
</pre>
<p>And that&rsquo;s it &ndash; I got my JSONP support! Consumption can now go back to normal:</p>
<pre class="brush: fsharp; title: ; notranslate">
JQuery.GetJSON(serverUrl + id + &quot;?enabledOptions=&quot; + !enabledOptions + &quot;&amp;callback=?&quot;,
  ...
</pre>
<h3>Better conversation definitions</h3>
<p>Admittedly, the current way of defining conversation lines with its enable/disable list is a bit archaic. Actually, it <em>does</em> serve its intended function, it&rsquo;s just not very convenient &ndash; especially if I want to define a rather large conversation without using a graphical DSL.</p>
<p>My approach to this problem was to create a factory class that would take care of routine problems and would keep track of all the items for subsequent insertion. What I ended up is the following:</p>
<pre class="brush: csharp; title: ; notranslate">
public class ConversationFactory
{
  private int id = 1;
  public List&lt;ConversationItem&gt; Items;
  public ConversationFactory()
  {
    Items = new List&lt;ConversationItem&gt;();
  }
  public ConversationItem Create(Party party, string speech, List&lt;int&gt; disableList = null, 
    params ConversationItem[] enabledItems)
  {
    var ci = new ConversationItem();
    ci.Id = id++;
    ci.Speech = speech;
    ci.PartyId = (int) party;
    ci.DisableList = disableList ?? new List&lt;int&gt;();
    ci.DisableList.Add(ci.Id);
    ci.EnableList = new List&lt;int&gt;();
    foreach (var i in enabledItems)
      ci.EnableList.Add(i.Id);
    Items.Add(ci);
    return ci;
  }
}
</pre>
<p>The above code generates the IDs and takes care of some of the obvious things, such as conversation items disabling themselves as soon as they are fired. Populating the site is then as easy as the following code:</p>
<pre class="brush: csharp; title: ; notranslate">
var f = new ConversationFactory();
f.Create(Party.Server, &quot;Welcome to my site! Feel free to ask questions.&quot;, null,
  f.Create(Party.Client, &quot;Tell me about your professional life&quot;),
  f.Create(Party.Client, &quot;Tell me about your personal life&quot;),
  f.Create(Party.Client, &quot;Tell me about how this site works&quot;),
  f.Create(Party.Client, &quot;Actually, I think I better go now&quot;)
  );
repository.Upsert(f.Items);
</pre>
<p>The above set-up totally rocks for creating a <em>simple</em> state machine. Why? Because statements can be nested, meaning I can alternate server/client dialogue items for as long as I like.</p>
<h3>Deployment</h3>
<p>Deployment for the WCF REST service follows the typical protocols: you make a web application in the folder where the service is located, ensure it&rsquo;s .Net 4, and specify wildcard mappings (yes, poor me, I&rsquo;m on IIS 6). Subsequently updating the service is easy &ndash; you can just do &lsquo;xcopy&rsquo; deployment via FTP. No restarts are necessary because generally IIS is smart enough to pick up changes on its own.</p>
<p>The great thing is that deployment of the client side is a breeze because it&rsquo;s pure HTML. So you just copy over the files and everything works, though I&rsquo;ve had to specify the default document (it&rsquo;s an <code>.html</code> file, after all). Since the client side is totally detached, you can actually use your browser to debug those JSONP calls (I found an error this way), as opposed to the tedium of having to go to the server via RDP or something. This is in sharp contrast with the WCF service itself.</p>
<h3>Conclusion &amp; Futures</h3>
<p>This series of posts has demonstrated some ways of working with a pure client-side web app that uses a REST backend. It is by no means complete, since I neglected to cover some of the important issues such as caching. However, it is my hope that this project serves as a reference application that one can build upon. ▪</p>
]]></content:encoded>
			<wfw:commentRss>http://devtalk.net/dotnet/restful-web-conversations-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>RESTful Web Conversations 2</title>
		<link>http://devtalk.net/fsharp/restful-web-conversations-2/</link>
		<comments>http://devtalk.net/fsharp/restful-web-conversations-2/#comments</comments>
		<pubDate>Fri, 13 May 2011 14:55:49 +0000</pubDate>
		<dc:creator>Dmitri Nesteruk</dc:creator>
				<category><![CDATA[FSharp]]></category>
		<category><![CDATA[jsonp]]></category>
		<category><![CDATA[rest]]></category>
		<category><![CDATA[wcf]]></category>
		<category><![CDATA[websharper]]></category>

		<guid isPermaLink="false">http://devtalk.net/?p=170</guid>
		<description><![CDATA[Having created a back-end using the new WCF Web API, I decided it was time to create a front-end and, not being a particular fan of JavaScript, went with WebSharper instead. Here&#8217;s a brief experience report. Source code is, as always, available here: https://bitbucket.org/nesteruk/restfulwebconversation JSONP, again&#8230; Before doing anything, I mirrored the conversation data structure [...]]]></description>
			<content:encoded><![CDATA[<p>Having created a back-end using the new WCF Web API, I decided it was time to create a front-end and, not being a particular fan of JavaScript, went with WebSharper instead. Here&rsquo;s a brief experience report.</p>
<p>Source code is, as always, available here: <a href="https://bitbucket.org/nesteruk/restfulwebconversation">https://bitbucket.org/nesteruk/restfulwebconversation</a></p>
<h3>JSONP, again&hellip;</h3>
<p>Before doing anything, I mirrored the conversation data structure using the F# record type:</p>
<pre class="brush: fsharp; title: ; notranslate">
type ConversationItem = {
  Id : int
  PartyId : int
  Speech : string
  Responses : ConversationItem list
  }
</pre>
<p>So to try things out, I wrote a very simple function that simply did a <code>GET</code> of some data from the server:</p>
<pre class="brush: fsharp; title: ; notranslate">
[&lt;JavaScript&gt;]
let serverUrl = &quot;http://localhost:51688/&quot;
[&lt;JavaScript&gt;]
let Update(id:string) =
  JQuery.GetJSON(serverUrl + id,
    fun (result:ConversationItem, msg) -&gt;
      JQuery.Of(&quot;#serverItem&quot;).Text(msg)) |&gt; ignore
</pre>
<p>This raised the all too familiar error message:</p>
<pre class="brush: csharp; title: ; notranslate">
XMLHttpRequest cannot load http://localhost:51688/. Origin null is not allowed by Access-Control-Allow-Origin.
</pre>
<p>For a moment I thought that maybe I&rsquo;ve gone crazy and I&rsquo;d have to implement JSONP support manually like I did for WCF REST (in a pre-.Net 4 scenario), so I tried to adjust the query string to <em>explicitly</em> invoke the callback:</p>
<pre class="brush: fsharp; title: ; notranslate">
[&lt;JavaScript&gt;]
let Update(id:string) =
  JQuery.GetJSON(serverUrl + id + &quot;?callback=?&quot;,
    fun (result:ConversationItem, msg) -&gt;
      JQuery.Of(&quot;#serverItem&quot;).Text(msg)) |&gt; ignore
</pre>
<p>Now that I got this working, I hit another problem: the result I got from the service was XML! Now I <em>know</em> that JSON works fine with the new API, but when I opened Fiddler, what I saw is that the header had an <code>Accept: */*</code> instead! As it turns out, with JSONP you cannot even customize it, which means that my nice, resource-oriented server must be <em>forced</em> to return JSON by default.</p>
<p>While waiting for clarification on how to do this (typical fiddling in <code>Web.config</code> didn&rsquo;t help one bit), I turned off Chrome web security and went with a JSON (as opposed to JSONP) approach. I suspect that the lack of JSONP support us due to the nature of the Web API, which isn&rsquo;t ready yet.</p>
<p>(On a side note, I noticed that the entity names of my lists in XML had a wrong name. So using XML would have been impossible anyway without further fiddling the XML serializer.)</p>
<h3>Consuming the Service</h3>
<p>So to start with I create a bare-minimum HTML structure to house my UI:</p>
<pre class="brush: fsharp; title: ; notranslate">
[&lt;JavaScript&gt;]
let Conversation() =
  Div [
    P [Id &quot;serverItem&quot;] -&lt; [Text &quot;Server text here&quot;]
    Div [Id &quot;clientItems&quot;]
    Button [Text &quot;Hello&quot;] |&gt;! OnClick (fun x y -&gt; Update(&quot;&quot;))
  ]
</pre>
<p>And I subsequently try to project each piece of data onto the UI using the following piece of code:</p>
<pre class="brush: fsharp; title: ; notranslate">
[&lt;JavaScript&gt;]
let Update(id:string) =
  JQuery.GetJSON(serverUrl + id,
    fun (item:ConversationItem, msg) -&gt;
      // what the server says
      JQuery.Of(&quot;#serverItem&quot;).Text(item.Speech).Ignore
      // what the client can respond with
      // hateoas but without atom:link
      if not (List.isEmpty item.Responses) then
        let listItems = 
          item.Responses |&gt; List.map (fun r -&gt; LI [ A [HRef &quot;#&quot;] -&lt; [Text r.Speech]])
        let wholeList = OL [] -&lt; listItems
        JQuery.Of(&quot;#clientItems&quot;).Empty().Append(wholeList.Dom).Ignore
    ) |&gt; ignore
</pre>
<p>Now, we can turn to the next and most painful part of our site &ndash; the handling of links.</p>
<h3>Links and HATEOAS</h3>
<p>Okay, so what <em>should</em> those links contain? Common sense dictates that the URL they point to should contain the link to the conversation item that has just been pressed, e.g., <code>http://mysite.com/123</code> where 123 is the ID of what I just said.</p>
<p>That&rsquo;s all well and good but gets us nowhere, because we&rsquo;re not interested in postbacks (it&rsquo;s pure AJAX) and because even if we get the data at the URL, we&rsquo;d still need to render it. Anyways, we can agree that we need the link, if only to do another AJAX call.</p>
<p>The moral of the story here is that you don&rsquo;t get nice permalinks, you cannot add a bookmark to a conversation point (largely because the conversation has a context which we cannot preserve), but you <em>can</em> define AJAX-based link handling actions <em>en masse</em>. Essentially, we make the <code>Update()</code> function recursive and then wire up each link to call it:</p>
<pre class="brush: fsharp; title: ; notranslate">
let listItems = 
  item.Responses |&gt; List.map 
    (fun r -&gt; LI [ A [HRef &quot;#&quot;] -&lt; [Text r.Speech]]
              |&gt;! OnClick(fun x y -&gt; Update(r.Id.ToString()))
    )
</pre>
<p>This works, but what about the progressive enabling/disabling of links? Our <code>Empty()</code> JavaScript call wipes all existing links but they must, presumably, be stored somewhere on the client in order to be useful.</p>
<p>If you remember my previous post, we agreed to make the list of enabled options a string such as <code>1,2,3</code>. The server then repopulates the set of links each time we get a response, taking into account the links we already have. Now, how can we put together this string without creating any extra data structures? The answer is, of course, to use jQuery.</p>
<p>The agreement here is to assign each link its ID</p>
<pre class="brush: fsharp; title: ; notranslate">
fun r -&gt; LI [ A [HRef &quot;#&quot;; Id (r.Id.ToString())] -&lt; [Text r.Speech]]
...
</pre>
<p>and subsequently iterate over all of them, creating the query string. Now, due to F#&lsquo;s statelessness, the code below uses ref cells and is a bit ugly:</p>
<pre class="brush: fsharp; title: ; notranslate">
let enabledOptions = ref &quot;&quot;
 
JQuery.Of(&quot;#clientItems&quot;).Find(&quot;a&quot;).Each(
  fun (e:Dom.Element) -&gt; let id = JQuery.Of(e).Attr(&quot;id&quot;)
                         enabledOptions := !enabledOptions + id + &quot;,&quot;).Ignore
</pre>
<p>And then, of course, we pass <code>enabledOptions</code> as a parameter to the URL. Note that this could be considered bad by some REST purists used to clean URLs. However, this is something I can live with.</p>
<h3>Conclusion</h3>
<p>As you can see, I am not posting the full example online yet. There are a few reasons why I am not doing this:</p>
<ul>
<li>
<p>I am still not sure what the situation with JSONP is right now. I hope that I&rsquo;m just missing something in the new API, as opposed to having to implement this myself. Same goes for having JSON as the <em>default</em> output type for the service.</p>
</li>
<li>
<p>I am still looking for a way to define conversations more efficiently. The main problem right now is that the way I&rsquo;m doing it with enable/disable list causes it to be a &rsquo;poor man&rsquo;s HSM&rsquo; instead of a proper one. Perhaps the <a href="http://nuget.org/List/Packages/Stateless" title="http://nuget.org/List/Packages/Stateless">Stateless</a> library could be of some use here.</p>
</li>
<li>
<p>Another problem I&rsquo;m having is that, due to the fact that HTML is generated via JavaScript, I can&rsquo;t see a place where I can initialize the content of my HTML <em>after</em> it has been returned. This is mainly due to my lack of knowledge of WebSharper, but I hope to figure it out before I post the next part.</p>
</li>
</ul>
<p>Overall though, I&rsquo;m happy to say that I didn&rsquo;t write a single line of JavaScript to get it all working. To be continued!</p>
]]></content:encoded>
			<wfw:commentRss>http://devtalk.net/fsharp/restful-web-conversations-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>RESTful Web Conversations</title>
		<link>http://devtalk.net/csharp/restful-web-conversations/</link>
		<comments>http://devtalk.net/csharp/restful-web-conversations/#comments</comments>
		<pubDate>Tue, 03 May 2011 18:09:52 +0000</pubDate>
		<dc:creator>Dmitri Nesteruk</dc:creator>
				<category><![CDATA[CSharp]]></category>
		<category><![CDATA[rest]]></category>
		<category><![CDATA[wcf]]></category>
		<category><![CDATA[web api]]></category>

		<guid isPermaLink="false">http://devtalk.net/?p=161</guid>
		<description><![CDATA[My previous post concerning a conversation system in WebSharper involved a purely client-side model, where all conversation information was stored on the client in the form of JavaScript declaration. In this post, I want to move the conversation data to a RESTful back-end which will use the new WCF Web API (courtesy of @gblock and [...]]]></description>
			<content:encoded><![CDATA[<p>My <a href="http://devtalk.net/fsharp/conversation-engine-websharper/" title="http://devtalk.net/fsharp/conversation-engine-websharper/">previous post</a> concerning a conversation system in WebSharper involved a purely client-side model, where all conversation information was stored on the client in the form of JavaScript declaration. In this post, I want to move the conversation data to a RESTful back-end which will use the <a href="http://wcf.codeplex.com/" title="http://wcf.codeplex.com/">new WCF Web API</a> (courtesy of <a href="http://twitter.com/gblock" title="gblock's posts on twitter">@gblock</a> and friends) and will follow the <a href="http://en.wikipedia.org/wiki/HATEOAS" title="http://en.wikipedia.org/wiki/HATEOAS">HATEOAS</a> paradigm.</p>
<p>The source code for this project is available online at <a href="http://bitbucket.org/nesteruk/RestfulWebConversation">http://bitbucket.org/nesteruk/RestfulWebConversation</a></p>
<h3>The Nature of Conversations</h3>
<p>Conversations are <em>great</em> for trying out RESTful services. They are, at the same time, stateless (the conversation structure doesn&rsquo;t change often on the server), and stateful in the sense that the user&rsquo;s <em>position</em> along a conversation line must be preserved somewhere. As a result, conversations are uniquely positioned to test out the new REST Web API that Microsoft is coming out with.</p>
<p>So let&rsquo;s get started. The first thing I&rsquo;m going to do is once again define the conversation entities for persisting them in a database. In this case, there is only one entity: a <code>ConversationItem</code>.</p>
<pre class="brush: csharp; title: ; notranslate">
public class ConversationItem
{
  [BsonId] public int Id;
  public int PartyId;
  public string Speech;
  public List&lt;int&gt; EnableList;
  public List&lt;int&gt; DisableList;
}
</pre>
<p>Now, we can easily create a <code>ConversationRepository</code> class that would implement the typically CRUD operations &ndash; I typically like to lump <code>Create</code> and <code>Update</code> into a single operation though.</p>
<p>With this structure defined, let&rsquo;s talk about the way we are going to serve the data via RESTful endpoints. My first attempt at creating this service was somewhat confusing: I couldn&rsquo;t figure out what project template we&rsquo;re meant to use together with the new WCF Web API. I mean, the libraries themselves are on NuGet, but what type of project should it be? And how should it be configured?</p>
<p>Not having any particular idea, I took the WCF REST for .Net 4 template off the gallery, but ended upthrowing away most of what got generated and adding in the WebAPI stuff.</p>
<h3>DTOs</h3>
<p>In order to get the data accross the wire, I added a pair of DTO classes. The first is a <code>ConversationItemDTO</code>, which is essentially a DTO (data transfer object) for the conversation items. It mirrors the original entity completely, but has a different type of &lsquo;noise&rsquo; attached to it &ndash; first, it uses properties instead of fields; second, it has prescriptive attributes that determine its layout should XML serialization be used (I care mainly about JSON, but still&hellip;).</p>
<pre class="brush: csharp; title: ; notranslate">
[XmlRoot(&quot;ConversationItem&quot;)]
public class ConversationItemDTO
{
  [XmlAttribute(&quot;Id&quot;)]
  public int Id { get; set; }
  [XmlAttribute(&quot;PartyId&quot;)]
  public int PartyId { get; set; }
  [XmlAttribute(&quot;Speech&quot;)]
  public string Speech { get; set; }
  [XmlAttribute(&quot;EnableList&quot;)]
  public List&lt;int&gt; EnableList { get; set; }
  [XmlAttribute(&quot;DisableList&quot;)]
  public List&lt;int&gt; DisableList { get; set; }
}
</pre>
<p>The second DTO entity is a list aggregation of the above:</p>
<pre class="brush: csharp; title: ; notranslate">
[XmlRoot(&quot;ConversationItems&quot;)]
public class ConversationItemList
{
  [XmlArray]
  public List&lt;ConversationItemDTO&gt; Items { get; set; }
}
</pre>
<p>Finally, I have added an entity-to-DTO extension method for the conversation items. It seems fitting that the transposition method is contained in neither the original entity nor the DTO, though we ould have easily stuck it into the DTO if need be:</p>
<pre class="brush: csharp; title: ; notranslate">
// booooring :)
public static ConversationItemDTO ToDTO(this ConversationItem item)
{
  var dto = new ConversationItemDTO();
  dto.Id = item.Id;
  dto.Speech = item.Speech;
  dto.PartyId = item.PartyId;
  dto.EnableList = item.EnableList;
  dto.DisableList = item.DisableList;
  return dto;
}
</pre>
<p>This may seem a bit trivial, but that&rsquo;s because the HATEOAS paradigm is not in play yet. In fact, we are currently <em>cheating</em> by returning enable/disable lists instead of telling the client which options are valid at a particular location. Let&rsquo;s try to fix this.</p>
<h3>HATEOAS</h3>
<p>Okay, so before we get to returning <em>links</em> to available conversation options (that&rsquo;s what HATEOAS is all about, in this case), let&rsquo;s do a few simple things. The first would be to return a set of initial conversation items on the default URL. Just like the RestCart sample, I have defined a resource class, which is a typical WCF service contract, but with a lot less noise:</p>
<pre class="brush: csharp; title: ; notranslate">
[ServiceContract]
public class ConversationResource
{
  private readonly IConversationRepository repository;
  public ConversationResource(IConversationRepository repository)
  {
    this.repository = repository;
  }
  [WebGet(UriTemplate = &quot;&quot;)]
  public ConversationItemDTO GetInitial()
  {
    var result = repository.FindOne(1).ToDTO();
    result.Responses = repository.FindMany(new[] {2}).Select(r =&gt; r.ToDTO()).ToList();
    return result;
  }
}
</pre>
<p>This is really as good as it gets &ndash; no huge attribute stacks, no complicated <code>Web.config</code> manipulation. This is all that is needed to publish an entity. In the above <code>Get()</code> method, you can see that I&rsquo;m simply using the original Mongo repository, taking the first 4 items, converting them to DTOs and returning them wrapped in a list.</p>
<p>So far so good, but no hypermedia links in sight. Let&rsquo;s try to add a few. In fact, we are going to <em>get rid of</em> the enabled/disabled lists and instead return the items relevant at this particular point. In other words, our DTO becomes something like the following:</p>
<pre class="brush: csharp; title: ; notranslate">
[XmlRoot(&quot;ConversationItem&quot;)]
public class ConversationItemDTO
{
  [XmlAttribute(&quot;Id&quot;)]
  public int Id { get; set; }
  [XmlAttribute(&quot;PartyId&quot;)]
  public int PartyId { get; set; }
  [XmlAttribute(&quot;Speech&quot;)]
  public string Speech { get; set; }
  [XmlArray(&quot;Responses&quot;)]
  public List&lt;ConversationItemDTO&gt; Responses { get; set; }
}
</pre>
<p>That&rsquo;s better, but still confusing: how do we incorporate <em>client state</em> (i.e., where the client is in the conversation thread) into this model? The answer is that we can simply pass an array of currently enabled items in a <code>GET</code> request. (Note: I&rsquo;m serious about this being a <code>GET</code> and not a <code>POST</code>. We are not changing server data, just providing some hints for the server to compute the next set of links.)</p>
<p>With that in mind, we define the following stub for a method getting a conversation item:</p>
<pre class="brush: csharp; title: ; notranslate">
[WebGet(UriTemplate = &quot;{id}?enabledOptions={enabledOptions}&quot;)]
public ConversationItemDTO Get(int id, string enabledOptions = null)
{
  ...
}
</pre>
<p>You&rsquo;ll notice that there is a <code>string</code> argument with a comma-separated list of currently enabled items. The <code>id</code> here refers to the conversation item the user chose. We start by checking that it&rsquo;s valid and returning a 404 if it&rsquo;s not:</p>
<pre class="brush: csharp; title: ; notranslate">
// get the chosen option from repository
var userResponse = repository.FindOne(id);
if (userResponse == null)
{
  var ctx = WebOperationContext.Current;
  ctx.OutgoingResponse.SetStatusAsNotFound(
    string.Format(&quot;Could not find a client response with id={0}&quot;, id));
  return null;
}
</pre>
<p>Next, we build a <code>HashSet&lt;int&gt;</code> with the relevant items and exclude the disabled ones:</p>
<pre class="brush: csharp; title: ; notranslate">
// compute the set of relevant items
var items = new HashSet&lt;int&gt;();
if (enabledOptions != null)
  items.UnionWith(enabledOptions.Split(',').Select(s =&gt; int.Parse(s)));
items.UnionWith(userResponse.EnableList);
items.ExceptWith(userResponse.DisableList);
</pre>
<p>Finally, we get the <em>actual</em> items from the server, split them into the server and client parts, and return the result.</p>
<pre class="brush: csharp; title: ; notranslate">
// get all the items
var all = repository.FindMany(items).OrderBy(i =&gt; i.Id);
var grouped = all.GroupBy(i =&gt; i.PartyId)
  .ToDictionary(k =&gt; k.Key, v =&gt; v.ToList());
      
// get server and client items
var server = grouped[(int) Party.Server].First();
const int clientKey = (int) Party.Client;
var client = grouped.ContainsKey(clientKey) ? grouped[clientKey] 
                                            : EmptyList&lt;ConversationItem&gt;.Instance;
// now - finally - build the response
var result = server.ToDTO();
result.Responses = client.Select(i =&gt; i.ToDTO()).ToList();
return result;
</pre>
<p>That&rsquo;s all there is to it! Let&rsquo;s discuss how it all works.</p>
<h3>Using the Service</h3>
<p>I will show the client-side usage of the service in the next post: probably when I get back to a computer that has a working WebSharper license on it. Meanwhile, let me explain how the service works.</p>
<p>When someone goes to <strong>http://myservice.com/</strong>, the service returns a representation of the default conversation items for the server (the outer <code>ConversationItem</code>) and the set of possible responses. This is completely in line with HATEOAS in the sense that we return a set of links to things that can be done.</p>
<p>When someone goes to <strong>http://myservice.com/X</strong>, we assume that the client chose conversation option with <code>id=X</code>. We calculate the server response and the next set of client responses and return them to the consumer.</p>
<p>When someone goes to <strong>http://myservice.com/X?enabledOptions=A,B,C</strong>, the server also includes the currently enabled items A, B and C in the set of possible responses. This is necessary because we are typically too lazy to include the <em>full set</em> of responses each time. Instead, we do things incrementally. I have not tested this with client-side jQuery invocation, but there should be no problem.</p>
<h3>Conclusion</h3>
<p>Building RESTful services is now <em>somewhat</em> easier with the Web API, but there are still several fundamental issues which are, overall, not addressed:</p>
<ul>
<li>
<p>First, there are no helpers for projecting data collections. The creation of DTOs is tedious, and I&rsquo;ve spent a few hours testing the service to make sure that things are returned correctly.</p>
</li>
<li>
<p>It is entirely unclear how to handle errors. Should we throw exceptions? Or just return 404 in the output stream and return <code>null</code>? It would be great to have some prescriptive guidance and a few mechanisms to ensure that if I&rsquo;m projecting data, all the typical problems (such as accessing an entity with a non-existent ID) are handled without my involvment.</p>
</li>
<li>
<p>The WCF Web API has no built-in mechanism for creating state machines and wiring them into a HATEOAS paradigm. It would be great to have this &ndash; possibly in the WF4 updates that have come out in the .Net Framework 4 platform update.</p>
</li>
</ul>
<p>Overall, though, I&rsquo;m happy with the results I got from the Web API, and am also very happy with the way NuGet let me add a pile of references to the projects. In the next post, I&rsquo;ll build a single-page-AJAX front end and will probably hit an altogether different set of issues.</p>
<p>That&rsquo;s all for now. Comments welcome!</p>
]]></content:encoded>
			<wfw:commentRss>http://devtalk.net/csharp/restful-web-conversations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Introducing MathSharp &#8211; Convert Math to Code</title>
		<link>http://devtalk.net/dotnet/introducing-mathsharp/</link>
		<comments>http://devtalk.net/dotnet/introducing-mathsharp/#comments</comments>
		<pubDate>Sun, 17 Apr 2011 15:18:05 +0000</pubDate>
		<dc:creator>Dmitri Nesteruk</dc:creator>
				<category><![CDATA[DotNet]]></category>

		<guid isPermaLink="false">http://devtalk.net/?p=155</guid>
		<description><![CDATA[Have you ever wished that you could take mathematical formulae and automatically turn them into code? A few years ago, I worked in a project where we had a huge number of such formulae to implement, and I always kept wishing for a better tool that would save me from boredom of manual translation. That [...]]]></description>
			<content:encoded><![CDATA[<p>Have you ever wished that you could take mathematical formulae and automatically turn them into code? A few years ago, I worked in a project where we had a huge number of such formulae to implement, and I always kept wishing for a better tool that would save me from boredom of manual translation.</p>
<p>That was then, but now I&#8217;m happy to announce <strong>ActiveMesa MathSharp</strong>: a tool to do just that! With MathSharp, you can take an equation from any MathML-producing application (such as Microsoft Word 2007/2010, MathType or Maple) and quickly convert it to C# or F# code. Here&#8217;s a video that demonstrates the way MathSharp works:</p>
<p><iframe src="http://player.vimeo.com/video/22251021?title=0&amp;byline=0&amp;portrait=0&amp;color=9dca68" width="640" height="480" frameborder="0"></iframe></p>
<p>To learn more, visit the MathSharp page at <a class="external" href="http://activemesa.com/mathsharp" title="http://activemesa.com/mathsharp">http://activemesa.com/mathsharp</a></p>
]]></content:encoded>
			<wfw:commentRss>http://devtalk.net/dotnet/introducing-mathsharp/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Building a conversation engine with WebSharper</title>
		<link>http://devtalk.net/fsharp/conversation-engine-websharper/</link>
		<comments>http://devtalk.net/fsharp/conversation-engine-websharper/#comments</comments>
		<pubDate>Thu, 10 Feb 2011 08:51:57 +0000</pubDate>
		<dc:creator>Dmitri Nesteruk</dc:creator>
				<category><![CDATA[FSharp]]></category>
		<category><![CDATA[websharper]]></category>

		<guid isPermaLink="false">http://devtalk.net/?p=149</guid>
		<description><![CDATA[Anyone who has ever played a role-playing game (yes, I admit: I did play CRPGs once) is familiar with scripted dialogues. You enter a dialogue with someone, they say something, you get a list of choices, and the conversation goes on until it ends, with your actions determining what happens next. Now, what if you [...]]]></description>
			<content:encoded><![CDATA[<p>Anyone who has ever played a role-playing game (yes, I admit: I did play CRPGs once) is familiar with scripted dialogues. You enter a dialogue with someone, they say something, you get a list of choices, and the conversation goes on until it ends, with your actions determining what happens next. Now, what if you could implement the same kind of interaction pattern using JavaScript?</p>
<p>Well, admittedly, writing the pure JavaScript by hand is probably less than pleasant. However, seeing how I dabble in <a href="http://www.websharper.com" title="http://www.websharper.com">WebSharper</a> from time to time, I figured this would be a good opportunity to try something out. In this case, I decided to build a conversation system that would let us define the conversation graph<sup><a href="#Reference1" title="I&rsquo;m stretching things a little when calling a scripted conversation a graph. It&rsquo;s really more like a state machine. The kind of conversations you have in games have much greater complexity, and they also have a measure of reentrancy and context-keeping that a simple graph doesn&rsquo;t support." name="BackReference1">1</a></sup> and the site user can then iteract with a site in the form of a scripted dialogue.</p>
<p><a href="http://nesteruk.org/projects/conversation" title="http://nesteruk.org/projects/conversation">Click here to see the demo</a></p>
<h3>Defining Conversations</h3>
<p>A conversation is a sequence of speeches (can&rsquo;t think of a better word) that people deliver in turn. Each conversation has the text that someone says, but it also involves a couple of other things. Take a look at the definition of a conversation item:</p>
<pre class="brush: fsharp; title: ; notranslate">
type ConversationItem = {
  mutable Enabled : bool
  Id : int
  PartyId : int
  Speech : string
  EnableList : int list
  DisableList : int list
  }
</pre>
<p>Each item has an <code>Id</code> used to uniquely identify it among others. It also has an <code>Enabled</code> field used to indicate whether this conversation item is relevant at the current point in time. Then there&rsquo;s the <code>PartyId</code> indicating who the conversation item belongs to (in our case &ndash; either the Client or the Server).</p>
<p>And then there are the two lists &ndash; <code>EnableList</code> and <code>DisableList</code>. These hold list of <code>Id</code>s of items that get enabled or disabled when this conversation item is &lsquo;fired&rsquo; (said). Since people don&rsquo;t typically repeat themselves, the item is itself disabled right after it is used<sup><a href="#Reference2" title="It&rsquo;s worth noting that in a real-world interaction scenario, conversation choices affect a lot more than whether some item is enabled or disabled. However, given that we are working with a virtually object-oriented representation, it&rsquo;s fairly easy to attach any sort of context-oriented action to particular conversation items. I leave this as an exercise for the reader." name="BackReference2">2</a></sup>.</p>
<p>With this model in mind, let&rsquo;s try building the conversation engine.</p>
<h3>Conversation Engine</h3>
<p>The conversation engine consists of the conversation graph &ndash; a graph of all possible conversation items and the relationships between them &ndash; and a number of utility functions for getting the client and server responses or &lsquo;speeches&rsquo;.</p>
<p>Let&rsquo;s look at the graph itself. The graph is simply a list of all possible conversation items:</p>
<pre class="brush: fsharp; title: ; notranslate">
[&lt;JavaScript&gt;]
let private ConversationGraph = [
    {server with Id = 1; Enabled = true; Speech = &quot;Welcome to a demo of Conversations. Please select one of the options below&quot;}
    {client with Id = 2; Enabled = true; Speech = &quot;Tell me what this is all about.&quot;; EnableList=[6]; DisableList = [1]}
    {client with Id = 3; Enabled = true; Speech = &quot;Tell me about the technology used to implement this&quot;; EnableList=[7]; DisableList=[1]}
    {client with Id = 4; Enabled = true; Speech = &quot;Actually... I'm not that interested&quot;; EnableList = [5]; DisableList = [1;2;3]}
    {server with Id = 5; Speech = &quot;Well, okay, fair enough&quot;; DisableList = [2;3;4]}
    {server with Id = 6; Speech = &quot;Well, essentially, it's all about using F# to generate awesome JavaScript&quot;}
    {server with Id = 7; Speech = &quot;This demo uses pure HTML and JavaScript courtesy of WebSharper and F#&quot;}
  ]
</pre>
<p>The graph is built upon two prototypes called <code>client</code> and <code>server</code>. These simply set the correct <code>PartyId</code> fields and also a number of useful defaults.</p>
<pre class="brush: fsharp; title: ; notranslate">
[&lt;JavaScript&gt;]
let private ServerId = 1
[&lt;JavaScript&gt;]
let private ClientId = 2;
 
[&lt;JavaScript&gt;]
let private server = { Enabled = false; Id = ServerId; Speech = &quot;&quot;; PartyId = 1; EnableList = []; DisableList = [] }
  
[&lt;JavaScript&gt;]
let private client = { server with PartyId = ClientId; }
</pre>
<p>With the conversation graph fully defined, we can write methods to provide the server and client items relevant at a particular point in the conversation:</p>
<pre class="brush: fsharp; title: ; notranslate">
[&lt;JavaScript&gt;]
let ServerSpeech() =
  ConversationGraph 
  |&gt; List.find (fun f -&gt; f.PartyId = ServerId &amp;&amp; f.Enabled)
 
[&lt;JavaScript&gt;]
let ClientSpeech() =
  ConversationGraph
  |&gt; List.filter (fun f -&gt; f.PartyId = ClientId &amp;&amp; f.Enabled)
</pre>
<p>Last but not least, we need a method for when a speech item gets fired. This is where we disable the item just fired, and also apply its enable/disable lists to other items.</p>
<pre class="brush: fsharp; title: ; notranslate">
[&lt;JavaScript&gt;]
let SpeechItemFired id =
  let item = ConversationGraph |&gt; List.find(fun f -&gt; f.Id = id)
  item.Enabled &lt;- false // assume all fired items are not re-used
  // enable and disable all items with this id
  ConversationGraph
  |&gt; List.iter(fun f -&gt; 
    // if contains in the enable list, enable it
    item.EnableList  |&gt; List.iter(fun en -&gt; if en = f.Id then f.Enabled &lt;- true)
    item.DisableList |&gt; List.iter(fun de -&gt; if de = f.Id then f.Enabled &lt;- false)
    )
</pre>
<p>And that concludes the <code>ConversationEngine</code> module in all its simplistic beauty. We now have a pure JS-driven conversation definition, so it&rsquo;s time to make use of it on the page.</p>
<h3>Presenting Conversations</h3>
<p>Let&rsquo;s start with a simple thing &ndash; the conversation layout. For brevity&rsquo;s sake, we&rsquo;ll have two <code>Div</code>s one on top of another.</p>
<pre class="brush: fsharp; title: ; notranslate">
[&lt;JavaScript&gt;]
let Conversation() =
  Div [Attr.Style &quot;width: 700px; height: 450px; border: 1px solid gray&quot;] -&lt; [
    Div [Attr.Style &quot;height: 300px&quot;] -&lt; [
      P [Id &quot;serverSpeech&quot;; ConversationEngine.ServerSpeech().Speech |&gt; Text]
    ]
    Div [Attr.Style &quot;height: 150px&quot;] -&lt; [
      WiredClientSpeech()
    ]
  ]
</pre>
<p>Notice how we&rsquo;re using <code>ServerSpeech()</code> directly, but the client-side part refers to something called <code>WiredClientSpeech()</code>. This is necessary because server speech is simply paragraph text, but client speech is a bunch of links with <code>OnClick()</code> event handlers attached to them.</p>
<p>Here comes a major F# dilemma: links update conversations, but a conversation update forces the replacement of these links (and whatever is holding them). How can we handle this? Well, in F# there&rsquo;s no other way but using <em>mutually recursive functions</em>, which sounds scary, but is actually fairly simple. So, we have a function called <code>WiredClientSpeech()</code> &ndash; let&rsquo;s take a look at the way it&rsquo;s defined:</p>
<pre class="brush: fsharp; title: ; notranslate">
[&lt;JavaScript&gt;] WiredClientSpeech() =
  let stuff =
    ConversationEngine.ClientSpeech()
    |&gt; List.map(fun f -&gt;
       let id = f.Id
       LI [ 
         A [HRef &quot;#&quot;] -&lt; [Text f.Speech]
         |&gt;! OnClick(fun x y -&gt; UpdateConversation id |&gt; ignore)
       ] )
  OL [Id &quot;clientSpeech&quot;] -&lt; stuff
</pre>
<p>Okay, so what happens here is we get a list of <code>LI</code> elements which are then fed into an <code>OL</code>, which we also give a specific id. The slight peculiarity of the way the above is defined is due to the fact that you cannot simply place a list of <code>LI</code>s inside an <code>OL</code> &ndash; you will experience <em>type inferencing failure</em>. That&rsquo;s right &ndash; F# isn&rsquo;t perfect! Anyways, it&rsquo;s easily solvable with the handy <code>-&lt;</code> operator, or you could just pipe it via <code>|&gt; OL</code>. Of course, we also needed to provide an <code>Id</code>, thus things are defined the way they are.</p>
<p>In the above, you see a call to <code>UpdateConversation</code> with a cached (to prevent closure mishaps) <code>id</code> parameter. <code>UpdateConversation()</code> is the function that uses the conversation manager and actually puts converation items into the DOM.</p>
<pre class="brush: fsharp; title: ; notranslate">
let rec UpdateConversation id =
  ConversationEngine.SpeechItemFired id
  let srv = ConversationEngine.ServerSpeech()
  JQuery.Of(&quot;#serverSpeech&quot;).Text(srv.Speech) |&gt; ignore
  ConversationEngine.SpeechItemFired srv.Id
  JQuery.Of(&quot;#clientSpeech&quot;).ReplaceWith((WiredClientSpeech() :&gt; Element).Body)
</pre>
<p>So, what&rsquo;s going on here? Well, we tell the conversation engine that a speech item has been fired, we get the server item first and then simply replace paragraph text with the new item. Then, we also inform that a server item has been fired. Finally, we do something tricky &ndash; we replace the <code>#clientSpeech</code> element completely, substituting a <code>Dom.Element</code> that we create synthetically in <code>WiredClientSpeech()</code>. Note that a cast is necessary here because, once again, type inference seeks to mess with us.<sup><a href="#Reference3" title="I must admit that the process of organizing this methods was far from intuitive. I had to try a number of things before I figured out how to externalize everything and get it all to work. Admittedly, the code I got at the end isn&rsquo;t as readable or well-organized as it could be, but this is mainly due to F#&lsquo;s limitations." name="BackReference3">3</a></sup></p>
<h3>Conclusion</h3>
<p>The above problem is something that is very difficult (but doable) in ordinary JavaScript. However, with a little help from WebSharper, we managed to orchestrate the whole conversation process in terms of F#. There are a few caveats though, as always:</p>
<ul>
<li>
<p>The site isn&rsquo;t exactly small due to the JS infrastructure support. A large number of files was dragged in. They&rsquo;re necessary though &ndash; especially when the site is more &lsquo;real&rsquo;, in the sense of communicating to servers via JSON or whatnot.</p>
</li>
<li>
<p>The F#&rarr;JS transformation is very picky. You can easily mess it up and end up crashing the compiler. To be fair, Web# is beta, but it&rsquo;s still important to remember that not everything can be translated to JavaScript.</p>
</li>
<li>
<p>F#&lsquo;s preference for code to be &rsquo;in order&rsquo; is most inconvenient here. Mutually recursive functions are one thing, but I&rsquo;ve also been <em>forced</em> to move the conversation engine into a separate module, because keeping it in the main client module caused JavaScript to be emitted in the wrong order, thus spoiling the party.</p>
</li>
</ul>
<p>Overall, I&rsquo;m happy with my first little foray into the world of HTML sitelets. Now that Web# actually supports all of this, it makes sense to experiment with client-server REST interoperation. I&rsquo;m actually curious as to how Web# can help here, but for the server side there&rsquo;s always WCF REST or OpenRasta and the like.</p>
<p>Please check out the <a href="http://nesteruk.org/projects/conversation" title="http://nesteruk.org/projects/conversation">demo</a>! And stay tuned for more F#/WebSharper goodness!</p>
<h3>Notes</h3>
<ol>
<li><a name="Reference1"></a><a href="#BackReference1" title="Back to text">&uarr;</a> I&rsquo;m stretching things a little when calling a scripted conversation a <em>graph</em>. It&rsquo;s really more like a state machine. The kind of conversations you have in games have much greater complexity, and they also have a measure of reentrancy and context-keeping that a simple graph doesn&rsquo;t support.</li>
<li><a name="Reference2"></a><a href="#BackReference2" title="Back to text">&uarr;</a> It&rsquo;s worth noting that in a real-world interaction scenario, conversation choices affect a lot more than whether some item is enabled or disabled. However, given that we are working with a virtually object-oriented representation, it&rsquo;s fairly easy to attach any sort of context-oriented action to particular conversation items. I leave this as an exercise for the reader.</li>
<li><a name="Reference3"></a><a href="#BackReference3" title="Back to text">&uarr;</a> I must admit that the process of organizing this methods was far from intuitive. I had to try a number of things before I figured out how to externalize everything and get it all to work. Admittedly, the code I got at the end isn&rsquo;t as readable or well-organized as it could be, but this is mainly due to F#&lsquo;s limitations.</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://devtalk.net/fsharp/conversation-engine-websharper/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>A Simple Web Server in F#</title>
		<link>http://devtalk.net/fsharp/simple-web-server/</link>
		<comments>http://devtalk.net/fsharp/simple-web-server/#comments</comments>
		<pubDate>Mon, 17 Jan 2011 20:02:54 +0000</pubDate>
		<dc:creator>Maxim Moiseev</dc:creator>
				<category><![CDATA[FSharp]]></category>

		<guid isPermaLink="false">http://devtalk.net/?p=134</guid>
		<description><![CDATA[Intro Every once in a while we all suffer from the Not Invented Here syndrome. So do I. This time, despite of being able to use either one of available web servers or previously written ASP.NET MVC-like web serving framework, I decided to write my own. My requirements are that the server should serve JSON, [...]]]></description>
			<content:encoded><![CDATA[<h2>Intro</h2>
<p>Every once in a while we all suffer from the <a href="http://en.wikipedia.org/wiki/Not_Invented_Here">Not Invented Here syndrome</a>. So do I. This time, despite of being able to use either one of available web servers or previously written ASP.NET MVC-like web serving framework, I decided to write my own.</p>
<p>My requirements are that the server should serve JSON, provide meaningful URLs, be easy to use (anything that you write is by design easy to use for you), it should be hostable in a simple console app, should <em>not</em> use reflection as ASP.NET MVC does, and it should be written in F#. Because &ldquo;not-written-in-F#&rdquo; is a fundamental flaw of most existing systems I know of.</p>
<h2>Design</h2>
<p>Since this project is going to be a quick and dirty prototype of a future system &ndash; let&rsquo;s use <code>HttpListener</code> as a serving mechanism. It is pretty straightforward and easy to use. Ok. What&rsquo;s next?</p>
<p>Any kind of &lsquo;web serving&rsquo; starts with a URL. Those who tried <a href="http://www.djangoproject.com/">Django</a> already know how URL handling is performed there. For others, here are the basics. There is a single dictionary (I mean something like <code>System.Collections.Generic.IDictionary</code> here) that maps a URL to the function that should handle requests to that URL. I&rsquo;m oversimplifying but that&rsquo;s enough for our purposes. The request handling function should get something in and return back our JSON as a string, which then will be wrapped in a HTTP response and sent back to the user agent. The only question now is what should be passed to the handler function. If we were writing a real web server, it would require us to pass the whole response context into the function, but we want some REST here, therefore the requested URL would be enough. In Django, they use regular expression match groups to obtain arguments for handler functions from the requested URL. Why not do so as well? Let&rsquo;s create a simple URL mapping for clarity.</p>
<pre class="brush: fsharp; title: ; notranslate">
[(&quot;^/hello/([a-zA-Z]+)&quot;, helloNameHandler);]
</pre>
<p>The above means that when a URL matching the pattern is requested, we should take the URL substring containing a person&rsquo;s name and pass it to the handler function <code>helloNameHandler</code>. Let&rsquo;s not forget about the URL query string. We&rsquo;ll parse it as well and pass to the handling function as a list of <code>(string * string)</code> pairs.</p>
<h2>Implementation</h2>
<p>Enough said, lets start implementing. First of all we&rsquo;ll describe all the types already discussed:</p>
<pre class="brush: fsharp; title: ; notranslate">
type RequestData =
  // first list is url substrings, second list is query string pairs
  | RequestData of string list * (string * string) list
 
type ResponseData =
  | Json of string
 
type HandlerFunction = (RequestData -&gt; ResponseData)
type DispatchEntry = (string * HandlerFunction)
type DispatchEntryEx = (Regex * HandlerFunction)
</pre>
<p>Since we&rsquo;re using regular expressions for our patterns we might have some speed gain if they are compiled before usage, hence the <code>DispatchEntryEx</code> type.</p>
<pre class="brush: fsharp; title: ; notranslate">
let makeDispatcher (pattern, handler) =
  let fullPattern = sprintf &quot;%s/?.*&quot; pattern
  let rx = Regex(fullPattern, RegexOptions.Compiled)
  (rx, handler)
let prepareDispatchers (table:DispatchEntry list) : DispatchEntryEx list =
  List.map makeDispatcher table
module Query =
  let decode : string -&gt; string =
    HttpUtility.UrlDecode
  
  let processParams (s:string) =
    if String.IsNullOrEmpty(s) then
      []
    else
      let s' = s.TrimStart([|'?'|])
      s'.Split([|'&amp;'|])
      |&gt; Array.map (fun pair -&gt; pair.Split([|'='|]))
      |&gt; Array.map (fun  [|h;t|] -&gt; (h, t))
      |&gt; Array.toList
  
  let processPath (rx:Regex) (s:string) =
    rx.Match(s).Groups.Cast&lt;Group&gt;()
    |&gt; Seq.skip(1) // skipping the overall group
    |&gt; Seq.map (fun g -&gt; g.Value)
    |&gt; Seq.toList
</pre>
<p>Nothing interesting here: we are creating a dispatch table with compiled regular expressions and two functions to provide parameters to our handler functions. Now we are ready to implement a dispatch function, but first we should define its type.</p>
<p>The <code>HttpListener</code> class provides a <code>GetContext()</code> method of type <code>HttpListenerContext</code> that in turn has the <code>Request</code> and <code>Response</code> properties. Processing a request means reading from <code>context.Request</code> and writing something back into <code>context.Response</code> instance. That said, our dispatch function should have the following type: <code>DispatchEntryEx list -&gt; HttpListenerRequest -&gt; HttpListenerResponse -&gt; unit</code>. It does not return any value, because the actual result is written directly to the response as a side effect (We could purify the approach if we wanted to, but not this time).</p>
<pre class="brush: fsharp; title: ; notranslate">
let dispatch (ds:DispatchEntryEx list) request response =
  let (!!) = Query.decode
  let absPath = !! request.Url.AbsolutePath
  let queryString = !! request.Url.Query
  
  printfn &quot;(II) '%s' requested...&quot; &lt;| !! request.RawUrl
  
  let (rx, handler) =
    ds |&gt; Seq.find (fun (r, _) -&gt; r.IsMatch(request.Url.AbsolutePath))
  
  let path = Query.processPath rx request.Url.AbsolutePath
  let query = Query.processParams queryString
  
  let resultBytes =
    match handler (RequestData (path, query)) with
    | ResponseData.Json json -&gt;
      let callback = Query.get &quot;callback&quot; &quot;callback&quot; query
      json |&gt; Encoding.UTF8.GetBytes
  
  response.ContentLength64 &lt;- int64 resultBytes.Length
  response.OutputStream.Write(resultBytes, 0, resultBytes.Length)
</pre>
<p>Yet again, nothing complex. The function does exactly what it supposed to. First it searches for the matching handler in dispatch table, then parses the request URL path and query string, after that applies handler function and finally writes everything back to response stream.</p>
<p>The last thing we should implement before we could test our server, is server initialization function.</p>
<pre class="brush: fsharp; title: ; notranslate">
let start (prefix:string) (table:DispatchEntry list) =
  let listener = new HttpListener()
  listener.Prefixes.Add(prefix)
  listener.Start()
  
  let tableEx = prepareDispatchers table
  
  let requestProcessor =
    let processContext (ctx:HttpListenerContext) = async {
      dispatch tableEx ctx.Request ctx.Response
      ctx.Response.Close()
    }
    async {
      while true do
      try
        let ctx = listener.GetContext()
        processContext ctx |&gt; Async.Start
      with
      | ex -&gt; printfn &quot;(EE): %s&quot; ex.Message
    }
  
  requestProcessor
  |&gt; Async.StartAsTask
  |&gt; ignore
  
  {new IDisposable with
  member this.Dispose () =
  listener.Close()
  }
</pre>
<p>Please note the usage of async and Async.Start with the processContext function. Without it the whole server will be able to only process requests one after another. HttpListener.GetContext blocks execution until the request is received, right after that we start a new processing thread with Async.Start, which returns immediately and the while loop continues to the next call of GetContext leaving context processing to a separate thread.</p>
<p>Another thing to note is the return type of the start function. It returns IDisposable instance which will stop the listener when disposed, so we don&rsquo;t have to expose the fact that we use HttpListener to the user still having some control over listeners lifetime.</p>
<h2>Some improvements</h2>
<p>The code above seems to work (at least it should), but then we realize that JSON is not the only thing we&rsquo;d like to be able to serve. We would also need some binary data such as images. To support this we have to modify the return type of our handler function. Thanks to discriminated unions, it won&rsquo;t require too many changes in the code.</p>
<p>There are actually only two places in the whole code that are subjected to change in order to support serving images. First &ndash; the <code>ResponseData</code> type:</p>
<pre class="brush: fsharp; title: ; notranslate">
type ResponseData =
| Binary of byte[]
| Json of string
</pre>
<p>And second, the dispatch function:</p>
<pre class="brush: fsharp; title: ; notranslate">
let dispatch (ds:DispatchEntryEx list) request response =
//...
let resultBytes =
match handler (RequestData (path, query)) with
| ResponseData.Json json -&gt; json |&gt; Encoding.UTF8.GetBytes
| ResponseData.Binary bytes -&gt; bytes
// ...
</pre>
<p>That&rsquo;s all! We simply added support for a new case to all places where ResponseData is used. No need to change already developed handler functions.</p>
<h2>Possible further improvements</h2>
<p>Lets imagine that once this &ldquo;web server&rdquo; evolves into something more complex and we would need to support &ldquo;areas&rdquo; of site, where each area will process URLs separately so that dispatch table will become unbearably long and uncomfortable to use. F# discriminated unions can help us here as well, simply change the HandlerFunction into something like type <code>UrlHandler = | HandlerFunction of (...) | SiteArea of (...)</code> etc. Django also has this feature but here we don&rsquo;t use dynamic types.</p>
<p>It is also possible to use some templating libraries (or view engines) to render responses from handler functions. This will require just another case in ResponseData type and a slight change dispatch function.</p>
<h2>Conclusion</h2>
<p>In this article we developed a dead simple yet working web serving solution that can be used to prototype URL base REST services to be hosted in your application. It has not been properly tested and surely has limitations, but the development process showed that it is possible and pretty easy to implement a web serving solution in a .NET environment without using reflection or dynamic typing.</p>
]]></content:encoded>
			<wfw:commentRss>http://devtalk.net/fsharp/simple-web-server/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>JSON Processing in F#</title>
		<link>http://devtalk.net/fsharp/json-processing-in-f/</link>
		<comments>http://devtalk.net/fsharp/json-processing-in-f/#comments</comments>
		<pubDate>Tue, 11 Jan 2011 16:25:12 +0000</pubDate>
		<dc:creator>Maxim Moiseev</dc:creator>
				<category><![CDATA[FSharp]]></category>

		<guid isPermaLink="false">http://devtalk.net/?p=121</guid>
		<description><![CDATA[Intro The F# programming language is really fun to work with. It lets you improve your code almost infinitely, not only in terms of performance but also readability. Having finished reading through McConnell&#8217;s Code Complete I&#8217;ve decided to add some declarativeness to JSON processing code I developed for my little pet project Linq2vk. And since [...]]]></description>
			<content:encoded><![CDATA[<h3>Intro</h3>
<p>The F# programming language is really fun to work with. It lets you improve your code almost infinitely, not only in terms of performance but also readability. Having finished reading through McConnell&rsquo;s <a title="Code Complete" href="http://cc2e.com/" target="_blank">Code Complete</a> I&rsquo;ve decided to add some declarativeness to JSON processing code I developed for my little pet project <a href="http://bitbucket.org/moiseev/linq2vk">Linq2vk</a>. And since JSON is ubiquitous these days, I hope the technique described below might be of use to others as well.</p>
<h3>Data</h3>
<p>It is common for all modern online services to provide a public API with JSON as an option of data representation format and all the data we get in response from those services is either a huge JavaScript object or an array. Let me leave objects for further investigations and concentrate on arrays like the following one:</p>
<pre class="brush: fsharp; title: ; notranslate">
[123, &quot;Maxim&quot;, &quot;Moiseev&quot;,  &quot;http://bitbucket.org/moiseev&quot;]
</pre>
<p>This is an array (or list if you will) of simple objects, of which we are sure that it contains an integer for an Id and then three string values for first name, last name and homepage URL respectively. We are not going to actually parse JSON and represent it as a .NET list of tokens, it is better to use a great Json.NET library for that task. Our target is writing a function of type <code>JToken[] -&gt; Person</code>, where <code>JToken</code> is a list of JSON tokens provided by Json.NET and <code>Person</code> is a simple user defined .NET class. In other words, we are going to deserialize JSON array into an instance of a .NET class.</p>
<h3>Initial approach (naïve)</h3>
<p>There are (as always) several ways of achieving this. The simplest one, which I have used until now is as follows (for simplicity I won&rsquo;t define the <code>Person</code> class here, using a tuple instead):</p>
<pre class="brush: fsharp; title: ; notranslate">
let createPerson (ts: JToken[]) =
    let id = ts.[0] |&gt; int
    let name = ts.[1] |&gt; string
    let lastName = ts.[2] |&gt; string
    let url = ts.[3] |&gt; string
    (id, name, lastName, url)
</pre>
<p>Note that <code>int</code> and <code>string</code> here are type conversion functions, so we can use any other converter like for example this one:</p>
<pre class="brush: fsharp; title: ; notranslate">
let intBool (token:JToken) =
    0 &lt;&gt; (token |&gt; int)
</pre>
<p>This approach works perfectly until, say, the URL becomes optional so that the source JavaScript list can sometimes contain 4 tokens and sometimes only 3.</p>
<pre class="brush: fsharp; title: ; notranslate">
let createPerson (ts: JToken[]) =
    let id = ts.[0] |&gt; int
    let name = ts.[1] |&gt; string
    let lastName = ts.[2] |&gt; string
    let url =
        if ts.Length &gt; 3 then
            ts.[3] |&gt; string
        else
            String.empty
    (id, name, lastName, url)
</pre>
<p>Still, this works but looks rather ugly. Thanks to the <code>if</code> statement inside the almost declarative code. Let&rsquo;s try to avoid <code>if</code>s.</p>
<pre class="brush: fsharp; title: ; notranslate">
let optional&lt;'T&gt; (tokens:JToken[]) (index:int) convert =
    if index &lt; tokens.Length then
        convert tokens.[index]
    else
        Unchecked.defaultof&lt;'T&gt;
</pre>
<p>This optional function lets us process our list of JTokens like this:</p>
<pre class="brush: fsharp; title: ; notranslate">
let createPerson (ts: JToken[]) =
    let id = ts.[0] |&gt; int
    let name = ts.[1] |&gt; string
    let lastName = ts.[2] |&gt; string
    let url = optional&lt;string&gt; 3 string
    (id, name, lastName, url)
</pre>
<p>Much better now, but still field processing code does not look unified: normal fields are accessed directly while optional one works through a separate function, conversion function in former case is called as a part of pipe but is passed as a parameter in the latter. Still not good enough.</p>
<h3>Better approach</h3>
<p>Here comes the idea to use all the knowledge from multiple infinitely long and smart articles about monads and parser combinators. Luckily F# gives us its <a href="http://msdn.microsoft.com/en-us/library/dd233182.aspx">Computation Expressions</a> feature, which is all about those monads.</p>
<p>Fine. Let&rsquo;s go. We&rsquo;ll start with the definition of our parser type:</p>
<pre class="brush: fsharp; title: ; notranslate">
type JsonArrayParser&lt;'a&gt; =
    JsonArrayParser of (JToken[] -&gt; ('a * JToken[]) list
</pre>
<p>The parser is essentially a function that takes an array of tokens as its input and returns a list of pairs: an object of some type <code>'a</code> and an input array. In case of success, the result is a singleton list, otherwise it is an empty list. (List is used here for simplicity, we could define a discriminated union with two value constructors for either case or use a standard <code>Option&lt;'a&gt;</code> type).</p>
<p>Let&rsquo;s add some auxiliary code:</p>
<pre class="brush: fsharp; title: ; notranslate">
// running our parser
let runParser (JsonArrayParser p) tokens =
    p tokens
exception JsonParserException of string
// getting the parsing result
let getParsingResult = function
    | [] -&gt; raise &lt;| JsonParserException(&quot;Parsing failed&quot;)
    | [(res, _)] -&gt; res
    | _ -&gt; raise &lt;| System.NotSupportedException(&quot;This should not normally happen&quot;)
// and a combinations of these functions
let parse parser tokens =
    runParser parser tokens
        |&gt; getParsingResult
</pre>
<p>It is time now to define the Computation Expression builder:</p>
<pre class="brush: fsharp; title: ; notranslate">
type JsonArrayBuilder() =
    member this.Return(x) =
        JsonArrayParser (fun ts -&gt; [(x, ts)])
    member this.Bind(p, f) =
        JsonArrayParser (fun ts -&gt;
            match runParser p ts with
            | [(r, ts')] -&gt; runParser (f r) ts'
            | _ -&gt; []
        )
let jarr = JsonArrayBuilder()
</pre>
<p>That&rsquo;s all!</p>
<ul>
<li><code>Return</code> &ndash; well&hellip; returns a given value;</li>
<li><code>Bind</code> &ndash; given a parser A creates a new parser B that, depending on the result of A either calls a function to a A&rsquo;s result or returns an empty list as a sign of failure.</li>
</ul>
<p>Frankly speaking, this is not enough. We would also need some simple parsers:</p>
<pre class="brush: fsharp; title: ; notranslate">
let at idx =
    JsonArrayParser (fun ts -&gt;
        if ts.Length &lt;&gt; 0 &amp;amp;&amp;amp; idx &lt; ts.Length then
            [(ts.[idx]), ts]
        else
            []
    )
let tokenAtAs idx converter =
    jarr {
        let! t = at idx
        return (converter t)
    }
let (&lt;@&gt;) converter idx =
    tokenAtAs idx converter
</pre>
<p>Here is how we are now able to write our JSON processing:</p>
<pre class="brush: fsharp; title: ; notranslate">
let createPerson (ts: JToken[]) =
    jarr {
        let! id = int &lt;@&gt; 0
        let! name = string &lt;@&gt; 1
        let! lastName = string &lt;@&gt; 2
        let! url = string &lt;@&gt; 3
        return (id, name, lastName, url)
    }
// simple test
let tokens = JArray.Parse(&quot;[1,2]&quot;) |&gt; Seq.toArray
let me = parse createPerson tokens
</pre>
<p>Finally we are at the point where we started and again we are missing support for optional fields. This should not be a big deal this time however, since every piece of data processing is a parser &ndash; what we need is just another parser, or more precisely a parser combinator (a thing that gets parser as its input and returns a new parser back) that will return a default value if initial parser fails.</p>
<pre class="brush: fsharp; title: ; notranslate">
let parseOrDefault parser defaultValue =
    JsonArrayParser (fun ts -&gt;
        match runParser parser ts with
        | [] -&gt; [(defaultValue, ts)]
        | res -&gt; res
    )
let (&lt;|&gt;) = parseOrDefault
</pre>
<p>Voilà! Support for optionals is implemented:</p>
<pre class="brush: fsharp; title: ; notranslate">
let createPerson (ts:JToken[]) =
    // ...
    let! url = string &lt;@&gt; 3 &lt;|&gt; String.Empty
    // ...
</pre>
<p>Please note the fact that thanks to operator priority we don&rsquo;t need to use parentheses.</p>
<h3>A little more fun</h3>
<p>Lets imagine that sometimes parsing of a field depends on some external condition, for example, if id field is greater than 1000 then URL will not be present and we should use some default value instead.</p>
<pre class="brush: fsharp; title: ; notranslate">
let parseOrFail condition parser =
    JsonArrayParser (fun ts -&gt;
        if condition then
            runParser parser ts
        else
            []
    )
let (&lt;?&gt;) = parseOrFail
</pre>
<p>As a result of applying <code>&lt;?&gt;</code> to any parser A we get a new one &ndash; B &ndash; that, depending on a condition, does exactly what A does or returns empty list without even running A.</p>
<pre class="brush: fsharp; title: ; notranslate">
let createPerson (ts: JToken[]) =
    jarr {
        let! id = int &lt;@&gt; 0
        let! name = string &lt;@&gt; 1
        let! lastName = string &lt;@&gt; 2
        let! url = (id &gt; 1000) &lt;?&gt; (string &lt;@&gt; 3) &lt;|&gt; String.Default
        return (id, name, lastName, url)
    }
</pre>
<p>See how using <code>&lt;?&gt;</code> and <code>&lt;|&gt;</code> in the same statement resembles usage of standard ternary operator <code>?:</code>.</p>
<h3>Conclusion</h3>
<p>In the end we have a declarative way of processing JSON tokens and a simple parser framework capable of performing any kind of parsing task that may occur. As a next step we can implement a similar framework for processing JSON objects, with the only difference being the usage of field names instead of indices.</p>
]]></content:encoded>
			<wfw:commentRss>http://devtalk.net/fsharp/json-processing-in-f/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Continuous Testing</title>
		<link>http://devtalk.net/dotnet/continuous-testing/</link>
		<comments>http://devtalk.net/dotnet/continuous-testing/#comments</comments>
		<pubDate>Sat, 27 Nov 2010 08:20:27 +0000</pubDate>
		<dc:creator>Dmitri Nesteruk</dc:creator>
				<category><![CDATA[DotNet]]></category>

		<guid isPermaLink="false">http://devtalk.net/?p=113</guid>
		<description><![CDATA[Most people are used to the idea of continuous integration environments running tests. However, I often find myself wanting to have the tests run all the time. Such a practice is called Continuous Testing, and in the .Net space we currently don&#8217;t have a solution that allows this out-of-the-box. However, there is a small lifehack [...]]]></description>
			<content:encoded><![CDATA[<p>Most people are used to the idea of continuous integration environments running tests. However, I often find myself wanting to have the tests run all the time. Such a practice is called Continuous Testing, and in the .Net space we currently don&rsquo;t have a solution that allows this out-of-the-box.</p>
<p>However, there is a small lifehack you can employ that will get you there (to some extent) provided you buy into the idea of using multiple computers for development. Why multiple computers? Well, the assumption is that some stuff needs to run &lsquo;elsewhere&rsquo; to prevent interference with normal operation of the machine you&rsquo;re developing on.</p>
<h3>The Solution</h3>
<p>So here&rsquo;s how I do it. Let&rsquo;s say I have a solution that I want to test <em>continuously</em>, i.e. I want the tests rebuilt and run so frequently that I always get that &lsquo;dashboard&rsquo; feeling of knowing what&rsquo;s going on. Here&rsquo;s what I do to get this.</p>
<h4>1. Place the source code in synchronized cloud storage</h4>
<p>First, stick your code in cloud storage that syncs with many machines. <a href="http://www.dropbox.com/" title="http://www.dropbox.com/">DropBox</a> is great &ndash; it gives you 2Gb free space, and syncs flawlessly on all your machines.</p>
<h4>2. Optimize test-runner machine performance</h4>
<p>Ensure that the machine that builds the tests and runs them is optimized for just that. Do the lightest possible OS install (e.g., Windows XP). Also, ensure disk access is lightning-fast: I swap to RAM, and you can&rsquo;t really get any better speed than this. Seeing how most developers have 8-16Gb RAM nowadays, allocating a bit of that and fitting a solution in there isn&rsquo;t such a big problem.</p>
<h4>3. Set up the scheduler to build your solution</h4>
<p>Pick a good time interval and set the Windows scheduler to run your build script. This will result in your solution being rebuilt over and over and over. If you followed my advice about keeping the solution in RAM (which, IMHO, <em>totally fits</em> with the cloud storage practice), builds should be somewhat faster than builds from your Raptor or whatnot. Don&rsquo;t forget to fiddle MSBuild to do its multithreading right.</p>
<p>
  <small>Of course, if you have a cloud build solution (IncrediBuild, Electric Cloud, etc.), just use that.</small>
</p>
<h4>4. Set up the test runner to rerun all tests whenever binaries change</h4>
<p>That&rsquo;s the easy part &ndash; get your runner to rerun tests whenever your build artifacts change. That way, you will be constantly informed about how many tests you caused to fail. Naturally, this implies you have a separate screen that shows you tests and allows you to navigate them. To be able to navigate tests on a different computer, just use <a href="http://synergy-foss.org/" title="http://synergy-foss.org/">Synergy</a>.</p>
<h3>Discussion</h3>
<p>The approach I describe above is workable, but it&rsquo;s far from perfect. Here are some issues you will encounter with it.</p>
<p>First, there&rsquo;s no way to avoid rebuilding the whole solution, because currently no software is able to intelligently detect which systems a particular tests affects. And even if you <em>could</em>, it would still not work because, currently, we simply have a blanket call for a single build script <em>whatever happens</em>, whereas to have smarter builds we would need to specify explicitly which test assemblies need to be rebuilt.</p>
<p>Another problem is that a solution like DropBox does not sync with our building, which sometimes causes problems when we try to do a build while the file is being updated. Because we cannot reasonably predict <em>when</em> DropBox will be syncing files, we just have to hope there&rsquo;s no collision. Also, on a side note, I don&rsquo;t recommend sharing DropBox between developers: use ordinary source control for that. If you try to use DropBox as source control, developers will be constantly interrupting each other&rsquo;s work, causing uncompilable code, and so on. In other words: the solution I present currently works best for <em>just one developer</em>.</p>
<p>Finally, if you&rsquo;re into things like coverage, you&rsquo;re somewhat out of luck: you won&rsquo;t be able to view coverage inside on your development machine because coverage calculations have actually happened elsewhere. Of course, nothing prevents you from running code coverage analysis and simply presenting aggregated results, but those are more or less useless without you actually being able to tell which spots your tests seem to miss.</p>
]]></content:encoded>
			<wfw:commentRss>http://devtalk.net/dotnet/continuous-testing/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Dynamic Prototyping</title>
		<link>http://devtalk.net/dotnet/dynamic-prototyping/</link>
		<comments>http://devtalk.net/dotnet/dynamic-prototyping/#comments</comments>
		<pubDate>Tue, 02 Nov 2010 18:00:11 +0000</pubDate>
		<dc:creator>Dmitri Nesteruk</dc:creator>
				<category><![CDATA[DotNet]]></category>

		<guid isPermaLink="false">http://devtalk.net/?p=97</guid>
		<description><![CDATA[In this article I want to talk about something called dynamic prototyping. The idea for this sort of software development approach came into my head as I got frustrated with the never-ending cycle of run-recompile-run that all of us developers are plagued with. So in this post I&#8217;m going to explain the dynamic prototyping concept, [...]]]></description>
			<content:encoded><![CDATA[<p>In this article I want to talk about something called <em>dynamic prototyping</em>. The idea for this sort of software development approach came into my head as I got frustrated with the never-ending cycle of run-recompile-run that all of us developers are plagued with. So in this post I&rsquo;m going to explain the dynamic prototyping concept, discuss its implementation, and demonstrate its use.</p>
<p>Source code (VS10 solution): <a href="https://bitbucket.org/nesteruk/dynamicprototyping">https://bitbucket.org/nesteruk/dynamicprototyping</a></p>
<h3>The Problem</h3>
<p>Software development tasks come in various sizes &ndash; some huge, some tiny. Depending on the functionality you&rsquo;re trying to implement, a task may take a minute or a month. The minute-length tasks are very annoying, because their verification (let&rsquo;s forget about unit tests for a moment) takes longer than the correction itself. They are even more annoying because they break my concentration.</p>
<p>As a result of this dissatisfaction, I started probing around the idea of getting rid of the roundtrip associated with recompile cycles. There are, essentially, just two options on how to handle this.</p>
<p>The first option is to <strong>rely on the DLR</strong> for code segments that need to be modified. However, this approach results in code that&rsquo;s slower, and also gets us to use strange languages that we might not be willing to use in the first place.</p>
<p>The second option, and the one I favor, is <strong>in-process compilation</strong>. Since every .Net program has a capacity to compile other .Net programs <em>from within</em>, it is realistically possible to be able to <em>modify a running program</em> and &ndash; what&rsquo;s more important &ndash; to be able to immediately see the results.</p>
<h3>Basic Infrastructural Concerns</h3>
<p>Since a diligent developer might instantly find several issues with this approach, I&rsquo;m going to address some obvious concerns beforehand.</p>
<h4>Speed</h4>
<p>The first issue to address is: will the program be <em>fundamentally slower</em> because of this? Convention wisdom suggests that it will, quite simply because many of my readers are already thinking of cross-domain marshaling and things like that. In fact, you may have noticed that at no point in time did I suggest unloading assemblies. In actual fact, this is not necessary in order to get things running.</p>
<p>Why not? Well, mainly because nothing prevents you from loading several copies of the same assembly. Sure, you pay the price for that, and some additional fiddling is necessary, but the net result is that</p>
<ul>
<li>The assembly you change is compiled and loaded <em>immediately</em> after you&rsquo;re done with it</li>
<li>The newly loaded assembly is immediately put in use <em>in lieu</em> of the previous version</li>
</ul>
<p>Of course, prudent planning and thought-out development practices are required to guarantee that things don&rsquo;t go wrong when loading the new assembly and using it. We&rsquo;ll talk about those in a while.</p>
<h4>Roundtrip and Shipping</h4>
<p>So the next concern is somewhat multi-faceted. Namely, the following questions come to mind:</p>
<ol>
<li>How do you both package the source code and compile it into the program at the same time?</li>
<li>How do you ensure that in-memory changes actually &lsquo;return&rsquo; back to the program?</li>
<li>How do you ensure that none of this hackery ever gets to the deployed program?</li>
</ol>
<p>Let me address these concerns in turn:</p>
<p>First, the source code is <em>both compiled and embedded</em> in the application. As a result, you already have a binary representation to work with, plus a textual representation that you can also use.</p>
<p>Second, in-memory changes return to the program because, realistically, there&rsquo;s nothing preventing you from serializing some text to <code>..\..\SomeClass.cs</code>. Your breakpoints (hint!) will be broken, of course, but apart from that, everything will function normally.</p>
<p>Third, the proposed infrastructure is <em>intended</em> (not saying that&rsquo;s what you <em>should</em> do) to be Debug-only. Realistically, though, it doesn&rsquo;t have to be &ndash; you can persist the program&rsquo;s source code somewhere. Of course, you can also encrypt it so that it&rsquo;s not human-readable.</p>
<p>Just to expand on that last point, the idea is that source code is typically available in the solution folder, and is not packaged in any way. Rather, it is simply kept where it needs to be &ndash; in the project directory! Now it should (hopefully) be obvious as to why there&rsquo;s no real roundtrip concern &ndash; because we&rsquo;re using the original program files for implementation!</p>
<h4>Architectural Change</h4>
<p>Okay, so you might imagine that a new assembly loaded with the same types as before would require re-wiring every necessary type in the IoC container, and you&rsquo;re certainly correct &ndash; that&rsquo;s how it&rsquo;s done. However, this requirement is in line with best practices anyway, and arguing against it is like saying we shouldn&rsquo;t brush our teeth.</p>
<h3>Implementation</h3>
<p>So, time to write some code. For the purposes of this article, I&rsquo;ll present a <em>minimal</em> implementation of a program which is used for HTML encoding. The idea is that the HTML-encoding part of the program is an <em>editable service</em>, for which we&rsquo;ll create provisions.</p>
<h4>Default Implementation</h4>
<p>Okay, so let&rsquo;s say I have some interface called <code>IConverter</code>:</p>
<pre class="brush: csharp; title: ; notranslate">
public interface IConverter
{
  string Convert(string source);
}
</pre>
<p>And subsequently I create my (minimal) implementation for HTML encoding:</p>
<pre class="brush: csharp; title: ; notranslate">
public class HtmlConverter : IConverter
{
  public string Convert(string source)
  {
    var sb = new StringBuilder(source);
    sb.Replace(&quot;&lt;&quot;, &quot;&amp;lt;&quot;);
    return sb.ToString();
  }
}
</pre>
<p>Now, being a good boy, I inject an <code>IConverter</code> into my main window, and use it to perform the conversion:</p>
<pre class="brush: csharp; title: ; notranslate">
public partial class MainFrame : Form
{
  private IConverter converter;
  public MainFrame(IConverter converter)
  {
    this.converter = converter;
    InitializeComponent();
  }
  private void btnConvert_Click(object sender, EventArgs e)
  {
    tbConverted.Text = converter.Convert(tbSource.Text);
  }
}
</pre>
<p>Finally, I configure the container&hellip;</p>
<pre class="brush: csharp; title: ; notranslate">
static void Main()
{
  var uc = new UnityContainer();
  uc.RegisterType&lt;IConverter, HtmlConverter&gt;();
  
  Application.EnableVisualStyles();
  Application.SetCompatibleTextRenderingDefault(false);
  Application.Run(uc.Resolve&lt;MainFrame&gt;());
}
</pre>
<p>And the application is usable:</p>
<p>
  <img src="http://nesteruk.org/pix/0/96428199-c941-4a7b-9107-e837907dcea7.jpg" alt="" style="border:0"/>
</p>
<h4>Showing the Editor</h4>
<p>Okay, so for the purposes of this exercise, I&rsquo;m going to <em>assume</em> (meaning I&rsquo;m not going to implement this just yet) that everything related to dynamic prototyping is either wrapped in <code>#if DEBUG</code> or has a <code>[Conditional("DEBUG")]</code> in front of this. And with this in mind, we can show the editor.</p>
<p>
  <img src="http://nesteruk.org/pix/0/21cb360e-5f62-4029-ae06-36276ed31142.jpg" alt="" style="border:0"/>
</p>
<p>If you&rsquo;re wondering as to <em>how</em> we figured out which file to open, the answer is simple: typically, you would need to write debug-specific code to actually show this window, so you may as well <em>hardcode</em> the file name. If you want a more industrial-strength solution, feel free to create your own infrastructure with nice little menus letting you specify the type/file to edit.</p>
<h4>Rebuilding the Type</h4>
<p>Okay, so we got an editor that lets us edit a file right from the solution and, naturally, lets us persist it back to where it came from. What next? Oh, we still have to compile and load the thing. Let&rsquo;s deal with compilation first.</p>
<p>Compilation is actually easy, the only caveat being that you need to have a reference to your original executable and any related DLLs. Here&rsquo;s an example:</p>
<pre class="brush: csharp; title: ; notranslate">
public class InProcessCompiler
{
  public object CompileAndInstantiate(string sourceCode)
  {
    var ps = new CompilerParameters {GenerateInMemory = true, GenerateExecutable = false};
    ps.ReferencedAssemblies.Add(&quot;System.Drawing.dll&quot;);
    ps.ReferencedAssemblies.Add(&quot;System.Core.dll&quot;);
    ps.ReferencedAssemblies.Add(&quot;DynamicPrototypingSample.exe&quot;);
    var po = new Dictionary&lt;string, string&gt; {{&quot;CompilerVersion&quot;, &quot;v4.0&quot;}};
    var p = new CSharpCodeProvider(po);
    var results = p.CompileAssemblyFromSource(ps, new[] {sourceCode});
    if (results.Errors.HasErrors)
    {
      var sb = new StringBuilder();
      foreach (var e in results.Errors)
        sb.AppendLine(e.ToString());
      throw new Exception(sb.ToString());
    }
    var ass = results.CompiledAssembly;
    var mainType = ass.GetTypes()[0];
    return Activator.CreateInstance(mainType);
  }
}
</pre>
<p>Plenty of hackery up above &ndash; specifying the explicit DLLs and our EXE to add as references, compiling source code under 4.0 and, last but not least &ndash; creating the first of all available types. Actually, that last point is prudent because in this case I&rsquo;m only interested in compiling one type, and that&rsquo;s the type found first in the generated assembly.</p>
<h4>Final Touches</h4>
<p>Having created an instance of the generated type, we do one simple thing: assign it to the variable. Thus, the whole process becomes as follows:</p>
<ul>
<li>Throw the editing UI</li>
<li>Try compile the type</li>
<li>If successful, save the new instance</li>
<li>Overwrite the <code>.cs</code> file with new source</li>
</ul>
<p>Here&rsquo;s the event handler for our edit button:</p>
<pre class="brush: csharp; title: ; notranslate">
private void btnEditProgram_Click(object sender, EventArgs e)
{
  string path = @&quot;..\..\HtmlConverter.cs&quot;;
  var ce = new CodeEditor(path);
  if (ce.ShowDialog() == DialogResult.OK)
  {
    try
    {
      converter = (IConverter) Compiler.CompileAndInstantiate(ce.SourceCode);
      File.WriteAllText(path, ce.SourceCode, Encoding.UTF8);
    } 
    catch (Exception ex)
    {
      MessageBox.Show(ex.ToString());
    }
  }
}
</pre>
<p>And that&rsquo;s pretty much it!</p>
<h3>Conclusion</h3>
<p>Okay, so as you can see, the implementation is not too complex. Of course, it can be &lsquo;pruned&rsquo; so that the instrumentation of this in-process editing is only available in Debug code. And, by giving more time to the way you handle the compilation and &lsquo;uptake&rsquo; of the code, you can make your prototyping development a little easier.</p>
<p>One useful thing which I do (but cannot show in this article) is using a commercial control for C# editing instead of just editing it as plain text. Apart from that, the set-up I use is pretty much like I described here.</p>
<p>That&#8217;s it! Thanks for reading! If you liked this article, please <a href="http://www.codeproject.com/KB/dotnet/dynamic-prototyping.aspx">vote for it</a> on CodeProject.</p>
]]></content:encoded>
			<wfw:commentRss>http://devtalk.net/dotnet/dynamic-prototyping/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Async, Await and C# vNext</title>
		<link>http://devtalk.net/csharp/async-await-and-c-vnext/</link>
		<comments>http://devtalk.net/csharp/async-await-and-c-vnext/#comments</comments>
		<pubDate>Sun, 31 Oct 2010 10:40:30 +0000</pubDate>
		<dc:creator>Dmitri Nesteruk</dc:creator>
				<category><![CDATA[CSharp]]></category>

		<guid isPermaLink="false">http://devtalk.net/?p=89</guid>
		<description><![CDATA[It would be somewhat naïve not to discuss the new stuff we&#8217;ve been told about at the PDC, so I figure it&#8217;s a good time to discuss the Async CTP, specifically, but also it&#8217;s another opportunity to speculate on the subject of C# vNext. What Was Before we got continuations in the Async CTP (download [...]]]></description>
			<content:encoded><![CDATA[<p>It would be somewhat naïve not to discuss the new stuff we&rsquo;ve been told about at the PDC, so I figure it&rsquo;s a good time to discuss the Async CTP, specifically, but also it&rsquo;s another opportunity to speculate on the subject of C# vNext.</p>
<h3>What Was</h3>
<p>Before we got continuations in the <a href="http://www.microsoft.com/downloads/en/details.aspx?FamilyID=18712f38-fcd2-4e9f-9028-8373dc5732b2&#038;displaylang=en" title="http://www.microsoft.com/downloads/en/details.aspx?FamilyID=18712f38-fcd2-4e9f-9028-8373dc5732b2&#038;displaylang=en">Async CTP</a> (download it now if you haven&rsquo;t &ndash; it&rsquo;s a non-breaking incremental update), barring doing our own <code>BeginXxx/EndXxx</code>-related management we had two legitimate and <em>somewhat</em> understandable ways of doing continuations.</p>
<p>The first option was to use F# async workflows. The idea itself is rather primitive &ndash; an F# workflow is simply a named scope within which the behavior of certain operators &ndash; such as <code>let!</code> or <code>return!</code> is <em>redefined</em> to do something related specifically to that workflow. In the case of F#, we had a mechanism for defining our own <code>Begin</code> and <code>End</code> pairs&hellip;</p>
<pre class="brush: fsharp; title: ; notranslate">
type WebRequest with
  member x.GetResponseAsync() =
    Async.BuildPrimitive(x.BeginGetResponse, x.EndGetResponse)
</pre>
<p>&hellip;and subsequently within an async workflow we could use the <code>let!</code> and <code>return!</code> operators to wait for an operation to complete.</p>
<pre class="brush: fsharp; title: ; notranslate">
let private DownloadPage(url:string) =
  async {
    try
      let r = WebRequest.Create(url)
      let! resp = r.GetResponseAsync() // wait for the result
      use stream = resp.GetResponseStream()
      use reader = new StreamReader(stream)
      let html = reader.ReadToEnd()
      use fs = new FileStream(@&quot;c:\temp\file.htm&quot;, FileMode.Create,
                              FileAccess.Write, FileShare.None, 1024, true);
      let bytes = Encoding.UTF8.GetBytes(html);
      do! fs.AsyncWrite(bytes, 0, bytes.Length) // wait while everything is written
    with
      | :? WebException -&gt; ()
  }
 
Async.RunSynchronously(DownloadPage(&quot;http://devtalk.net&quot;))
</pre>
<p>The second option for managing callbacks was given to us by Jeffrey Richet&rsquo;s <code>AsyncEnumerator</code> (part of the <a href="http://Wintellect.com/PowerThreading.aspx" title="http://Wintellect.com/PowerThreading.aspx">PowerThreading </a>library). The trick here is to use iterators and the <code>yield</code> keyword to &lsquo;step out&rsquo; of a method, thereby instrumenting an artificial continuation. This option, while innovative, does have its shortcomings, such as an inability to work within try-catch blocks.</p>
<pre class="brush: csharp; title: ; notranslate">
public IEnumerator&lt;int&gt; DownloadPage(string url, AsyncEnumerator ae)
{
  var wr = WebRequest.Create(url);
  wr.BeginGetResponse(ae.End(), null);
  yield return 1;
  var resp = wr.EndGetResponse(ae.DequeueAsyncResult());
  var stream = resp.GetResponseStream();
  var reader = new StreamReader(stream);
  string html = reader.ReadToEnd();
  using (var fs = new FileStream(@&quot;c:\temp\file.htm&quot;, FileMode.Create,
                      FileAccess.Write, FileShare.None, 1024, true))
  {
    var bytes = Encoding.UTF8.GetBytes(html);
    fs.BeginWrite(bytes, 0, bytes.Length, ae.End(), null);
    yield return 1;
    fs.EndWrite(ae.DequeueAsyncResult());
  }
}
</pre>
<p>In fact, from what we heard on the PDC (and beforehand) it was Jeffrey&rsquo;s consulting that helped Microsoft come up with what we now got as Async CTP.</p>
<h3>What Is</h3>
<p>So, we now have support for continuations in C# and VB, though the mechanisms are different. In actual fact, everything is painfully easy.</p>
<p>First of all, we got an ability to &ldquo;await&rdquo; something, and that&rsquo;s what the new <code>await</code> keyword is for. As a parameter, it takes a <code>Task</code>, and simply waits for the task (beneath it is a <code>TaskAwaiter</code> &ndash; just generate a dependency diagram to explore this stuff). The real upside here is that through the <code>Task</code>-related infrastructure we can manage cancelations and exceptions better. And, of course, we&rsquo;re already used to tasks since they&rsquo;re part of TPL.</p>
<p>Second, we can now do async calls not via Begin-End pairs, but by simply marking the method as <code>async</code> and <code>await</code>ing it. This saves us from <code>IAsyncResult</code>-related headaches. Now, all that is required to make an asynchronous method is to use the <code>async</code> keyword and change its return type to <code>Task</code> (more on that later).</p>
<p>By the way, the <code>async</code> and <code>await</code> keywords are intertwined &ndash; if a method uses <code>await</code>, then it <em>must</em> be marked as <code>async</code>.</p>
<p>Okay, so let&rsquo;s look at a &lsquo;live&rsquo; example with the same old scenario &ndash; downloading a webpage and saving it to a local file.</p>
<pre class="brush: csharp; title: ; notranslate">
public static async Task DownloadInformation(int id)
{
  Contract.Requires(id &gt;= 0);
  
  string filename = @&quot;c:\temp\somesite.com\&quot; + id + &quot;.htm&quot;;
  if (File.Exists(filename))
    return;
  var ct = new CancellationToken();
  var r = new Reporter(id);
  string data = await new WebClient().DownloadStringTaskAsync(
    new Uri(@&quot;http://somesite.com/&quot; + id), ct, r);
  
  using (var fs = new FileStream(filename, FileMode.CreateNew, FileAccess.Write, FileShare.Write))
  {
    var bytes = Encoding.Default.GetBytes(data);
    await fs.WriteAsync(bytes, 0, bytes.Length);
    fs.Close();
  }
}
</pre>
<p>The first paradox of perception is that even though our method doesn&rsquo;t return anything (can you see a <code>return</code> anywhere?), its return type is not <code>void</code> but rather <code>Task</code>. This is the Async CTP trick, though I&rsquo;m not sure how adequate it is (c&rsquo;mon guys, you&rsquo;re breaking the natural match between a method&rsquo;s return type that that which is actually returned). At any rate, the idea is that the method which uses <code>await</code> must be marked as <code>async</code> and must also have a return type of <code>Task</code> (if it is <code>void</code>) and, predictably enough, <code>Task&lt;T&gt;</code> if the method returns a <code>T</code>.</p>
<p>
  <small>Unfortunately, <code>out</code>/<code>ref</code> parameters are not supported, which will cause a small outcry because, as you all know, working with tuples in C# is not exactly easy.</small>
</p>
<p>So&hellip; in addition to the typical methods, the Async CTP adds a <code>DownloadStringTaskAsync()</code> method to the <code>WebClient</code>, which is a pretty good hint as to what will happen there (though it can be <em>confusing</em> because <code>WebClient</code> already has a <code>DownloadStringAsync()</code> method). In addition, for example, the <code>FileStream</code> class gets a <code>WriteAsync()</code> method (where is the <code>Task</code> bit?), though my opinion is that it would be a lot more convenient if they added (hey, I&rsquo;m sure they will) a <code>File.WriteAllTextAsync()</code> so I don&rsquo;t have to bother with all the extra initialization. At any rate, both methods are usable with <code>await</code>.</p>
<p>Oh, speaking of which, one useful thing which I liked is the ability to use an <code>IProgress&lt;&gt;</code> implementation as a parameter to <code>DownloadStringTaskAsync()</code>. We often need to track the completion of a file download, and having this built-in is just great. I&rsquo;m using it in the code above, with the definition of the <code>Reporter</code> class as follows:</p>
<pre class="brush: csharp; title: ; notranslate">
private class Reporter : IProgress&lt;DownloadProgressChangedEventArgs&gt;
{
  private int id;
  public Reporter(int id)
  {
    this.id = id;
  }
  public void Report(DownloadProgressChangedEventArgs value)
  {
    Console.WriteLine(&quot;{0}:{1}&quot;, id, 
      string.Empty.PadRight(value.ProgressPercentage / 10, '*'));
  }
}
</pre>
<p>Now, here&rsquo;s my way of invoking the above code:</p>
<pre class="brush: csharp; title: ; notranslate">
static async void Main()
{
  var ct = new CancellationTokenSource();
  Console.CancelKeyPress += (s, e) =&gt; ct.Cancel();
  try
  {
    var po = new ParallelOptions();
    po.MaxDegreeOfParallelism = 64;
    po.CancellationToken = ct.Token;
    Parallel.For(1, 100, po, i =&gt;
    {
      po.CancellationToken.ThrowIfCancellationRequested();
      DownloadInformation(i);
    });
  } 
  catch (Exception e)
  {
    Console.WriteLine(e);
  }
  finally
  {
    Console.ReadKey();
  }
}
</pre>
<p>What&rsquo;s of note here is that we also had to mark <code>Main()</code> as <code>async</code> &ndash; there is a viral nature to async calls!</p>
<p>And now for the things I <em>didn&rsquo;t</em> like. First, I&rsquo;m as yet uncertain about what to do if the URL of the file to be downloaded doesn&rsquo;t resolve to anything (i.e., page doesn&rsquo;t exist). Right now, everything just stops and I get no exception or other indication of what&rsquo;s going on. Another thing that worries me is that Debugging doesn&rsquo;t work for me yet &ndash; right after the first <code>await</code> it bounces me to the caller, and that&rsquo;s it. Then again, this is a CTP, so I guess I have to be patient.</p>
<h3>Now What?</h3>
<p>So now we got ourselves the ability to &lsquo;lighten up&rsquo; on syntax, and code readbility has grown even compared to F#. We can now describe algorithms with continuations though, predictably enough, it makes little sense for singular calls &ndash; it&rsquo;s mainly benefitial if you are making lots of these, either via <code>Parallel.For()</code> or, for example, by creating several tasks and then doing <code>Task.WaitAll()</code>.</p>
<p>Since the Async CTP came out, the C# mailing lists have exploded &ndash; everyone&rsquo;s experimenting with the &lsquo;kit&rsquo; and trying things out. I actually put the code above into &lsquo;live&rsquo; use &ndash; the risk is minimal and everything is working well, so I can afford it. The code above has already worked for a few hours, and I have no complaints so far. Then again, this use-case is fairly trivial.</p>
<h3>Other PDC Goodies</h3>
<p>It would be nice if Anders mentioned something mind-blowing, but instead I was somewhat surprised even that while talking about metaprogramming in C#, when asked about aspect-oriented programming, he said he wasn&rsquo;t sure it&rsquo;s a good idea and that C# vNext is unlikely to support it. I find this bizarre because my understanding of metaprogramming is having a capability to do exactly that. Of course, the differentiator here is that, e.g., PostSharp&rsquo;s approach is to post-process existing assemblies, which might not be what the &lsquo;compiler-as-a-service&rsquo; is attuned for.</p>
<p>Then again, I don&rsquo;t need metaprogramming for AOP &ndash; I need it to auto-implement <code>INotifyPropertyChanged</code>, generatively create complex data structures or help create internal DSLs for better descriptions of algorithms. And C# vNext should be perfect for that. Unless of course I get the temptation to migrate everything to JetBrains MPS. Hey, it could happen.&nbsp;■</p>
]]></content:encoded>
			<wfw:commentRss>http://devtalk.net/csharp/async-await-and-c-vnext/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Extension Method Patterns</title>
		<link>http://devtalk.net/csharp/extension-method-patterns/</link>
		<comments>http://devtalk.net/csharp/extension-method-patterns/#comments</comments>
		<pubDate>Thu, 30 Sep 2010 16:14:03 +0000</pubDate>
		<dc:creator>Dmitri Nesteruk</dc:creator>
				<category><![CDATA[CSharp]]></category>

		<guid isPermaLink="false">http://devtalk.net/?p=82</guid>
		<description><![CDATA[In almost every application I work with somebody &#8211; either me or another developer &#8211; uses extension methods to add what they believe to be &#8216;missing&#8217; functionality to classes. Having seen a huge number of examples, I&#8217;ve began to realize that there are, in fact, implementation patterns related to extension method usage. In other words, [...]]]></description>
			<content:encoded><![CDATA[<p>In almost every application I work with somebody &ndash; either me or another developer &ndash; uses extension methods to add what they believe to be &lsquo;missing&rsquo; functionality to classes. Having seen a huge number of examples, I&rsquo;ve began to realize that there are, in fact, implementation patterns related to extension method usage. In other words, there are typical problems that extension methods are used to solve. This article is an overview of these problems.</p>
<h3>Composite Extension Method</h3>
<p>This type of method is created when you need to call two (or more) methods together, and you want to simplify the call. There&rsquo;s a myriad of situations where this is needed &ndash; for example, the <code>StringBuilder</code> class has an <code>AppendFormat()</code> and an <code>AppendLine()</code>, but what if you want to output a formatted string <em>with</em> a line break? A composite extension method helps you do just that.</p>
<pre class="brush: csharp; title: ; notranslate">
public static StringBuilder AppendFormatLine(
  this StringBuilder sb, string format, params object[] args)
{
  return sb.AppendFormat(format, args).AppendLine();
}
</pre>
<p>In actual fact, there are many use-cases for method combinations, but they typical one is sequential call (i.e., call <code>A()</code> then <code>B()</code>).</p>
<h3>Recursive Extension Method</h3>
<p>This type of method helps you avoid recursive calls by wrapping the &lsquo;folding&rsquo; into an extension method. For example, the <code>Path.Combine()</code> method takes only two parameters, which isn&rsquo;t very convenient if you have more than two elements in a path.</p>
<pre class="brush: csharp; title: ; notranslate">
// we have to write this
Path.Combine(a, Path.Combine(b, c));
// but we _want_ to write this
new[]{a, b, c}.PathCombine();
</pre>
<h3>Params Extension Method</h3>
<p>Since in .Net <code>T[]</code> is not equivalent to <code>params T[]</code>, we can&rsquo;t simply make a bunch of <code>T</code> arguments and pass them arbitrarily to a method that takes an array. The solution here is to create extenion methods which take a <code>params</code> array and proxy the calls then and there. For example, we can define the following:</p>
<pre class="brush: csharp; title: ; notranslate">
public static void AddRange&lt;T&gt;(this IList&lt;T&gt; list, params T[] objects)
{
  foreach (T obj in objects)
    list.Add(obj);
}
</pre>
<p>And here&rsquo;s how one would use it:</p>
<pre class="brush: csharp; title: ; notranslate">
var list = new List&lt;int&gt;();
// previously, you would have to write this
list.AddRange(new[] {1, 2, 3});
// but now you can write this
list.AddRange(1, 2, 3);
</pre>
<h3>Anti-static Extension Method</h3>
<p>Instead of calling a static method of class <code>X</code>, we instead call an extension method on this class (if this is possible, that is). The classical example to this approach is the way <code>String.Format()</code> gets turned into an extension method:</p>
<pre class="brush: csharp; title: ; notranslate">
public static string ƒ(this string format, params object[] args)
{
  return string.Format(format, args);
}
</pre>
<p>Are you spooked by the curly <em>f</em>?</p>
<h3>Factory Extension Method</h3>
<p>These methods let you completely bypass the object constructor, hiding it behind more concise, intention-revealing methods. One popular example is the creation of a date from a fluent expression so that one can write <code>19.June(1986)</code>. Note that the name of the method itself is an <em>implicit parameter</em> used for the creation of the <code>DateTime</code> structure:</p>
<pre class="brush: csharp; title: ; notranslate">
public static DateTime June(this int day, int year)
{
  return new DateTime(year, 6, day);
}
</pre>
<p>The factory method is not obliged to attach this method to the first parameter&rsquo;s type. For example, if your goal is the creation of an object (say, from a line of Xml) from a key-value structure, you can pass the whle object. We just need to remind ourselves that C# supports anonymous types. Then, the creation of an arbitrary piece of Xml can look like this:</p>
<pre class="brush: csharp; title: ; notranslate">
new { Name=&quot;Dmitri&quot;, Age=25}.ToXElements();
// will give us &lt;Name&gt;Dmitri&lt;/Name&gt; and &lt;Age&gt;25&lt;/Age&gt;
</pre>
<p>I won&rsquo;t show the implementation of this method here &ndash; you can find it in <a href="http://www.yoda.arachsys.com/csharp/miscutil/" title="http://www.yoda.arachsys.com/csharp/miscutil/"> MiscUtil</a> &ndash; but I hope this is a good reminder to our readers that an anonymous class is <em>de facto</em> a key-value collection. And hey &ndash; Asp.Net MVC happily exploits this language feature.</p>
<h3>Monadic Extension Method</h3>
<p>Monadic extension methods let you implement what I call <em>monadic syntax</em>. My <a href="http://devtalk.net/csharp/chained-null-checks-and-the-maybe-monad/" title="http://devtalk.net/csharp/chained-null-checks-and-the-maybe-monad/">previous article</a> shows fairly clear examples of what this is and what it&rsquo;s for, but I&rsquo;ll mention it here too for posterity &ndash; here&rsquo;s an extension method that allows chain calls that only &lsquo;happen&rsquo; if the argument is non-<code>null</code>:</p>
<pre class="brush: csharp; title: ; notranslate">
public static TResult With&lt;TInput, TResult&gt;(
  this TInput o, Func&lt;TInput, TResult&gt; evaluator)
  where TResult : class where TInput : class
{
  if (o == null) return null;
  return evaluator(o);
}
</pre>
<p>I&rsquo;d like to point out here that monadic extension methods are typically useful in domain areas where F# is more useful than C#. And, as you may remember, F# has not just extension methods but also extension properties, which adds an extra aspect usability-wise&hellip; but at the expense of all the headaches you&rsquo;ll get related to immutability and other capricious behavior.</p>
<h3>Proxy Extension Method</h3>
<p>Sometimes, in order to create a fully-fledged fluent interface, it&rsquo;s useful to keep some state associated with an object. Since in the conditions of staticity (everything is <code>static</code>) persistence is very difficult, we use a proxy object which can act as some sort of configurator or &lsquo;smart parameter&rsquo; for something else. Besides that, it can implement a host of methods, which will not pollute the global scope were they extensions over <code>object</code>.</p>
<p>Here&rsquo;s an exampe &ndash; <code>SomeProxy&lt;T&gt;</code> which acts as a convertible wrapper for <code>T</code>:</p>
<pre class="brush: csharp; title: ; notranslate">
public class SomeProxy&lt;T&gt;
{
  private readonly T subject;
  private object something;
  internal SomeProxy(T subject, object something)
  {
    this.subject = subject;
    this.something = something;
  }
  public static implicit operator T(SomeProxy&lt;T&gt; obj)
  {
    return obj.subject;
  }
  // other useful operators here
}
</pre>
<p>This class can then be &lsquo;substituted&rsquo; in lieu of the original object with an extension method:</p>
<pre class="brush: csharp; title: ; notranslate">
public static SomeProxy&lt;T&gt; Configure&lt;T&gt;(this T subject, object something)
{
  return new SomeProxy&lt;T&gt;(subject, something);
}
</pre>
<p>Unfortunately, you won&rsquo;t be able to &lsquo;layer&rsquo; these mixin-like constructs over one another without having to perform casts.</p>
<h3>Functionality Extension Method</h3>
<p>This is the catch-all type for any type of extension method. A typical example is the (yet missing) <code>ForEach()</code> method for Linq, which Eric Lippert <a href="http://blogs.msdn.com/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx" title="http://blogs.msdn.com/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx">blogged</a> about. It&rsquo;s an interesting read &ndash; mainly concerned with immutability that <em>everyone</em> seems to be obsessing over these days.</p>
<p>The internet is positively <em>teeming</em> with various mini-libraries of functionality extension methods &ndash; not just <code>ForEach()</code>, but also really bizarre constructs that are often, upon close ovservation, very obscure. For example, the <code>Step()</code> method which is simply a <code>for</code>-loop replacement. You would use it like this:</p>
<pre class="brush: csharp; title: ; notranslate">
// all numbers from 5 to 9 with a step of 2 are written to the console
5.Step (9, 2, i =&gt; Console.WriteLine (i));
</pre>
<h3>Conclusion</h3>
<p>I&rsquo;m not sure if it&rsquo;s fully valid to speak of &lsquo;extension method patterns&rsquo; in the same architectural sense as, say, GoF design patterns, but&hellip; it&rsquo;s something that caught my eye, and I guess putting it down on paper (so to speak) helps me better spot and classify these when I see them.</p>
]]></content:encoded>
			<wfw:commentRss>http://devtalk.net/csharp/extension-method-patterns/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Event Brokers in .Net</title>
		<link>http://devtalk.net/dotnet/event-brokers/</link>
		<comments>http://devtalk.net/dotnet/event-brokers/#comments</comments>
		<pubDate>Mon, 20 Sep 2010 08:36:14 +0000</pubDate>
		<dc:creator>Dmitri Nesteruk</dc:creator>
				<category><![CDATA[DotNet]]></category>

		<guid isPermaLink="false">http://devtalk.net/?p=74</guid>
		<description><![CDATA[Introduction As soon as software systems become reasonably complex, it gets very hard to organize things. We&#8217;re lucky to have sorted out the problem of component creation (with Inversion of Control and Dependency Injection), but when it comes to reacting to events, the framework give us very few organizational hints. As a consequence, people naturally [...]]]></description>
			<content:encoded><![CDATA[<h3>Introduction</h3>
<p>As soon as software systems become reasonably complex, it gets very hard to organize things. We&rsquo;re lucky to have sorted out the problem of component creation (with Inversion of Control and Dependency Injection), but when it comes to reacting to events, the framework give us very few organizational hints. As a consequence, people naturally create various infrastructural solutions for organized event handling. This is what we&rsquo;re going to discuss in this article.</p>
<p><img src="http://devtalk.net/wp-content/uploads/2010/09/vs2010_sln_icon.png" alt="Visual Studio 2010 Solution Icon" title="Visual Studio 2010 Solution Icon" width="16" height="16" class="alignnone size-full wp-image-73" style="border:0" valign="middle" />&nbsp;<a href="http://bitbucket.org/nesteruk/eventbrokers">Get Source Code Here</a></p>
<h3>Problem statement</h3>
<p>For the vast majority of developers, the task of handling events either doesn&rsquo;t exist, or exists &lsquo;in full force&rsquo; but in a very predictable key &ndash; for example when someone handles a WinForms <code>button_Click</code> event.</p>
<p>That&rsquo;s all well and good, but as soon as as things get complex, things break down. Here&rsquo;s an (albeit synthetic) example &ndash; let&rsquo;s try modeling the interaction between a football coach and player:</p>
<pre class="brush: csharp; title: ; notranslate">
public class FootballPlayer
{
  public string Name { get;set; }
  public void Score()
  {
    var e = Scored;
    if (e != null) e(this, new EventArgs());
  }
  public event EventHandler Scored;
}
public class FootballCoach
{
  public void Watch(FootballPlayer p)
  {
    p.Scored += (_, __) =&gt;
    {
      Console.WriteLine(&quot;I'm happy that {0} scored&quot;, p.Name);
    };
  }
}
</pre>
<p>In the above example, subscription and notification works just fine. But what if we do this?</p>
<pre class="brush: csharp; title: ; notranslate">
var p2 = c.Clone(); // deep copy :)
p.Score();
</pre>
<p>The issue here is that when you copy an object (either via <code>MemberwiseClone()</code> or via deep copy using, say, <code>BinaryFormatter</code>), all subscriptions will be lost.</p>
<p>Now, truth be told, subscriptions can be restored by hand&hellip; or, I don&rsquo;t know, you can try to abuse <code>Expression&lt;T&gt;</code> and the like. But that&rsquo;s really only part of the problem.</p>
<p>The next issue is that, one day, you&rsquo;re going to wish that your objects subscribed to events <em>automatically</em>. For example, as soon as a football player walks out onto the field, the coach starts observing him. Same goes for unsubscribing, too. As a consequence, you might end up with the following:</p>
<pre class="brush: csharp; title: ; notranslate">
class FootballCoach
{
  public FootballCoach(FootballPlayer[] players)
  {
    foreach (var p in players) {
      p.EntersField += new EventHandler(StartWatchingPlayer);
      p.LeavesField += new EventHandler(StopWatchingPlayer);
    }
  }
}
</pre>
<p>And so on &ndash; in each <code>StartXxx</code> you would have to subscribe, and in each <code>EndXxx</code> you would unsubscribe. But even this is not all.</p>
<p>Okay, so now imagine that your system contains <em>many</em> such objects. And they all send messages to one another. If we try to manage the subscriptions with the <code>+=</code> operator (as we&rsquo;re used to), we&rsquo;ll get really crazy coupling as well as virtually untestable code (event testing is a pain in any case).</p>
<p>And finally, let us not forget the whole &lsquo;configuration&rsquo; issue. Because sometimes it makes sense to receive events of a specific type <em>regardless of who sent them</em>. For example, the coach doesn&rsquo;t really care who is swearing at him &ndash; a player, the other coach, or the referee. Also, beleive it or not, sometimes it&rsquo;s beneficial to perform various manipulations related to event handling, such as batching events in blocks of 100 and handling them only on Friday 13<sup>th</sup> during a full moon. As you may have guessed, the simple event infrastructure is poorly suited to handle these sorts of demands.</p>
<h3>Simple Event Broker</h3>
<p>So given the requirements above, a sane developer would start writing something called an Event Arggregator or Event Broker &ndash; a separate component that can help us manage the madness of events. It all starts with a class similar to the following:</p>
<pre class="brush: csharp; title: ; notranslate">
public class EventBroker
{
  private MultiDictionary&lt;string, Delegate&gt; subscriptions =
    new MultiDictionary&lt;string, Delegate&gt;(true);
  public void Publish&lt;T&gt;(string name, object sender, T args)
  {
    foreach (var h in subscriptions[name])
      h.DynamicInvoke(sender, args);
  }
  public void Subscribe&lt;T&gt;(string name, Delegate handler)
  {
    subscriptions.Add(name, handler);
  }
}
</pre>
<p>Thread safety notwithstanding, we got ourselves a broker that can manage subscriptions. Of course, you&rsquo;re not getting any QoS (Quality of Service) here, and any aggregation/transformation logic related to events has to be done by hand, but we&rsquo;re already improving on the original situation &ndash; for example, by using <code>name</code> as the classifier above, we got ourselves a situation in which one class can subscribe a handler for several different events.</p>
<p>So, with this implemented, our football player doesn&rsquo;t publish events anymore:</p>
<pre class="brush: csharp; title: ; notranslate">
public class FootballPlayer
{
  private readonly EventBroker broker;
  public string Name { get; set; }
  public FootballPlayer(EventBroker broker)
  {
    this.broker = broker;
  }
  public void Injured()
  {
    broker.Publish(&quot;LeavingField&quot;, this, new EventArgs());
  }
  public void SentOff()
  { // event args can be different for this one
    broker.Publish(&quot;LeavingField&quot;, this, new EventArgs());
  }
}
</pre>
<p>And the football coach now subscribes to events via the broker:</p>
<pre class="brush: csharp; title: ; notranslate">
public class FootballCoach
{
  private readonly EventBroker broker;
  public FootballCoach(EventBroker broker)
  {
    this.broker = broker;
  }
  public void Watch(FootballPlayer player)
  {
    broker.Subscribe&lt;EventArgs&gt;(&quot;LeavingField&quot;,
                                new EventHandler(PlayerIsLeavingField));
  }
  public void PlayerIsLeavingField(object sender, EventArgs args)
  {
    Console.WriteLine(&quot;Where are you going, {0}?&quot;,
                      (sender as FootballPlayer).Name);
  }
}
</pre>
<p>In the above, we&rsquo;re relying on polymorphism and the idea that all events, being good citizens, inherit from <code>EventArgs</code>. Strong typing is not critical here because you can always do a type case. And here&rsquo;s how you could use it all in a client app:</p>
<pre class="brush: csharp; title: ; notranslate">
var uc = new UnityContainer();
uc.RegisterType&lt;EventBroker&gt;(
  new ContainerControlledLifetimeManager());
var p = uc.Resolve&lt;FootballPlayer&gt;();
p.Name = &quot;Arshavin&quot;;
var c = uc.Resolve&lt;FootballCoach&gt;();
c.Watch(p);
p.Injured();
p.SentOff();
</pre>
<p>One thing that you should note is that events got effectively replaced by messaging. If, like me, you work with frameworks such as NServiceBus, this might appear for you to be a very natural metamorphosis.</p>
<p>In the above example, the broker is registered as a singleton, so both the the coach and the player receive the same instance. What I&rsquo;m hinting at is that in <em>static</em> scenarios, when you know in advance who subscribes to what, it makes more sense to describe subscriptions declaratively. We&rsquo;ll get to that in a moment.</p>
<h4>Issues</h4>
<p>The solution presented here is not final for a number of reasons. First, it&rsquo;s really not a good idea to have direct coupling between the component and the broker &ndash; this implies that you need to splice the broker through domain classes and use it explicitly. As we&rsquo;ll see in the next section, this problem is easy to resolve.</p>
<p>The second problem, which I&rsquo;ve already mentioned, is that event handling logic currently only uses one criterion &ndash; a string literal that acts as a &lsquo;classifier&rsquo;. To limit event processing logic thus is somewhat unwise, especially with the pressent of such a powerful instrument as LINQ.</p>
<h3>Reactive Extensions Event Broker</h3>
<p>Okay, so in the previous example I described an event broker implemented with plain C# by switching from events to message passing, leaving behind the <code>event</code> keyword and all the problems which typically accompany it. Now, let us try to exploit a library solution. We&rsquo;re going to try and build an event broker using Reactive Extensions, which should allow us to apply complex selection logic to events, and would also simplify unsubscriptions via its <code>IDisposable</code> tie-in.</p>
<h4>Subscription</h4>
<p>To start with, we&rsquo;ll begin by looking at a subscription not as some <code>KeyValuePair</code>, but rather an <code>IDisposable</code>, with the understanding that the subscription only exists while the subscriber exists, and that when the subscriber dies (e.g., gets disposed), it makes sense to unsubscribe from all events it was monitoring. Consenquently, we write the simplest possible implementation:</p>
<pre class="brush: csharp; title: ; notranslate">
private class Subscription : IDisposable
{
  private readonly EventBroker broker;
  public IObserver&lt;EventArgs&gt; Subscriber { get; private set; }
  public Subscription(EventBroker broker, IObserver&lt;EventArgs&gt; subscriber)
  {
    this.broker = broker;
    this.Subscriber = subscriber;
  }
  public void Dispose()
  {
    broker.Unsubscribe(Subscriber);
  }
}
</pre>
<p>This is a <em>private</em> class that lives inside the broker. All it does is keep a reference to the subscriber. The subscription itself is stored in the broker (coming up!) and is <em>served to the subscriber</em> just in case the subscriber wants to die at a later stage.</p>
<h4>The Broker</h4>
<p>Our new Rx-driven broker implements <code>IObservable&lt;T&gt;</code>, which lets the subscriber perform various operations <em>right on the broker</em> before subscribing to anything. This may sound a bit surreal, but if you think of LINQ as a generator of some proxy between all of broker&rsquo;s objects and the ones that we actually need, it starts to make more sense.</p>
<p>So, our broker has 2 fields &ndash; the list of subscribers (yes, a list, and not a <code>HashSet</code>) and a <code>ReaderWriterLockSlim</code> just in case the broker is used from several threads.</p>
<pre class="brush: csharp; title: ; notranslate">
class EventBroker : IObservable&lt;EventArgs&gt;
{
  private readonly List&lt;Subscription&gt; subscribers = new List&lt;Subscription&gt;();
  private readonly ReaderWriterLockSlim myLock = new ReaderWriterLockSlim();
  ...
}
</pre>
<p>The broker has three methods. The first &ndash; <code>Subscribe()</code> &ndash; lets anyone subscribe and manipulate with LINQ a push-collection of events that come from this broker. Each subscription forces a check on the absence of existing subscriptions, which makes messy code even more messy:</p>
<pre class="brush: csharp; title: ; notranslate">
public IDisposable Subscribe(IObserver&lt;EventArgs&gt; subscriber)
{
  Subscription sub = new Subscription(this, subscriber);
  myLock.EnterUpgradeableReadLock();
  try
  {
    if (!subscribers.Any(s =&gt; s.Subscriber == subscriber))
    {
      myLock.EnterWriteLock();
      try
      {
        subscribers.Add(sub);
      }
      finally {
        myLock.ExitWriteLock();
      }
    }
  } finally
  {
    myLock.ExitUpgradeableReadLock();
  }
  return sub;
}
</pre>
<p>As you can see, the return value <em>as dictated</em> by <code>IObservable&lt;T&gt;</code> has a type of <code>IDisposable</code> &ndash; that&rsquo;s the reason why we had to create a separate <code>Subscription</code> class. The purpose of this is simple &ndash; if you need to unsubscribe from the event stream, you can just call <code>Dispose()</code>.</p>
<p>Here&rsquo;s what unsubscribing looks like:</p>
<pre class="brush: csharp; title: ; notranslate">
public void Unsubscribe(IObserver&lt;EventArgs&gt; subscriber)
{
  myLock.EnterWriteLock();
  try
  {
    subscribers.RemoveAll(s =&gt; s.Subscriber == subscriber);
  }
  finally
  {
    myLock.ExitWriteLock();
  }
}
</pre>
<p>Nothing unusual here. You can call this method yourself, but it&rsquo;s also called by <code>Subscription</code> during the moment of deletion. Whichever works for you.</p>
<p>Finally, the third method is the one to publish something.</p>
<pre class="brush: csharp; title: ; notranslate">
public void Publish&lt;T&gt;(T args) where T : EventArgs
{
  myLock.EnterReadLock();
  try
  {
    var subs = subscribers.ToArray();
    foreach (var s in subs)
      s.Subscriber.OnNext(args);
  }
  finally { myLock.ExitReadLock(); }
}
</pre>
<p>There is a tiny hack in the above code. Can you see where? The issue above is that <code>OnNext()</code> can, theoretically, cause a destruction of a subscription, utterly invalidating the <code>subscribers</code> list. Which is why we make a copy.</p>
<h4>Domain Objects</h4>
<p>So, coming back to our &lsquo;coach and player&rsquo; example. The player, unfortunately, continues to keep a reference to the broker. It uses <code>EventBroker.Publish()</code> where necessary to inform everyone that he has just scored a goal:</p>
<pre class="brush: csharp; title: ; notranslate">
class FootballPlayer
{
  public string Name { get; set; }
  [Dependency]
  public EventBroker EventBroker { get; set; }
  public void Score()
  {
    Console.WriteLine(&quot;{0} scored!!!&quot;, Name);
    EventBroker.Publish(new GenericEventArgs(this, Name));
  }
}
</pre>
<p>As for the coach, he also has a dependency on the broker. In fact, he may as well take it as a constructor parameter (via DI, perhaps?) and subscribe to events then and there. Of course, since we are using Rx, we are at liberty to use LINQ to filter and manipulate the event stream.</p>
<pre class="brush: csharp; title: ; notranslate">
class FootballCoach
{
  private readonly EventBroker broker;
  public FootballCoach(EventBroker broker)
  {
    broker.OfType&lt;GenericEventArgs&gt;().Subscribe(args =&gt;
      Console.WriteLine(&quot;Well done, {0}!&quot;, args.Data));
  }
}
</pre>
<p>Just to be complete, here is the event argument type:</p>
<pre class="brush: csharp; title: ; notranslate">
class GenericEventArgs : EventArgs
{
  public GenericEventArgs(object sender, string data)
  {
    Sender = sender;
    Data = data;
  }
  public object Sender { get; set; }
  public string Data { get; set; }
}
</pre>
<p>And, after all this is done, simple wireup with Unity finishes things off:</p>
<pre class="brush: csharp; title: ; notranslate">
var uc = new UnityContainer();
uc.RegisterType&lt;EventBroker&gt;(new ContainerControlledLifetimeManager());
var p = uc.Resolve&lt;FootballPlayer&gt;();
p.Name = &quot;Arshavin&quot;;
var c = uc.Resolve&lt;FootballCoach&gt;();
p.Score();
</pre>
<h4>What is the Point?</h4>
<p>Some of you might think that we haven&rsquo;t really achieved anything &ndash; after all, just like with the simple broker, we have to propagate the broker through our entities. Even if this wasn&rsquo;t a broker but rather some <code>Subject&lt;T&gt;</code> (an Rx interface for classes that both publish and subscribe), it&rsquo;s still not very neat.</p>
<p>On the other hand, we got one very serious advantage &ndash; the ability to use Linq combinators for complex manipulations. For example, if the coach starts noticing a player only after he scores his third goal, you could describe it like so:</p>
<pre class="brush: csharp; title: ; notranslate">
broker.OfType&lt;GenericEventArgs&gt;().Skip(2).Take(5).Subscribe(args =&gt;
  Console.WriteLine(&quot;Well done, {0}!&quot;, args.Data));
</pre>
<p>&ldquo;But wait,&rdquo; you might say, &ldquo;didn&rsquo;t you promise to talk about declarative subscriptions?&rdquo; Indeed I did. That&rsquo;s what the next section is about.</p>
<h3>Unity 2.0 Event Broker</h3>
<p>So, moving on with our event broker discussion, let&rsquo;s take a look at the use of an event broker in static scenarios (where all subscriptions are known at compile-time). We are going to abuse the Unity Application Block to implement declarative event brokerage via attributes and extensions to the Unity container.</p>
<p>The example presented here is originally taken from the corresponding example in the <code>ObjectBuilder</code> project, but have been adapted to support Unity 2.0.</p>
<h4>The Broker</h4>
<p>Let&rsquo;s begin with the broker itself. Broker implmenetation imples two immortal constructs &ndash; the subscriber (or event sink) and someone who publishes the events (event source). In the Unity implementation of the event broker, these participants are divided into separate classes &ndash; somewhat differs from our previous example with a single <code>Subscription</code> class. Why? It&rsquo;s simple &ndash; with Rx, we are attached to a particular interface, whereas what we&rsquo;re trying to get right here is true loose coupling. All we know is that the publisher publishes an event (yes, an <code>event</code>, not a message), and as for the &lsquo;receiving&rsquo; class, we only know the method that takes the predictable <code>(object, EventArgs)</code> pair that we&rsquo;re all used to.</p>
<p>So, let&rsquo;s take a look at the infrastructure that we need.</p>
<h5>EventSource</h5>
<p>This class encapsulates information pertaining to an event source &ndash; that&rsquo;s why the constructor has an <code>EventInfo</code> parameter. Based on the information about an event, we dynamically create and add a subscription <em>to that event</em>. Also, by analogy with our previous example, this class is marked as <code>IDisposable</code> and its <code>Dispose()</code> method does&hellip; guess what! That&rsquo;s right &ndash; it unsubscribes all handlers from this event.</p>
<pre class="brush: csharp; title: ; notranslate">
internal class EventSource : IDisposable
{
  readonly string eventID;
  readonly EventInfo eventInfo;
  readonly MethodInfo handlerMethod;
  readonly EventBroker broker;
  readonly WeakReference source;
  public EventSource(EventBroker broker,
                      object source,
                      EventInfo eventInfo,
                      string eventID)
  {
    this.broker = broker;
    this.source = new WeakReference(source);
    this.eventInfo = eventInfo;
    this.eventID = eventID;
    handlerMethod = GetType().GetMethod(&quot;SourceHandler&quot;);
    Delegate @delegate = Delegate.CreateDelegate(eventInfo.EventHandlerType, this, handlerMethod);
    eventInfo.AddEventHandler(source, @delegate);
  }
  public object Source
  {
    get { return source.Target; }
  }
  public void Dispose()
  {
    object sourceObj = source.Target;
    if (sourceObj != null)
    {
      Delegate @delegate = Delegate.CreateDelegate(eventInfo.EventHandlerType, this, handlerMethod);
      eventInfo.RemoveEventHandler(sourceObj, @delegate);
    }
  }
  public void SourceHandler(object sender,
                            EventArgs e)
  {
    broker.Fire(eventID, sender, e);
  }
}
</pre>
<h5>EventSink</h5>
<p>This class represents an event &lsquo;receiver&rsquo;. It does two things &ndash; firstly, it &lsquo;registers&rsquo; a relationship between a particular event and its handler &ndash; that&rsquo;s why the constructor has a <code>MethodInfo</code> parameter. The constructor also creates an <code>EventArgs</code> type which is later passed to the handler.</p>
<p>The second thing the event sink is concerned with is the creation and invocation of the delegate that&rsquo;s responsible for the handling of a particular event.</p>
<pre class="brush: csharp; title: ; notranslate">
internal class EventSink
{
  readonly Type handlerEventArgsType;
  readonly MethodInfo methodInfo;
  readonly WeakReference sink;
  public EventSink(object sink,
                    MethodInfo methodInfo)
  {
    this.sink = new WeakReference(sink);
    this.methodInfo = methodInfo;
    ParameterInfo[] parameters = methodInfo.GetParameters();
    if (parameters.Length != 2 || !typeof(EventArgs).IsAssignableFrom(parameters[1].ParameterType))
      throw new ArgumentException(&quot;Method does not appear to be a valid event handler&quot;, &quot;methodInfo&quot;);
    handlerEventArgsType = typeof(EventHandler&lt;&gt;).MakeGenericType(parameters[1].ParameterType);
  }
  public object Sink
  {
    get { return sink.Target; }
  }
  public Exception Invoke(object sender,
                          EventArgs e)
  {
    object sinkObject = sink.Target;
    try
    {
      if (sinkObject != null)
      {
        Delegate @delegate = Delegate.CreateDelegate(handlerEventArgsType, sinkObject, methodInfo);
        @delegate.DynamicInvoke(sender, e);
      }
      return null;
    }
    catch (TargetInvocationException ex)
    {
      return ex.InnerException;
    }
  }
}
</pre>
<h4>Extending Unity</h4>
<p>It won&rsquo;t be a surprise to anyone that Unity can, in fact, be extended with new features. To create your own extension, you simply inherit from <code>UnityContainerExtension</code> and add the strategies that implement your extension. Here is the container extension for our broker:</p>
<pre class="brush: csharp; title: ; notranslate">
public class BrokerExtension : UnityContainerExtension
{
  private readonly EventBroker broker = new EventBroker();
  protected override void Initialize()
  {
    Context.Container.RegisterInstance(broker,
      new ExternallyControlledLifetimeManager());
    Context.Strategies.AddNew&lt;BrokerReflectionStrategy&gt;(
      UnityBuildStage.PreCreation);
    Context.Strategies.Add(new BrokerWireupStrategy(broker),
                            UnityBuildStage.Initialization);
  }
}
</pre>
<p>In this example, the <code>Context</code> variable gives us access to the container itself (into which we add the broker itself) as well as the collection of strategies that will be applied. For each strategy we define the stage at which the build-up happens. There are two strategies for our broker. The first &ndash; <code>BrokerReflectionStrategy</code> uses reflection to find out about potential publishers and subscribers:</p>
<pre class="brush: csharp; title: ; notranslate">
public class BrokerReflectionStrategy : BuilderStrategy
{
  public override void PreBuildUp(IBuilderContext context)
  {
    Type typeToBuild = context.BuildKey.Type;
    if (typeToBuild != null)
    {
      var policy = new EventBrokerPolicy();
      RegisterSinks(policy, typeToBuild);
      RegisterSources(policy, typeToBuild);
      if (!policy.IsEmpty)
        context.Policies.Set&lt;IEventBrokerPolicy&gt;(policy, context.BuildKey);
    }
    base.PreBuildUp(context);
  }
  static void RegisterSinks(EventBrokerPolicy policy,
                            Type type)
  {
    foreach (MethodInfo method in type.GetMethods())
      foreach (SubscribesToAttribute attr in method.GetCustomAttributes(typeof(SubscribesToAttribute), true))
        policy.AddSink(method, attr.Name);
  }
  static void RegisterSources(EventBrokerPolicy policy, Type type)
  {
    foreach (EventInfo @event in type.GetEvents())
      foreach (PublishesAttribute attr in @event.GetCustomAttributes(typeof(PublishesAttribute), true))
        policy.AddSource(@event, attr.Name);
  }
}
</pre>
<p>The second &ndash; <code>BrokerWireupStrategy</code> &ndash; is used to actually register subscriptions:</p>
<pre class="brush: csharp; title: ; notranslate">
public class BrokerWireupStrategy : BuilderStrategy
{
  private readonly EventBroker broker;
  public BrokerWireupStrategy(EventBroker broker)
  {
    this.broker = broker;
  }
  public override void PreBuildUp(IBuilderContext context)
  {
    var policy = context.Policies.Get&lt;IEventBrokerPolicy&gt;(context.BuildKey);
    if (policy != null &amp;&amp; broker != null)
    {
      foreach (KeyValuePair&lt;string, MethodInfo&gt; kvp in policy.Sinks)
        broker.RegisterSink(context.Existing, kvp.Value, kvp.Key);
      foreach (KeyValuePair&lt;string, EventInfo&gt; kvp in policy.Sources)
        broker.RegisterSource(context.Existing, kvp.Value, kvp.Key);
    }
    base.PreBuildUp(context);
  }
}
</pre>
<p>A strange thing is happening here &ndash; we&rsquo;re using two strategies instead of one. Also, there&rsquo;s a policy class called <code>EventBrokerPolicy</code> that&rsquo;s used here &ndash; it allows us to pass data from one strategy eo another. One of the reasons behind this is that, in the context of strategies, there&rsquo;s no direct access to the container itself. In other words, the <code>EventBrokerPolicy</code> class is simply a DTO.</p>
<pre class="brush: csharp; title: ; notranslate">
public class EventBrokerPolicy : IEventBrokerPolicy
{
  readonly Dictionary&lt;string, MethodInfo&gt; sinks = new Dictionary&lt;string, MethodInfo&gt;();
  readonly Dictionary&lt;string, EventInfo&gt; sources = new Dictionary&lt;string, EventInfo&gt;();
  public bool IsEmpty
  {
    get { return sinks.Count == 0 &amp;&amp; sources.Count == 0; }
  }
  public IEnumerable&lt;KeyValuePair&lt;string, MethodInfo&gt;&gt; Sinks
  {
    get { return sinks; }
  }
  public IEnumerable&lt;KeyValuePair&lt;string, EventInfo&gt;&gt; Sources
  {
    get { return sources; }
  }
  public void AddSink(MethodInfo method,
                      string eventID)
  {
    sinks.Add(eventID, method);
  }
  public void AddSource(EventInfo @event,
                        string eventID)
  {
    sources.Add(eventID, @event);
  }
}
</pre>
<h4>Putting It All Together</h4>
<p>So, we&rsquo;re going to get Unity to find subscriptions via <code>Publishes</code> and <code>SubscribesTo</code> attributes. In our example, we once again used a string identifier to describe events &ndash; thus, we get a form of loose coupling in the sense that a competely arbitrary component that gets plugged into the system can easily subscribe to a particular event &ndash; so long as it knows its name.</p>
<p>Let&rsquo;s take a look at actual usage. First thing you should notice is that our coach and player classes got a lot simpler:</p>
<pre class="brush: csharp; title: ; notranslate">
public class FootballPlayer
{
  [Publishes(&quot;score&quot;)]
  public event EventHandler PlayerScored;
  public string Name { get; set; }
  public void Score()
  {
    var ps = PlayerScored;
    if (ps != null)
      ps(this, new EventArgs());
  }
}
</pre>
<p>Naturally, event arguments in the above example could be a more copmlex type &ndash; we have already seen how Unity determines this type and builds a delegate based on it. As for the coach, here&rsquo;s the new definition:</p>
<pre class="brush: csharp; title: ; notranslate">
public class FootballCoach
{
  [SubscribesTo(&quot;score&quot;)]
  public void PlayerScored(object sender, EventArgs args)
  {
    var p = sender as FootballPlayer;
    Console.Write(&quot;Well done, {0}!&quot;, p.Name);
  }
}
</pre>
<p>In other words, we got a purely declarative event handling infrastructure. That&rsquo;s it! All that remains is to actually use it!</p>
<pre class="brush: csharp; title: ; notranslate">
var uc = new UnityContainer();
uc.AddNewExtension&lt;BrokerExtension&gt;();
var p = uc.Resolve&lt;FootballPlayer&gt;();
p.Name = &quot;Maradona&quot;;
var c = uc.Resolve&lt;FootballCoach&gt;();
p.Score();
p.Score();
</pre>
<h3>Conclusion</h3>
<p>In this article, I have presented three distinct approaches to implementing an event broker &ndash; a simple Dictionary-based broker, a broker based on Reactive Extensions, and a declarative broker infrastructure as a Unity 2.0 extension. There are many more possible broker implementations out there &ndash; the one you choose is up to you.&nbsp;■</p>
]]></content:encoded>
			<wfw:commentRss>http://devtalk.net/dotnet/event-brokers/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Making DSLs in F#</title>
		<link>http://devtalk.net/fsharp/making-dsls-in-fsharp/</link>
		<comments>http://devtalk.net/fsharp/making-dsls-in-fsharp/#comments</comments>
		<pubDate>Tue, 14 Sep 2010 11:38:35 +0000</pubDate>
		<dc:creator>Dmitri Nesteruk</dc:creator>
				<category><![CDATA[FSharp]]></category>

		<guid isPermaLink="false">http://devtalk.net/?p=43</guid>
		<description><![CDATA[If you&#8217;re like me, you are already fed up with people throwing the term &#8216;DSL&#8217; around without showing a good example of how it&#8217;s done and where they are used &#8211; not to mention giving a decent, human-readable description of DSLs that doesn&#8217;t allude to extraneous concepts (I&#8217;m talking about things like Oslo or MPS, [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://devtalk.net/wp-content/uploads/2010/09/FSharp.png" alt="F#" title="FSharp" width="150" height="131" style="border:0" class="alignright size-full wp-image-56" /></p>
<p>If you&rsquo;re like me, you are already fed up with people throwing the term &lsquo;DSL&rsquo; around without showing a good example of how it&rsquo;s done and where they are used &ndash; not to mention giving a decent, human-readable description of DSLs that doesn&rsquo;t allude to extraneous concepts (I&rsquo;m talking about things like Oslo or MPS, mainly).</p>
<p>Okay, what on Earth is a DSL? A DSL is a way of defining domain-specific (you could say industry-specific, but it can be much narrower) logic using English instead of a programming language. The obvious benefit is that non-technical people can edit the DSL, without worrying about curly braces, semicolons, that sort of thing.</p>
<p>In this article, I&rsquo;m going to show how to use the F# programming language to make a simple DSL that helps with software estimation. Just so you know, it&rsquo;s a real-life example, with a more complex version of the DSL being used at our company. All right, let&rsquo;s hit it!</p>
<p>Just to say upfront, this article doesn&rsquo;t present book-perfect F# code, the reason being that it doesn&rsquo;t really matter since F# code is not our end-product. I can think of a dozen ways to improve the F# code presented, but, as I said, that&rsquo;s not the purpose of this exercise.</p>
<h3>Problem Statement</h3>
<p>When someone wants software written, they typically contact a software development company with something called an RFP, short for &ldquo;Request for Proposal&rdquo;. Depending on the level of detail of this RFP, the code shop can either do a detailed estimate or give a ballpark figure. Barring cases of clients wanting dedicated teams or having vague requirements, the estimate the code shop makes is a fixed-price project timeline. Yeah, I know it doesn&rsquo;t sound particularly agile to people, but in situations where the prospective client has done lots of up-front design, it actually makes sense.</p>
<p>Anyway, someone has to do the estimate, i.e. partition the project into tasks, give them duration, assign resources (= people) to tasks, define milestones, et cetera. This sort of estimate can be done in a program such as Microsoft Project &ndash; a good choice in our case, since automating Office from an F# app is easy.</p>
<p>So why a DSL then? Well to be honest, you can probably do an estimate at the 10<sup>th</sup> of the time it takes to draw up the GANTT chart with all the reorderings and point-and-click mechanics of Project. Not only that, but typically you need to apply some sort of logic (i.e. use your brain, ugh!) to make sure the project plan is nice and balanced (I mean resource utilization and such). Having a DSL means you can optimize and autogenerate the plan. With a DSL, you can stick as much business logic into your planning procedure as you want &ndash; for example, if your company has a process database (this is CMMI Level 4-ish, btw), you could try validating the plan against empirical data.</p>
<p>Are you sold on the DSL idea for estimates? If not, here&rsquo;s another boon: integration. You can integrate Project with other systems to get more value from existing data. For example, if you run Dynamics CRM, you can tweak resource pricing for a particular client in order to put better developers on the features they consider important. It all sounds very pompous and BI-ish, but that&rsquo;s life of a code shop.</p>
<h4>End Users</h4>
<p>In most code shops, barring a few exceptions, estimates are done by project managers (PMs). These guys are sometimes techies, sometimes not, so you can&rsquo;t expect them to know programming. But you can certainly expect them to be able to work with a DSL and then press some magic key to generate a project plan or otherwise involve their DSL scribblings in an estimation BI scenario.</p>
<h4>Continuous Process Improvement</h4>
<p>At the risk of sounding cheeky, if you are constantly working on your (say) estimation DSL, improving it and tailoring it, it&rsquo;s an excellent opportunity for improving your business processes. Think about it &ndash; as a code shop, you can use idle dev resources to improve the efficiency of your business. Is this great, or what? I think it is, anyway.</p>
<h3>Choosing a Language</h3>
<p>With the problem out of the way, let&rsquo;s think of a solution. You can certainly make a free-form DSL language and write a parser, but it&rsquo;s kind of tedious. A simpler solution is to use a programming language which looks so English (no cultural bias here &ndash; feel free to use Japanese or any other language) that the end user won&rsquo;t know the difference. Of course, some language syntax will creep into the DSL, but its level varies.</p>
<p>Popular languages for DSLs include Boo (which Ayende is trying to make popular), Ruby and F#. Boo is extremely powerful, and for cases where you need metaprogramming support (not our scenario), it&rsquo;s fantastic. Ruby I know next to nothing about, so no comment. Now, F# is a popular language, and a first-class citizen of .NET infrastructure (as of VS2010 especially). So we&rsquo;re going to look at making an infrastructure in which PMs can easily write project estimates.</p>
<p>Let me issue a small disclaimer: being a language geared towards immutability, F# looks a bit weird when used with highly mutable concepts, such as a project which can accumulate tasks or milestones. This weirdness can be easily compensated by writing the DSL data structures in C# and then using them from F#. However, for this example, I&rsquo;ll use F# exclusively.</p>
<h3>First DSL Statement</h3>
<p>I&rsquo;ll try to keep this simple. Let&rsquo;s start by defining a project with a name and start date:</p>
<pre class="brush: fsharp; title: ; notranslate">
project &quot;Write F# DSL Article&quot; starts_on &quot;16/8/2009&quot;
</pre>
<p>The above is a completely legal F# statement. It&rsquo;s basically a function call to a function called <code>project</code> which takes 3 parameters. The first parameter is a project name &ndash; no, you can&rsquo;t avoid the quotes here unless you want to parse stuff yourself. The second parameter is a dummy &ndash; a constant whose value is unimportant; its only purpose here is to make the spec readable and BDD-esque. You&rsquo;re welcome to expand the <code>starts_on</code> keyword into two separate parts, but I prefer not to overdo it, especially when there&rsquo;s a risk of keywords creeping in. The third parameter is the project starting date as a string.</p>
<p>Believe it or not, the DSL uses OOP constructs in order to manage the constructed project. For example, we have a <code>Project</code> class which is our DSL representation of a project. It&rsquo;s shown below. Skipping ahead a bit, make sure your types don&rsquo;t collide with other assemblies&rsquo; types. After all, Microsoft Project assemblies might just have a <code>Project</code> type too.</p>
<pre class="brush: fsharp; title: ; notranslate">
type Project() =
  [&lt;DefaultValue&gt;] val mutable Name : string
  [&lt;DefaultValue&gt;] val mutable Resources : Resource list
  [&lt;DefaultValue&gt;] val mutable StartDate : DateTime
  [&lt;DefaultValue&gt;] val mutable Groups : Group list
</pre>
<p>I did warn about the strange syntax, did I not? The above is F#&rsquo;s way of making public fields. You&rsquo;ll notice also that I use list types instead of the <code>System.Collections.Generic</code> ones. It doesn&rsquo;t really matter what you use for the DSL so long as it works.</p>
<p>Our DSL will support just one project which will be at &lsquo;global scope&rsquo;, so to speak:</p>
<pre class="brush: fsharp; title: ; notranslate">
let mutable my_project = new Project()
</pre>
<p>The naming convention is a bit <em>ad hoc</em> here save for the fact that, when we get to the end of the spec, we need a statement to actually do something and <code>my_project</code> is a nice identifier name for that action. But now, we can finally show the <code>project</code> statement from earlier.</p>
<pre class="brush: fsharp; title: ; notranslate">
let project name startskey start =
  my_project &lt;- new Project()
  my_project.Name &lt;- name
  my_project.Resources &lt;- []
  my_project.Groups &lt;- []
  my_project.StartDate &lt;- DateTime.Parse(start)
</pre>
<p>There. I have probably revealed 90% of what DSL construction is like. You can close this article and go off exploring right now, since you already know how it all works. In the rest of this article, I&rsquo;ll be showing a few F# implementation details.</p>
<h3>Handling Lists</h3>
<p>Work in projects is done by resources (not very gratifying, is it?). A resource is a particular person (&ldquo;John&rdquo;) with a particular job title (&ldquo;Junior DBA&rdquo;) and a particular hourly rate ($65). A project keeps references to resources via a <code>Resource list</code> (see, F# is human-readable). Let&rsquo;s look at the definition of <code>Resource</code>:</p>
<pre class="brush: fsharp; title: ; notranslate">
type Resource() =
  [&lt;DefaultValue&gt;] val mutable Name : string
  [&lt;DefaultValue&gt;] val mutable Position : string
  [&lt;DefaultValue&gt;] val mutable Rate : int
</pre>
<p>I&rsquo;m abusing F# once again, but at least the structure is easy to work with. Now, a resource definition is also part of our DSL, and might look as follows:</p>
<pre class="brush: fsharp; title: ; notranslate">
resource &quot;Dmitri&quot; isa &quot;Project Manager&quot; with_rate 140
</pre>
<p>The above statement employs the same trickery as <code>project</code> except that it acts on an already-existing global variable <code>my_project</code>:</p>
<pre class="brush: fsharp; title: ; notranslate">
let resource name isakey position ratekey rate =
  let r = new Resource()
  r.Name &lt;- name
  r.Position &lt;- position
  r.Rate &lt;- rate
  my_project.Resources &lt;- r :: my_project.Resources
</pre>
<p>Resources and all other lists we use end up being listed in <em>reverse order</em>. It&rsquo;s not a problem though &ndash; we reverse them when the time comes. If you don&rsquo;t like it, use <code>List&lt;T&gt;</code> instead.</p>
<h3>Referencing with Strings</h3>
<p>The next concept of our DSL I want to introduct is a <em>group</em> of tasks. A group of tasks is typically done by one person to maintain, ahem, cognitive cohesion. We define a group as follows:</p>
<pre class="brush: fsharp; title: ; notranslate">
group &quot;Project Coordination&quot; done_by &quot;Dmitri&quot;
</pre>
<p>To put things in context, let&rsquo;s look at the <code>Group</code> class:</p>
<pre class="brush: fsharp; title: ; notranslate">
type Group() =
  [&lt;DefaultValue&gt;] val mutable Name : string
  [&lt;DefaultValue&gt;] val mutable Person : Resource
  [&lt;DefaultValue&gt;] val mutable Tasks : Task list
</pre>
<p>A group references a particular resource, which our DSL specifies only as a string. Problem? I don&rsquo;t think so:</p>
<pre class="brush: fsharp; title: ; notranslate">
let group name donebytoken resource =
  let g = new Group()
  g.Name &lt;- name
  g.Person &lt;- my_project.Resources |&gt; List.find(fun f -&gt; f.Name = resource)
  g.Tasks &lt;- []
  my_project.Groups &lt;- g :: my_project.Groups
</pre>
<p>Notice how, unlike with LINQ, we don&rsquo;t have to call <code>Single()</code> after searching for the right resource.</p>
<h3>Greater Fluency</h3>
<p>Last but not least, we define tasks. Now, isn&rsquo;t it great when you can say, for example, the following:</p>
<pre class="brush: fsharp; title: ; notranslate">
task &quot;PayPal Integration&quot; takes 2 weeks
</pre>
<p>In fact, you can. This type of fluency is achieved by judiciously defining timespan constants so that their values are <em>meaningful</em>. For example:</p>
<pre class="brush: fsharp; title: ; notranslate">
let hours = 1
let hour = 1
let days = 2
let day = 2
let weeks = 3
let week = 3
let months = 4
let month = 4
</pre>
<p>The values do not matter so long as they are distinct. Now we can define a task&hellip;</p>
<pre class="brush: fsharp; title: ; notranslate">
type Task() =
  [&lt;DefaultValue&gt;] val mutable Name : string
  [&lt;DefaultValue&gt;] val mutable Duration : string
</pre>
<p>&hellip; and add it to the project:</p>
<pre class="brush: fsharp; title: ; notranslate">
let task name takestoken count timeunit =
  let t = new Task()
  t.Name &lt;- name
  let dummy = 1 + count
  match timeunit with
  | 1 -&gt; t.Duration &lt;- String.Format(&quot;{0}h&quot;, count)
  | 2 -&gt; t.Duration &lt;- String.Format(&quot;{0}d&quot;, count)
  | 3 -&gt; t.Duration &lt;- String.Format(&quot;{0}wk&quot;, count)
  | 4 -&gt; t.Duration &lt;- String.Format(&quot;{0}mon&quot;, count)
  | _ -&gt; raise(ArgumentException(&quot;only spans of hour(s), day(s), week(s) and month(s) are supported&quot;))
  let g = List.head my_project.Groups
  g.Tasks &lt;- t :: g.Tasks
</pre>
<p>Notice that for each timespan, I slightly change the way the duration is phrased so that Project is capable of eating the spec. The dummy expression above tells F# that <code>count</code> is an integer &ndash; I could have defined it explicitly, of course, but I&rsquo;m just too lazy. Oh, by the way, notice how easy it is for us to find the current (i.e., last) task. Because we&rsquo;re using F#, this task is actually <em>first</em> in the list, so we can just call <code>List.head</code>.</p>
<h3>Generating the Project</h3>
<p>We&rsquo;ve got <em>everything</em> and are ready to generate the project. The following (somewhat cheesy) command does it:</p>
<pre class="brush: fsharp; title: ; notranslate">
prepare my_project
</pre>
<p>Now, I&rsquo;m about to show you the <em>whole</em> <code>prepare</code> definition, which uses the Project API to make the, umm, project. Notice how succinct F# is:</p>
<pre class="brush: fsharp; title: ; notranslate">
let prepare (proj:Project) =
  let app = new ApplicationClass()
  app.Visible &lt;- true
  let p = app.Projects.Add()
  p.Name &lt;- proj.Name
  proj.Resources |&gt; List.iter(fun r -&gt;
    let r' = p.Resources.Add()
    r'.Name &lt;- r.Position // position, not name :)
    let tables = r'.CostRateTables
    let table = tables.[1]
    table.PayRates.[1].StandardRate &lt;- r.Rate
    table.PayRates.[1].OvertimeRate &lt;- (r.Rate + (r.Rate &gt;&gt;&gt; 1)))
  // make root task with project name
  let root = p.Tasks.Add()
  root.Name &lt;- proj.Name
  // add groups
  proj.Groups |&gt; List.rev |&gt; List.iter(fun g -&gt; 
    let t = p.Tasks.Add()
    t.Name &lt;- g.Name
    t.OutlineLevel &lt;- 2s
    // who is responsible for this group?
    t.ResourceNames &lt;- g.Person.Position
    // add tasks
    let tasksInOrder = g.Tasks |&gt; List.rev
    tasksInOrder |&gt; List.iter(fun t' -&gt;
        let t'' = p.Tasks.Add(t'.Name)
        t''.Duration &lt;- t'.Duration
        t''.OutlineLevel &lt;- 3s
        // make task follow previous
        let idx = tasksInOrder |&gt; List.findIndex(fun f -&gt; f.Equals(t'))
        if (idx &gt; 0) then 
          t''.Predecessors &lt;- Convert.ToString(t''.Index - 1)
      )
    )
</pre>
<p>Yep, we finally reverse those backward lists with <code>List.rev</code> &ndash; probably not the fastest operation in the world, but I don&rsquo;t care. All that matters is that the script runs and gives us the results we want &ndash; resource definitions, group names and tasks which are grouped and linked. What more could a PM ask for? (Quite a bit actually, but that&rsquo;s another story.)</p>
<p>A complete project definition can therefore look like this:</p>
<pre class="brush: fsharp; title: ; notranslate">
project &quot;F# DSL Article&quot; starts &quot;01/01/2009&quot;
resource &quot;Dmitri&quot; isa &quot;Writer&quot; with_rate 140
resource &quot;Computer&quot; isa &quot;Dumb Machine&quot; with_rate 0
group &quot;DSL Popularization&quot; done_by &quot;Dmitri&quot;
task &quot;Create basic estimation DSL&quot; takes 1 day
task &quot;Write article&quot; takes 1 day
task &quot;Post article and wait for comments&quot; takes 1 week
group &quot;Infrastructure Support&quot; done_by &quot;Computer&quot;
task &quot;Provide VS2010 and MS Project&quot; takes 1 day
task &quot;Download and deploy TypograFix&quot; takes 1 day
task &quot;Sit idly while owner waits for comments&quot; takes 1 week
prepare my_project
</pre>
<p>And here is the project plan after it is generated:</p>
<p>
  <img src="http://devtalk.net/wp-content/uploads/2010/09/Gantt.png" alt="" title="Gantt" width="815" height="314" class="alignnone size-full wp-image-44" />
</p>
<h3>Conclusion</h3>
<p>This article shows that making a DSL in F# is really simple. Of course, the thing about DSLs is they are <em>domain-specific</em>, so for the domain you choose you might encounter a lot more challenges. Have fun!</p>
<p><img src="http://devtalk.net/wp-content/uploads/2010/09/vs2010_sln_icon.png" alt="Visual Studio 2010 Solution Icon" title="Visual Studio 2010 Solution" width="16" height="16" class="alignnone size-full wp-image-73" style="border:0" valign="middle" />&nbsp;<a href="http://pastebin.com/xnSTVaTx">Get Source Code Here</a></p>
]]></content:encoded>
			<wfw:commentRss>http://devtalk.net/fsharp/making-dsls-in-fsharp/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Chained null checks and the Maybe monad</title>
		<link>http://devtalk.net/csharp/chained-null-checks-and-the-maybe-monad/</link>
		<comments>http://devtalk.net/csharp/chained-null-checks-and-the-maybe-monad/#comments</comments>
		<pubDate>Sun, 12 Sep 2010 09:05:33 +0000</pubDate>
		<dc:creator>Dmitri Nesteruk</dc:creator>
				<category><![CDATA[CSharp]]></category>

		<guid isPermaLink="false">http://devtalk.net/?p=33</guid>
		<description><![CDATA[A great many programmers have met a situation where, while accessing a nested object property (e.g., person.Address.PostCode), they have to do several null checks. This requirement frequently pops up in XML parsing where missing elements and attributes can return null when you attempt to access them (and subsequently trying to access Value throws a NullReferenceException). [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://devtalk.net/wp-content/uploads/2010/09/nested-ifs.png" alt="Nested IF Statements" title="nested-ifs" width="150" height="103" class="alignright" />A great many programmers have met a situation where, while accessing a nested object property (e.g., <code>person.Address.PostCode</code>), they have to do several <code>null</code> checks. This requirement frequently pops up in XML parsing where missing elements and attributes can return <code>null</code> when you attempt to access them (and subsequently trying to access <code>Value</code> throws a <code>NullReferenceException</code>). In this article, I&rsquo;ll show how a take on the Maybe monad in C#, coupled with use of extension methods, can be used to improve readability.</p>
<h3>Problem Description</h3>
<p>So, to start with, let&rsquo;s look at the way to get a person&rsquo;s post code (just imagine you&rsquo;re working with XML or something). The code shown below does several <code>null</code> checks and assigns the value only if it is available.</p>
<pre class="brush: fsharp; title: ; notranslate">
string postCode = null;
if (person != null &amp;&amp; person.Address != null &amp;&amp; person.Address.PostCode != null)
{
  postCode = person.Address.PostCode.ToString();
}
</pre>
<p>What you&rsquo;ve got up there is some fairly unreadable (and un-maintainable) code. Actually, we&rsquo;re lucky to have all of our code fall under a single <code>if</code> &ndash; something that might not be possible in a more complex scenario. Let&rsquo;s imagine a more complicated situation &ndash; say we need to perform some operation between the <code>if</code> evaluations. What do we get? That&rsquo;s right &ndash; a chain of <code>if</code>s.</p>
<pre class="brush: fsharp; title: ; notranslate">
string postCode;
if (person != null)
{
  if (HasMedicalRecord(person) &amp;&amp; person.Address != null)
  {
    CheckAddress(person.Address);
    if (person.Address.PostCode != null)
      postCode = person.Address.PostCode.ToString();
    else
      postCode = &quot;UNKNOWN&quot;;
  }
}
</pre>
<p>The code presented above contains a lot of excess data &ndash; for example, <code>person.Address.PostCode</code> is mentioned twice. There&rsquo;s nothing incorrect about the code <em>per se</em>, it just has a bit too many symbols. To sum up, we want our code to communicate better that</p>
<ul style="list-style-type:square">
<li>If the value is <code>null</code>, no further evaluations should be done; if the value is <em>not</em> <code>null</code>, then this is the value we&rsquo;re going to work with</li>
<li>If we perform some action, it only happens on a valid object</li>
</ul>
<p>So what am I suggesting? I propose that we create a fluent interface that will satisfy the above conditions <em>without any nesting</em>. To do that, we are going to employ the <a href="http://en.wikipedia.org/wiki/Monad_(functional_programming)#Maybe_monad" title="http://en.wikipedia.org/wiki/Monad_(functional_programming)#Maybe_monad">Maybe monad</a>.</p>
<p>For those of you who know F#, the Maybe monad will be familiar as the Option type. For C# developers, let&rsquo;s just assume that you can have variable that either have <code>Some</code> value or no value (<code>None</code>). Of course, C# doesn&rsquo;t directly support this none-some duality except by using <code>null</code>. Which is precisely why I&rsquo;m proposing the chained extension solution presented below.</p>
<h3>With</h3>
<p>Our primary concern is to do the <code>null</code> checks to &lsquo;shorten&rsquo; them so they don&rsquo;t pollute our code. For that, we&rsquo;ll define a <code>With()</code> extension method:</p>
<pre class="brush: fsharp; title: ; notranslate">
public static TResult With&lt;TInput, TResult&gt;(this TInput o, Func&lt;TInput, TResult&gt; evaluator)
  where TResult : class where TInput : class
{
  if (o == null) return null;
  return evaluator(o);
}
</pre>
<p>The above method can be attached to any type (because <code>TInput</code> is effectively <code>object</code>). As a parameter, this method takes a function which defines <em>the next value in the chain</em>. If we passed <code>null</code>, we get <code>null</code> back. Let&rsquo;s rewrite our first example using this method:</p>
<pre class="brush: fsharp; title: ; notranslate">
string postCode = this.With(x =&gt; person)
                      .With(x =&gt; x.Address)
                      .With(x =&gt; x.PostCode);
</pre>
<p>I suppose, in the above example, we could replace <code>Func&lt;&gt;</code> with <code>Expression&lt;&gt;</code> and try to pull properties, but I&rsquo;ve seen this done and the resulting code is <em>too slow</em> and it&rsquo;s also somewhat limiting &ndash; it assumes that you&rsquo;re working with just one object, whereas my Maybe chains can (and do) drag in many objects.</p>
<h3>Return</h3>
<p>Here comes another piece of syntactic sugar &ndash; the <code>Return()</code> method. This method will return the &lsquo;current&rsquo; value just like <code>Where()</code> does, but in case <code>null</code> was passed, it will return a different value that we supply. Consider this a kind of «<code>Where()</code> with fallback» method.</p>
<pre class="brush: fsharp; title: ; notranslate">
public static TResult Return&lt;TInput,TResult&gt;(this TInput o, 
  Func&lt;TInput, TResult&gt; evaluator, TResult failureValue) where TInput: class
{
  if (o == null) return failureValue;
  return evaluator(o);
}
</pre>
<p>So let&rsquo;s assume now that, with the absense of a postcode, we want to return, say, <code>string.Empty</code>. Here&rsquo;s how:</p>
<pre class="brush: fsharp; title: ; notranslate">
string postCode = this.With(x =&gt; person).With(x =&gt; x.Address)
                      .Return(x =&gt; x.PostCode, string.Empty);
</pre>
<p>By the way, you could rewrite the extension method so that <code>failureValue</code> would also be computed via a <code>Func&lt;&gt;</code> &ndash; I am yet to meet a scenario where this is required, though. It is typically the case that we never know at which stage the chain failed (and yielded <code>null</code>), so the terminal <code>Return()</code> is typically an indicator (either <code>true/false</code> or <code>null</code>/not <code>null</code>).</p>
<h3>If &amp; Unless</h3>
<p>Going through the call chain, you sometimes need to do checks not related to <code>null</code>. Theoretically, you could suspend the chain and use an <code>if</code>, or you could use an <code>if</code> in one of the delegates, but&hellip; you can simply define an <code>If()</code> extension method (and an <code>Unless()</code> if you feel like it) and plug it into the chain:</p>
<pre class="brush: fsharp; title: ; notranslate">
public static TInput If&lt;TInput&gt;(this TInput o, Func&lt;TInput, bool&gt; evaluator) 
  where TInput : class
{
  if (o == null) return null;
  return evaluator(o) ? o : null;
}
 
public static TInput Unless&lt;TInput&gt;(this TInput o, Func&lt;TInput, bool&gt; evaluator)
  where TInput : class
{
  if (o == null) return null;
  return evaluator(o) ? null : o;
}
</pre>
<h3>Do</h3>
<p>Seeing how we&rsquo;re having a party here, let&rsquo;s add yet another method that simply calls a delegate &ndash; and that&rsquo;s it. Of course, this method is best used for one-line calls and not for evaluating 20-line algorithms with convoluted logic. Nevertheless, the call is quite useful in practice.</p>
<pre class="brush: fsharp; title: ; notranslate">
public static TInput Do&lt;TInput&gt;(this TInput o, Action&lt;TInput&gt; action) 
  where TInput: class
{
  if (o == null) return null;
  action(o);
  return o;
}
</pre>
<p>So, we&rsquo;re done: we&rsquo;ve got the infrastructure we need to get our post code extraction to be a bit more readable. Here is the end result:</p>
<pre class="brush: fsharp; title: ; notranslate">
string postCode = this.With(x =&gt; person)
    .If(x =&gt; HasMedicalRecord(x))]
    .With(x =&gt; x.Address)
    .Do(x =&gt; CheckAddress(x))
    .With(x =&gt; x.PostCode)
    .Return(x =&gt; x.ToString(), &quot;UNKNOWN&quot;);
</pre>
<p>As you can see, the depth of nesting has fallen to zero &ndash; no more curly braces!</p>
<h3>Discussion</h3>
<p>I use these Maybe-monadic-chain-null-extension-methods (call them how you will) in my <a href="http://activemesa.com/r2p" title="http://activemesa.com/r2p">R2P</a> software product. Here&rsquo;s an example of real-life use of these constructs:</p>
<pre class="brush: fsharp; title: ; notranslate">
public override void VisitInvocationExpression(IInvocationExpression expression)
{
  base.VisitInvocationExpression(expression);
  string typeName = this.With(x =&gt; expression)
    .With(x =&gt; x.InvokedExpression)
    .With(x =&gt; x as IReferenceExpression)
    .With(x =&gt; x.Reference)
    .With(x =&gt; x.Resolve())
    .With(x =&gt; x.DeclaredElement)
    .With(x =&gt; x.GetContainingType())
    .Return(x =&gt; x.CLRName, null);
  this.If(x =&gt; Array.IndexOf(types, typeName) != -1)
    .With(x =&gt; ExpressionStatementNavigator.GetByExpression(expression))
    .Do(x =&gt;
          {
            var suggestion = new SideEffectSuggestion(typeName);
            var highlightInfo = new HighlightingInfo(
              expression.GetDocumentRange(),
              suggestion);
            context.HighlightingInfos.Add(highlightInfo);
          });
}
</pre>
<p>I have to point out here that, at any point, you can stop the chain and start a new one. Why would you want that? Well, for example, you cannot define shared variables within the chain (unless you refactor it all to have a <code>Dictionary&lt;string,object&gt;</code>-like parameter).</p>
<p>By the way, quite frequently I find myself making additional, domain-specific methods to plug into this chain. For example:</p>
<pre class="brush: fsharp; title: ; notranslate">
public static IElement IsWithin&lt;TContainingType&gt;(this IElement self) 
  where TContainingType: class, IElement
{
  if (self == null) return self;
  var owner = self.GetContainingElement&lt;TContainingType&gt;(false);
  return owner == null ? self : null;
}
</pre>
<p>One more thing: this type of notation is actually light obfuscation because, as I&rsquo;m sure you&rsquo;ve guessed, each extension method call will be shown as a <code>static</code> method call in Reflector:</p>
<pre class="brush: fsharp; title: ; notranslate">
public override void VisitInvocationExpression(IInvocationExpression expression)
{
    base.VisitInvocationExpression(expression);
    string typeName = this.With&lt;SideEffectAnalyser, IInvocationExpression&gt;(
    delegate (SideEffectAnalyser x) {
        return expression;
    }).With&lt;IInvocationExpression, ICSharpExpression&gt;(delegate (IInvocationExpression x) {
        return x.InvokedExpression;
    }).With&lt;ICSharpExpression, IReferenceExpression&gt;(delegate (ICSharpExpression x) {
        return (x as IReferenceExpression);
    }).With&lt;IReferenceExpression, IReference&gt;(delegate (IReferenceExpression x) {
        return x.Reference;
    })
    ⋮
    // and so on
}
</pre>
<p>This approach is easily extensible &ndash; for example, a colleague of mine does <code>try-catch</code> checks in his chains, too. Hey, this is kind of like AOP, but without post-build or dynamic proxies. Oh, and the performance hit for these chains is <em>negligible</em> compared to <code>if</code> statements.</p>
<p>That&rsquo;s it! Comments are, as always, welcome! Oh, and if you like this article, please <a href="http://www.codeproject.com/KB/cs/maybemonads.aspx">vote for it</a> on CodeProject. &nbsp;■</p>
]]></content:encoded>
			<wfw:commentRss>http://devtalk.net/csharp/chained-null-checks-and-the-maybe-monad/feed/</wfw:commentRss>
		<slash:comments>27</slash:comments>
		</item>
		<item>
		<title>Launching DevTalk.net</title>
		<link>http://devtalk.net/uncategorized/launch/</link>
		<comments>http://devtalk.net/uncategorized/launch/#comments</comments>
		<pubDate>Sat, 11 Sep 2010 16:39:20 +0000</pubDate>
		<dc:creator>Dmitri Nesteruk</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://devtalk.net/?p=27</guid>
		<description><![CDATA[After all the trials and tribulations, I&#8217;m happy to announce the launch of DevTalk.net &#8212; a .Net-oriented blog that I will post to myself, and that others may (or may not) like to post to. It is my hope that this will become a valuable resource for anyone interested in cutting-edge .Net development materials. Wish [...]]]></description>
			<content:encoded><![CDATA[<p>After all the trials and tribulations, I&rsquo;m happy to announce the launch of DevTalk.net &mdash; a .Net-oriented blog that I will post to myself, and that others may (or may not) like to post to. It is my hope that this will become a valuable resource for anyone interested in cutting-edge .Net development materials. Wish me luck! :)</p>
]]></content:encoded>
			<wfw:commentRss>http://devtalk.net/uncategorized/launch/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
