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

<channel>
	<title>Jamie&#039;s Blog &#187; Delphi Prism</title>
	<atom:link href="http://jamiei.com/blog/topic/development/delphi/delphi-prism-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>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>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>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>
		<item>
		<title>Delphi Prism and the Cirrus Framework</title>
		<link>http://jamiei.com/blog/2009/06/delphi-prism-cirrus-framework/</link>
		<comments>http://jamiei.com/blog/2009/06/delphi-prism-cirrus-framework/#comments</comments>
		<pubDate>Mon, 29 Jun 2009 08:10:48 +0000</pubDate>
		<dc:creator>jamiei</dc:creator>
				<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Delphi Prism]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[aop]]></category>
		<category><![CDATA[cirrus]]></category>
		<category><![CDATA[delphi prism]]></category>

		<guid isPermaLink="false">http://jamiei.com/blog/?p=337</guid>
		<description><![CDATA[The May 2009 Release of Delphi Prism introduced the Cirrus layer that provides Delphi Prism developers access to a library for Aspect Oriented Programming natively for the first time. The AOP Wikipedia article has a much more detailed explaination than I could provide but for those who don&#8217;t want to read the full article AOP [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://edn.embarcadero.com/article/39578">May 2009 Release</a> of Delphi Prism introduced the <a href="http://prismwiki.codegear.com/en/Cirrus">Cirrus</a> layer that provides Delphi Prism developers access to a library for <a href="http://en.wikipedia.org/wiki/Aspect_Oriented_Programming">Aspect Oriented Programming</a> natively for the first time. The <a href="http://en.wikipedia.org/wiki/Aspect_Oriented_Programming">AOP Wikipedia</a> article has a much more detailed explaination than I could provide but for those who don&#8217;t want to read the full article AOP represents a new programming paradigm which claims to allow a cleaner separation of concerns. The general idea is that you can write your code as an <em>Aspect</em> which can then be injected into your target class, allowing the <em>Aspec</em>t code to replace, wrap or alter the target code. There are a few 3rd party frameworks for Delphi Win32 such as <a href="http://code.google.com/p/meaop/">MeAOP</a> but I&#8217;m not sure if their support is anything like as extensive as Cirrus.</p>
<h4>Why would you need  to use AOP?</h4>
<p>Many people don&#8217;t really understand why they would need to use AOP in any way. It&#8217;s true that nearly all programming paradigms support some form of separation and modularity but to see where this can quickly fall down, you simply have to look at the classic <a href="http://prismwiki.codegear.com/en/Cirrus_Introduction">logging example</a> which has been the staple diet of coverage of the <a href="http://prismwiki.codegear.com/en/Cirrus">Cirrus framework</a>. Logging is a good example because it is likely that if your application implements logging features, then you probably have logging code mixed up in your beautifully designed business objects at various places tainting the implementation of your once clean object.</p>
<h4>A Simple Example</h4>
<p>For the purposes of those people who weren&#8217;t convinced on it&#8217;s usefulness from the example given. Imagine we have a very important Business object of a Type called <strong>TCustomer</strong>. We&#8217;ve been told that we need to log everything done to our Customer objects for audit purposes (and you wouldn&#8217;t want to get on the wrong side of the Internal Audit team..).  We could easily add our logging calls into every function of TCustomer but this going to require a lot of <em>CTRL+C</em>, <em>CTRL+V</em> and is a lot of identical code-repetition and shouldn&#8217;t we be striving to avoid code repetition? This might also get your local overly-sensitive <a href="http://www.secretgeek.net/copy_paste_dont_do_it.asp">Anti Copy-Paste mafia</a> up in arms. There is another problem with simply inserting our code into each method: What happens if later on, another programmer adds another method for updating, deleting or even just saving a copy of our Customer. Internal Audit are not going to be happy. Of course, you could blame it on your inexperienced colleague but that&#8217;s not going to make much difference, it&#8217;s a team failure after all.</p>
<p>Had we used AOP we could have used something as simple as the <a href="http://prismwiki.codegear.com/en/Cirrus_Introduction">Cirrus Introduction</a> LogToMethod code, tagged our <strong>TCustomer</strong> class with a single attribute and been saved from this potential oversight:</p>
<pre class="brush: delphi;">// For the full code for this example, please see the original introductory tutorial at:
// http://prismwiki.codegear.com/en/Cirrus_Introduction
namespace MyLogToMethodAspect;

interface
uses
  RemObjects.Oxygene.Cirrus;

type
  [AttributeUsage(AttributeTargets.Class or AttributeTargets.Struct)]
  LogToMethodAttribute = public class(System.Attribute, IMethodImplementationDecorator)
  public
    [Aspect:AutoInjectIntoTarget]
    class method LogMessage(aEnter: Boolean; aName: String; Args: Array of object);

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

implementation

class method LogToMethodAttribute.LogMessage(aEnter: Boolean; aName: String;
  Args: Array of object);
begin
  if aEnter then
    Console.WriteLine('Entering ' + aName)
  else
    Console.WriteLine('Exiting ' + aName);
end;

method LogToMethodAttribute.HandleImplementation(Services: IServices; aMethod: IMethodDefinition);
begin
  if String.Equals(aMethod.Name, 'LogMessage',
    StringComparison.OrdinalIgnoreCase) then exit;
  if String.Equals(aMethod.Name, '.ctor',
    StringComparison.OrdinalIgnoreCase) then exit;

  // Cool use of anonymous methods here....
  aMethod.SetBody(Services,
    method begin
      LogMessage(true, Aspects.MethodName, Aspects.GetParameters);
      try
        Aspects.OriginalBody;
      finally
        LogMessage(false, Aspects.MethodName, Aspects.GetParameters);
      end;
    end);
end;

end.</pre>
<p>Of course, you don&#8217;t <strong>need</strong> Aspect Oriented Programming in the same way as you don&#8217;t <strong>need</strong> Object Oriented Programming, we could just revert to procedural programming but as programmers we strive to separate various concerns cleanly and this is another step towards that.</p>
<h4>What&#8217;s the catch?</h4>
<p>The problem with separating our code in such a way is that potentially, it could be hard for a programmer unfamiliar with AOP to understand the code as the only clue of any logging activity for our target class might be a single attribute in our interface section. Our Aspect might also rely upon the underlying method in which case we could run into problems if we restructure or  move our methods around causing unintended consequences. There is also a concern that a serious bug in our Aspect code could lead to a more widespread failure in the program (as it has the potential to be applied to large swathes of code easily).</p>
<p>However, with careful testing and implementation these potential drawbacks can be mitigated.</p>
<h4>Apart from Logging, what else can I use it for?</h4>
<p>Typical uses include logging, authentication, caching and dependency injection. <a href="http://blog.moshine.com/blog/Default.aspx">John Moshakis</a> has been blogging some elegant real-life uses of the Cirrus framework such as <a href="http://blog.moshine.com/blog/post/2009/05/Implementing-Dependency-Injection-using-AOP.aspx">Implementing Dependency Injection</a>, allowing him to switch seamlessly between test and production services in an app.</p>
<h4>My Own Journey to AOP</h4>
<p>After the Cirrus Framework was released I wanted to try to build my own Aspect which wasn&#8217;t the logging sample provided. I had a service that retrieved a string of XML from a REST Web Service at frequent intervals which I felt could be improved with caching functionality. The Code for the Web Service and for the Cache were just test classes for the purpose of this experiment but I would imagine that you could extend this to use the <a href="http://msdn.microsoft.com/en-us/library/dd203226.aspx">The Caching Application Block</a> from the <a href="http://msdn.microsoft.com/en-us/library/dd203099.aspx">Microsoft Enterprise Library</a> if you wished. Normally, I could add caching to each method by modifying it like so:</p>
<pre class="brush: delphi;">method TFlickr.GetUserInformation(username: String): String;
begin
  // Do we have this information in our cache?
  if (MyCache.HasData('UserInfo_' + username)) then
  begin
    // We do, use the cache'd data.
    Result := MyCache.GetData('UserInfo_' + username);
  end
  else
  begin
    // No cache'd version, retrieve a new set of data.
    { Open our TCP Socket, call the webservice with the
      correct parameters and return the result.     }
    // Add our newly retrieved data to the cache.
    MyCache.SetData('UserInfo_' + username, Result);
  end;
end;</pre>
<p>This method of implementation would lead to me having to put this code into each method and would lead to code repetition and possibly bugs being introduced (for example, if I forgot to update the cache key string on one method). I wondered if I could have a CacheString attribute that would allow me to automaticaly add my generic &#8220;do we have cache&#8217;d data? if so use it else carry on&#8221;  code to each method.</p>
<p>First of all, I tried essentially moving this code into a Method Aspect and adding a generic key function which takes the method name and method arguements and turns it into a consistent string using the Aspects.MethodName and Aspects.GetParameters methods:</p>
<p><span style="color: #ff0000;"><strong>WARNING! BROKEN CODE:</strong></span></p>
<pre class="brush: delphi;">class method MyCache.getKeyFromMethod(aName: String; Args: Array of object): String;
begin
  var argConcat: String;

  argConcat := aName;
  for argTemp: String in Args do
  begin
    argConcat := argConcat + argTemp;
  end;

  Result := argConcat;
end;

method MyCacheAttribute.HandleImplementation(Services: IServices; aMethod: IMethodDefinition);
begin
  aMethod.SetBody(Services,
    method begin
	  var cacheKey := MyCache.getKeyFromMethod(Aspects.MethodName, Aspects.GetParameters);
	  // Do we have this information in our cache?
	  if (MyCache.HasData(cacheKey)) then
	  begin
		// We do, use the cache'd data.
		Result := MyCache.GetData(cacheKey);
	  end
	  else
	  begin
        Aspects.OriginalBody;

        // Send the result of the Original Method to the Cache for next time.
        MyCache.setData(cacheKey, Result);
      end;
    end);
end;</pre>
<p>Unfortunately it is not quite as simple as just placing your code into the AMethod.SetBody Anonymous method. Luckily it turned out that the <a href="http://prismwiki.codegear.com/en/Cirrus">Cirrus documentation</a> on the Wiki had recently been updated and I discovered the <a href="http://prismwiki.codegear.com/en/Cirrus_Statements_Namespace">Cirrus Statements</a> and <a href="http://prismwiki.codegear.com/en/Cirrus_Values_Namespace">Cirrus Values</a> namespaces after a bit of helpful guidance from <a href="http://twitter.com/moshakis">John Moshakis</a> on StackOverflow and Twitter (thank-you for that John!). I discovered that what you are required to do in most cases is to construct your code in an almost compiler like fashion using the Statement and Values namespaces.</p>
<p>Eventually after playing around with the Cirrus API, I eventually ended up with the following code:</p>
<pre class="brush: delphi;">
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.MyCache');
  // 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 := MyCache.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.
          MyCache.setData(cacheKey, resultOriginal);
        end;
      end;
    end);
end;</pre>
<p>According to the <a href="http://www.red-gate.com/products/reflector/">Red Gate .NET Reflector</a> and Disassembler, this produces the following code:</p>
<pre class="brush: delphi;">
    function TFlickr.GetUserInformation(username: String): String;
    var
        Result: string;
    begin
        cacheKey := MyCache.getKeyFromMethod('GetUserInformation', New(array[1] of TObject, ( ( userid ) )));
        try
            Result := MyCache.getData(cacheKey)
        except
            on E: Exception do
            begin
                // This is where we do our _ORIGINAL_ function
                resultOriginal := Result;
                MyCache.setData(cacheKey, resultOriginal)
            end
        end;
        begin
            Result := Result;
            exit
        end
    end;</pre>
<p>This means that I can now add caching to any of my string returning web service methods in my class by simply tagging the methods that I want cached with a code attribute:</p>
<pre class="brush: delphi;">
  TFlickr = public class
  private
	{code}
  public
    {more code etc, etc}
    [Aspect:MyStringCache]
    method TFlickr.GetUserInformation(username: String): String;
  end;
</pre>
<p>This works perfectly but there are a few problems with this code:</p>
<ul>
<li>As you can see: constructing statements using the Cirrus API (in the statements before the aMethod.setBody) doesn&#8217;t exactly make for readable code. You may wish to consider outlining each statement with <a href="http://en.wikipedia.org/wiki/Pseudocode">psuedocode</a> so that it is clearer at a glance what the API calls produce.</li>
<li>I should be using the <a href="http://prismwiki.codegear.com/en/ProcValue_Class">Cirrus Procedure Value</a> calls for all three calls to the Static &#8220;MyCache&#8221; class but am not because I couldn&#8217;t quite get this working. Please be aware that John informs me that the method I use in the first and third instance is <strong>not</strong> the correct way to go about this.</li>
<li>This exact method only currently works for System.String returning methods. There must be a way of abstracting this function to apply it to almost a method returning almost any type (if anyone has any suggestions about how this might be accomplished then, by all means post a link in the comments).</li>
</ul>
<p>Please note that the code above is <strong>NOT</strong> intended to be a reference implementation for AOP or Application Caching but is merely intended to show you my own learning path with Cirrus and AOP. The Cirrus API is quite difficult to work with at first and can give you frustrating compiler errors but it&#8217;s worth keeping an eye on the <a href="http://prismwiki.codegear.com/en/Cirrus">documentation</a> pages and as more examples appear online it will become easier to work with. You should have the <a href="http://www.red-gate.com/products/reflector/">Red Gate .NET Reflector</a> on hand with its disassemble function to confirm exactly what the resulting code in your Output assemblies looks like.</p>
<p>If you have any constructive suggestions for my code above then please let me know. Additionally, if you think it would be useful for me to post the downloadable Delphi Prism project then please also let me know in the comments below.</p>
<h4>Starting your own journey to Cirrus/AOP</h4>
<ul>
<li><a href="http://prismwiki.codegear.com/en/Cirrus">Delphi Prism Wiki &#8211; Cirrus Documentation</a> &#8211; The Definitive Reference.</li>
<li><a href="http://it-republik.de/konferenzen/delphi_live/material/DelphiLive2009_mckeeth_aspect_oriented_programming.zip">Jim McKeeth&#8217;s DelphiLive! Presentation on AOP</a> &#8211; A Good Introduction and Overview to AOP.</li>
<li><a href="http://prismwiki.codegear.com/en/Cirrus_Introduction">Delphi Prism Wiki &#8211; Cirrus Introduction</a> &#8211; An Introductory guide to Cirrus and AOP that will guide you into building the logging example shown in this post.</li>
<li><a href="http://blog.moshine.com/blog/Default.aspx">John Moshakis&#8217;s Blog </a>- Some Excellent Examples of real applications of the Cirrus Framework.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://jamiei.com/blog/2009/06/delphi-prism-cirrus-framework/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Diary of a C# to Delphi Prism conversion</title>
		<link>http://jamiei.com/blog/2009/04/diary-of-a-c-to-delphi-prism-conversion/</link>
		<comments>http://jamiei.com/blog/2009/04/diary-of-a-c-to-delphi-prism-conversion/#comments</comments>
		<pubDate>Tue, 28 Apr 2009 14:15:25 +0000</pubDate>
		<dc:creator>jamiei</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Delphi Prism]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Podcast at Delphi]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[delphi prism]]></category>
		<category><![CDATA[project conversion]]></category>

		<guid isPermaLink="false">http://jamiei.com/blog/?p=271</guid>
		<description><![CDATA[I have in the past written up a few tips for converting a Delphi.NET project to Delphi Prism but this time I thought it might be useful for me to write up my experiences on converting this C# Project to Delphi Prism by initially using the C#ToPas Tool from RemObjects. Many of you who attended CodeRage [...]]]></description>
			<content:encoded><![CDATA[<p>I have in the past written up a few tips for <a href="http://jamiei.com/blog/2008/12/migrating-a-project-to-delphi-prism-from-delphinet/">converting a Delphi.NET project to Delphi Prism</a> but this time I thought it might be useful for me to write up my experiences on converting this C# Project to Delphi Prism by initially using the C#ToPas Tool from RemObjects. Many of you who attended <a href="http://conferences.codegear.com/coderage08">CodeRage III</a> (in a virtual manner) might remember <a href="http://www.delphi.org">Jim McKeeth</a>&#8216;s <a href="http://www.delphi.org/robot-rage/">Revenge of Delphi Robot rage</a> session. The aim of the session was to build a <a href="http://www.unrealtournament3.com/">Unreal Tournament 3</a> Bot to fight it out against other competitor&#8217;s bots in an Unreal Tournament 3 arena using the (then) newly recently <a href="http://www.codegear.com/products/delphi/prism">Delphi Prism</a> tool. For those who didn&#8217;t attend, I&#8217;ll spoil the ending and just tell you that somehow <a href="http://www.delphi.org/2008/12/18-coderage-iii-wrap-up/">my bot won</a>. <img src='http://jamiei.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p>Jim is planning another session for the <a href="http://www.delphilive.com/">DelphiLive</a> conference (which I really wish I could go to, check it out if you haven&#8217;t already). However when running the last tournament we encountered a number of fatal bugs in the .NET UT3 Bot library which was originally put together by <a href="http://www.utbots.com/">Andy Sterland &amp; James Lissiak</a>. As a result Jim and I had been discussing the idea of porting the original library to Delphi Prism so that we could fix a few of the more serious bugs, it would also allow potential Prism Developers who were not familiar with C# to dig into the library itself. This is a project conversion diary which will outline the approaches I tried, any hurdles I encountered and a few tips for trying to avoid them when converting your own project.</p>
<p>I started by running the <a href="http://code.remobjects.com/p/csharptoxy/">C#ToOxygene</a> Tool on all of the source files within the project, It&#8217;s a very simple and easy to use tool that as its name implies aims to convert C# source files to Delphi Prism files. I was able to run the tool without issue on every C# source file except for 3 where for some reason it exited producing the error:  &#8221;<em><strong>Error during processing: Index was out of range</strong></em>&#8221; (Issue logged (rather clumsily) as #<a href="http://code.remobjects.com/p/csharptoxy/issues/37/">37</a>).</p>
<p>Having started on the basics of the translation using the conversion tool to do the grunt work I then dived into the code with the <a href="http://prismwiki.codegear.com/">Prism Wiki</a> and <a href="http://msdn.microsoft.com/en-us/library/618ayhy6(VS.80).aspx">MSDN C# documentation</a> open to make a start on correcting the <strong>600-odd errors</strong> that the resulting project produced upon an attempted Build.</p>
<p>At first glance I felt that the resultant code was a little bit visually &#8220;messy&#8221; in places and I felt it might be easier to prettify the code using a Code Formatter such as the <a href="http://jedicodeformat.sourceforge.net/">JEDI Code Format</a> tool to clean up the auto generated code and highlight any mismatched parenthesis or similar errors. However unfortunately the JEDI tool is not compatible with Prism and therefore refused to help me. If anyone knows of a Code Formatting tool which is compatible with Delphi Prism then please let me know in the comments below.</p>
<p>A few other issues which I encountered with the generated code or more generally are outlined below:</p>
<h3>Internal Keyword</h3>
<p><span style="font-weight: normal; font-size: 13px;">The C# <strong>internal</strong> (<a href="http://msdn.microsoft.com/en-us/library/7c5ka91b(VS.80).aspx">msdn doc</a>) keyword was not correctly translated &#8211; for this I took a trip to the Prism Wiki and looked up the <a href="http://prismwiki.codegear.com/en/Class_Member_Visibility_Levels">Class Member Visibility Levels</a> page to find that the equivalent level <strong>assembly</strong> is listed there (Issue #<a href="http://code.remobjects.com/p/csharptoxy/issues/42/">42</a>). Note that in Delphi Prism you can also have </span><span style="font-weight: normal; font-size: 13px;"><strong>assembly or protected</strong></span><span style="font-weight: normal; font-size: 13px;"> or </span><span style="font-weight: normal; font-size: 13px;"><strong>assembly and protected</strong></span><span style="font-weight: normal; font-size: 13px;"> depending upon whether you wish the class to be visible to descendants.</span></p>
<h3>The C# &#8220;this&#8221; Keyword</h3>
<p>The C# <strong>this.</strong> (<a href="http://msdn.microsoft.com/en-us/library/dk1507sz(VS.80).aspx">msdn doc</a>) keyword was not correctly translated to the Delphi Prism <strong>Self.</strong> equivalent that we&#8217;re all accustomed to. This isn&#8217;t hard to spot when going through the generated code and the issue had already been logged by Anton Kasyanov (Issue #<a href="http://code.remobjects.com/p/csharptoxy/issues/39/">39</a>) and should be fixed shortly.</p>
<h3>Float Types</h3>
<p>One class made extensive use of the <strong>float</strong> type (<a href="http://msdn.microsoft.com/en-us/library/b1e65aza(VS.80).aspx">msdn doc</a>) which doesn&#8217;t exist as is a built-in type for Delphi Prism so you&#8217;ll need to convert it to one of the <a href="http://prismwiki.codegear.com/en/Floats">two Float types</a> depending upon the precision you require.</p>
<h3>Operator Overloading</h3>
<p>Operator Overloading is not something that Delphi developers may be traditionally used to but Delphi Prism supports this nicely. However instead of using the sign operator that C# Developers use you&#8217;ll need to lookup the operator name and declaration on the <a href="http://prismwiki.codegear.com/en/Operator_Overloading">Operator Overloading Wiki Page</a>. eg. The Equals operator is declared as so:</p>
<pre class="brush: delphi;">class operator Equal(obj1, obj2: UTIdentifier): boolean;</pre>
<h3>Differences between return, Result and exit</h3>
<p>This should be obvious to any C# Developer but it could be easy to forget about. Don&#8217;t forget that the <strong>return</strong> C# method (<a href="http://msdn.microsoft.com/en-us/library/1h3swy84(VS.80).aspx">msdn doc</a>) terminates execution of the method in which it is being executed and returns to the calling method and therefore be wary of using <strong>Result</strong> blindly in an identical manner, particularly with boolean statements that rely upon this fact. Eg. Consider the following C# Code:</p>
<pre class="brush: csharp;">public override bool Equals(object obj)
{
	if (obj is UTVector)
	{
		if (this._x == ((UTVector)obj)._x &amp;&amp;
			this._y == ((UTVector)obj)._y &amp;&amp;
			this._z == ((UTVector)obj)._z)
		{
			return true;
		}
	}
	return false;
}</pre>
<p>Clearly, if you simply replace the <strong>return false;</strong> with <strong>Result := False;</strong> you will end up with a method that always returns False because the expression will always be executed no matter what Result is set to earlier in the method. In this case I simply moved the <strong>Result := false;</strong> to the top of the method. Delphi Prism also supports the <a href="http://prismwiki.codegear.com/en/Exit_(keyword)">Exit keyword</a> which also allows you to Return a result parameter. This method is a lot closer to the C# return keyword and usage but the <a href="http://prismwiki.codegear.com/en/Exit_(keyword)">Exit page</a> on the Prism Wiki warns against using too many exit keywords to avoid making the code harder to maintain.</p>
<h3>Constructors are not named</h3>
<p>This is a rare example of where the original C# code actually looks much closer to the end Delphi Prism code than a traditional Delphi programmer might think. In C# you might have a class and constructor that might look like this:</p>
<pre class="brush: csharp;">public class UTIdentifier
{
	internal UTIdentifier(string Id)
	{
	}
}</pre>
<p>In Prism, we have nameless <a href="http://prismwiki.codegear.com/en/Constructors">constructors</a> which means that the equivalent Delphi Prism constructor implementation might look like this:</p>
<pre class="brush: delphi;">  constructor UTIdentifier(id: String);
  begin
  end;</pre>
<p>It is important to note that in your class interface should adhere to this rule too. eg <strong>constructor(id: String);</strong></p>
<p>This was something that the C#ToPas tool also generated incorrectly. (Issue #<a href="http://code.remobjects.com/p/csharptoxy/issues/44/">44</a>)</p>
<h3>Short-Circuit Boolean Expressions</h3>
<p>I came across the C# <a href="http://msdn.microsoft.com/en-us/library/6373h346(VS.80).aspx"><strong>||</strong></a> operator which performs a short-circuited OR boolean evaluation of the operands. I wasn&#8217;t sure that the Delphi Prism <strong>or</strong> operator produces the same behaviour but if I read the <a href="http://prismwiki.codegear.com/en/Expression_Evaluation#Boolean_Short-Circuit_Evaluation">Expression Evaluation</a> page correctly then I believe it does (In Delphi 2009, at least, this behaviour is set through the <a href="http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/devcommon/compdirsbooleanshortcircuitevaluation_xml.html">{$B+/-}</a> compiler flag) .</p>
<h3>Event Assignment</h3>
<p>The Event Assignment routine for multicast delegate type events is slightly different in Delphi Prism from what we&#8217;re used to in Delphi Win32. Looking at the <a href="http://prismwiki.codegear.com/en/Event_Assignment_Operators">Event Assignment</a> page in the wiki we can see that the actual method for assignment is much closer to the C# equivalent and uses the same C# <strong>+=</strong> and <strong>-=</strong> operators. The C#ToPas tool converted this code a little too literally converted this C# code:</p>
<pre class="brush: csharp;">this._connection.OnDataReceived += new EventHandler(DataReceived);
this._connection.OnErrorOccurred += new EventHandler(ErrorOccurred);</pre>
<p>to this:</p>
<pre class="brush: delphi;">Self._connection.OnDataReceived := Self._connection.OnDataReceived + new EventHandler(DataReceived);
Self._connection.OnErrorOccurred := Self._connection.OnErrorOccurred + new EventHandler(ErrorOccurred)</pre>
<p>Which produces a compiler Error that Events in Delphi Prism don&#8217;t allow access to the underlying field. You should use the += operator instead <a href="http://prismwiki.codegear.com/en/Event_Assignment_Operators">as seen on the Wiki</a>. (C#ToPas Issue logged as Issue #<a href="http://code.remobjects.com/p/csharptoxy/issues/45/">45</a>).</p>
<p><em>UPDATE: I&#8217;ve just noticed (after logging my own issue) that the event assignment issue has already been reported and has been marked as Won&#8217;t Fix (Issue #<a href="http://code.remobjects.com/p/csharptoxy/issues/27/">27</a>) so it looks like you&#8217;ll need to check _every_ event assignment in your project manually.</em></p>
<h3>Switch and Case Statements</h3>
<p>The C#ToPas tool did not appear to react well at all to use of the C# <a href="http://msdn.microsoft.com/en-us/library/06tc147t.aspx">switch</a> and case statements. I can&#8217;t give you any specific advice on how to fix these because each case statement was generated slightly differently in my converted code and therefore I can only advise that you check these manually or rewrite each of these methods by hand.</p>
<h3>Reserved Keywords</h3>
<p>Sadly this isn&#8217;t an issue that is related to the C#ToPas tool but more of an intrinsic difficulty when converting interoperable code between languages. I encountered at least one class that made use of a few reserved words in Delphi such as begin and end &#8211; I&#8217;m still not sure what to do with these for now.</p>
<h3>Overall Impression</h3>
<p>Despite a few early bugs the <a href="http://code.remobjects.com/p/csharptoxy/">C#ToPas</a> Tool is a good platform to begin converting your C# code to Delphi Prism although you may wish to ensure that you have some extensive Unit Tests for your code before the main code is converted so as to ensure that any bugs introduced can be picked up on quickly (which you have anyway right?). It is also worth noting that the <a href="http://prismwiki.codegear.com">Delphi Prism Wiki</a> (which now <a href="http://blogs.remobjects.com/blogs/mh/2009/04/27/p277">authenticates via your CDN login</a>) has <strong>excellent coverage</strong> and is an absolutely <strong>invaluable reference</strong> for anyone working with Delphi Prism.</p>
<p>By the time this entry is published I suspect that <a href="http://blogs.remobjects.com/blogs/ck/">Carlo</a> will be very close to fixing some or most of the above bugs in the C#ToPas tool.</p>
<p>The code is nowhere near complete yet and most of the files are still straight out of the Automatic conversion and therefore <strong>will not compile in any way</strong> but I&#8217;ve put what we have so far up on the rather smooth <a href="http://www.github.com">Github</a> site at the <a href="http://github.com/jamiei/PrismUT3RemoteBot">PrismUT3RemoteBot</a> project which anyone can fork and push changes back to. <a href="http://git-scm.com/">Git</a> is a little strange to work with at first because it&#8217;s a different mindset to SubVersion/CVS but it&#8217;s worth checking out if you haven&#8217;t already.</p>
<p>[<strong>UPDATE</strong>: The Prism UT3 Remote Bot conversion project has been completed since this original post and may be used during Jim McKeeth's session at <a href="http://www.delphilive.com/">DelphiLive! Germany Sept 28 - Oct 2 2009</a>.]</p>
]]></content:encoded>
			<wfw:commentRss>http://jamiei.com/blog/2009/04/diary-of-a-c-to-delphi-prism-conversion/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>New Language Features in Delphi Prism</title>
		<link>http://jamiei.com/blog/2009/01/new-language-features-in-delphi-prism/</link>
		<comments>http://jamiei.com/blog/2009/01/new-language-features-in-delphi-prism/#comments</comments>
		<pubDate>Sun, 11 Jan 2009 17:47:11 +0000</pubDate>
		<dc:creator>jamiei</dc:creator>
				<category><![CDATA[.NET General]]></category>
		<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Delphi Prism]]></category>
		<category><![CDATA[codegear]]></category>
		<category><![CDATA[delphi prism]]></category>
		<category><![CDATA[features]]></category>
		<category><![CDATA[language]]></category>
		<category><![CDATA[linq]]></category>

		<guid isPermaLink="false">http://jamiei.com/blog/?p=64</guid>
		<description><![CDATA[Continuing my look at Delphi Prism, in my previous post I took a (very short) look at some of the compatibility changes required to port my Delphi.NET  Twitter Library to Delphi Prism, I mentioned that I now needed to learn about some of the new language features provided by Prism. Ever since the release of [...]]]></description>
			<content:encoded><![CDATA[<p>Continuing my look at <a href="http://www.codegear.com/products/delphi/prism">Delphi Prism</a>, in my previous post I took a (very short) look at some of the compatibility changes required to <a href="http://jamiei.com/blog/2008/12/migrating-a-project-to-delphi-prism-from-delphinet/">port my Delphi.NET</a>  Twitter Library to Delphi Prism, I mentioned that I now needed to learn about some of the new language features provided by Prism.</p>
<p>Ever since the release of Delphi.NET there has been much confusion surrounding why you would choose the Delphi language for .NET Development. When Delphi.NET was released there was concern that it was not a first class member of the .NET framework and always seemed to lag 12-18 months behind the lightning fast pace of development of the .NET Framework. With Prism Delphi offerings for .NET are based upon the <a href="http://www.remobjects.com">RemObjects</a> Oxygene compiler which isn&#8217;t required to maintain a loose language compatibility with the Win 32 Delphi compiler and therefore is able to progress at a much faster pace.  </p>
<p>Still, despite this: A recent <a href="http://stackoverflow.com/questions/242584/will-you-use-delphi-prism">Delphi Prism related thread</a> at <a href="http://stackoverflow.com/questions/tagged/delphi">StackOverflow</a> showed that there still seems to be a general feeling that Delphi is a second class citizen in the .NET Development World. Some even seemed to suggest that the language features in Prism make it unrecognisable as Delphi. To try to dispense with this idea: I thought that I would show off some of <em>my own</em> favourite new language features in Delphi Prism and ones which for me make it a natural fit for .NET.  </p>
<p>Please note: This is <strong>not</strong> intended to be a comprehensive guide to the new language features. For that you&#8217;ll need to refer to the <a href="http://prismwiki.codegear.com/en/Main_Page">Delphi Prism Wiki</a> page on <a href="http://prismwiki.codegear.com/en/Delphi_Prism_Syntax_compared_with_Win32_Delphi">Compatibility with Win 32 Delphi</a>.</p>
<p>My favourite new language features which Prism brings to the table for Delphi Developers is <a href="http://msdn.microsoft.com/en-gb/library/bb308959.aspx">LINQ</a>. <a href="http://www.monien.net/blog/">Olaf Monien</a>, who I also follow on Twitter (<a href="http://twitter.com/omonien">@omonien</a>), posted a beautifully simple<a href="http://www.monien.net/blog/index.php/2008/12/delphi-can-do-linq/"> example of using LINQ with Delphi Prism</a> on his own blog and then showed how Delphi Prism can also do <a href="http://www.monien.net/blog/index.php/2008/12/delphi-can-even-linq-to-sql/">LINQ to SQL</a>. I have replicated his basic example below because it also demonstrates another great language feature.</p>
<pre class="brush: delphi;">// Type Declaration
  MusicAlbum = record
  public
    Name: string;
    Artist: string;
    AlbumYear: integer;
  end;</pre>
<pre class="brush: delphi;">var
  MyAlbum: MusicAlbum;
  MyAlbums : List&lt;MusicAlbum&gt;;
begin
// Create our Album List
MyAlbums := new List&lt;MusicAlbum&gt;; 

// Setup a our records
MyAlbum := new MusicAlbum;
MyAlbum.Artist := 'Kanye West';
MyAlbum.Name := '808s and Heartbreak';
MyAlbum.AlbumYear := 2008;
MyAlbums.Add(MyAlbum);  

// Execute our LINQ Query
var AlbumsLastYear := from Album in MyAlbums where Album.AlbumYear.Equals(2008); 

// Add the result to our listbox
for Album in AlbumsLastYear do
begin
  lbFoundAlbums.Items.Add(Album.Artist + ' - ' + Album.Name + ' (' + Album.AlbumYear + ')');
end;

end;</pre>
<p> <br />
This code clipping also demonstrates <a href="http://prismwiki.codegear.com/en/Type_Inference">Type Inference</a> which allows a variable type to be inferred from the context of it&#8217;s usage. For example, consider writing the following: <strong><em>var</em></strong><em> MyGreatList := </em><span class="hl kwa"><strong><em>new</em></strong></span><em> List&lt;</em><span class="hl kwb"><em>String</em></span><em>&gt;; </em>or even something as simple as <strong><em>var</em></strong><em> s := &#8216;string&#8217;;</em>. Type Inference is a useful addition which I can see myself making extensive use of. My only concern about Type Inference is how it affect&#8217;s the readability of the code as I am used to reviewing the var section of a method for a guide to what types are used within a method.</p>
<p>LINQ can also be used with XML. The below example takes our previous sample and reads the data from an XML file instead: </p>
<pre class="brush: delphi;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;albums&gt;
		&lt;album&gt;
			&lt;artist&gt;Kanye West&lt;/artist&gt;
			&lt;title&gt;808s and Heartbreak&lt;/title&gt;
			&lt;albumyear&gt;2008&lt;/albumyear&gt;
		&lt;/album&gt;
		&lt;album&gt;
			&lt;artist&gt;Kanye West&lt;/artist&gt;
			&lt;title&gt;Graduation&lt;/title&gt;
			&lt;albumyear&gt;2007&lt;/albumyear&gt;
		&lt;/album&gt;
		&lt;album&gt;
			&lt;artist&gt;Nas&lt;/artist&gt;
			&lt;title&gt;Unartistd&lt;/title&gt;
			&lt;albumyear&gt;2008&lt;/albumyear&gt;
		&lt;/album&gt;
		&lt;album&gt;
			&lt;artist&gt;Notorious OST&lt;/artist&gt;
			&lt;title&gt;The Notorious B.I.G.&lt;/title&gt;
			&lt;albumyear&gt;2009&lt;/albumyear&gt;
		&lt;/album&gt;
&lt;/albums&gt;
</pre>
<pre class="brush: delphi;">

var
  AlbumData: XDocument;
begin
  // Load our XML Document with a System.Xml.Linq.XDocument
  AlbumData := XDocument.Load('../../albums.xml');

  // Query for albums in the year 2008
  var AlbumsLastYear := from Album in AlbumData.Descendants('album') where Album.Element('albumyear').Value = '2008' select Album;

  for Album in AlbumsLastYear do
  begin
    var s := String.Format('{0} - {1} ({2})', Album.Element('artist').Value, Album.Element('title').Value , Album.Element('albumyear').Value);
    lbFoundAlbums.Items.Add(s);
  end;
</pre>
<p> </p>
<p>Another new language feature that I like in principle but will completely admit to not fully understanding yet is <a href="http://prismwiki.codegear.com/en/Anonymous_Methods_and_Delegates">Anonymous Methods and Delegates</a> which make executing code with different threads much easier. Sadly in my brief testing of Anonymous methods I discovered that they are only available in projects which link to the .NET Framework 3.0 and above (and, in my case, only WPF projects). In order to execute our ListBox adding code from the first code sample as an Anonymous Delegate you can do the following:</p>
<pre class="brush: delphi;">
// Add the result to our listbox
for Album in AlbumsLastYear do
begin
  Dispatcher.Invoke(DispatcherPriority.ApplicationIdle, method(MyAlbum : MusicAlbum);
      begin
      lbFoundAlbums.Items.Add(MyAlbum.Artist + ' - ' + MyAlbum.Name + ' (' + MyAlbum.AlbumYear + ')');
      end, Album);
end;
</pre>
<p>This means that the compiler declares a delegate with a signature matching our anonymous method and we have now easily executed this code within a seperate thread with a minimum of code.</p>
<p>There are several new language features which I personally have no use for but which facilitate the use of the Microsoft Parallels framework such as <a href="http://prismwiki.codegear.com/en/Futures">Futures</a> and <a href="http://prismwiki.codegear.com/en/Sequences">Parallel sequences</a>. Delphi Prism also supports Generics and as well as most of the standard Delphi Win32 syntax.<br />
 <br />
There are also lots of small additions that aren&#8217;t .NET features per-se but demonstrate the usefulness of freeing the Prism compiler and allowing more rapid progression such as <a href="http://prismwiki.codegear.com/en/Boolean_Double_Comparison">Double Boolean Expressions</a>. I&#8217;m sure we&#8217;ve all written a statement like this before:<strong> if</strong> (cost > 400) <strong>and</strong> (cost < 600) <strong>then</strong>. In Delphi Prism this can also be written as: <strong>if</strong> 400 < cost < 600 <strong>then</strong>. </p>
<p>As I quickly discovered whilst going through the Delphi Prism Wiki: the language changes to Delphi Prism were easier to adapt to and to learn than I had originally imagined. The New language features gained mostly did not affect my coding style too much <strong>so any developers who were concerned that Delphi Prism is nothing like Delphi have nothing</strong> to worry about. Many of the new features are useful for compatibility with the .NET Framework and will be a natural fit for existing Delphi or .NET Developers</p>
]]></content:encoded>
			<wfw:commentRss>http://jamiei.com/blog/2009/01/new-language-features-in-delphi-prism/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Migrating a Project to Delphi Prism from Delphi.NET</title>
		<link>http://jamiei.com/blog/2008/12/migrating-a-project-to-delphi-prism-from-delphinet/</link>
		<comments>http://jamiei.com/blog/2008/12/migrating-a-project-to-delphi-prism-from-delphinet/#comments</comments>
		<pubDate>Sun, 21 Dec 2008 16:25:04 +0000</pubDate>
		<dc:creator>jamiei</dc:creator>
				<category><![CDATA[.NET General]]></category>
		<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Delphi Prism]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Windows Development]]></category>
		<category><![CDATA[codegear]]></category>
		<category><![CDATA[delphi prism]]></category>
		<category><![CDATA[project conversion]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://jamiei.com/blog/?p=59</guid>
		<description><![CDATA[As we know, now that the future of Delphi.NET is Delphi Prism (based on the RemObjects Oxygene compiler) we have to migrate our Delphi.NET projects to be compatible with the Prism compiler. The Easiest way to get started is to look at the free Oxidizer tool provided on the RemObjects Wiki. The tool helps with [...]]]></description>
			<content:encoded><![CDATA[<p>As we know, now that the future of Delphi.NET is <a href="http://www.codegear.com/products/delphi/prism">Delphi Prism</a> (based on the <a href="http://www.remobjects.com">RemObjects Oxygene</a> compiler) we have to migrate our Delphi.NET projects to be compatible with the Prism compiler.<a href="http://www.codegear.com/products/delphi/prism"><img class="alignright" title="Codegear Delphi Prism Logo " src="http://www.codegear.com/article/38820/images/38820/prism.png" alt="" width="112" height="75" /></a></p>
<p>The Easiest way to get started is to look at the free <a href="http://prismwiki.codegear.com/en/Oxidizer">Oxidizer tool</a> provided on the <a href="http://prismwiki.codegear.com/en/Main_Page">RemObjects Wiki</a>. The tool helps with the conversion of Delphi Win32 projects to Delphi Prism (but I&#8217;m uncertain about how it performs on Delphi.NET to Delphi Prism). The Wiki is also an excellent place to get started, particularly the pages on <a href="http://prismwiki.codegear.com/en/Win32_Delphi_vs._Delphi_Prism">Delphi Win32 vs Delphi Prism</a> which list the major incompatibilities between the two languages. </p>
<p> </p>
<p>Whilst converting my Delphi.NET Library for accessing Twitter, I encountered a few basic hints and tips which I felt I should share here:</p>
<ul>
<li>You need to specify the <strong>namespace</strong> keyword at the top of your unit file instead of the <strong>unit</strong> keyword. The first time I tried to compile after doing this Prism still complained about not having a namespace keyword present, this was fixed by closing the solution and re-opening.</li>
<li>Delphi Prism automatically makes classes that are not explicitly marked otherwise as <strong>strict private</strong>. This meant that I had to go through my library and mark all classes that I wanted to make public. eg. <em>TMyClass = <strong>public </strong>class(System.Object);</em></li>
<li>The <strong>overload</strong> keyword isn&#8217;t neccesary as overloading is now implicit. This isn&#8217;t a problem at all and isn&#8217;t dificult to fix as it simply meant doing a Search and Replace for the overload keyword and removing it.</li>
<li><strong>TObject </strong>no long exists and instead needs to be replaced with <strong>System.Object</strong> which has much the same properties. </li>
<li>I encountered a few problems with the use of <strong>for .. in</strong> loops. It would seem that Delphi Prism loop variables are local to the loop and therefore should be declared at the beginning of the loop (see the <a href="http://prismwiki.codegear.com/en/For_(keyword)">for</a> wiki page for more info). In reality this meant changing: <strong><em>for </em></strong><em>strItem </em><strong><em>in</em></strong><em> list </em><strong><em>do </em><span style="font-weight: normal;">to<em> </em><strong><em>for </em></strong><em>strItem: string </em></span><em>in</em><span style="font-weight: normal;"><em> list </em><strong><em>do</em></strong> and then removing the </span>strItem: string; <span style="font-weight: normal;">declaration in the method var section.</span></strong></li>
<li>The <strong>TObject.Create([...]);</strong> constructor still exists however it is now <a href="http://prismwiki.codegear.com/en/New_(keyword)">recommended</a> that you switch to the <strong>new Object([..]) </strong>keyword for new projects. This may come as a shock to traditional Delphi&#8217;ers who have been <strong>.Create()</strong>&#8216;ing since the dawn of Borland but this is the construction method that sems to fit in with the .NET framework better. There is also a compatibility flag in the Project properties which allows the compiler to work some magic to allow .Create to continue to function.</li>
</ul>
<p>These are not the only changes that you will probably need to make but I found them to be a good starting point. You should definitely consult the <a href="http://prismwiki.codegear.com/en/Main_Page">Prism Wiki</a> for help in which I was able to find answers very quickly (no wading boots required!).</p>
<p>Lastly: My project could do with a lot of refactoring in order to take advatages of the unique language features of Prism. This will take considerably more time as it means learning the new language features first!</p>
]]></content:encoded>
			<wfw:commentRss>http://jamiei.com/blog/2008/12/migrating-a-project-to-delphi-prism-from-delphinet/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

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