<?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; Development</title>
	<atom:link href="http://jamiei.com/blog/topic/development/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>Sun, 05 Sep 2010 21:27:50 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=abc</generator>
<cloud domain='jamiei.com' port='80' path='/blog/?rsscloud=notify' registerProcedure='' protocol='http-post' />
		<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;">
  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;">
  [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;">
  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;">
  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;">
  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;">
  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;">
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;">
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;">
  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;">
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;">
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>3</slash:comments>
		</item>
		<item>
		<title>Warblecamp</title>
		<link>http://jamiei.com/blog/2010/05/warblecamp/</link>
		<comments>http://jamiei.com/blog/2010/05/warblecamp/#comments</comments>
		<pubDate>Sun, 09 May 2010 20:59:57 +0000</pubDate>
		<dc:creator>jamiei</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[twitter]]></category>
		<category><![CDATA[warblecamp]]></category>

		<guid isPermaLink="false">http://jamiei.com/blog/?p=643</guid>
		<description><![CDATA[I spent this weekend at the rather smart Guardian offices at King&#8217;s place near King&#8217;s Cross to visit Warblecamp and I thought I&#8217;d write up my thoughts on some of what I&#8217;d learned. WarbleCamp is a free unconference style event for the UK/Euro Twitter developer community which was held at the offices of the guardian. I [...]]]></description>
			<content:encoded><![CDATA[<p>I spent this weekend at the rather smart <a href="http://www.guardian.co.uk/">Guardian</a> offices at King&#8217;s place near King&#8217;s Cross to visit <a href="http://warblecamp.org/">Warblecamp</a> and I thought I&#8217;d write up my thoughts on some of what I&#8217;d learned.</p>
<p style="text-align: left;">WarbleCamp is a free <a href="http://en.wikipedia.org/wiki/Unconference">unconference</a> style event for the UK/Euro Twitter developer community which was held at the offices of the <a href="http://www.guardian.co.uk/">guardian</a>. I was lucky enough to see an announcement notice before the first set of tickets had vanished in a very short space of time. We arrived at the very smart guardian offices where guardian staff were still working throughout the weekend (apparently there is some sort of <a href="http://www.guardian.co.uk/global/2010/may/09/general-election-2010-hung-parliament">big news unfolding</a> or something?) and watched @<a href="http://twitter.com/jot">jot</a> and @<a href="http://twitter.com/kalv">kalv</a> give the opening introduction to the event.</p>
<div class="wp-caption aligncenter" style="width: 510px"><a href="http://www.flickr.com/photos/raffik/4588798986/"><img title="Warblecamp Introduction by @jot and @kalv (Photo courtest of @raffi)" src="http://farm5.static.flickr.com/4062/4588798986_9659c2aff0.jpg" alt="" width="500" height="375" /></a><p class="wp-caption-text">Session boards at Warblecamp (Photo from @raffi)</p></div>
<p style="text-align: left;">
<p style="text-align: left;">The day was broken up into Barcamp style sessions where anyone could propose a session simply by writing it onto a notecard/post-it note and finding a free timeslot and room on the wall board.</p>
<div class="wp-caption aligncenter" style="width: 510px"><a href="http://www.flickr.com/photos/raffik/4588223713/"><img title="Session boards at Warblecamp (Photo from @raffi)" src="http://farm5.static.flickr.com/4015/4588223713_e13f11db4c.jpg" alt="" width="500" height="375" /></a><p class="wp-caption-text">Session boards at Warblecamp (Photo from @raffi)</p></div>
<p style="text-align: left;">
<p style="text-align: left;">After several introductions and conversations over cups of coffee and a Strawberry and Banana oatmeal breakfast courtesy of <a href="http://www.momafoods.co.uk/">moma foods</a> we selected our first session. I was a little disappointment that there seemed to be a quite a few people who had registered for tickets and then simply never turned up.</p>
<p style="text-align: left;">
<h3>Aral Balkan (@<a href="http://twitter.com/aral">aral</a>) &#8211; An Introduction to the Streaming API.</h3>
<p style="text-align: left;">I felt very sorry for Aral as he&#8217;d bravely volunteered to move his session to one of the first of the day which meant that delays in starting was to be inevitable while people found rooms etc. It also amazes me how you can put 40-50 geeks into a room and then find that noone can work a projector.</p>
<p style="text-align: left;">After changing rooms we finally got onto the subject of the new Twitter <a href="http://apiwiki.twitter.com/Streaming-API-Documentation">Streaming API</a>. The Streaming API is the 3rd Twitter API Subset which allows you to access various slices of public tweets. The Key differentiator is that unlike the other 2 twitter API services it actively pushes tweets to you in (sort of) real-time so that you don&#8217;t have to constantly poll Twitter&#8217;s servers to check for new information.</p>
<p style="text-align: left;">The <a href="http://apiwiki.twitter.com/Streaming-API-Documentation">Streaming API</a> is an invaluable addition to the API Services and also hints at how many API services of this type of data model should actually be modelled. This session was cut rather short but one point that stuck with me is that <a href="http://www.json.org/">Json</a> is now the preferred response type and they&#8217;re considering XML return methods for depreciation.</p>
<p style="text-align: left;">
<h3>Paul Mison (@blech) &#8211; Annotations vs Machine Tags</h3>
<p>This session was a good discussion around the uses and power of Machine Tags and Annotations which focussed around <a href="http://code.flickr.com/blog/2009/07/06/extraextraextra/">Flickr Machine Tag</a> usage as at this point in time Twitter doesn&#8217;t support adding metadata to Tweets (little did we know what was to come later in the day).</p>
<p>The basic concept is to decorate a resource with metadata in some way, this usually follows a simple model. This normally takes the form<em> Namespace:key=value</em>. For Example, on Flickr, One might tag a photo with <em>Car:Manufacturer=Ferrari</em> to indicate that it is a photo of a Ferrari car. This makes data about our photo more specific as a photo simply tagged &#8220;F357&#8243; might be be any number of things.. a room, a camera, a car.</p>
<p>@<a href="http://twitter.com/aral">aral</a> started a good discussion around how you might &#8220;standardise&#8221; the namespaces of these tags and the hierarchy as it&#8217;s entirely possible that people may have different words for the same descriptor. There was popular consensus for an organic community driven approach.</p>
<p>@<a href="http://twitter.com/tommorris">tommorris</a> raised a good point: that even with a hierarchy of key-value pairs, is this really enough to actually associate a relationship perspective with an object? The example he gave within the context of Annotated Tweets is that you can tag a tweet with a <em>book:title=&#8221;Treasure Island&#8221;</em> but how can you tell whether this refers to a book I&#8217;ve read, a book I bought, a book I wrote?</p>
<h3>Nick Halstead (@<a href="http://twitter.com/nickhalstead">nickhalstead</a>), CEO of Tweetmeme &#8211; #NoSQL</h3>
<p>Nick gave us a brief overview of <a href="http://www.tweetmeme.com">Tweetmeme</a>&#8216;s platform growth, they started with a well trodden track of a LAMP stack.</p>
<p>Tweetmeme services a fairly eye-watering amount of work: they store 4TB of data per day, index 500 million URLs and service 10,000 Req/s from about 25 servers. MySQL worked fine, following the usual Master / Slave division pattern until they got above a certain number of rows after which deletions started to become a pain point.</p>
<p>They have now moved to a Custom PHP job queuing system,  Nginx and HA_PROXY and use a tiered system of graceful degradation (similar to Twitter&#8217;s own system) which allows them to service requests differently according to the load on individual machines.</p>
<p>They first evaluated <a href="http://1978th.net/">Tokyo</a> and concluded that whilst it was very very fast  it was going to prove a difficult as it would mean carefully sharding data themselves.</p>
<p>They then evaluated <a href="http://code.google.com/p/redis/">Redis</a> from which they were very impressed with the clever features to create Lists and Sets of data.</p>
<p>Finally they settled on <a href="http://cassandra.apache.org/">Cassandra</a> which provides eventual consistency and easy scaling across commodity hardware (a key advantage for a startup like Tweetmeme).</p>
<h3>Christian Heilmann (@<a href="http://twitter.com/codepo8">codepo8</a>) &#8211; Geo Platforms</h3>
<p>I&#8217;ve been a follower of Christian on Twitter for quite a while so I&#8217;m used to his enthusiasm for the <a href="http://developer.yahoo.com/yql/">Yahoo YQL</a> platform but it was great to actually see his enthusiasm in person.</p>
<p>Whilst we were waiting for people to find their way to the room Christian revealed that some people are so into Geo that apparently they decide to walk around London on a particular trail in order to create a phallic route.. ergo <a href="http://www.gpscocks.com/2010/03/money-shot.html">gpsc**ks.com</a> (conceivably NSFW) was born.</p>
<p>He first made the point that we&#8217;re beyond the point of it being novel to be able to display our GPS location on our mobiles and how we actually needed to do something useful with it. He covered how a few lines of Javascript we can use the <a href="http://dev.w3.org/geo/api/spec-source.html">HTML5 Geo API</a> to locate a user (with varying degrees of accuracy). He pointed out that working with Geo locations is considerably more complicated than simply obtaining the Lat/Long of the current user. To help with this he suggested several resources:</p>
<ul>
<li><a href="http://isithackday.com/geoplanet-explorer/">Geo Planet Explorer</a> &#8211; A Yahoo web service that allows you to submit a WOE (Where on Earth) location and get back data about the neighbourhood and it&#8217;s neighbouring areas.</li>
<li><a href="http://isithackday.com/hacks/geo/yql-geo-library/">YQL Geo Library</a> &#8211; A JS Library which uses the YQL Library to provide services like geolocation, reverse geocoding, content analysis all in one easy library.</li>
</ul>
<p>He then gave us a live demo of the <a href="http://developer.yahoo.com/yql/console/">YQL Service</a> which which truly very powerful. It provides structured, consistent access to a whole load of different web services and datasets. This reminded me of what Ander Heijlberg said in his <a href="http://channel9.msdn.com/posts/adebruyn/TechDays-2010-Developer-Keynote-by-Anders-Hejlsberg/">Technet 2010 keynote</a> about programming for the <em>what</em> and not the <em>how</em>.</p>
<p>An example of a YQL queries might be: <em>select * from geo.places where text=&#8221;san francisco, ca&#8221;</em></p>
<p>As someone who is used to working with web services the hard way, the YQL frees you from some of the effort of Authentication, gives you a consistent output format and does some caching on the server side.</p>
<h3>Raffi Krikorian (@<a href="http://twitter.com/raffi">raffi</a>) &#8211; Twitter Annotations</h3>
<p>@<a href="http://twitter.com/raffi">raffi</a> is Twitter&#8217;s Dev Lead for the API Platform (aside from being a generally nice chap) and had gotten permission just before he flew out to the UK to give us the first public draft of the upcoming annotations feature planned. You can check out his slides on the <a href="http://slidesha.re/9o2tHx">Twitter API Annotations</a> and even watch <a href="http://vimeo.com/11587053">the recording</a> of the talk over on Vimeo.</p>
<p>The basic idea is that you will shortly be able to decorate tweets with up to 512 Bytes of data (excluding formatting and data classification structures). This could be used to append data about a book that the tweet refers to, a movie which it is talking about or any number of uses, including pure machine-to-machine communication.</p>
<p>This adds context to a tweet, something which twitter started doing when it added GeoLocated tweets and intends on doing more of in the future.</p>
<p>It is stressed that this is still a very early draft but that the Annotations may look something like the following:</p>
<pre class="brush: jscript;">
{(type =&gt;  (attribute =&gt; value),
               (attribute =&gt; value)}
</pre>
<p>And as an example:</p>
<pre class="brush: jscript;">
[(“tv episode” =&gt; {“episode” =&gt; “The Vampires of Venice”,
		“series” =&gt; “Dr Who”,
		“air date” =&gt; “8 May 2010”}}]
</pre>
<p>The names of types and attributes will be allowed to grow organically from the community although they will have a broad set in use at the time of launch with support from a few partners. Attribute types and key name usage will be tracked and stats made available on <a href="http://dev.twitter.com">dev.twitter.com</a> to allow developers to browse existing usage implementations.</p>
<p>@<a href="http://twitter.com/codepo8">codepo8</a> asked if they looked at RDF and microformats to see if they could adopt an existing standard for metadata and while they wouldn&#8217;t have been directly applicable, there is still a chance that they could reuse some of the taxonomy.</p>
<p>Lots of people asked if it would be possible to have metadata only tweets so that you could filter out all those annoying Foursquare checkin tweets and those &#8220;I&#8217;m listening to&#8221; tweets. This is now easily doable with the support of 3rd party client providers.</p>
<p>As with nearly all the previous new features released by Twitter, this may eventually be built into the twitter.com interface but it is initially planned as an API Platform feature.</p>
<p>Annotations will be made available to application developers  first as a preview within the next month sometime.</p>
<h3>Others</h3>
<p>There were several more sessions that I particularly enjoyed including <a href="http://remysharp.com/">Remy Sharp</a>&#8216;s (@<a href="http://twitter.com/rem">rem</a>) presentation on a conference dashboard he built he built for Chirp conference that works entirely with Javascript. <a href="http://aralbalkan.com/">Aral Balkan</a> (@<a href="http://twitter.com/aral">aral</a>) also chaired what turned out to be an introduction and discussion of Twitter&#8217;s xAuth process (an adapted version of OAuth for Desktop Applications) which turned out to be a penny drop moment for me with the workflow process for OAuth Desktop applications.</p>
<p>I&#8217;m also keen to follow up on @<a href="http://twitter.com/ketan">ketan</a>&#8216;s proposal for a <a href="http://www.stereoartist.com/blog/in-search-of-the-twitter-protocol-to-rule-them-all">twitter://</a> protocol handler and to have a play around with the User Streaming API.</p>
<p>Thanks to the organisers, speakers and sponsors of warblecamp, I think it&#8217;s safe to say it was a well deserved great success. A special thanks to the primary sponsors, <a href="http://www.guardian.co.uk/open-platform">Guardian Open Platform</a>, <a href="http://oneforty.com/">oneforty</a>, <a href="http://developer.yahoo.com/">Yahoo Developer Network</a>, <a href="http://x.com/">Paypal X</a> and <a href="http://www.o2litmus.co.uk/">O2 litmus</a> and to the micro-sponsors for supporting us with food, drink and entertainment.</p>
<p style="text-align: left;">
<p style="text-align: left;">
<p style="text-align: left;">
]]></content:encoded>
			<wfw:commentRss>http://jamiei.com/blog/2010/05/warblecamp/feed/</wfw:commentRss>
		<slash:comments>1</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;">
   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;">
    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;">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;">
    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;">
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>11</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];">
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; toolbar: true;">
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; toolbar: true;">
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;">
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];">
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; toolbar: true;">
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;">
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;">

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;">
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>
		<item>
		<title>Time to bury this &#8220;Is Delphi Dying&#8221; nonsense</title>
		<link>http://jamiei.com/blog/2009/10/time-to-bury-this-is-delphi-dying-nonsense/</link>
		<comments>http://jamiei.com/blog/2009/10/time-to-bury-this-is-delphi-dying-nonsense/#comments</comments>
		<pubDate>Sat, 24 Oct 2009 12:05:45 +0000</pubDate>
		<dc:creator>jamiei</dc:creator>
				<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Much ado about Nothing]]></category>
		<category><![CDATA[codegear]]></category>
		<category><![CDATA[fun]]></category>
		<category><![CDATA[joke]]></category>

		<guid isPermaLink="false">http://jamiei.com/blog/?p=477</guid>
		<description><![CDATA[Every 3-6 months or, more frequently it seems, someone has the urge to post some attention grabbing headline such as &#8220;Is Delphi Dying&#8221; or &#8220;Is Delphi a Dead language?&#8221; (yes, even unintentionally negative headlines hurt). It recently even despicably overflowed onto StackOverflow. Enough is enough, I thought, I am utterly bored with this discussion. So, I decided to do [...]]]></description>
			<content:encoded><![CDATA[<p>Every 3-6 months or, more frequently it seems, someone has the urge to post some attention grabbing headline such as &#8220;<a href="http://www.google.co.uk/search?hl=en&amp;rlz=1C1GGLS_en-GBGB331GB331&amp;q=%22Is+delphi+dying%22&amp;btnG=Search&amp;meta=&amp;aq=f&amp;oq=">Is Delphi Dying</a>&#8221; or &#8220;Is Delphi a Dead language?&#8221; (yes, even <a href="http://wings-of-wind.com/2009/10/18/delphi-is-dying-tm/">unintentionally negative</a> headlines hurt). It recently even <a href="http://stackoverflow.com/questions/1584760/what-to-do-when-delphi-dies">despicably</a> overflowed onto StackOverflow. Enough is enough, I thought, I am <strong>utterly bored</strong> with this discussion.<img class="alignright size-medium wp-image-480" title="Google Suggest" src="http://jamiei.com/blog/wp-content/uploads/2009/10/googlesays-300x167.png" alt="Google Suggest" width="300" height="167" /></p>
<p>So, I decided to do something about it. Some of you might have seen some of the marvellous single purpose websites floating around the internet such as:</p>
<ul>
<li><a href="http://letsturnthisfuckingwebsiteyellow.com/">Lets turn this f***ing website yellow</a></li>
<li><a href="http://www.isapplestoredown.com/">Is the Apple Store Down?</a></li>
<li><a href="http://dowebsitesneedtolookexactlythesameineverybrowser.com/">Do websites need to look the same in every browser?</a></li>
<li><a href="http://www.islostarepeat.com/">Is Lost a repeat?</a></li>
<li>and <a href="http://www.yetanotheruselesswebsite.com/">Yet another useless website.</a></li>
</ul>
<p>All are simple, single purpose websites, which generally do <strong>exactly </strong>what they say on the tin (or in the URL as is the case here) and as we know: The information they give must be true after all: &#8220;<em>I read it on the internet, so it must be true&#8221;</em>. So, late last night I got thinking..</p>
<p>May I proudly introduce to you, the Delphi community&#8217;s new and hopefully favourite single serving sites:</p>
<ul>
<li><a href="http://www.isdelphidead.com">www.</a><a href="http://www.isdelphidead.com">isdelphidead</a><a href="http://www.isdelphidead.com">.com</a></li>
<li><a href="http://www.isdelphidying.com">www.isdelphidying.com</a></li>
</ul>
<p>Next time you see someone on a forum, in the newsgroups or on stackoverflow asking the most dull and tedious of all the questions I could possibly hear: <a href="http://www.isdelphidying.com/">Is Delphi Dying?</a> or <a href="http://www.isdelphidead.com/">Is Delphi Dead?</a>,  point them to one of these sites.</p>
<div id="attachment_482" class="wp-caption alignright" style="width: 310px"><img class="size-medium wp-image-482" title="Is Delphi Dying?" src="http://jamiei.com/blog/wp-content/uploads/2009/10/isit-300x174.png" alt="Is Delphi Dead? Is Delphi Dying?" width="300" height="174" /><p class="wp-caption-text">Is Delphi Dead? Is Delphi Dying?</p></div>
<p>I should point out that the people who like to bring up this particular topic are normally quite persistent. In order to dissuade them from rehashing the same <a href="http://wings-of-wind.com/2009/10/18/delphi-is-dying-tm/#comment-1288">tedious</a> and <a href="http://stackoverflow.com/questions/1584760/what-to-do-when-delphi-dies">dull</a> discussions time and time again I have cunningly built in an API.</p>
<p>People who are concerned that that answer might change without them being informed can build an application based on the API which spits out your choice of <a href="http://www.isdelphidying.com/API/?xml">XML</a> or <a href="http://www.isdelphidying.com/API/?json">JSON</a>. This way, the aforementioned doom mongerers can simply build an application (in <a href="http://www.embarcadero.com/products/delphi">Delphi</a>, of course) that sits in their tray and periodically polls the service and reassures those greatly concerned of the answer.</p>
<p>The API is very simple, you merely need to append</p>
<pre class="brush: delphi;">/API</pre>
<p>to the <a href="http://isdelphidead.com">isdelphidead.com</a> or <a href="http://isdelphidying.com">isdelphidying.com</a> domain of your choice and then request either format by querying for XML (default):</p>
<pre class="brush: delphi;">/API?xml</pre>
<p>or JSON:</p>
<pre class="brush: delphi;">/API?json</pre>
<p>It&#8217;s that simple.  So go now and <strong>spread the word</strong> so that the rest of us can carry on in peace.</p>
<p><strong>[Update 01/11/09]:</strong> Russian Delphi programmer <a href="http://www.isdelphidying.narod.ru/">Valerian Kadyshev</a> has posted <a href="http://jamiei.com/blog/2009/10/time-to-bury-this-is-delphi-dying-nonsense/comment-page-1/#comment-595">below</a> to inform us that he has in fact made a tray monitoring application (in Delphi of course!) so that concerned people can download his pre-made one if they don&#8217;t even want to goto the trouble of making it themselves. You can find version 1 of his &#8220;<a href="http://www.isdelphidying.narod.ru/">Is Delphi Dying Monitor</a>&#8221; over on <a href="http://www.isdelphidying.narod.ru/">his site</a>. Marvellous Work Valerian!</p>
]]></content:encoded>
			<wfw:commentRss>http://jamiei.com/blog/2009/10/time-to-bury-this-is-delphi-dying-nonsense/feed/</wfw:commentRss>
		<slash:comments>44</slash:comments>
		</item>
		<item>
		<title>Dynamically generating code with Delphi Prism</title>
		<link>http://jamiei.com/blog/2009/10/dynamically-generating-code-with-delphi-prism/</link>
		<comments>http://jamiei.com/blog/2009/10/dynamically-generating-code-with-delphi-prism/#comments</comments>
		<pubDate>Sat, 03 Oct 2009 12:21:32 +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[introduction]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://jamiei.com/blog/?p=458</guid>
		<description><![CDATA[In my last post I covered dynamically compiling code with Delphi Prism and this time I&#8217;m going to introduce dynamically creating code which could then be written out to a source file or compiled from in memory. You might want to generate code dynamically for a wide variety of reasons, whether it be to bootstrap [...]]]></description>
			<content:encoded><![CDATA[<p>In my last post I covered <a href="http://jamiei.com/blog/2009/09/dynamically-compiling-code-with-delphi-prism/">dynamically compiling code with Delphi Prism</a> and this time I&#8217;m going to introduce dynamically creating code which could then be written out to a source file or compiled from in memory. You might want to generate code dynamically for a wide variety of reasons, whether it be to bootstrap a project easily, automatically add some utility code or generate wrapper classes automatically. Dynamically generating code with Delphi Prism is (like almost everything in .NET) no different to the process in which it is done in C# or VB.NET. It is easy to forget that Delphi Prism is fully compatible with the whole of the .NET Framework and this means that you can now safely go back to having the <a href="http://msdn.microsoft.com/en-us/netframework/default.aspx">MSDN Documentation</a> as your best friend.</p>
<p>Before you get too hasty with building your own class generators it&#8217;s also worth noting that Microsoft&#8217;s <a href="http://msdn.microsoft.com/en-us/library/x6c1kb0s.aspx">xsd.exe</a> tool can also be used with Delphi Prism (thanks to <a href="http://wiert.wordpress.com/2009/09/04/net-delphi-prism-how-to-generate-wrapper-classes-code-from-xsd-file/">Jeroen Pluimers</a> and <a href="http://stackoverflow.com/questions/917418/how-to-generate-pascal-code-from-an-xml-schema-in-delphi-prism">Peter Nowotnick</a> for sharing this tip with us).</p>
<h3>Getting Started</h3>
<p>In Order to get started you&#8217;ll need to reference the <strong>RemObjects.Oxygene.CodeModel.dll</strong> and add the CodeDom namespace from this plus System.CodeDom to your uses.</p>
<p>It is worth noting that automated code generation is like our work with the <a href="http://jamiei.com/blog/2009/06/delphi-prism-cirrus-framework/">Delphi Prism AOP Cirrus framework</a> in that the code required to create a small amount of target output code can become quite hard to read at a glance so organise it well.</p>
<p>We&#8217;re going to start off by creating a basic class for Saying Hello (highly innovative you understand! <img src='http://jamiei.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' />  ) and then generating the code and writing it to a new .pas file. Our basic first steps in generating a class involve setting up the unit (with a <a href="http://msdn.microsoft.com/en-us/library/system.codedom.codecompileunit.aspx">CodeCompileUnit</a>), the namespace (with a <a href="http://msdn.microsoft.com/en-us/library/system.codedom.codenamespace.aspx">CodeNamespace</a>) and the class itself (with a <a href="http://msdn.microsoft.com/en-us/library/system.codedom.codetypedeclaration.aspx">CodeTypeDeclaration</a>):</p>
<pre class="brush: delphi;">
namespace CodeDomGeneration;

interface

uses
  System.Linq,
  System.Reflection,
  System.IO,
  System.CodeDom,
  System.CodeDom.Compiler,
  RemObjects.Oxygene.CodeDom;

type
  ConsoleApp = class
  public
    class method Main;
  end;

implementation

class method ConsoleApp.Main;
const
  outputFile = 'uMyClass.pas';
var
  uNewUnit: CodeCompileUnit;
  MyHelloNS: CodeNamespace;
  MyNewClass: CodeTypeDeclaration;
  provider: CodeDomProvider;

begin
  uNewUnit := new CodeCompileUnit;

  MyHelloNS := new CodeNamespace('Hello');
  MyHelloNS.Imports.Add(new CodeNamespaceImport('System'));

  MyNewClass := new CodeTypeDeclaration('TSayHelloClass');
  MyNewClass.IsClass := true;
  MyNewClass.TypeAttributes := TypeAttributes.Public + TypeAttributes.Sealed;
  MyNewClass.Comments.Add(new CodeCommentStatement('This is our CodeDom created class <img src='http://jamiei.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> '));

  MyHelloNS.Types.Add(MyNewClass);
  uNewUnit.Namespaces.Add(MyHelloNS);

  // Get our CodeDomProvider
  provider := CodeDomProvider.CreateProvider('Oxygene');

  // Options.
  var options: CodeGeneratorOptions := new CodeGeneratorOptions();

  // Create our output filestream.
  var sourceWriter: StreamWriter;
  sourceWriter := new StreamWriter(outputFile);

  // Generate our code.
  provider.GenerateCodeFromCompileUnit(uNewUnit, sourceWriter, options);

  // Close our output filestream
  sourceWriter.Close();

  Console.WriteLine('Press Enter to exit..');
  Console.ReadLine;
end;

end.
</pre>
<p>If you run this code, you&#8217;ll find a new <strong>uMyClass.pas</strong> file has been generated in the output directory which contains little more than a class shell and a couple of comments: One to note that the source file was auto-generated by a tool and another to which is our own comment on the TSayHelloClass. You&#8217;ll also note that unlike the previous article, we&#8217;re using:</p>
<pre class="brush: delphi;"> CodeDomProvider.GenerateCodeFromCompileUnit();   </pre>
<p>To <a href="http://msdn.microsoft.com/en-us/library/system.codedom.compiler.codedomprovider.generatecodefromcompileunit.aspx">Generate code</a> from the Code Document Object Model rather than the <a href="http://msdn.microsoft.com/en-us/library/system.codedom.compiler.codedomprovider.compileassemblyfromsource.aspx">Compile</a> method we used last time. You could also compile directly from a CodeDom object as alluded to in my previous post on <a href="http://jamiei.com/blog/2009/09/dynamically-compiling-code-with-delphi-prism/">Dynamically compiling Delphi Prism code </a>using the <a href="http://msdn.microsoft.com/en-us/library/system.codedom.compiler.codedomprovider.compileassemblyfromdom.aspx">CodeDomProvider.CompileAssemblyFromDom method</a>.</p>
<p>The Next step is to add a private field (<a href="http://msdn.microsoft.com/en-us/library/system.codedom.codememberfield.aspx">CodeMemberField</a>) and a public property (<a href="http://msdn.microsoft.com/en-us/library/system.codedom.codememberproperty.aspx">CodeMemberProperty</a>) to our class with its own getter and setter methods:</p>
<pre class="brush: delphi;">
  var MyNameProperty: CodeMemberProperty;
  var MyNameField: CodeMemberField;

 // Add our private field.
  MyNameField := new CodeMemberField;
  MyNameField.Name := 'fFullName';
  MyNameField.Type := new CodeTypeReference('System.String');
  MyNameField.Attributes := MemberAttributes.Private;

  // Add the public property with a Getter and Setter
  MyNameProperty := new CodeMemberProperty;
  MyNameProperty.Name := 'FullName';
  MyNameProperty.Type := new CodeTypeReference('System.String');
  MyNameProperty.Attributes := MemberAttributes.Public;
  MyNameProperty.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), 'fFullName')));
  MyNameProperty.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), 'fFullName'), new CodePropertySetValueReferenceExpression()));

  // Add our two new objects to the parent code tree
  MyNewClass.Members.Add(MyNameField);
  MyNewClass.Members.Add(MyNameProperty);
</pre>
<p> It could very easy to get carried away creating an initialising your new class, methods, fields or properties and forget to .Add() them to the target <a href="http://msdn.microsoft.com/en-us/library/system.codedom.codestatementcollection.aspx">CodeStatementCollection</a> so if your new objects do not show up in the generated code, check that you have actually added them. We can now add a public SayHello method to our class which will greet the previously named entity:</p>
<pre class="brush: delphi;">
  var MySayHello: CodeMemberMethod;

  // Our public method to say &quot;Well Hi there &lt;fFullName&gt;&quot;
  MySayHello := new CodeMemberMethod();
  MySayHello.Name := 'SayHello';
  MySayHello.ReturnType := new CodeTypeReference(typeof(System.String));
  MySayHello.Attributes := MemberAttributes.Public;
  MySayHello.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression(new CodePrimitiveExpression('Well Hi there '), CodeBinaryOperatorType.Add, new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), 'fFullName'))));

  // Add our new method to the parent class.
  MyNewClass.Members.Add(MySayHello);
</pre>
<p>The Method statements that I have added here have been created on the fly and not been structured well for readability at all. As I mentioned at the beginning, you will need to structure your code carefully to ensure readability. If you run this code again now, you should see our SayHello Method as below:</p>
<pre class="brush: delphi;">
method TSayHelloClass.SayHello: System.String;
begin
    exit(('Well Hi there ' + self.fFullName));
end;
</pre>
<p>You can also add statements from &#8220;<em>snippets</em>&#8220;, which allows you to essentially inject code as a string using the <a href="http://msdn.microsoft.com/en-us/library/system.codedom.codesnippetexpression.aspx">CodeSnippetExpression</a> class: </p>
<pre class="brush: delphi;">
  var snippetSayHelloMethod:  CodeSnippetExpression  := new CodeSnippetExpression('Result := Self.fFieldName');
  //Convert the snippets into Expression statements.
  var stmtSayHelloResult: CodeExpressionStatement := new CodeExpressionStatement(snippetSayHelloMethod);
  // Add it to our SayHello Method
  MySayHello.Statements.Add(stmtSayHelloResult);
</pre>
<p><strong>Warning: </strong>Adding method statements from snippets in this manner should be used with great care as you have very little protection against a typo causing a mal-formed code output and I would not recommend generating complex code statements from the <a href="http://msdn.microsoft.com/en-us/library/system.codedom.codesnippetexpression.aspx">CodeSnippetExpression</a>.</p>
<p>There is a Code object representation of anything that you could want to generate, you simply need to find the right class. For example, if we wanted to add a class entry point to our class then we could create one with the <a href="http://msdn.microsoft.com/en-us/library/system.codedom.codeentrypointmethod.aspx">CodeEntryPointMethod</a> class:</p>
<pre class="brush: delphi;">
  var MyMain: CodeEntryPointMethod := new CodeEntryPointMethod();
  MyMain.Name := 'Main';
  MyMain.Attributes := MemberAttributes.Public + MemberAttributes.Static;
  var cs1: CodeMethodInvokeExpression  := new CodeMethodInvokeExpression(
        new CodeTypeReferenceExpression('System.Console'), 'WriteLine',
        new CodePrimitiveExpression('Hello World!') );
  MyMain.Statements.Add(cs1);

  MyNewClass.Members.Add(MyMain);
</pre>
<h3>Conclusion</h3>
<p>The <a href="http://msdn.microsoft.com/en-us/library/system.codedom.aspx">System.CodeDom</a> space is a very very powerful tool and one that developers used to developing native Win32 Delphi might not be aware of. You will probably be able to dream up of a number of cases where generating some of your Delphi Prism code dynamically could save you time. Use it wisely.</p>
]]></content:encoded>
			<wfw:commentRss>http://jamiei.com/blog/2009/10/dynamically-generating-code-with-delphi-prism/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Dynamically compiling code with Delphi Prism</title>
		<link>http://jamiei.com/blog/2009/09/dynamically-compiling-code-with-delphi-prism/</link>
		<comments>http://jamiei.com/blog/2009/09/dynamically-compiling-code-with-delphi-prism/#comments</comments>
		<pubDate>Wed, 02 Sep 2009 13:13:21 +0000</pubDate>
		<dc:creator>jamiei</dc:creator>
				<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Delphi Prism]]></category>
		<category><![CDATA[code generation]]></category>
		<category><![CDATA[compilation]]></category>
		<category><![CDATA[delphi prism]]></category>

		<guid isPermaLink="false">http://jamiei.com/blog/?p=414</guid>
		<description><![CDATA[Delphi Prism and the .NET Framework are both extremely powerful tools and bring a lot of flexibility that Delphi for Win32 cannot necessarily provide, particularly when it comes to reflection and code generation. I recently started a project where I wanted to be able to compile a string with Delphi Prism code into an assembly without hacking my [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.embarcadero.com/products/delphi-prism">Delphi Prism</a> and the .NET Framework are both extremely powerful tools and bring a lot of flexibility that Delphi for Win32 cannot necessarily provide, particularly when it comes to reflection and code generation. I recently started a project where I wanted to be able to compile a string with Delphi Prism code into an assembly without hacking my way around with the <a href="https://downloads.embarcadero.com/free/delphi_prism">Delphi Prism command line compiler</a>.  This could be used to potentially create a Delphi Prism Snippet Compiler similar to the <a href="http://www.sliver.com/dotnet/SnippetCompiler/">.NET Snippet Compiler</a> from Jeff Key.</p>
<p>It is my intention that this post should introduce you to the process of dynamically compiling code and that the next part will hopefully be an introduction to the process of dynamically generating and compiling code using the .NET CodeDom.</p>
<p>To begin with, create a <strong>New Console Application</strong> in <strong>Delphi Prism</strong> and Add a Reference to the <strong>RemObjects.Oxygene.CodeModel</strong> assembly. For my installation, this was found in the <strong>Bin</strong> directory of the Delphi Prism program files directory.</p>
<p>Once you&#8217;ve done this you can use the following code:</p>
<pre class="brush: delphi;">namespace DynamicCompilation;

interface

uses
  System.Collections,
  System.CodeDom.Compiler,
  RemObjects.Oxygene.CodeDom;

type
  ConsoleApp = class
  public
    class method Main;
  end;

implementation

class method ConsoleApp.Main;
var
  provider: CodeDomProvider;
  strFileOut: string;
  results: CompilerResults;
  cp: CompilerParameters;
  strSource: String;
begin

strSource := &quot;namespace HelloWorld;

interface

type
  ConsoleApp = public class
  public
    class method Main;
  end;

implementation

class method ConsoleApp.Main;
begin
  Console.WriteLine('Hello World.');
end;
end.&quot;;

  // Get our CodeDomProvider
  provider := CodeDomProvider.CreateProvider('Oxygene');

  cp := new System.CodeDom.Compiler.CompilerParameters;
  cp.CompilerOptions := '';
  // Defaults to false which creates a dll instead.
  cp.GenerateExecutable := true;
  strFileOut := 'C:\test.exe';
  cp.OutputAssembly := strFileOut;

  // Compile our code.
  results := provider.CompileAssemblyFromSource(cp, [strSource]);

  Console.WriteLine('Number of Errors Encountered: {0}', results.Errors.Count);
  for error: CompilerError in results.Errors do
      begin
        Console.WriteLine('{0}: {1}', [error.ErrorNumber, error.ErrorText]);
      end;
  if (Assigned(results.PathToAssembly)) then
     begin
       Console.WriteLine('Path to Assembly: {0}', results.PathToAssembly);
     end;

  Console.WriteLine('Press Enter to exit..');
  Console.ReadLine;
end;

end.</pre>
<div id="attachment_424" class="wp-caption aligncenter" style="width: 310px"><a href="http://jamiei.com/blog/wp-content/uploads/2009/09/DynamicCompilation_TestConsoleOutput.png"><img class="size-medium wp-image-424" title="DynamicCompilation_TestConsoleOutput" src="http://jamiei.com/blog/wp-content/uploads/2009/09/DynamicCompilation_TestConsoleOutput-300x151.png" alt="Our Test Console Output" width="300" height="151" /></a><p class="wp-caption-text">Our Test Console Output</p></div>
<p>This code should be fairly straight forward to understand but there are a few parts that are worth drawing attention to. The first is this line:</p>
<pre class="brush: delphi;">provider := CodeDomProvider.CreateProvider('Oxygene');</pre>
<p>I originally tried to create a new instance of the RemObjects.Oxygene.CodeModel.OxygeneCodeProvider as you can when <a href="http://msdn.microsoft.com/en-us/library/bb537926.aspx">creating a CSharpCodeProvider</a>:</p>
<pre class="brush: delphi;">            var provider_options = new Dictionary
                         {
                             {&quot;CompilerVersion&quot;,&quot;v3.5&quot;}
                         };
            var provider = new Microsoft.CSharp.CSharpCodeProvider(provider_options);</pre>
<p>However in my experience calling the constructor on the OxygeneCodeProvider class merely causes a Null Reference Exception when you actually try to use a Compile method on the resulting class. It is worth noting that by replacing the string &#8216;Oxygene&#8217; above with &#8216;VisualBasic&#8217; or &#8216;CSharp&#8217; you can obtain an instance of other language providers.</p>
<p>The next part worth paying careful attention to is the setup of the CompilerParameters:</p>
<pre class="brush: delphi;">  cp := new System.CodeDom.Compiler.CompilerParameters;
  cp.GenerateExecutable := true;
  strFileOut := 'C:\test.exe';
  cp.OutputAssembly := strFileOut;</pre>
<p>This part of the code, configures the Provider to generate an executable instead an assembly (which is the default configuration) and tells the Provider where to output the resulting executable. This should be relatively straightforward and for a full reference of <strong>CompilerParameters</strong> &#8211; see the MSDN documentation on <a href="http://msdn.microsoft.com/en-us/library/system.codedom.compiler.compilerparameters.aspx">System.CodeDom.Compiler.Compilerparameters</a>.</p>
<p>Those sharp-eyed amongst you may have noticed that the code that I&#8217;m compiling above does not contain any <strong>uses</strong> declarations. First we need to Reference the relevant assemblies using the CompilerParameters.<a href="http://msdn.microsoft.com/en-us/library/system.codedom.compiler.compilerparameters.referencedassemblies.aspx">ReferencedAssemblies</a> StringCollection:</p>
<pre class="brush: delphi;">  cp := new System.CodeDom.Compiler.CompilerParameters;
  // Clear our Assembly List
  cp.ReferencedAssemblies.Clear;
  // Add a few usual suspects
  cp.ReferencedAssemblies.Add('System.dll');
  cp.ReferencedAssemblies.Add('System.Core.dll');</pre>
<p>You can then &#8220;<strong>uses</strong>&#8221; any namespace in the referenced assemblies (be careful: There is no official .NET assembly called <em>System.Linq.dll</em> for example).</p>
<p>The final part which is worth drawing attention to is the actual compile command:</p>
<pre class="brush: delphi;">   results := provider.CompileAssemblyFromSource(cp, [strSource]);</pre>
<p>For reference, the relevant parts of the declaration for a CodeDomProvider might look something like the following:</p>
<pre class="brush: delphi;">public CodeDomProvider = class abstract(Component)
    public function CompileAssemblyFromDom(options: CompilerParameters; [ParamArray] compilationUnits: CodeCompileUnit[]): CompilerResults; virtual;
    public function CompileAssemblyFromFile(options: CompilerParameters; [ParamArray] fileNames: string[]): CompilerResults; virtual;
    public function CompileAssemblyFromSource(options: CompilerParameters; [ParamArray] sources: string[]): CompilerResults; virtual;</pre>
<p>You can feed the CompileAssemblyFrom methods several different files, strings, or Dom structures which might represent different .pas files that you would create when you created a project in Delphi Prism. The example below includes an additional class:</p>
<pre class="brush: delphi; collapse: true; light: false; toolbar: true;">namespace DynamicCompilation;

interface

uses
  System.Collections,
  System.CodeDom.Compiler,
  RemObjects.Oxygene.CodeDom;

type
  ConsoleApp = class
  public
    class method Main;
  end;

implementation

class method ConsoleApp.Main;
var
  provider: CodeDomProvider;
  strFileOut: string;
  results: CompilerResults;
  cp: CompilerParameters;
  strSource: String;
begin

strSource := &quot;namespace HelloWorld;

interface

type
  ConsoleApp = public class
  public
    class method Main;
  end;

implementation

class method ConsoleApp.Main;
var
  PingPong: TPingPong;
begin
  PingPong := new TPingPong;
  Console.WriteLine(PingPong.Ping);
  Console.WriteLine('Hello World.');
end;
end.&quot;;

var strSource2 := &quot;namespace HelloWorld;

interface

type
  TPingPong = public class
  public
    method Ping: string;
  end;

implementation

method TPingPong.Ping: string;
begin
  Result := 'PONG!';
end;
end.&quot;;

  // Get our CodeDomProvider
  provider := CodeDomProvider.CreateProvider('Oxygene');

  cp := new System.CodeDom.Compiler.CompilerParameters;

  cp.CompilerOptions := '';
  // Defaults to false which creates a dll instead.
  cp.GenerateExecutable := true;
  strFileOut := 'C:\test.exe';
  cp.OutputAssembly := strFileOut;

  // Clear our Assembly List
  cp.ReferencedAssemblies.Clear;
  // Add a few usual suspects
  cp.ReferencedAssemblies.Add('System.dll');
  cp.ReferencedAssemblies.Add('System.Data.dll');

  // Compile our code.
  results := provider.CompileAssemblyFromSource(cp, [strSource2, strSource]);

  //Console.WriteLine('Generated assembly name: ' + results.CompiledAssembly.FullName);
  Console.WriteLine('Number of Errors Encountered: {0}', results.Errors.Count);
  for error: CompilerError in results.Errors do
      begin
        Console.WriteLine('{0}: {1}', [error.ErrorNumber, error.ErrorText]);
      end;
  if (Assigned(results.PathToAssembly)) then
     begin
       Console.WriteLine('Path to Assembly: {0}', results.PathToAssembly);
     end;

  Console.WriteLine('Press Enter to exit..');
  Console.ReadLine;
end;

end.</pre>
<p>And voila.. the output from our dynamically compiled executable can be seen as below:</p>
<div id="attachment_425" class="wp-caption aligncenter" style="width: 310px"><a href="http://jamiei.com/blog/wp-content/uploads/2009/09/DynamicCompilation_ExecutableOutput.png"><img class="size-medium wp-image-425" title="DynamicCompilation_ExecutableOutput" src="http://jamiei.com/blog/wp-content/uploads/2009/09/DynamicCompilation_ExecutableOutput-300x151.png" alt="The output from our dynamically generated executable" width="300" height="151" /></a><p class="wp-caption-text">The output from our dynamically generated executable</p></div>
<p>If the other compiler methods available with our CodeProvider caught your eye then this leads me nicely onto my intended next steps. While generating code from a string containing your code is nice and easy, sometimes it may not be the best way to approach Code Generation. </p>
<p>I realise that the end result of the above could have been achieved by simply writing a file out and then executing the command line compiler but where&#8217;s the fun in that? Next time I intend on looking at generating a CodeDom tree and providing this to the Compiler (no more potentially troublesome string manipulation required).</p>
]]></content:encoded>
			<wfw:commentRss>http://jamiei.com/blog/2009/09/dynamically-compiling-code-with-delphi-prism/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic Page Served (once) in 1.154 seconds -->
