<?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>Jamie&#039;s Blog &#187; Delphi</title>
	<atom:link href="http://jamiei.com/blog/topic/development/delphi/feed/" rel="self" type="application/rss+xml" />
	<link>http://jamiei.com/blog</link>
	<description>Delphi Programming, Web Development, General Technology and, of course, Midget Gems</description>
	<lastBuildDate>Mon, 19 Dec 2011 09:19:31 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=</generator>
<cloud domain='jamiei.com' port='80' path='/blog/?rsscloud=notify' registerProcedure='' protocol='http-post' />
		<item>
		<title>tgrep challenge</title>
		<link>http://jamiei.com/blog/2011/10/tgrep-challenge/</link>
		<comments>http://jamiei.com/blog/2011/10/tgrep-challenge/#comments</comments>
		<pubDate>Tue, 25 Oct 2011 22:00:56 +0000</pubDate>
		<dc:creator>jamiei</dc:creator>
				<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[file search]]></category>
		<category><![CDATA[tgrep]]></category>

		<guid isPermaLink="false">http://jamiei.com/blog/?p=840</guid>
		<description><![CDATA[I thought many of you might enjoy a little programming challenge that I came across. I&#8217;ve long been a fan of reddit, and especially the programming and delphi sub reddits. reddit, who seem to finally be getting the support that they need, posted an interesting job ad about 8 months ago, which seemed like a nice [...]]]></description>
			<content:encoded><![CDATA[<p>I thought many of you might enjoy a little programming challenge that I came across. I&#8217;ve long been a fan of <a href="http://www.reddit.com">reddit</a>, and especially the <a href="http://programming.reddit.com">programming</a> and <a href="http://delphi.reddit.com">delphi sub reddits</a>. reddit, who seem to finally be getting the support that they need, posted an <a href="http://www.reddit.com/r/blog/comments/fjgit/reddit_is_doubling_the_size_of_its_programming/">interesting job ad</a> about 8 months ago, which seemed like a nice little project.</p>
<p>The challenge, to summarise, is to devise an application which can search through <em>very</em> large log files for lines which match the time (the name of the challenge will give away the purpose for those familiar with the grep tool). The challenge focuses specifically on <a href="http://haproxy.1wt.eu/">HAProxy</a> logs and although they&#8217;re not hard to generate yourself they do provide a <a href="http://www.reddit.com/r/blog/comments/fjgit/reddit_is_doubling_the_size_of_its_programming/c1ge0ri">sample perl generator</a>. The main behaviour of the application is that a user should be able to provide either a time or time range and optionally a log path (with a default) and have the lines within the scope of the log file returned:</p>
<pre style="padding: 0px; margin: 10px;"><code style="font-style: normal;">$ tgrep 8:42:04 </code></pre>
<pre style="padding: 0px; margin: 10px;"><code style="font-style: normal;">[log lines with that precise timestamp] </code></pre>
<pre style="padding: 0px; margin: 10px;"><code style="font-style: normal;">$ tgrep 10:01 </code></pre>
<pre style="padding: 0px; margin: 10px;"><code style="font-style: normal;">[log lines with timestamps between 10:01:00 and 10:01:59] </code></pre>
<pre style="padding: 0px; margin: 10px;"><code style="font-style: normal;">$ tgrep 23:59-0:03 </code></pre>
<pre style="padding: 0px; margin: 10px;"><code style="font-style: normal;">[log lines between 23:59:00 and 0:03:59]</code></pre>
<p>For the purpose of this challenge, the log files can be assumed to have been rotated every 24 hours and you will therefore only need to worry about the time of a line and not a date changeover.</p>
<p>A successful application in the strict interpretation of this challenge would also need to work on Linux and would therefore likely need to be compiled with <a href="http://www.freepascal.org/">Freepascal</a>.</p>
<p>What I like about this challenge is that there are many levels of solution which you could dive into. Clearly, as the challenge states, you are unlikely to achieve any real speed when searching through log files of many gigabytes if you perform a linear search. The size of the files involved will also cause problems any solution which isn&#8217;t careful about memory consumption.</p>
<p>For my first iteration I initially opted for a straightforward interpolative search, which turned out to be much more buggy than I&#8217;d originally thought however luckily, I had written my <a href="http://www.extremeprogramming.org/rules/testfirst.html">tests first</a> even though I had to resort to a form of integration testing instead of using mock objects (<a href="http://www.nickhodges.com/post/Delphi-Mocks-The-Basics.aspx">Nick Hodges</a> would not be happy!). It&#8217;s a shame that none of the current Mocking libraries appear to be compatible with Delphi 2009 so I thought I&#8217;d leave the mocks until a later iteration. My initial iteration works and although I haven&#8217;t performance tested it fully yet, I fully expect it to pale in comparison with some of the excellent <a href="https://github.com/search?langOverride=&amp;q=tgrep&amp;repo=&amp;start_value=1&amp;type=Repositories">tgrep entries made available</a> via github. Of particular note is <a href="https://github.com/Evansbee/tgrep">EvansBee&#8217;s C version</a>, which in the few tests that I ran was very quick.</p>
<p>For my second iteration, I expect that it can be optimised in real-world conditions by taking account of the peaks and troughs in traffic that I would imagine reddit get during certain intervals of the day.</p>
<p><img class="aligncenter" title="reddit traffic stats" src="http://3.bp.blogspot.com/_SMII3qiVCz8/TD9bxgtruyI/AAAAAAAAAKA/OaH2wBNkpp0/s1600/googleanalytics.png" alt="" width="631" height="381" /></p>
<p>If anyone feels like they might like to give the tgrep challenge a go with some absurdly clever way of tackling this problem in delphi/fpc then feel free to comment/get in contact. It might be fun to put them all up on github so that we can all compare and contrast. If someone was really clever then they might even be able to hookup some kind of clever super project which builds a bunch of <a href="http://book.git-scm.com/5_submodules.html">git submodules</a> and tests them all.</p>
<h4>Links</h4>
<ul>
<li><a href="http://www.reddit.com/r/blog/comments/fjgit/reddit_is_doubling_the_size_of_its_programming/">tgrep challenge</a> &#8211; the original job ad, explaining the details.</li>
<li><a href="http://www.reddit.com/r/blog/comments/fjgit/reddit_is_doubling_the_size_of_its_programming/c1ge0ri">A perl log sample generator</a> &#8211; It is perl, but it works.</li>
<li><a href="https://github.com/search?langOverride=&amp;q=tgrep&amp;repo=&amp;start_value=1&amp;type=Repositories">github tgrep projects</a> &#8211; Some of these contain some interesting ideas, if you&#8217;re stuck for an approach.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://jamiei.com/blog/2011/10/tgrep-challenge/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Delivering software continuously and why you should</title>
		<link>http://jamiei.com/blog/2011/06/delivering-software-continuously-and-why-you-should/</link>
		<comments>http://jamiei.com/blog/2011/06/delivering-software-continuously-and-why-you-should/#comments</comments>
		<pubDate>Thu, 23 Jun 2011 22:11:59 +0000</pubDate>
		<dc:creator>jamiei</dc:creator>
				<category><![CDATA[Continuous Delivery]]></category>
		<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Development process]]></category>
		<category><![CDATA[continuous delivery]]></category>
		<category><![CDATA[software]]></category>

		<guid isPermaLink="false">http://jamiei.com/blog/?p=824</guid>
		<description><![CDATA[I&#8217;ve recently really been getting into a Software Delivery methodology which for me, wraps up a selection of the most potent benefits of Agile, TDD, Continuous Integration which requires Development and Operations to work very closely. Holy cow, all those flashy words in a single description, that must mean this is some enterprisey buzzwordy new [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve recently really been getting into a Software Delivery methodology which for me, wraps up a selection of the most potent benefits of Agile, TDD, Continuous Integration which requires Development and Operations to work very closely.</p>
<p>Holy cow, all those flashy words in a single description, that must mean this is some enterprisey buzzwordy new fangled thing, right? Nope. This is an extension of all those ideas that we know that we &#8220;should&#8221; and &#8220;could&#8221; have always been doing, and in fact some of you may already be doing it.</p>
<p>Continuous Delivery, in a nutshell, is about delivering your software in small, very frequent incremental updates through a huge quantity and quality of automation in build, testing and deployment. Traditionally, the release process for many teams culminates in a lockdown period for release followed by many hours or days of manual release process, followed by triage and observation. This is a broken and problematic approach and we all know it.</p>
<p>Instead, continuous delivery is the way forwards for delivering software and in future blog posts I will aiming to cover more of the implementation process, potential problems and cultural impact.</p>
<p>My interest was piqued when I attended a presentation by one of the authors of <a href="http://www.amazon.co.uk/gp/redirect.html?ie=UTF8&amp;location=http%3A%2F%2Fwww.amazon.co.uk%2FContinuous-Delivery-Deployment-Automation-Addison-Wesley%2Fdp%2F0321601912&amp;tag=jamsblo-21&amp;linkCode=ur2&amp;camp=1634&amp;creative=6738">Continuous Delivery</a>, which as the name would suggest is the currently definitive book on the subject. <img class="alignright" src="http://martinfowler.com/continuousDelivery.jpg" alt="Continuous Delivery (Jez Humble and David Farley)" width="200" height="300" /> David and Jez developed the principles for Continuous Delivery at <a href="http://www.thoughtworks.com/">Thoughtworks</a>, where Jez currently also works as the Product manager for <a href="http://www.thoughtworks-studios.com/go-agile-release-management">Go</a> (yes, neither this <a href="http://golang.org/">Go</a>, nor this <a href="http://en.wikipedia.org/wiki/Go_(game)">Go</a>).</p>
<p>Continuous Delivery is about automating everything from build to deployment into production. This also means that methodologies such as <a href="http://martinfowler.com/articles/continuousIntegration.html">Continuous Integration</a> and <a href="http://www.amazon.co.uk/Agile-Testing-Practical-Addison-Wesley-Signature/dp/0321534468/ref=sr_1_1?ie=UTF8&amp;qid=1308866681&amp;sr=8-1">Agile testing</a> could be viewed as a specific subset of Continuous Delivery. I also recently attended &#8216;<a href="http://www.meetup.com/Continuous-Integration-London/events/17119676/">Evolving Continuous Delivery</a>&#8216; with the <a href="http://www.meetup.com/Continuous-Integration-London/">London Continuous Integration Meetup</a> where <a href="http://www.chris-read.net/">Chris Read</a> gave us the quote of the night:</p>
<blockquote><p>Until your code is in production making money or doing what it is meant to do, you have simply wasted your time</p></blockquote>
<p>The Value proposition for Continuous Delivery is very simple: getting business value into production as quickly as possible. By repeatedly deploying to production in a controlled manner we also:</p>
<ul>
<li>Validate the business decisions which we&#8217;ve made more quickly by taking small steps towards our goal and gaining feedback before you&#8217;ve invested the full cost.</li>
<li>Allow us to deliver our business value at lower risk because we make smaller changes at each step. Smaller changes are less risky than large packages of change.</li>
<li>Encourages the culture that nothing is truly &#8220;done&#8221; until it is delivered to your users and more importantly proven before delivery.</li>
</ul>
<p>Every build artefact should be considered a potentially releasable artefact, your comprehensive suite of tests are there to prove that it is <strong>not </strong>suitable. With each test passed, the build should be promoted through the pipeline to the next test. In order to be confident that your release is not risky, you need to be able to test everything in a release. Obviously, this means testing code changes, but also deployment processes and configuration. Being certain of your configuration also means testing your system configuration as well as your application configuration. We&#8217;ve all seen how &#8220;minor&#8221; OS patches can cause massive knock on effects to the performance or stability of an application unknowingly, it&#8217;s vital that you should be able to monitor and roll back. When you begin to consider what conditions you may want to roll back or draw attention to your release, you may need add specific monitoring and instrumentation to your application to monitor if you notice:</p>
<ul>
<li>Increased Latency</li>
<li>Increased Load</li>
<li>Lost Dependencies after a configuration change</li>
<li>Poorer Business Performance</li>
<li>Failed Basic Functionality of the application</li>
</ul>
<p>Finally, deploying continuously may require cultural and process changes to the way you develop your products. In particular, your SCM and branching strategy may need to reflect the need to release partially implemented features as disabled (also known as feature toggles).  A presentation worth watching on this topic is Chuck Rossi on &#8216;<a href="https://www.facebook.com/video/video.php?v=10100259101684977&amp;oid=9445547199&amp;comments">How facebook releases software</a>&#8216;. Your application architecture may also need to be updated to allow continuous deployment in a safe manner.</p>
<p>Continuous Delivery isn&#8217;t just for Web Applications (although it, clearly has massive benefits to them) but as the <a href="http://www.codinghorror.com/blog/2011/05/the-infinite-version.html">Google Chrome team have demonstrated</a>, can provide great benefits for Desktop applications (even Delphi ones!) too although requires different tools and approaches. Imagine being able to push a series of very <a href="http://blog.chromium.org/2009/07/smaller-is-faster-and-safer-too.html">efficient diffs</a> to all the users of your application every time it successfully passes a full range of exhaustive tests.</p>
<p>Many companies currently use some form of Continuous Deployment to manage their operations, such as <a href="http://code.flickr.com/">Flickr</a>, <a href="http://codeascraft.etsy.com/2011/02/04/how-does-etsy-manage-development-and-operations/">Etsy</a>, Netflix and more who I&#8217;ve forgotten. Continuous Delivery is a topic that impacts all areas of operations, development, marketing, and possibly any regulatory concerns. I intend on diving into detailed posts of various areas of the overall topic.</p>
<p>Further Reading</p>
<ul>
<li><a href="http://www.amazon.co.uk/gp/redirect.html?ie=UTF8&amp;location=http%3A%2F%2Fwww.amazon.co.uk%2FContinuous-Delivery-Deployment-Automation-Addison-Wesley%2Fdp%2F0321601912&amp;tag=jamsblo-21&amp;linkCode=ur2&amp;camp=1634&amp;creative=6738">Continuous Delivery</a> by Jez Humble and Dave Farley &#8211; The Book</li>
<li><a href="http://www.infoq.com/presentations/Continuous-Delivery">Jez Humble at DevOps Days 2010</a> &#8211; A presentation by Jez on Continuous Delivery</li>
<li><a href="http://www.thoughtworks.com/events/push-the-button">Push the Button</a> &#8211; A recent talk by Sam Newman, a principle consultant at Thoughtworks on Continuous Delivery.</li>
<li><a href="http://www.informit.com/articles/article.aspx?p=1641923">The Value Proposition</a> &#8211; An article about the value proposition on Continuous Delivery</li>
<li><a href="http://www.methodsandtools.com/archive/archive.php?id=121">Continuous Delivery using Build Pipelines and Ant</a> &#8211; A great end to end article on the Build Tools side by James Betteley, who I met at the London CI meetup.</li>
</ul>
<p>I would like to thank my good friend <a href="http://scalabound.org/">Kingsley Davies</a> for encouraging me to pickup this vein of blogging.</p>
]]></content:encoded>
			<wfw:commentRss>http://jamiei.com/blog/2011/06/delivering-software-continuously-and-why-you-should/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Open source kindness and a Delphi yajl update</title>
		<link>http://jamiei.com/blog/2011/03/open-source-and-a-delphi-yajl-update/</link>
		<comments>http://jamiei.com/blog/2011/03/open-source-and-a-delphi-yajl-update/#comments</comments>
		<pubDate>Tue, 08 Mar 2011 22:54:23 +0000</pubDate>
		<dc:creator>jamiei</dc:creator>
				<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[git]]></category>
		<category><![CDATA[github]]></category>

		<guid isPermaLink="false">http://jamiei.com/blog/?p=808</guid>
		<description><![CDATA[I&#8217;m always pleasantly surprised at the generosity of the Delphi community when it comes to helping other developers or open source efforts. There are many places to host open source code, each community usually has a particular bias towards one system (.NET langs towards Codeplex, Python langs towards BitBucket, Ruby and Javascript to Github). The [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m always pleasantly surprised at the generosity of the Delphi community when it comes to helping other developers or open source efforts. There are many places to host open source code, each community usually has a particular bias towards one system (.NET langs towards <a href="http://www.codeplex.com/">Codeplex</a>, Python langs towards <a href="https://bitbucket.org/">BitBucket</a>, Ruby and Javascript to <a href="http://github.com/">Github</a>).<img src="http://jamiei.com/blog/wp-content/uploads/2011/03/github-profile-200x300.png" alt="The Github logo" title="github logo" width="200" height="300" class="alignright size-medium wp-image-818" /> The impression I&#8217;ve always gotten is that Open Source Delphi projects tend to veer towards <a href="http://code.google.com/">Google Code</a> and self-hosted solutions (which I&#8217;ve never really understood). I have always preferred <a href="http://github.com/">Github</a> because I like Git, the Github site is very fast and easy to use and because there is a very vibrant community which makes project discovery really easy.</p>
<p>I had hosted my <a href="http://jamiei.com/blog/2010/03/yajl-for-delphi/">Delphi headers for the yajl json library</a> on Github at <a href="https://github.com/jamiei/Delphi-yajl">Delphi-yajl</a>, which were sadly in a broken state as I was unable to solve some of my conversion problems myself. I recently received a <a href="https://github.com/blog/712-pull-requests-2-0">pull request</a> on Github for my project from the ever active Delphi&#8217;er on github <a href="http://www.jasontpenny.com/blog/">Jason T Penny</a>. He very kindly forked my Delphi-yajl repo and submitted a <a href="https://github.com/jamiei/Delphi-yajl/pull/1">set of changes</a> which fixed up my botched conversion job and pushed it back. As a result, I&#8217;m pleased to announce that the <a href="https://github.com/jamiei/Delphi-yajl">Delphi yajl</a> code is in working order and I now plan on adding a higher level wrapper which allows slightly more Delphi-like usage but if you need lightning fast SAX-style json parsing then feel free to try it out. I can imagine that it would be perfect for situations where you need to parse a stream of json, such as if you were streaming the <a href="http://dev.twitter.com/pages/streaming_api">Twitter Streaming API</a>.</p>
<p>He also has some pretty cool other repos on his <a href="https://github.com/jasonpenny">Github profile</a>, including his <a href="https://github.com/libgit2/GitForDelphi">GitForDelphi Project</a>. <a href="https://github.com/libgit2/GitForDelphi">GitForDelphi</a> is a conversion of the <a href="http://libgit2.github.com/">libgit2</a> headers. <a href="http://libgit2.github.com/">libgit2</a> is portable, pure C implementation of the core git methods which allow you to effectively implement git functionality without having to call git command line (much cooler). The Delphi bindings are in a working state already and in order to return the favour, I do plan on helping him out by contributing some tests. I would encourage all Delphi developers to have a hunt around on Github as there are some interesting little gems to be found and it&#8217;s a very cool community to explore. </p>
<h3>Further Reading</h3>
<ul>
<li><a href="http://learn.github.com/p/intro.html">An introduction to Git</a> -The Github introduction to Git.</li>
<li><a href="http://help.github.com/">A Bootcamp guide to Gtihub</a> &#8211; The best guide to getting involved to github.</li>
<li><a href="http://libgit2.github.com">libgit2</a> &#8211; The amazing native linkable implementation of git.</li>
<li><a href="https://github.com/jamiei/Delphi-yajl">Delphi-yajl</a> &#8211; Delphi header translations for yajl</li>
<li><a href="http://lloyd.github.com/yajl/">yajl</a> &#8211; The yajl (Yet Another Json Library) home.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://jamiei.com/blog/2011/03/open-source-and-a-delphi-yajl-update/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>F# for a Delphi Programmer</title>
		<link>http://jamiei.com/blog/2011/02/f-for-a-delphi-programmer/</link>
		<comments>http://jamiei.com/blog/2011/02/f-for-a-delphi-programmer/#comments</comments>
		<pubDate>Thu, 10 Feb 2011 22:21:57 +0000</pubDate>
		<dc:creator>jamiei</dc:creator>
				<category><![CDATA[.NET General]]></category>
		<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Windows Development]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[introduction]]></category>

		<guid isPermaLink="false">http://jamiei.com/blog/?p=637</guid>
		<description><![CDATA[When Visual Studio 2010 was released and it included a large number of great new features, one of which in particular was portrayed as a stealth revolution by an article in The Register: F#. F# is a new .NET based functional programming language which emerged from Microsoft&#8217;s Cambridge Research lab as the primary focus of Don [...]]]></description>
			<content:encoded><![CDATA[<p>When <a href="http://www.microsoft.com/visualstudio/">Visual Studio 2010</a> was released and it included a large number of great new features, one of which in particular was portrayed as a <a href="http://www.theregister.co.uk/2010/04/19/microsoft_f_sharp/">stealth revolution</a> by an article in The Register: F#. F# is a new .NET based functional programming language which emerged from Microsoft&#8217;s Cambridge Research lab as the primary focus of <a href="http://research.microsoft.com/en-us/people/dsyme/">Don Syme</a>. F# is a major new first class .NET language citizen which is now built into the VS2010 product. The language takes a lot of inspiration from <a href="http://www.ocaml-tutorial.org/">OCaml</a>. Anders Hejlsberg recently spoke very encouragingly about it in his <a href="http://channel9.msdn.com/posts/adebruyn/TechDays-2010-Developer-Keynote-by-Anders-Hejlsberg/">Future Trends in Programming languages</a> talk at TechDays in Belgium, which is certainly worth watching if you haven&#8217;t seen it before. I&#8217;ve only been playing with F# for a while but it&#8217;s pretty nice and it&#8217;s certainly worth looking at functional programming if you haven&#8217;t already if only because it&#8217;s an interesting set of new techniques and requires a slightly different approach to problems.</p>
<p><img src="http://blogs.msdn.com/blogfiles/kathleen/WindowsLiveWriter/CreatingYourFirstFProgramwithVisualStudi_1046E/FSharp_1.png" alt="F# in Visual Studio 2010" /></p>
<p>The <a href="http://blogs.msdn.com/b/dsyme/archive/2010/11/04/announcing-the-f-compiler-library-source-code-drop.aspx">F# compiler and libraries</a> were also recently released as Open Source under the Apache 2.0 license which should make for some exciting developments in the future, not to mention better support for Mono.</p>
<p>I also found F# a good way to understand the slightly functional constructs that <a href="http://jamiei.com/blog/2010/06/new-goodies-in-delphi-prism-2011/">appeared in Delphi Prism 2011</a>. I&#8217;ve only just started beginning to learn F# but I thought I would highlight some of the particularly interesting differences that I&#8217;ve found compared to Delphi.</p>
<h3>Identifiers and let bindings</h3>
<p>Identifiers are the way which you assign names to your values so that you can reference them later, using the let keyword. To a Delphi programmer this may sound like the concept of variables, however there is one important difference in F#: Variables are immutable and therefore <em>normally</em> can&#8217;t be changed and once a value has been assigned to it. Consider the following:</p>
<pre class="brush: plain; title: ; notranslate">
open System

let x = 1
printfn &quot;%d&quot; x

let x = 2
printfn &quot;%d&quot; x
</pre>
<p>This will produce a compiler error where we attempt to reassign a new value to the identifier x. F# shares the type inference approach of C# 3.0 onwards so you do not need to explicitly declare the types of your variables as you do in Delphi (while Delphi Prism shares the C# approach). It should also be noted that as in Delphi, you can also assign identifiers to methods. For example, in Delphi you might do something like the following:</p>
<pre class="brush: delphi; title: ; notranslate">
var
  i: integer;
  myAdder: TFunc&lt;integer, integer, integer&gt;;
begin
  myAdder :=
    function(a, b: integer): integer
    begin
      result := a + b;
    end;
  i := myAdder(1, 2);
end;
</pre>
<p>The equivalent F# code might look like this where F# Functions are values in their own right anyway:</p>
<pre class="brush: plain; title: ; notranslate">
// Could also be written in longform as:
// let myAdder = fun a b -&gt; a + b

let myAdder a b = a + b
let i = myAdder 1 2
</pre>
<p>If you&#8217;re coming from Delphi, it is also worth noting that identifier names are case-sensitive.</p>
<h3>Scope</h3>
<p>F# defines scope, by default, using whitespace and indentation creates new scope, and the end of that particular scope is signaled by the end of the indented block. The following example demonstrates this, by reusing the identifier &#8216;z&#8217; as a midway calculation half way through a block.</p>
<pre class="brush: plain; title: ; notranslate">
let z = 1

let y =
    let z = 3 * 2
    z / 2

printfn &quot;%d&quot; y
</pre>
<p>This code also demonstrates that like the <a href="http://www.ruby-lang.org/en/">Ruby language</a>, you do no need to explicitly state a return value for a method. This can be quite freeing in many ways.<br />
It should also be noted that you can redefine identifiers with the <em>let</em> keyword whilst in the scope of a function. </p>
<h3>Pattern Matching</h3>
<p>Another favoured building block for functional programming is pattern matching. A very simple example of this might be compared to series of <strong>case</strong> or <strong>if</strong> statements in Delphi. For example, if we look at an implementation of the FizzBuzz problem in Delphi:</p>
<pre class="brush: delphi; title: ; notranslate">
	// if ((i mod 15 = 0)) then
        if ((i mod 3 = 0) and (i mod 5 = 0)) then
        begin
          WriteLn('FizzBuzz');
        end
        else if (i mod 3 = 0) then
        begin
          WriteLn('Fizz');
        end
        else if (i mod 5 = 0) then
        begin
          WriteLn('Buzz');
        end
        else
        begin
          WriteLn(i);
        end;
      end;
</pre>
<p>And then using pattern matching in F#:</p>
<pre class="brush: plain; title: ; notranslate">
// FizzBuzz Solution - @jamiei
open System

let FizzBuzz() =
    let nums = [1..100]
    let printbuzz x =
        match x with
        // | x when x%15=0 -&gt; printfn(&quot;FizzBuzz&quot;)
        | x when x%3=0 &amp;&amp; x%5=0 -&gt; printfn(&quot;FizzBuzz&quot;)
        | x when x%3=0 -&gt; printfn(&quot;Fizz&quot;)
        | x when x%5=0 -&gt; printfn(&quot;Buzz&quot;)
        | _ -&gt; printfn &quot;%d&quot; x;
    nums |&gt; List.iter(fun x -&gt; printbuzz x)
FizzBuzz()
let _ = Console.ReadLine()
</pre>
<p>Pattern matching must either be complete (i.e. must match all possible values of an identifier) or incomplete and include a wildcard (&#8220;_&#8221; in the above example) or the compiler will raise an exception at runtime. The compiler will also emit a warning for rules which will never be matched.</p>
<pre class="brush: plain; title: ; notranslate">
let rand = new Random()
let randNum = rand.Next(0, 100);
let coinToss =
    match randNum % 2 = 0 with
    | true -&gt; &quot;heads&quot;
    //| false -&gt; &quot;tails&quot;
printfn &quot;%A&quot; coinToss
</pre>
<p>Pattern matching may appear to be a simple tool but it&#8217;s an extremely concise way of controlling the flow of an application, particularly to get rid of what would otherwise turn into a spaghetti ball of if statements. Pattern matching can also be active, which means that they allow you to execute a function to determine the match.</p>
<h3>Units of measurement</h3>
<p>If you were listening carefully to the <a href="http://www.delphi.org">Podcast of Delphi.org</a> when <a href="http://blogs.remobjects.com/blogs/mh">marc hoffman</a> was talking to Jim McKeeth about the future of Delphi Prism, you&#8217;ll remember that he mentioned that this might be coming to Delphi Prism. This represents a pretty nifty way of marking the units of a value which makes you less likely to accidentally make a mistake when combining them with less effort than in Delphi where you would have to declare and create a class for each. The following code in F#, will throw an exception:</p>
<pre class="brush: plain; title: ; notranslate">
[&lt;Measure&gt;]type centimetre
[&lt;Measure&gt;]type inch
let distanceToMyThumb = 1&lt;inch&gt;
let distanceToMyOtherThumb = 2.5&lt;centimetre&gt;
let newVol = distanceToMyThumb + distanceToMyOtherThumb
</pre>
<h3>Summary</h3>
<p>F# is a very expressive language and the more I read and use it, the more I find that the expressions and constructs that it allows give me new ways to think about certain problems. It is also great that it is built upon the .NET Framework and can interact fully with the standard .NET libraries. My F# test modules can also interact with and be interacted by any Delphi Prism applications that I need it to. If your curiosity is piqued by functional programming and you are already familiar with the .NET framework then F# is a great way to try your hands. </p>
<h3> Further Information </h3>
<p>You can find more information on F# here:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/fsharp/default">F# MSDN Home</a></li>
<li><a href="http://fsharpsamples.codeplex.com/">F# Community Samples</a></li>
<li><a href="http://msdn.microsoft.com/en-us/magazine/ee336127.aspx">An Introduction to Functional Programming for .NET Developers</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://jamiei.com/blog/2011/02/f-for-a-delphi-programmer/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Flying with MEF in Delphi Prism</title>
		<link>http://jamiei.com/blog/2010/09/flying-with-mef-in-delphi-prism/</link>
		<comments>http://jamiei.com/blog/2010/09/flying-with-mef-in-delphi-prism/#comments</comments>
		<pubDate>Sun, 05 Sep 2010 21:27:50 +0000</pubDate>
		<dc:creator>jamiei</dc:creator>
				<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Delphi Prism]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[delphi prism]]></category>
		<category><![CDATA[mef]]></category>
		<category><![CDATA[plugins]]></category>

		<guid isPermaLink="false">http://jamiei.com/blog/?p=770</guid>
		<description><![CDATA[The Managed Extensibility Framework (or MEF for short)  has been around the .NET world for a while but I thought I might go through my foray into using MEF with Delphi Prism. MEF is a new library in .NET Framework 4 and Silverlight 4 that addresses the problem of easily extending and componentising applications by [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://mef.codeplex.com/">Managed Extensibility Framework</a> (or MEF for short)  has been around the .NET world for a while but I thought I might go through my foray into using MEF with Delphi Prism.</p>
<p><a href="http://mef.codeplex.com/">MEF</a> is a new library in .NET Framework 4 and Silverlight 4 that addresses the problem of easily extending and componentising applications by providing a nifty framework. Adding an easy ability to extend your application, whether it be for the purposes of componentising your application or allowing others to extend your application has always been available to Delphi users in the guise of frameworks like <a href="http://www.remobjects.com/hydra.aspx">RemObjects Hydra</a>, the <a href="http://www.tmssoftware.com/site/tpf.asp">TMS Plugin Framework</a> or <a href="http://stackoverflow.com/questions/365968/how-best-to-add-plugin-capability-to-a-delphi-program/366626#366626">building your own homebrew solution</a> but MEF is very nice framework.</p>
<p>MEF is incredibly powerful and I&#8217;ll only really be scratching the surface and introducing it here.</p>
<p>Imagine an application which runs a sequential series of processes on an imaginary input file, not exactly rocket science but this is only a basic introduction after all.</p>
<p>First I begin by defining an Interface in a separate assembly which all my plugins will adhere to:</p>
<pre class="brush: delphi; title: ; notranslate">
  IFileAction = public interface
    method ProcessFile(path: String);
    property Name: String read;
    property Version: String read;
  end;
</pre>
<p>We then write our first plugin, which we&#8217;ll conveniently call the <strong>MyHelloPlugin</strong>. First create a new assembly and reference the base plugin assembly which contains our <strong>IFileAction</strong> interface and the <strong>System.ComponentModel.Composition</strong> assembly. We also need to ensure that we reference these in our <strong>uses</strong> clause of the unit containing our Hello Plugin class. The My Hello Plugin class looks like this:</p>
<pre class="brush: delphi; title: ; notranslate">
  [Export(typeof(IFileAction))]
  MyHelloPlugin = public class(IFileAction)
  const
     MYNAME = 'The My Hello Plugin';
     MYVERSION = '1.0.1';
  public
    method ProcessFile(path: String);
    property Name: String read MYNAME;
    property Version: String read MYVERSION;
  end;
</pre>
<p>This should be pretty self explanatory but we have two properties for our name and version and a ProcessFile method which will be called by our host app, providing it with a path for the file that we&#8217;re processing. You&#8217;ll notice the <strong><a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.exportattribute.aspx">Export</a> </strong>attribute which denotes what we&#8217;re exporting. We&#8217;re specifying the type of the export but in many cases you may not even need to do this. MEF has a very powerful <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.exportmetadataattribute.aspx">ExportMetaData</a> system for providing information about what you&#8217;re exporting which is also worth reading up on.</p>
<p>Next, of course, we need to actually consume the plugins in our main application. To manage my collection of plugins, I&#8217;ll create a small, basic class to hold and manage them:</p>
<pre class="brush: delphi; title: ; notranslate">
  PluginList = class
  public
    [ImportMany(typeof(IFileAction))]
    property FileActions: IList&lt;IFileAction&gt; read write;
    constructor;
  end;
</pre>
<p>Here I&#8217;m using the <strong><a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.importmanyattribute.aspx">ImportMany</a></strong> attribute to indicate that I&#8217;m expecting to import many <strong>IFileAction</strong> instances and then providing a list with which to populate (which, as always, you must remember to instantiate before you attempt to fill it!).</p>
<p>Next I&#8217;ll load up my <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.hosting.aspx">Hosting catalog</a> and compose the parts of my application.</p>
<pre class="brush: delphi; title: ; notranslate">
  var aggregateCat := new AggregateCatalog();
  // var catalog := new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly());
  // var catalog := new AssemblyCatalog('plugins\MyHelloPlugin.dll');
  var dirCatalog := new DirectoryCatalog('plugins');

  // Add our Catalogs here,
  aggregateCat.Catalogs.Add(dirCatalog);

  var container := new CompositionContainer(aggregateCat);
  // Create our plugin hosting object
  var pluginList := new PluginList();
  // Compose the parts.
  container.ComposeParts(pluginList);
</pre>
<p>You&#8217;ll note that I create an <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.hosting.aggregatecatalog.aspx">AggregateCatalog</a> which isn&#8217;t strictly necessary in this case because I&#8217;m only adding one <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.primitives.composablepartcatalog.aspx">ComposablePartCatalog</a> to it but in other uses this would also allow me to separately load single Assemblies or a collection of DirectoryCatalog&#8217;s. I then load the catalog into a composition container before creating my aforementioned PluginList class and finally pulling all the parts together. It really is that simple. You can test what has been loaded using our now populated PluginList.FileActions collection, like this:</p>
<pre class="brush: delphi; title: ; notranslate">
  for each plugin: IFileAction in pluginList.FileActions do
  begin
    Console.WriteLine('Loaded ' + plugin.Name + ', version ' + plugin.Version);
  end;
</pre>
<p>You can now create a new and entirely different plugin assembly (or many, many more) and providing it conforms to our <strong>IFileAction</strong> interface and is either in our target directory or loaded manually, it will now appear in our list as if by magic.</p>
<p>Once you&#8217;ve begun using MEF, you&#8217;ll find out how powerful it can be and how easy it makes building modular applications.</p>
<p>If anyone is interested in me uploading the complete project set for this sample then please let me know in the comments below and I can upload it to github. If anyone else has any excellent samples of MEF usage that they can publish we could even start a sample repository.</p>
<h4>Further Reading</h4>
<ul>
<li><a href="http://mef.codeplex.com/wikipage?title=Architecture&amp;referringTitle=Documentation">The MEF Architecture Overview</a></li>
<li><a href="http://mef.codeplex.com/wikipage?title=Guide&amp;referringTitle=Documentation">The MEF Programming Guide</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.aspx">The MSDN System.ComponentModel.Composition Guide</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://jamiei.com/blog/2010/09/flying-with-mef-in-delphi-prism/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Time to get the Delphi community back</title>
		<link>http://jamiei.com/blog/2010/08/time-to-get-the-delphi-community-back/</link>
		<comments>http://jamiei.com/blog/2010/08/time-to-get-the-delphi-community-back/#comments</comments>
		<pubDate>Tue, 17 Aug 2010 19:29:06 +0000</pubDate>
		<dc:creator>jamiei</dc:creator>
				<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://jamiei.com/blog/?p=745</guid>
		<description><![CDATA[I&#8217;ve been a long time lurker and enjoyer of reddit. I find that the content post to proggit is much much better than that posted to similar services. One element of programming.reddit that has always made me quite sad is the apparent lack of fresh Delphi content submitted. I recently started trying to post more content [...]]]></description>
			<content:encoded><![CDATA[<p><span style="font-weight: normal;">I&#8217;ve been a long time lurker and enjoyer of <a href="http://www.reddit.com">reddit</a>. I find that the content post to <a href="http://programming.reddit.com">proggit</a> is much much better than that posted to <a href="http://www.digg.com">similar services</a>. One element of programming.reddit that has always made me quite sad is the apparent lack of <a href="http://www.reddit.com/search?q=delphi&amp;restrict_sr=off&amp;sort=relevance">fresh Delphi content</a> submitted. I recently started trying to post more content and encourage more discussion on the <a href="http://delphi.reddit.com">Delphi.subreddit</a> which could benefit with a little activity.</span></p>
<p style="text-align: center;"><img class="aligncenter" title="Reddit.com" src="http://thatwasthenmusic.com/wp-content/comment-image/917.jpg" alt="Reddit.com" width="600" height="783" /></p>
<p>I still believe that participating in these communities and making visible &#8220;noise&#8221; does credit to the delphi community. Some of you may remember that I extolled the virtues of this point just over a year ago in another post, <a href="http://jamiei.com/blog/2009/07/the-delphi-community-from-the-outside/">The Delphi Community: From the outside</a>.</p>
<p>This is all particularly relevant in a month when, the largest community gathering, <a href="https://forums.codegear.com/forum.jspa?forumID=67">delphi.non-technical</a> has been filled to the brim with little which might give a potential newcomer to the community any kind of welcome feeling what-so-ever. Also this month a set of <a href="http://www.r-chart.com/2010/08/github-stats-on-programming-languages.html">stats generated</a> from the <a href="http://github.com">GitHub</a> API showed that Delphi was the 39th largest language on there, another online property that I advocated our further involvement with. Without saying that we should be <em>much</em> higher, I would say that I would like to see more Open Source Delphi projects on there. We could also do with more of a vocal presence in many <a href="http://langpop.com/">other areas too</a> but I guess this requires organic community growth (allbeit slightly prompted).</p>
<p>The recently unveiled previews of <a href="http://www.embarcadero.com/rad-studio-xe-preview">RAD Studio XE</a> may not be the cross-platform upgrade that some people hoped it would be, it does represent the next product version of the Delphi we know and love. If what the Embarcadero staff are saying in the newsgroups of the quality this release is true then it will be a worthy addition to the family (if not as groundbreaking as we&#8217;d originally hoped). Indeed I liked the look of the new <a href="http://blog.marcocantu.com/blog/delphi_xe_second_video.html">integrated tools for the Delphi IDE</a> revealed today and will await the next previews but even if that isn&#8217;t your cup of tea it still leaves plenty to shout about.</p>
<p>What I&#8217;m advocating is that we retain a little perspective and focus on what <strong>is</strong> in the Delphi XE release and not what <strong>isn&#8217;t</strong> and use this as a conversation starting point to start making more noise about Delphi in &#8220;public places&#8221; with a view to reinvigorating the community. Which reminds me: what other communities/online properties could the Delphi community benefit from making better use of?</p>
<p><em>In other news: I&#8217;ve also got what I consider to be an exciting Delphi community based side-project which you may all potentially get to see very soon&#8230;</em></p>
]]></content:encoded>
			<wfw:commentRss>http://jamiei.com/blog/2010/08/time-to-get-the-delphi-community-back/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>New Goodies in Delphi Prism 2011</title>
		<link>http://jamiei.com/blog/2010/06/new-goodies-in-delphi-prism-2011/</link>
		<comments>http://jamiei.com/blog/2010/06/new-goodies-in-delphi-prism-2011/#comments</comments>
		<pubDate>Tue, 08 Jun 2010 09:00:23 +0000</pubDate>
		<dc:creator>jamiei</dc:creator>
				<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Delphi Prism]]></category>
		<category><![CDATA[2011]]></category>
		<category><![CDATA[delphi prism]]></category>
		<category><![CDATA[new]]></category>

		<guid isPermaLink="false">http://jamiei.com/blog/?p=692</guid>
		<description><![CDATA[As the announcements have recently proclaimed: Delphi Prism 2011 is out now and the Software Assurance emails went out particularly quickly after the announcements (great work team embarcadero!). I thought I might share what I&#8217;ve found to be new and cool in the Delphi 2011 Release. Visual Studio 2010 Support I&#8217;ll start with the most obvious [...]]]></description>
			<content:encoded><![CDATA[<p>As the announcements have recently proclaimed: <a href="http://www.embarcadero.com/press-releases/embarcadero-extends-cross-platform-capabilities-for-_net-development-with-delphi-prism-2011">Delphi Prism 2011 is out now</a> and the Software Assurance emails went out particularly quickly after the announcements (great work team embarcadero!). I thought I might share what I&#8217;ve found to be <a href="http://prismwiki.codegear.com/en/New_Features">new and cool</a> in the Delphi 2011 Release.</p>
<h4>Visual Studio 2010 Support</h4>
<p>I&#8217;ll start with the most obvious change: Delphi Prism now supports Visual Studio 2010 which was only released just over a month ago. The Visual Studio 2010 IDE looks great, feels faster than 2008 and most importantly, in my experience, is very stable.</p>
<div id="attachment_701" class="wp-caption aligncenter" style="width: 310px"><a href="http://jamiei.com/blog/wp-content/uploads/2010/06/DelphiPrismInVS20102.png"><img class="size-medium wp-image-701" title="Delphi Prism in VS2010" src="http://jamiei.com/blog/wp-content/uploads/2010/06/DelphiPrismInVS20102-300x174.png" alt="" width="300" height="174" /></a><p class="wp-caption-text">Visual Studio 2010 with Delphi Prism</p></div>
<p>The shell is based on WPF and has had considerable work put into allowing it to be flexible and extensible which I understand has allowed a whole host of new <a href="http://visualstudiogallery.msdn.microsoft.com/en-us/">plugins</a> to flourish. It&#8217;s an extremely minor point but I&#8217;ve also found it much better in allowing themes for the code editor, springing forth sites like <a href="http://studiostyles.info/">http://studiostyles.info/</a>. My favourite scheme  is <a href="http://studiostyles.info/schemes/son-of-obsidian">Son of Obsidian</a> which works marvellously for C# code and works reasonably well for Delphi Prism code too. It&#8217;s great that we can take advantage of community extras like this, although it would also be great if we could tailor some of these themes specifically for Delphi Prism.</p>
<p>As marc mentioned back on <a href="http://www.delphi.org/2010/03/39-marc-hoffman-on-prism-and-mac/">episode #39</a> of the <a href="http://www.delphi.org/">Podcast at Delphi</a> there are a lot of <em>free</em> minor improvements that come with moving to Visual Studio 2010 (not financially free but that were inherent with the migration).</p>
<p>Other cool stuff includes support for Silverlight 4 and the &#8220;<a href="http://prismwiki.codegear.com/en/Paste_CSharp_as_Oxygene">Paste C# as Oxygene</a>&#8221; feature which allows you to translate code snippets on the fly. This release also includes <a href="http://prismwiki.codegear.com/en/IDE_Integration_(MonoDevelop)">MonoDevelop</a> which includes support for Mac and Windows.</p>
<h4>For, If and Case Expressions</h4>
<p>For, if and case I hear you say? Haven&#8217;t we had those for as long as we can remember? Not like this we haven&#8217;t. Delphi Prism now supports them as <em>expressions</em>. This allows you to do operations like this:</p>
<pre class="brush: delphi; title: ; notranslate">
  var sourceList: Array of Integer := [1 ,2 ,4 ,8 ,16 ,32 ,64 ,128];
  var sqList := for each num in sourceList yield num * num;
</pre>
<p>Now this sample could just as easily be done with a LINQ operation or a separate loop but this is another option available at your disposal and introduces a slightly Functional Programming feel. Delphi Prism now also supports If expressions and my favourite expression addition: case.</p>
<p>These expressions, as with so many language features hold the potential for misuse but they can also make things a little more concise:</p>
<pre class="brush: delphi; title: ; notranslate">
method NotifierStr(newMails: integer): string;
begin
  result := 'You have ' + newMails.ToString() + ' new ' +
    case newMails of
      0: 'emails';
      1: 'email';
    else
      'emails';
    end;
end;
</pre>
<p>Please forgive the horrible string concatenation but I wanted to demonstrate it in this way because I thought it might help make it a little clearer.</p>
<h4>Dynamic</h4>
<p>Delphi Prism 2011 includes support for the (in some cases) contraversial <a href="http://msdn.microsoft.com/en-us/library/dd264736.aspx">.NET 4 dynamic type</a>. To quote <a href="http://www.hanselman.com/blog/CommentView.aspx?guid=43d88b49-93f6-4c03-a0ed-062b0aa1a348">Scott Hanselman on dynamics</a>: A dynamic is a statically typed dynamic type. Dynamics leave a lot more till run-time and allow a much cleaner interop with the Dynamic Scripting languages built upon the CLR.</p>
<p>For example, the <a href="http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject(v=VS.100).aspx">ExpandoObject</a> enables you to add and delete members at runtime, something might be useful when serialising and deserialising JSON or XML where you do not know the spec ahead of time:</p>
<pre class="brush: delphi; title: ; notranslate">
dynamic tweetresult := new ExpandoObject();
tweetresult.Id = 1243535345;
tweetresult.Username = 'delphifeeds';
</pre>
<p>The Delphi Prism 2011 implementation has a required dependency upon a separate assembly, <em>RemObjects.Oxygene.Dynamic.dll</em>, which is freely re-distributable.</p>
<p>For a much better idea of what dynamics are and can be used for, I would refer you to Scott Hanselman&#8217;s <a href="http://www.hanselman.com/blog/CommentView.aspx?guid=43d88b49-93f6-4c03-a0ed-062b0aa1a348">whirlwind tour of dynamics</a> and the MSDN reference on <a href="http://msdn.microsoft.com/en-us/library/dd264736.aspx">using dynamics</a>.</p>
<h4>Tail Calls</h4>
<p><a href="http://prismwiki.codegear.com/en/Tail_Calls">Tail Calls</a> are another feature that could be seen as similar to a Functional Programming Language construct. They are essentially an exit statement followed by a call to a method. They have to be explicitly enabled and disabled for a method using the <em>{$TAILCALL ON}</em> flag. This allows you to code recursive functions, particularly useful for maths based methods. This concept will probably take a bit of getting used to and are something I&#8217;d like to cover in subsequent posts.</p>
<h4>Tuples</h4>
<p>A <a href="http://msdn.microsoft.com/en-us/library/system.tuple.aspx">Tuple</a> is an ordered list of Elements. They can contain 1 to 7 different references and types with an 8th reference being used to reference another Tuple if you need to hold more than 7. They are similar to an array and a class/record but unlike an array can contain more than one type and require considerably less declaration than a class/record. A <a href="http://prismwiki.codegear.com/en/Tuples">Tuple in Delphi Prism</a> might be used as follows:</p>
<pre class="brush: delphi; title: ; notranslate">
  var telephoneList := new Dictionary&lt;Tuple&lt;string, integer&gt;, String&gt;();
  telephoneList.Add(Tuple.Create('Josh Moore', 1283843), '+0014158343131');
  Console.WriteLine(telephoneList[Tuple.Create('Josh Moore', 1283843)]);
</pre>
<p>They are particularly useful for returning more than one value from a method where you would otherwise need to explicitly declare a class or record to hold the data otherwise. Tuples are a good way to solve a specific problem and will be more familiar to those who have used them in other languages such as the <a href="http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences">Tuple support in Python</a>.</p>
<h4>Parallel Loops (not actually a new feature)</h4>
<p>Parallel loops have been a part of the Delphi Prism (and formerly Oxygene) language for a long, long time. However what I hadn&#8217;t appreciated was that the Parallel Task Library upon which it relied was officially bundled into the <a href="http://blogs.msdn.com/b/pfxteam/archive/2008/10/10/8994927.aspx">.NET 4.0 Framework</a> libraries. As such I felt it necessary to re-raise it and show just how nifty it is here even though it isn&#8217;t really new to Delphi Prism 2011.</p>
<p>Just to recap, with the <strong>parallel </strong>keyword you can parallelise a loop.</p>
<p>As a fully fledged .NET 4 language we can also use the <a href="http://msdn.microsoft.com/en-us/library/system.linq.parallelenumerable.asparallel.aspx">AsParallel</a>() method in order to return a <a href="http://msdn.microsoft.com/en-us/library/system.linq.parallelenumerable.aspx">ParallelEnumerable</a> source capable of being queried with the .NET <a href="http://msdn.microsoft.com/en-us/library/dd460688.aspx">Parallel LINQ library</a>.</p>
<p>The rough and ready example below demonstrate these two techniques:</p>
<pre class="brush: delphi; title: ; notranslate">
class method ConsoleApp.Main(args: array of string);
begin
  var anagramletters := 'mite';
  var filepath := 'mydictionary.txt';

  var dictList := new List&lt;string&gt;();
  dictList.AddRange(System.IO.File.ReadAllLines(filepath));
  Console.WriteLine('Added ' + dictList.Count + ' lines to the file');

  var sortedList := new Dictionary&lt;string, string&gt;();

  for parallel i: Integer := 0 to dictList.Count - 1 do
  begin
    sortedList[dictList.Item[i]] := dictList[i].Sort();
  end;

  var matchingwords := sortedList.AsParallel().Where(w -&gt; ((w.Value.Length = anagramletters.Length) and (w.Value = anagramletters.Sort()))).Select(w -&gt; w.Key);

  Console.WriteLine('Found: ' + matchingwords.Count().ToString() + ' results');
  matchingwords.ToList().ForEach(x -&gt; Console.WriteLine(x));

  Console.ReadLine;

end;
</pre>
<p>The code above reads a dictionary file in and then builds an index using a parallel loop before finding the words that are anagrams of the provided string using a <a href="http://msdn.microsoft.com/en-us/library/dd460688.aspx">Parallel LINQ</a> query.</p>
<h4>Extension Methods</h4>
<p>I consider it a slightly more minor point as I&#8217;ve already briefly <a href="http://jamiei.com/blog/2010/03/delphi-prism-and-the-microsoft-rx-framework/">talked about</a> the new method of defining <a href="http://prismwiki.codegear.com/en/Extension_Methods_(Writing)">Extension Methods</a>, but this is now baked into Delphi Prism 2011 and is a pretty useful tool to have. I used the new Extension Methods syntax in the Parallel Example above to add an implementation specific <em>Sort()</em> method to my strings like so:</p>
<pre class="brush: delphi; title: ; notranslate">
interface

extension method String.Sort : String;

implementation

extension method String.Sort : String;
begin
  var c := self.ToCharArray();
  Array.Sort(c);
  result := new string(c);
end;
</pre>
<h4>Summary</h4>
<p>Overall Delphi Prism 2011 is a pretty significant release and contains lots of new features that represent a lot of interesting new potential both on the language side and the IDE side, congratulations to the RemObjects team.</p>
<h4>Further Reading</h4>
<ul>
<li><a href="http://www.embarcadero.com/products/delphi-prism/whats-new">What&#8217;s new in Delphi Prism 2011</a> &#8211; The Official Embarcadero page.</li>
<li><a href="http://prismwiki.codegear.com/en/New_Features">New Features</a> &#8211; The Delphi Prism Documentation Wiki page listing newly added features.</li>
<li><a href="http://edn.embarcadero.com/article/40579">Delphi Prism 2011 Release Notes</a> &#8211; Is what it says on the tin.</li>
<li><a href="http://msdn.microsoft.com/en-us/library/dd264736.aspx">Using Type dynamic in .NET 4.0</a> &#8211; MSDN reference on the dynamic type.</li>
<li><a href="http://stackoverflow.com/questions/33923/what-is-tail-recursion">What is tail-recusion</a> &#8211; StackOverflow answer on Tail Recursion which might help you to better understand Tail Calls in Delphi Prism.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://jamiei.com/blog/2010/06/new-goodies-in-delphi-prism-2011/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Converting C headers is hard &#8211; yajl for Delphi</title>
		<link>http://jamiei.com/blog/2010/03/yajl-for-delphi/</link>
		<comments>http://jamiei.com/blog/2010/03/yajl-for-delphi/#comments</comments>
		<pubDate>Wed, 31 Mar 2010 20:40:13 +0000</pubDate>
		<dc:creator>jamiei</dc:creator>
				<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Windows Development]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[native library]]></category>
		<category><![CDATA[yajl]]></category>

		<guid isPermaLink="false">http://jamiei.com/blog/?p=575</guid>
		<description><![CDATA[Introduction I have been toying with the idea of trying to convert the yajl parser bindings to Delphi in order to build a wrapper on top of the original C dll. yajl (Yet Another JSON Library) is a small fast SAX style JSON parser written and open sourced in C over at lloyd&#8217;s yajl GitHub [...]]]></description>
			<content:encoded><![CDATA[<h4>Introduction</h4>
<p>I have been toying with the idea of trying to convert the <a href="http://lloyd.github.com/yajl/">yajl</a> parser bindings to Delphi in order to build a wrapper on top of the original C dll. <a href="http://lloyd.github.com/yajl/">yajl</a> (Yet Another JSON Library) is a small fast SAX style <a href="http://www.json.org/">JSON</a> parser written and open sourced in C over at <a href="http://github.com/lloyd/yajl">lloyd&#8217;s yajl GitHub</a> page. I wanted to be able to use this library in particular because it&#8217;s very fast, small, portable and able parse from a stream. Plus, I had never really done any conversion of this nature on C header files before so I thought it might be a small, easy project to start with&#8230; I was a perhaps a little naive on this front!</p>
<p>I&#8217;ll leave you with a disclaimer early on: the code that I&#8217;ve been working on and have shared is not currently in a working state. This is the first part of my journey and I do intend on posting further as I learn from the major mistakes that I make in the process.</p>
<h4>Approach</h4>
<p>The 3 header files that I need to translate can be found in the <a href="http://github.com/lloyd/yajl/tree/master/src/api/">src/api</a> directory:</p>
<ul>
<li><a href="http://github.com/lloyd/yajl/blob/master/src/api/yajl_common.h">yajl_common.h</a></li>
<li><a href="http://github.com/lloyd/yajl/blob/master/src/api/yajl_gen.h">yajl_gen.h</a></li>
<li><a href="http://github.com/lloyd/yajl/blob/master/src/api/yajl_parse.h">yajl_parse.h</a></li>
</ul>
<p>I&#8217;m not sure what a *typical* process for conversion might look like but I started out by trying to use Dr Bob&#8217;s <a href="http://www.drbob42.com/delphi/headconv.htm">HeadConv</a> tool as a way of getting me started and doing some of the legwork. However, the callback structure used by the parsing callbacks confused the tool and it never produced anything of use. After this setback I tried to install <a href="http://rvelthuis.de/">Rudy Velthuis</a>&#8216;s <a href="http://rvelthuis.de/programs/convertpack.html">Conversion Helper Tool</a> but I wasn&#8217;t able to load this into the Delphi 2009 IDE.</p>
<p>Having failed to get any of the conversion tools to do any of the work for me, I accepted my task and began to convert the headers from scratch. There were two resources that I found invaluable: the first is the Type Conversion table half way down the page on Dr Bob&#8217;s <a href="http://www.drbob42.com/headconv/index.htm">HeadConv page</a>.  The second was the comprehensive <a href="http://rvelthuis.de/articles/articles-convert.html">Pitfalls of Conversion</a> guide from Rudy.</p>
<p>As I began converting the headers I realised that although I thought I was translating the headers without a problem, <strong>the devil is in the detail</strong> and as my first major conversion project, I didn&#8217;t have the specfic knowledge necessary to correct my specific mistakes. As a result, please correct me if I have misunderstood any bits which I have picked up in the process.</p>
<h5><strong>Const parameters</strong></h5>
<p>One issue that I did notice is that there were quite a few parameters marked const in the header files, such as this declaration in <strong>yajl_parse</strong>:</p>
<pre class="brush: cpp; title: ; notranslate">
   YAJL_API unsigned char * yajl_get_error(yajl_handle hand, int verbose,
                                            const unsigned char * jsonText,
                                            unsigned int jsonTextLength);
</pre>
<p>Rudy&#8217;s guide states that where possible Delphi programmers should <a href="http://rvelthuis.de/articles/articles-convert.html#constparams">ignore the const</a> declaration as it&#8217;s easy to get wrong depending on whether the argument is passed by value or by reference, complicated by the issue that it means something subtly different in C. I translated this heading and simply ignored the const keyword:</p>
<pre class="brush: delphi; title: ; notranslate">
    Tyajl_get_error = function(handle: yajl_handle;
                               verbose: integer;
                               jsonText: PChar;
                               jsonTextLegnth: Cardinal): PChar; stdcall;
</pre>
<h5><strong>Multiple Indirection Parameters</strong></h5>
<p>There was one declaration that I had to do a bit of searching for: it was in the <strong>yajl_gen</strong> file, in the declaration of <strong>yajl_gen_get_buf</strong> function:</p>
<pre class="brush: cpp; title: ; notranslate">YAJL_API yajl_gen_status yajl_gen_get_buf(yajl_gen hand,
                                              const unsigned char ** buf,
                                             unsigned int * len);</pre>
<p>I had never seen the double asterisk before and found it surprisingly difficult to reliably Google for it. Luckily, this comprehensive page on <a href="http://boredzo.org/pointers/">C pointers</a> was pretty useful in explaining that it is in fact a technique called <a href="http://boredzo.org/pointers/#multiple_indirection">multiple indirection</a> which essentially creates a pointer to a pointer, in this case to a char.</p>
<pre class="brush: delphi; title: ; notranslate">
    Tyajl_gen_get_buf = function (handle: Tyajl_gen;
                                 out buf: PChar;
                                 out len: Cardinal): yajl_gen_status; stdcall;
</pre>
<p>I wasn&#8217;t sure if this was indeed the correct translation but if you know otherwise then please let me know in the comments below.</p>
<h5><strong>Record Alignment and Enum size</strong></h5>
<p>When reading up on the perils of record alignment and enum sizes I found this blog post from Vlad loan Topan on <a href="http://vtopan.wordpress.com/2009/03/10/translating-headers-struct-record-field-alignment-in-c-delphi/">Record Alignment and Enum sizes</a>. Both problems are potentially applicable to the yajl header files. In his post, Vlad mentions that in order to line up the enum sizes you will need to use the {Z4} compiler directive to change the size from the Delphi default of 1 to the C compatible 4 as so:</p>
<pre class="brush: delphi; title: ; notranslate">
type
  {$Z4}
  yajl_status = (
                  // no error was encountered
                  yajl_status_ok,
                  // a client callback returned zero, stopping the parse
                  yajl_status_client_canceled,
  ... snip ...
</pre>
<p>Reading through the <a href="http://rvelthuis.de/articles/articles-convert.html#aligns">Record alignment</a> section of Rudy&#8217;s article I understood that I needed to search through the yajl project source to look for an Alignment setting. However, I couldn&#8217;t find a reference to the pragma directive anywhere in  the  source.</p>
<h4>Next Steps</h4>
<p>Well, it doesn&#8217;t actually work yet but I have put the <a href="http://github.com/jamiei/Delphi-yajl">Delphi-yajl</a> project on GitHub where you can view my efforts so far, fork it and hopefully provide feedback or code contributions to show me where I&#8217;m going wrong. I have also setup a <a href="http://jamiei.com/blog/code/delphi-yajl/">Delphi-yajl</a> page here to serve as a placeholder for when it actually works!</p>
<h4>Futher Reading</h4>
<ul>
<li><a href="http://lloyd.github.com/yajl/">yajl</a> &#8211; The yajl project home page.</li>
<li><a href="http://www.drbob42.com/delphi/headconv.htm">Dr Bob&#8217;s Header Conversion Tool</a> &#8211; The useful tool from the ever excellent Dr Bob.</li>
<li><a href="http://rvelthuis.de/articles/articles-convert.html">The Pitfalls of Conversion</a> &#8211; Rudy Velthuis&#8217;s long but excellent article on commonly encountered problems when converting</li>
<li><a href="http://rvelthuis.de/programs/convertpack.html">Conversion Helper Package</a> &#8211; The Conversion package helper from Rudy but I&#8217;m uncertain as to how compatible it is any more.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://jamiei.com/blog/2010/03/yajl-for-delphi/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Delphi Prism and the Microsoft Rx Framework</title>
		<link>http://jamiei.com/blog/2010/03/delphi-prism-and-the-microsoft-rx-framework/</link>
		<comments>http://jamiei.com/blog/2010/03/delphi-prism-and-the-microsoft-rx-framework/#comments</comments>
		<pubDate>Sat, 20 Mar 2010 16:01:58 +0000</pubDate>
		<dc:creator>jamiei</dc:creator>
				<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Delphi Prism]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[delphi prism]]></category>
		<category><![CDATA[reactive]]></category>
		<category><![CDATA[rx]]></category>

		<guid isPermaLink="false">http://jamiei.com/blog/?p=537</guid>
		<description><![CDATA[It&#8217;s very easy to overlook the fact that Delphi Prism fully supports .NET 3.5 and parts of .NET 4 and with it, the amazing range of Frameworks and Libraries that the .NET eco-system contains. One such framework that I&#8217;ve been waiting to get working with is the Microsoft Reactive Extensions for .NET (aka Rx Framework). [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s very easy to overlook the fact that Delphi Prism fully supports .NET 3.5 and parts of .NET 4 and with it, the amazing range of Frameworks and Libraries that the .NET eco-system contains. One such framework that I&#8217;ve been waiting to get working with is the <a href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx">Microsoft Reactive Extensions</a> for .NET (aka Rx Framework).</p>
<h3>So what is the Rx Framework?</h3>
<p>It&#8217;s a framework for asynchronous programming from Microsoft Research (including <a href="http://research.microsoft.com/en-us/um/people/emeijer/">Erik Meijer</a> &amp; <a href="http://blogs.msdn.com/wesdyer/">Wes Dyer</a> amongst others) which could potentially be para-phrased as LINQ to Events. The basic problem is that Asynchronous programming is hard, the exacerbating issue for this problem is that it is entirely necessary for modern development. It is pretty common for Desktop applications to need to chain a series of events together with the correct order and sometimes correct time but doing so at present can land you in a spaghetti-like sea of event callbacks. Enter the <a href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx">Microsoft Rx Framework</a>.</p>
<h3>What do I need?</h3>
<p>The Framework requires a minimum .NET Framework version of .NET 3.5 SP1 or .NET 4 but <a href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx">downloads for both</a> versions are available on the Microsoft Research site. I couldn&#8217;t work out why but Delphi Prism appears to have a problem with the Libraries use of Extension Methods but this issue appears to be fixed in the latest Beta of Delphi Prism. I now suspect it might have started working as a result of the updated support for <a href="http://blogs.remobjects.com/blogs/mh/2010/02/17/p1086">Extension methods</a> which <a href="http://blogs.remobjects.com/blogs/mh/">marc hoffman</a> recently posted about.</p>
<h3>How does it work?</h3>
<p>In Brief: The Rx Framework introduces a of a pair of interfaces, the <a href="http://msdn.microsoft.com/en-us/library/dd783449(VS.100).aspx">IObserver</a> &amp; <a href="http://msdn.microsoft.com/en-us/library/dd990377(VS.100).aspx">IObservable</a>, which allow you to represent push-based observable collections, along with a library of extension methods (the bit that wasn&#8217;t previously working in Delphi Prims) that implement the Standard LINQ Query Operators.</p>
<h3>And&#8230;</h3>
<p>I always find that the easiest way to understand it is to view some examples. First you&#8217;ll need to make sure reference the <strong>System.CoreEx</strong> and <strong>System.Reactive</strong> assemblies.</p>
<p>As with always, we&#8217;ll start with an entirely useless example just to demonstrate a basic example which uses an Observable Timespan interval to print out a number which doubles every 2 seconds:</p>
<pre class="brush: delphi; highlight: [5,6]; title: ; notranslate">
class method ConsoleApp.Main(args: array of string);
begin
  var oneNumberPerSecond := Observable.Interval(TimeSpan.FromSeconds(2));

  var numbersTimesTwo := from n in oneNumberPerSecond
                        select n * 2;

  Console.WriteLine('Numbers * 2:');

  numbersTimesTwo.Subscribe(num -&gt; begin Console.WriteLine(num) end);

  Console.ReadKey();
end;
</pre>
<p>Clearly, this is a contrived example but I think this hints at a few of the more powerful features and versatility of the Rx Framework. The first thing to note is that this is an Asynchronous process, imagine the same code using the standard .NET <a href="http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx">Timer</a> class. This is a demonstration of the power of the Observable Interfaces and how it can allow standard interfaces to concepts that would otherwise complicate our code such time windows to be easily expressed. The second lines to notice is the highlighted LINQ To Events code on lines 5 and 6 which show how easily you can filter specific events from any events. This is a truly powerful and important concept because it is fairly common to generate a stream of events, only some of which we want to react to and the Linq extensions allow us to express this in a succinct way.</p>
<p>This is only a basic console application but it&#8217;s not hard to imagine how this could make the complex ordering and timing of GUI events in many applications much easier. As another example I have translated the C# <a href="http://rxwiki.wikidot.com/101samples#toc39">ISubject ping pong</a> example which mimics the classic <a href="http://www.scala-lang.org/node/242">Ping Pong Actor example</a> that the <a href="http://www.scala-lang.org/">Scala</a> folks get so excited about.</p>
<p>First of all the Ping ISubject and Pong ISubject classes:</p>
<pre class="brush: delphi; collapse: true; light: false; title: ; toolbar: true; notranslate">
namespace PingPongExample;

interface

uses
  System.Collections.Generic,
  System.Linq,
  System.Text;

type
  Pong = public class (ISubject&lt;Ping, Pong&gt;)
  private
  protected
  public
    method OnError(exception: System.Exception);
    method OnCompleted;
    method Dispose;
    method Subscribe(observer: System.IObserver&lt;PingPongExample.Pong&gt;): System.IDisposable;
    method OnNext(value: PingPongExample.Ping);
  end;

implementation

method Pong.Dispose;
begin
  OnCompleted();
end;

method Pong.OnCompleted;
begin
  Console.WriteLine('Pong finished Ponging');
end;

method Pong.OnError(exception: System.Exception);
begin
  Console.WriteLine('Exception');
end;

method Pong.OnNext(value: PingPongExample.Ping);
begin
  Console.WriteLine('Pong received Ping..');
end;

method Pong.Subscribe(observer: System.IObserver&lt;PingPongExample.Pong&gt;): System.IDisposable;
begin
  result := Observable.Interval(TimeSpan.FromSeconds(2.5))
                .Where(n -&gt; n &lt; 10)
                .Select(n -&gt; Self)
                .Subscribe(observer);
end;

end.
</pre>
<pre class="brush: delphi; collapse: true; light: false; title: ; toolbar: true; notranslate">
namespace PingPongExample;

interface

uses
  System.Collections.Generic,
  System.Linq,
  System.Text;

type
  Ping = public class (ISubject&lt;Pong, Ping&gt;)
  private
  protected
  public
    method OnNext(value: Pong);
    method OnError(error: Exception);
    method OnFinished;
    method Subscribe(observer: System.IObserver&lt;PingPongExample.Ping&gt;): System.IDisposable;
    method OnCompleted;
    method Dispose;
  end;

implementation

method Ping.OnNext(value: Pong);
begin
  Console.WriteLine('Ping received Pong..');
end;

method Ping.OnError(error: Exception);
begin
  Console.WriteLine('Exception');
end;

method Ping.OnFinished;
begin
  Console.WriteLine('Completed Ping Ponging');
end;

method Ping.Dispose;
begin
  OnFinished();
end;

method Ping.OnCompleted;
begin

end;

method Ping.Subscribe(observer: System.IObserver&lt;PingPongExample.Ping&gt;): System.IDisposable;
begin
  result := Observable.Interval(TimeSpan.FromSeconds(2))
                .Where(n -&gt; n &lt; 10)
                .Select(n -&gt; Self)
                .Subscribe(observer);
end;

end.
</pre>
<p>And then our setup code:</p>
<pre class="brush: delphi; title: ; notranslate">
class method ConsoleApp.Main(args: array of string);
begin
  var ping := new Ping();
  var pong := new Pong();

  Console.WriteLine('Any key to stop..');

  var pingSubscription := ping.Subscribe(pong);
  var pongSubscription := pong.Subscribe(ping);

  Console.ReadKey();

  pongSubscription.Dispose();
  pingSubscription.Dispose();

  Console.WriteLine('Ping Pong Completed..');
end;
</pre>
<p>You can embrace <a href="http://msdn.microsoft.com/en-us/library/dd990377(VS.100).aspx">IObservable</a> in your own business objects quite easily and begin pushing events throughout your application asynchronously:</p>
<pre class="brush: delphi; highlight: [23]; title: ; notranslate">
type
  Invoice = class

  private
    paidDate: DateTime;
    paidSubject: Subject&lt;Invoice&gt;;
  public
    constructor;
    method MarkPaid(paidDate: DateTime);
    property Paid: IObservable&lt;Invoice&gt; read paidSubject.Hide();
  end;

  ConsoleApp = class
  public
    class method Main(args: array of string);
  end;

implementation

class method ConsoleApp.Main(args: array of string);
begin
  var myInvoice := new Invoice();
  myInvoice.Paid.Subscribe(n -&gt; Console.WriteLine('Paid'));
  myInvoice.MarkPaid(DateTime.Now);
  Console.ReadLine();
end;

constructor Invoice;
begin
  Self.paidSubject := new Subject&lt;Invoice&gt;;
end;

method Invoice.MarkPaid(paidDate: DateTime);
begin
  Self.paidDate := paidDate;
  Self.paidSubject.OnNext(Self);
end;
</pre>
<p>It&#8217;s true that the examples above can be replicated quite easily without using the Rx Framework but within a short time of experimenting with the Rx Framework, I would hope that you should be able to see that it allows asynchronous event handling patterns to be expressed in a standard and more expressive manner.</p>
<p>I realise that this post is a little short on more practical examples but in my next post I&#8217;ll expand on some slightly more practical examples and some examples which demonstrate the Frameworks Power in handling GUI events in WPF Applications. It is also worth noting that the Rx Team recently released the <a href="http://go.microsoft.com/fwlink/?LinkId=182999">RxJs framework</a> which brings the Reactive Programming environment to Javascript.</p>
<h3>Further Reading</h3>
<p>For further information I would recommend:</p>
<ul>
<li><a href="http://rxwiki.wikidot.com/">The Rx Wiki</a></li>
<li><a href="http://blogs.msdn.com/wesdyer/archive/2009/11/18/a-brief-introduction-to-the-reactive-extensions-for-net-rx.aspx">Wes Dyer&#8217;s introduction to the Rx Framework</a></li>
<li><a href="http://channel9.msdn.com/posts/J.Van.Gogh/Reactive-Extensions-API-in-depth-marble-diagrams-select--where/">Wes Dyer and Erik Meijer from MS Research explaining the Rx Framework</a></li>
<li><a href="http://rxwiki.wikidot.com/101samples">101 Rx Samples (not quite 101 yet!)</a></li>
</ul>
<p>Does the framework appeal to you? As always, if you have any thoughts or questions about using the Rx Framework with Delphi Prism then let me know in the comments below. </p>
]]></content:encoded>
			<wfw:commentRss>http://jamiei.com/blog/2010/03/delphi-prism-and-the-microsoft-rx-framework/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>An Improved Cirrus Caching Aspect</title>
		<link>http://jamiei.com/blog/2009/11/an-improved-cirrus-caching-aspect/</link>
		<comments>http://jamiei.com/blog/2009/11/an-improved-cirrus-caching-aspect/#comments</comments>
		<pubDate>Mon, 09 Nov 2009 09:30:24 +0000</pubDate>
		<dc:creator>jamiei</dc:creator>
				<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Delphi Prism]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[caching]]></category>
		<category><![CDATA[cirrus]]></category>
		<category><![CDATA[delphi prism]]></category>

		<guid isPermaLink="false">http://jamiei.com/blog/?p=496</guid>
		<description><![CDATA[In my original introduction to Cirrus framework I drew up a basic method result caching attribute for Delphi Prism. This weekend I thought I&#8217;d give it another go and try to create a more general purpose Caching Aspect that integrates with a well known Cache library. I decided to use the opportunity to experiment with [...]]]></description>
			<content:encoded><![CDATA[<p>In my original <a href="http://jamiei.com/blog/2009/06/delphi-prism-cirrus-framework/">introduction to Cirrus framework</a> I drew up a basic method result caching attribute for Delphi Prism. This weekend I thought I&#8217;d give it another go and try to create a more general purpose Caching Aspect that integrates with a well known Cache library. I decided to use the opportunity to experiment with the <a href="http://msdn.microsoft.com/en-us/library/dd203226.aspx">Caching Application Block</a> from the <a href="http://msdn.microsoft.com/en-us/library/dd203099.aspx">Microsoft Patterns and Practice Enterprise Library</a> which you should definitely <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=1643758B-2986-47F7-B529-3E41584B6CE5&amp;displaylang=en">download</a> and do some research into if you haven&#8217;t already.</p>
<p>Last time, I had created an attribute which could only be attached to methods returning strings and used a home-made caching class, the Aspect looked like this:</p>
<pre class="brush: delphi; collapse: true; light: false; title: ; toolbar: true; notranslate">
namespace AOPCacheLibrary;

interface

uses
  RemObjects.Oxygene.Cirrus.*,
  RemObjects.Oxygene.Aspects;

type
   [AttributeUsage(AttributeTargets.Method)]
  MemCacheAttribute = public class(System.Attribute, IMethodImplementationDecorator)
  private
  public

    method HandleImplementation(Services: IServices; aMethod: IMethodDefinition);
  end;

implementation

method MemCacheAttribute.HandleImplementation(Services: IServices; aMethod: IMethodDefinition);
begin
  // Get a Reference to our Result Value
  var newResult := new ResultValue();

  // Get our MemCache Object
  var cacheType := Services.FindType('AOPCacheLibrary.MemCache');
  // Setup our static methods.
  var getDataProc := new ProcValue(new TypeValue(cacheType), 'getData', [new NamedLocalValue('cacheKey')]);

  // Assign the result of our cache request to a local variable.
  var getDataAssignment := new AssignmentStatement(new NamedLocalValue('strData'), getDataProc);

  // CACHE DATA USED: To assign our Cache'd data to the Method Result
  var useCacheData := new AssignmentStatement(newResult, new NamedLocalValue('strData'));
  // CACHE DATA NOT USED: To assign the result of our OriginalBody to the Method Result.
  var useOriginalMethodResult := new AssignmentStatement(new NamedLocalValue('resultOriginal'), newResult);

  aMethod.SetBody(Services,
    method begin
      var strData: String;
      // Get our Cache Key Name
      var cacheKey := MemCache.getKeyFromMethod(Aspects.MethodName, Aspects.GetParameters);

      try
        // See if we have anything in the cache for this key.
        unquote(getDataAssignment);
        // Replace this
        unquote(useCacheData);
      except
        on E: Exception do
        begin
          var resultOriginal: String;
          // No cache data found, execute the original method body.
          Aspects.OriginalBody;

          // Assign the result of the Original Method to a new variable.
          unquote(useOriginalMethodResult);
          // Send the result of the Original Method to the Cache for next time.
          MemCache.setData(cacheKey, resultOriginal);
        end;
      end;
    end);
end;

end.
</pre>
<p>Modifying my original code into working with the Microsoft Enterprise Caching black wasn&#8217;t particularly hard. If you haven&#8217;t worked with the Microsoft P&amp;P Enterprise Library Caching Block before I highly recommend the <a href="http://msdn.microsoft.com/en-us/library/dd203278.aspx">Quickstart guide</a>. The Enterprise Caching Block allows you to <a href="http://msdn.microsoft.com/en-us/library/dd203112.aspx">configure your cache using configuration file</a> and change the backing store to suit own your needs. I would certainly recommend tweaking the expiration time and frequency of cache cleaning times before you begin.</p>
<p>Whilst rewriting the code of my Aspect I found it absolutely invaluable to have the <a href="http://prismwiki.codegear.com/en/Cirrus">Cirrus documentation wiki</a> open and a piece of paper next to my keyboard with the approximate psuedo-code that I was intending to build with Cirrus written on it. I did actually find that despite the fact that the code I was building was not complicated, I did require a reminder of the statements and structure of it.</p>
<p>One additional problem that I did encounter very quickly on my modification was that I had a method which would generate a string key from the method name being called and its parameters which looked like this:</p>
<pre class="brush: delphi; title: ; notranslate">
class method CacheKeyFactory.GetKeyFromMethod(aName: String; Args: Array of object): String;
begin
  var argConcat: String;

  argConcat := aName;
  for argTemp in Args do
  begin
    argConcat := argConcat + argTemp.ToString();
  end;

  Result := argConcat;
end;
</pre>
<p>Which I had intended to inject into the target class using the <a href="http://prismwiki.codegear.com/en/AutoInjectIntoTargetAttribute_Class">AutoInjectIntoTargetAttribute</a> which as the name suggests creates the method tagged within the class you are targetting with your attribute. The problem I encountered was that I used this Attribute on a method within an <a href="http://prismwiki.codegear.com/en/Cirrus_Overview">IMethodImplementationDecorator</a> attribute which meant that it worked perfectly when I applied my attribute to just one method within a class but applying my attribute to more than one meant that the AutoInjected method got injected more than once &#8211; causing a conflict (<em>Is this a bug? I was told not but it seems odd to me</em>).</p>
<p><em>[Update: 22/11/2009] I have reported this issue as QC: </em><a href="http://qc.embarcadero.com/wc/qcmain.aspx?d=79705"><em>79705</em></a><em>. [/Update]</em></p>
<p>Therefore as a workaround, I was forced to move this key generating method into a static class elsewhere in the assembly but maybe someone can work out a way around this limitation.</p>
<p>I also encountered an annoying trait of the Cirrus Framework which is that some errors produce a fairly unhelpful message and lead you to a line in the Project&#8217;s build file which whilst being logical can be infuriating when you&#8217;re presented with this:</p>
<div id="attachment_505" class="wp-caption aligncenter" style="width: 310px"><a href="http://jamiei.com/blog/wp-content/uploads/2009/11/CirrusExceptionHandling.png"><img class="size-medium wp-image-505" title="CirrusExceptionHandling" src="http://jamiei.com/blog/wp-content/uploads/2009/11/CirrusExceptionHandling.png" alt="A rather confusing exception and causal code identification." width="300" height="181" /></a><p class="wp-caption-text">A rather confusing exception and causal code identification.</p></div>
<p>After a tiny bit of tweaking, My next iteration of the Caching Attribute looks like this:</p>
<pre class="brush: delphi; title: ; notranslate">

type
  [AttributeUsage(AttributeTargets.Method)]
  MethodCacheAttribute = public class(System.Attribute, IMethodImplementationDecorator)
  private
  public
    method HandleImplementation(Services: IServices; aMethod: IMethodDefinition);
  end;

implementation

method MethodCacheAttribute.HandleImplementation(Services: IServices; aMethod: IMethodDefinition);
begin
  // Get a Reference to our Result Value
  var methodResult := new ResultValue();

  // Get a reference to our Static Key Factory.
  var cacheKeyGen := Services.FindType('CirrusCachingAspect.CacheKeyFactory');
  // Generate our cache key from the method name and it's parameters
  var getCacheKey := new AssignmentStatement(new NamedLocalValue('cacheKey'), new ProcValue(new TypeValue(cacheKeyGen), 'GetKeyFromMethod', [aMethod.Name, aMethod.GetParameterArrayValue()]));

  // Get our CacheManager Type and our CacheFactory Type
  var cacheType := Services.FindType('Microsoft.Practices.EnterpriseLibrary.Caching.CacheManager');
  var cacheFactoryType := Services.FindType('Microsoft.Practices.EnterpriseLibrary.Caching.CacheFactory');

  // Get a Reference to our Cache Instance.
  var getCacheInstance := new AssignmentStatement(new NamedLocalValue('methodCache'), new ProcValue(new TypeValue(cacheFactoryType), 'GetCacheManager'));

  // Get data from our cache.
  var getDataFromCache := new ProcValue(new NamedLocalValue('methodCache'), 'GetData', [new NamedLocalValue('cacheKey')]);

  // Cast our result from the Cache to the Result Type.
  var valueCastToResultType := new UnaryValue(new NamedLocalValue('cacheData'), UnaryOperator.Cast, aMethod.Result);

  // Assign the result of our cache request to a local variable.
  var getDataAssignment := new AssignmentStatement(new NamedLocalValue('cacheData'), getDataFromCache);

  // Assign our Cache'd data to the Method Result
  var useCacheData := new AssignmentStatement(methodResult, valueCastToResultType);

  // Add our data to the Cache for next time
  var addDataToCache := new StandAloneStatement(new ProcValue(new NamedLocalValue('methodCache'), 'Add', [new NamedLocalValue('cacheKey'), methodResult]));

  // Key not found in the cache, insert the original body and add a call to the Cache.Add() method.
  var notFoundInCache := new BeginStatement();
  notFoundInCache.Add(new PlaceHolderStatement());
  notFoundInCache.Add(addDataToCache);

  // If found in the cache.
  var ifCacheResult := new IfStatement(new BinaryValue(new NamedLocalValue('cacheData'), new NilValue(), BinaryOperator.Equal), notFoundInCache, useCacheData);

  aMethod.SetBody(Services,
    method begin
      var cacheData: Object;
      var methodCache: CacheManager;
      var cacheKey: String;

      // Get out cache instance
      unquote(getCacheInstance);

      // Generate a key for this method call.
      unquote(getCacheKey);

      // Try to retrieve the data from the cache.
      unquote(getDataAssignment);

      // If data from cache = nil then
      //    call original method
      //    add to cache
      // else
      //    return the data from the cache
      unquote(ifCacheResult);

    end);
end;
</pre>
<p>Which may look quite complex at first but when you look at the actual statements and values being passed around, you can quickly get a feel for how the code works. We can then easily apply this attribute and cache the result of any method in a class automatically like this:</p>
<pre class="brush: delphi; title: ; notranslate">
type
  Flickr = public class
  private
    _username: string;
  public
    method Flickr(username: String);
    [Aspect:MethodCache]
    method GetPhotos: XmlDocument;
    [Aspect:MethodCache]
    method GetUsername: String;
    [Aspect:MethodCache]
    method GetAuthLevel(user: String): Integer;
  end;
</pre>
<p>Where GetPhotos, GetUsername and GetAuthLevel will all have their results cached automatically by our Aspect. You can see the resulting AOP&#8217;d code disassembled in the reflector below:</p>
<div id="attachment_505" class="wp-caption aligncenter" style="width: 310px"><a href="http://jamiei.com/blog/wp-content/uploads/2009/11/ReflectedMethods-1024x619.png"><img class="size-medium wp-image-505" title="ReflectedMethods" src="http://jamiei.com/blog/wp-content/uploads/2009/11/ReflectedMethods-300x181.png" alt="The RedGate .NET Reflector showing our Cirrus doctored caching code." width="300" height="181" /></a><p class="wp-caption-text">The RedGate .NET Reflector showing our Cirrus doctored caching code.</p></div>
<p>There is still one slight limitation in our method of key generation which is that it will currently only generate a unique key for a method with parameters if the Types of the methods parameters provide a proper implementation of <a href="http://msdn.microsoft.com/en-us/library/system.object.tostring.aspx">ToString()</a> that identifies them. Before you mention it, I had considered using the <a href="http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx">GetHashCode()</a> method for this purpose but the default implementation of the GetHashCode method does not guarantee unique return values for different objects which makes it no more useful than relying on the user to implement the ToString() method.</p>
<p>I have made my implementation available on GitHub as the <a href="http://github.com/jamiei/CirrusCachingAspect">CirrusCachingAttribute</a> where you can feel free to download and play with the source but please note that you will need to <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=1643758B-2986-47F7-B529-3E41584B6CE5&amp;displaylang=en">download and install</a> the Enterprise Library from Microsoft first. I have also added a stub to the Code section on my site for the <a href="http://jamiei.com/blog/code/cirruscachingaspect-for-delphi-prism/">Cirrus Caching Attribute</a>.</p>
<p>There is also a <a href="http://code.remobjects.com/p/prismaspects/">Standard Library of Aspects</a> over on <a href="http://code.remobjects.com">code.remobjects.com</a> which provides a good set of Aspects from which you can learn more about how Cirrus works.</p>
]]></content:encoded>
			<wfw:commentRss>http://jamiei.com/blog/2009/11/an-improved-cirrus-caching-aspect/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

