<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
		<title>Topten Software</title>
		<link>http://www.toptensoftware.com</link>
		<copyright>copyright &#169; 2013 Topten Software</copyright>
		<description></description>
		<managingEditor>Brad Robinson</managingEditor>
		<language>en-US</language>
		<generator>Jab2</generator>
		<atom:link href="www.toptensoftware.com/Feed" rel="self" type="application/rss+xml" />
<item>
			<title>MarkdownDeep Update</title>
			<author>brobinson</author>
			<pubDate>Mon, 20 Aug 2012 03:51:53 GMT</pubDate>
			<description><![CDATA[<p>MarkdownDeep hasn't been updated for a while, but here's a few updates...</p>
<p>I've just uploaded a new version of MarkdownDeep with a a few tweaks pulled in from github pull requests:</p>
<ol>
<li>Merged Ben Swaynes changes for the GUI editor markup and styles, as described on his blog post - <a href="http://www.benswayne.com/improving-markdowndeep-jquery-editor-markup" target="_blank">http://www.benswayne.com/improving-markdowndeep-jquery-editor-markup</a>.  Thanks Ben.</li>
<li>Merged some fixes relating to footnote formatting (incorrect # prefix on element ids + missing closing angle bracket on the closing list tag).</li>
</ol>
<p>Both sets of changes are up in github and in nuget now.</p>
]]></description>
			<link>http://www.toptensoftware.com/Articles/140/MarkdownDeep-Update</link>
			<guid isPermaLink="false">http://www.toptensoftware.com/Articles/140/MarkdownDeep-Update</guid>
			<comments>http://www.toptensoftware.com/Articles/140/MarkdownDeep-Update</comments>
			<category>MarkdownDeep</category>
			</item><item>
			<title>Icon Evolution</title>
			<author>brobinson</author>
			<pubDate>Fri, 29 Jun 2012 07:49:22 GMT</pubDate>
			<description><![CDATA[<p>I don't usually write about graphic design because although I'm interested in it, I certainly don't consider myself a graphic artist... and I've got the history of a recent attempt to prove it.</p>
<p>I mentioned in my previous <a href="http://www.toptensoftware.com/Articles/138/Building-MiniComp">post about building Minicomp</a> that it took a long time to get MiniComp's application icon right.  Today while cleaning up I noticed a set of SVG files that shows roughly how that went...</p>
<table>
<tbody>
<tr>
	<td><img src="http://www.toptensoftware.com/Files/MiniCompIcon1.png" alt="Icon1" width="180" height="180" /></td>
	<td>First attempt, too cartoony</td>
</tr>
<tr>
	<td><img src="http://www.toptensoftware.com/Files/MiniCompIcon2.png" alt="Icon2" width="180" height="180" /></td>
	<td>I've tried this cut-out style icon a few times, but it's never really worked out.</td>
</tr>
<tr>
	<td><img src="http://www.toptensoftware.com/Files/MiniCompIcon3.png" alt="Icon3" width="180" height="180" /></td>
	<td>Borrowing the striped green look from the messages app.  For a while I was considering a green lawn type theme.</td>
</tr>
<tr>
	<td><img src="http://www.toptensoftware.com/Files/MiniCompIcon4.png" alt="Icon4" width="180" height="180" /></td>
	<td>Back to a gold trophy look, but keeping the stripes.</td>
</tr>
<tr>
	<td><img src="http://www.toptensoftware.com/Files/MiniCompIcon5.png" alt="Icon5" width="180" height="180" /></td>
	<td>Back to green again (I really do have no idea what I'm doing), this time going for a simpler/cleaner look.</td>
</tr>
<tr>
	<td><img src="http://www.toptensoftware.com/Files/MiniCompIcon6.png" alt="Icon6" width="180" height="180" /></td>
	<td>I was using this grey mesh background in the app for a while (but it was bit too much).  The gold look is one of the effects in Inkscape, and while it looks nice and shiny it's too lumpy around the edges for my liking.</td>
</tr>
<tr>
	<td><img src="http://www.toptensoftware.com/Files/MiniCompIcon7.png" alt="Icon7" width="180" height="180" /></td>
	<td>Getting closer, this is where I'd settled on the in-app theme of carbon fiber background with blue accents.</td>
</tr>
<tr>
	<td><img src="http://www.toptensoftware.com/Files/MiniCompIcon9.png" alt="Icon9" width="180" height="180" /></td>
	<td>This was done after the final icon below and was used briefly for the debug build of the app.</td>
</tr>
<tr>
	<td><img src="http://www.toptensoftware.com/Files/MiniCompIcon8.png" alt="Icon8" width="180" height="180" /></td>
	<td>The final icon.  Carbon-fiber background, matching blue trophy and border, gloss-over effect.</td>
</tr>
</tbody>
</table>
<p>I called this post &quot;Icon Evolution&quot; but in retrospect it was more like &quot;Icon Trial and Error&quot;.  In the end, I'm really happy with it - it just took a long time to get there.</p>
<p>You can see a bigger 512x512 version of the icon in the <a href="http://minicompapp.com/Home/PressKit" target="_blank">MiniComp Press Kit</a>.</p>
]]></description>
			<link>http://www.toptensoftware.com/Articles/139/Icon-Evolution</link>
			<guid isPermaLink="false">http://www.toptensoftware.com/Articles/139/Icon-Evolution</guid>
			<comments>http://www.toptensoftware.com/Articles/139/Icon-Evolution</comments>
			<category>MiniComp</category>
			</item><item>
			<title>Building MiniComp</title>
			<author>brobinson</author>
			<pubDate>Thu, 28 Jun 2012 01:44:23 GMT</pubDate>
			<description><![CDATA[<p>Yesterday I released my first iPhone App - <a href="http://minicompapp.com" target="_blank">MiniComp</a>	, a simple way to run friendly competitions with your mates.  Today I thought I'd write up a little about how it was built.</p>
<h2 id="the-idea">The Idea</h2>
<p>The idea for MiniComp came about when my teenage son was telling me about a competition he and his mates were running for their school sport.  They play squash once a week and wanted to run a simple leaderboard, just to make it a little more fun.  The system they had was a bit flawed so I suggested using the Elo ranking algorithm (the same algorithm Zuckerberg used for FaceMash), and the idea for MiniComp sort of flowed from there. </p>
<p>It's pretty simple:</p>
<ol>
<li>Enter the names of everyone playing.</li>
<li>Enter the results of games as you play.</li>
<li>That's it! MiniComp ranks everyone and shows a leader board.</li>
</ol>
<h2 id="the-proof-of-concept">The Proof Of Concept</h2>
<p>As a long time fan of Mono, choosing <a href="http://xamarin.com/monotouch" target="_blank">MonoTouch</a> as the development tool was a no brainer.  I'd used MonoTouch before for some prototype work and some tiny throw away type apps and figured it would be perfect for this. And it was, the first version took just two nights to build and supported the basic idea described above as well as support for multiple competitions.</p>
<p>And it passed the proof of concept.  My son used it for their squash round the next day and immediately they were hooked.</p>
<p>It was at this point I realized this app might have some potential - mainly because of just how easy it is to use and the immediate leaderboard it generates.  There's no need write down results on scraps of paper, or to get back to a PC to enter results, no spreadsheets etc... it's just very convenient and the results are instant.  It simply adds a new layer of fun.</p>
<p>As for the name? It's just something I grabbed out of thin air right at the moment I created the C# project.</p>
<h2 id="a-little-more-functionality">A Little More Functionality</h2>
<p>Thinking about how MiniComp might be used I realized that with a few simple options I could make it flexible enough to work with just about any game or sport.</p>
<ul>
<li>
<p>Scoring Mode controls whether to record actual point score results, and whether highest or lowest score wins.  In most games the highest score wins, but some games it's the opposite (eg: golf).  And sometimes there's just no score - it's either win/loss/draw situation, or perhaps you just couldn't be bothered entering a score.</p>
</li>
<li>
<p>Ranking System controls how players are ranked. Elo is great but sometimes the most wins, or most points is a better system.  It also supports a points-for-place mode where first place gets so many points, second gets so many etc...</p>
</li>
<li>
<p>Two Player and Multi Player.  Whether the game is played head-to-head between two players (eg: squash) or everyone plays at the same time (eg: motor racing).</p>
</li>
</ul>
<h2 id="some-polish">Some Polish</h2>
<p>I was now about a week in and happy with the functionality, but the UI looked a bit plain using the standard iOS controls.  So I just started playing around with colors and came up with the blue on black look which made the whole thing a little more interesting.</p>
<p>I also tried a few variations on the background texture before settling on the &quot;tiny carbon fiber&quot; look that's now used through out the app and the website.</p>
<p>All the artwork was done in Inkscape.  By picking a simple flat look, I managed to knock together all the in-app icons in practically no time. It's a minimal UI - as in minimal effort.</p>
<p>The main app icon was a different story altogether - this took alot of work and many iterations to get right, but worth it I think.</p>
<p>Total effort so far: two weeks part time.</p>
<h2 id="the-server">The Server</h2>
<p>By now, some of my son's mates were asking for copies of the results and it became obvious that the ability to publish and share the leaderboard would add another interesting dimension to it.  I didn't want to spend too much time on this so the requirements were the bare minimum:</p>
<ul>
<li>Ability to publish a competition without any signup or registration.</li>
<li>Ability to share published competitions by Twitter, Facebook and Email.</li>
<li>Enough security to prevent someone hacking your published competition.</li>
<li>Optional, minimal privacy by obscurity.</li>
</ul>
<p>The server is written in ASP.NET MVC and runs on a <a href="http://www.linode.com/?r=6f57fbefc9982f4c8d67f56c8624d620d9bce043" target="_blank">Linode</a> server under Mono.</p>
<p>Published competitions are stored in a single table database (using <a href="http://www.toptensoftware.com/petapoco">PetaPoco</a> of course) with the serialized competition stored as a text blob.  Because both the app and the server are written in C# all the serialization code for competitions just worked on both platforms and generating the leaderboard views was really just an excercise in HTML formatting.</p>
<p>Security takes the form of an authentication token that's allocated by the server when competition is published.  That token is required to update an already published competition and is returned to and stored by the app.</p>
<p>For privacy, although everything published to the website is publicly viewable you need to know the published URL.  Since thisis made up from the database record ID and the name of the competition in slug form it's pretty hard to guess.  For the insensitive nature of this data it's good enough to keep things private if you want... just don't give out the URL in public.</p>
<p>The server and the associated changes to the app took about another week, bringing it up to 3 weeks.</p>
<h2 id="the-promo-site">The Promo Site</h2>
<p>For the promo site I wanted something that looked slick, gave a brief overview of what the app was and then linked off to the AppStore.  It's a very simple design consisting of just the one landing page, but there's a few interesting things.</p>
<ul>
<li>
<p>It's <a href="http://en.wikipedia.org/wiki/Responsive_Web_Design" target="_blank">Responsive</a> and a scales well from iPhone resolution all the way up to a large desktop monitor.  I've not done a responsive design before and a simple site like this seemed a good way to learn the basics.  Also I figured it's the kind of site that will be viewed from range of different devices and therefore worth the effort.</p>
</li>
<li>
<p>It's Retina enabled.  Looking at the first version of the site on my iPad 3 the screenshots and icon was noticably blurry.  I thought I could use CSS media queries to do some simple image replacement, but in the end a simple JavaScript routine proved easier.  I might write this up in a later post, but you can view the source and figure it out pretty easily.  The site now looks super crisp even on high-res devices.</p>
</li>
<li>
<p>Getting Twitter buttons and Facebook Like buttons to look good together and on a dark background is difficult.  The biggest problem here was the white iFrame background that flashed behind the Like button - very distracting.  I tried a number of approaches to mitigate this, but in the end just hid their containing div until they finished loading and faded them in with jQuery.  The script is simple, view the source of the site if you're interested.</p>
</li>
</ul>
<p>Aside from the promo site I also set up a <a href="http://www.facebook.com/MiniCompApp" target="_blank">Facebook page</a>, <a href="http://twitter.com/minicompapp" target="_blank">Twitter account</a> , and a <a href="http://minicompapp.com/Home/PressKit" target="_blank">press kit</a> which includes marketing material, media images, a press release and more.</p>
<p>All up the promo site and marketing resources took about another week. 4 weeks elapsed.</p>
<h2 id="other-services">Other Services</h2>
<p>In building MiniComp I used a number of neat products and services:</p>
<h3 id="testflight">TestFlight</h3>
<p>I think anyone who's done iOS development would already be familiar with <a href="http://testflightapp.com" target="_blank">TestFlight</a>, but for those who aren't it's a way to distribute ad-hoc builds of your app to testers.  Beautifully designed, does what it says, worked perfectly.  
</p>
<p>Also, MonoDevelop has a built-in command to push to TestFlight. It's actually easier to publish to TestFlight from MonoDevelop than it is from XCode.</p>
<h3 id="flurry">Flurry</h3>
<p>I looked into a few analytics options, but decided on <a href="http://www.flurry.com/" target="_blank">Flurry</a> for two reasons - I liked the design of their site and MonoTouch already had bindings written for it.</p>
<h3 id="appannie">AppAnnie</h3>
<p>I haven't used <a href="http://www.appannie.com/" target="_blank">AppAnnie</a> much yet, but I'm confident. It's a better way to track downloads and sales figures from the AppStore.  Unlike the AppStore, AppAnnie keeps your sales figures indefinitely and seems to have nicer reports and charts.</p>
<p>Their sign-up process is painless, their emails are friendly and helpful, I can only assume the rest of the service lives up to the hype.</p>
<h3 id="prmac">prMac</h3>
<p><a href="http://prmac.com/" target="_blank">prMac</a> is a public relations outlet for Apple and Mac related news.  I'm not sure how effective this will be in the long run but I've been reasonably impressed so far.  For $20 they'll push out your press release to 700+ media partners. Their site also has some great of information on how to write a decent press release which I found very useful (I think you need to sign up before you can access this, but sign up is free).</p>
<h3 id="monotouch-and-mono">MonoTouch and Mono</h3>
<p>I've already mentioned Mono and <a href="http://xamarin.com/" target="_blank">Xamarin</a> but they really do deserve another mention. </p>
<p>At the same time as developing MiniComp I was doing contact work developing another mobile app for iOS and for Android, using ObjectiveC/XCode and Java/IntelliJ.  The difference between the two experiences was night and day - especially for the iOS development.  I find XCode/Objective-C to be overwhelmingly infuriating and switching back to MonoDevelop after using XCode all day was a huge relief.</p>
<p>Since this was the first complete app I'd done with MonoTouch I was a little concerned that it might start to crack around the edges as I got more into it, but it really didn't.  In fact the more I got into it the more it shone.</p>
<h2 id="conclusion">Conclusion</h2>
<p>So there you have it.  All up the whole project went extremely smoothly taking just 5 weeks, including a week of waiting for the the app submission/review cycle.  I have no idea how it will sell, but at the very least I've learned a lot and my son has a cool app.</p>
<p>Interested in MiniComp? Check it out here: <a href="http://minicompapp.com" target="_blank">http://minicompapp.com</a>.</p>
]]></description>
			<link>http://www.toptensoftware.com/Articles/138/Building-MiniComp</link>
			<guid isPermaLink="false">http://www.toptensoftware.com/Articles/138/Building-MiniComp</guid>
			<comments>http://www.toptensoftware.com/Articles/138/Building-MiniComp</comments>
			<category>Development</category>
			<category>MiniComp</category>
			<category>Mono</category>
			</item><item>
			<title>Long Time No Post and PetaPoco v5</title>
			<author>brobinson</author>
			<pubDate>Mon, 21 May 2012 03:18:34 GMT</pubDate>
			<description><![CDATA[<p>It's been over six months since my last post here because I've been slack and I've been busy.  Also, I've found a little time to spend on PetaPoco.</p>
<p>After a very busy 2011, I took the first couple of months of 2012 off and did pretty much nothing - at least nothing to do with software development - just alot of unwinding and I feel all the better for it.</p>
<p>Since then I've been working on a few different projects, including new version of <a href="http://www.cantabilesoftware.com" target="_blank">Cantabile</a>, some contract work doing mobile development for iOS and Android, and more recently I've been playing with OpenGL, Mono, MonoTouch and MonoDroid with thoughts of maybe doing a mobile game (it's been along time since I did any games programming).</p>
<p>The question I keep getting asked however is when will there be a new version of PetaPoco?  Well firstly I'm somewhat reluctant to change PetaPoco too much - simply because I want it to stay as simple as possible and well, I like it the way it is.  If you were hoping to see PetaPoco grow into something bigger, more feature rich, then I'm sorry to disappoint - but that's simply missing the point of what PetaPoco is.  Also since none of the projects I'm currently working on use PetaPoco it's easy to just leave well enough alone.</p>
<p>That said I have found some time to start on a new version - which will be called v5.  Even though there's nothing major about it, I have opted for a major version number bump because  it won't be drop-in backwardly compatible.</p>
<h2 id="dropping-the-single-c-file-approach">Dropping the Single C# File Approach</h2>
<p>The first thing I've done with v5 is to forget about trying to maintain the whole thing in a single C# source file.  Similarly I'm dropping the fascination with trying to keep the line count as small as possible.  These ideas served well to keep PetaPoco tiny during its inception, but really serve no practical purpose moving forward.</p>
<p>So the project is now a separate assembly and the original PetaPoco.cs source file has been split up into a series of source files (one class/interface/enum per file) and grouped into folders - all of which means the project is much easier to navigate around and therefore easier to maintain.</p>
<h2 id="but-i-like-a-single-c-file">But I Like a Single C# File</h2>
<p>Although for maintenance purposes having the code base in separate source files is a great, from the point of view of using it in a project there's a certain appeal to being able to drop in a single source file and not having to worry about assembly dependencies.  So, I've knocked together a tool that munges everything back into a stand-alone PetaPoco.cs file.  Best of both worlds!</p>
<p>CSJ (for CSharp Join) is a simple command line tool which you'll find in the PetaPoco solution that can join a bunch of C# files into a single file.  It works well enough for what I need for PetaPoco, but might work for other simple projects too.</p>
<p>CSJ is run automatically by the PetaPoco project during it's post-build phase.</p>
<h2 id="xml-documentation">XML Documentation</h2>
<p>Because of my previous line count obsession I had been reluctant to do XML documentation comments for PetaPoco.  Now that it's broken up into separate files I now feel like there's &quot;room&quot; for these.</p>
<p>The XML documentation on all the public parts of PetaPoco is now complete, however...  my eyes glazed over and my brain shut-down as I did it - there could be some weird comments in there.</p>
<h2 id="new-mapper-api">New Mapper API</h2>
<p>Turning PetaPoco into an assembly has some ramifications - particularly in relation to the static Database.Mapper property.  As an assembly, there's the possibility of it being used by two other assemblies at the same time and if both wanted to register type mappers it would be a case of last in best dressed.</p>
<p>So the old Database.Mapper property has been removed and replaced with a new <code>Mappers</code> class through which IMapper's can be registered - associating a mapper with either a specific POCO type, or for all the types in an assembly.</p>
<p>Aside from how they're registered the IMapper interface has also had a bit of clean up and PetaPoco's automatic built-in mapping is now implemented as a mapper itself.  See the IMapper interface for more on this.</p>
<h2 id="forcetoutc-changes">ForceToUtc Changes</h2>
<p>This feature was always a bit of hack.  Some DB providers return date time values with a DateTimeKind of Unknown.  The ForceToUtc option simply changes the returned values from Unkown to DateTimeKind.Utc - without actually changing the date value.  
</p>
<p>In PetaPoco 4, this was an option on the Database class - now it's an attribute of the POCO property.  eg: <code>Column[ForceToUtc = true]</code></p>
<p>Another important change... ForceToUtc used to be true by default, now it's false.</p>
<h2 id="renaming-things">Renaming Things</h2>
<p>As mentioned above, some things have been renamed for consistency:</p>
<p>PrimaryKeyAttribute properties:</p>
<ul>
<li>Value -&gt; PrimaryKey</li>
<li>sequenceName -&gt; SequenceName</li>
<li>autoIncrement -&gt; AutoIncrement</li>
</ul>
<p>TableNameAttribute properties:</p>
<ul>
<li>Value -&gt; TableName</li>
</ul>
<h2 id="tuples-for-dictionary-keys">Tuples for Dictionary Keys</h2>
<p>In PetaPoco v4 I was lazy with keying the internal dictionaries that PetaPoco uses.   Instead of declaring key objects and writing to associated Hash calculations I just dumped all the key values into a string and used that as a key.  With later versions of the runtime an easier (and I presume faster) approach is to use Tuples - which is what PetaPoco now does.</p>
<p>The downside to this is that PetaPoco now requires .NET 4.0.  To get it running on earlier versions should just require re-implementing some compatible Tuple classes, but I just haven't got around to it yet.</p>
<h2 id="other-internal-changes">Other Internal Changes</h2>
<p>Internally, PetaPoco has also had a bit of rework/refactor/cleanup:</p>
<ul>
<li>
<p>The old DBType property has been replaced with an abstract DatabaseType class that provides database engine specific functionality.  Old <code>if this database do this else do that</code> type code has been replaced with calls to the DatabaseType class.  (See the DatabaseTypes folder in the solution for more on these)</p>
</li>
<li>
<p>There's a new Cache classe that simplifies the caching of various objects within PetaPoco.</p>
</li>
<li>
<p>Lots of other minor bits and pieces.</p>
</li>
</ul>
<h2 id="pull-requests-merged">Pull Requests Merged</h2>
<p>At this point, the main functional changes are the following pull requests that have now been merged:</p>
<ul>
<li><a href="https://github.com/toptensoftware/PetaPoco/pull/107" target="_blank">Replace column names that conflict with CSharp keywords automatically</a></li>
<li><a href="https://github.com/toptensoftware/PetaPoco/pull/104" target="_blank">Add Page<T> override to support user defined SQL for Count and Paging</a></li>
<li><a href="https://github.com/toptensoftware/PetaPoco/pull/98" target="_blank">Fix for issue #91 - Template was selecting the clustered index, not the primary key.</a></li>
<li><a href="https://github.com/toptensoftware/PetaPoco/pull/95" target="_blank">Check connection state prior to Open() to avoid error: System.InvalidOperation</a></li>
<li><a href="https://github.com/toptensoftware/PetaPoco/pull/94" target="_blank">Change rxOrderBy Regex and logic to be less greedy during Page<T> query rewrite to support sub-select ordering</a></li>
<li><a href="https://github.com/toptensoftware/PetaPoco/pull/93" target="_blank">Add IsNew() Support for PK of Type Guid</a></li>
<li><a href="https://github.com/toptensoftware/PetaPoco/pull/92" target="_blank">Fix: ensure the primary key value is returned from Insert() when the primary key column is not an autoincrement.</a></li>
<li><a href="https://github.com/toptensoftware/PetaPoco/pull/88" target="_blank">Fix for Issue #81</a></li>
<li><a href="https://github.com/toptensoftware/PetaPoco/pull/77" target="_blank">Speeded up mapping with types containing enums.</a></li>
<li><a href="https://github.com/toptensoftware/PetaPoco/pull/76" target="_blank">Added fix for uint columns in SQLite</a></li>
<li><a href="https://github.com/toptensoftware/PetaPoco/pull/74" target="_blank">Allow Nullable T in ExecuteScalar</a></li>
<li><a href="https://github.com/toptensoftware/PetaPoco/pull/70" target="_blank">Fix for crash which would occur when trying to save more than 4000 characters into a SQLServerCE NText column</a></li>
</ul>
<p>(Tip: if you want to see something fixed in PetaPoco, your best chance is to submit a pull request).</p>
<h2 id="upgrade-checklist">Upgrade CheckList</h2>
<p>Here's a quick check list of things to consider/remember if upgrading from PetaPoco 4 to 5.</p>
<ol>
<li>If you need pre .NET 4 support, abort now.  (or write some tuple classes as described above)</li>
<li>Get the latest version from GitHub on the v5 (not master) branch</li>
<li>
Decide on whether you prefer the Assembly or Single Source File version of PetaPoco.  

<ul>
<li>If you want the assembly version you'll need to build the PetaPoco project in the supplied solution. Remove PetaPoco.cs from your existing project and add the assembly reference.</li>
<li>If you want to continue using the Single Source File, just copy the new PetaPoco.cs over the old one.</li>
</ul>
</li>
<li>If you're using custom mappers, you'll need to switch from assiging the Database.Mapper property to calling Mappers.Register().</li>
<li>You might get build errors on some attribute properties that have been renamed.  Typically these are just upper/lower case issues and should be easily fixed.</li>
<li>If you're using ForceToUtc option, be warned.  You'll need to explicitly decorate all DateTime Columns with the appropriate attribute or, write a custom mapper to do it.</li>
<li>Cross your fingers :)</li>
</ol>
<h2 id="availability">Availability</h2>
<p>All of this is available in a new 'v5' branch on GitHub, but shouldn't be considered production quality.  Feel free to grab it and give it a go and let me know what you think, but more importantly what's broken.  Once I'm confident that it's stable I'll put up a new build to Nuget.</p>
<h2 id="whats-this-about-an-ios-game">What's this about an iOS Game?</h2>
<p>Yes, I've been doing some iOS game development.   Nothing too fancy, but certainly fun - I might post some info about this soon.</p>
]]></description>
			<link>http://www.toptensoftware.com/Articles/137/Long-Time-No-Post-and-PetaPoco-v5</link>
			<guid isPermaLink="false">http://www.toptensoftware.com/Articles/137/Long-Time-No-Post-and-PetaPoco-v5</guid>
			<comments>http://www.toptensoftware.com/Articles/137/Long-Time-No-Post-and-PetaPoco-v5</comments>
			<category>PetaPoco</category>
			</item><item>
			<title>Change of Plans, Prefix Shelved.</title>
			<author>brobinson</author>
			<pubDate>Sun, 20 Nov 2011 00:00:00 GMT</pubDate>
			<description><![CDATA[<p>I've decided to suspend development of Prefix for the time being.</p>
<p>As you may have noticed I haven't posted anything here for a while - primarily because development of Prefix has been suspended.  There's a couple of reasons for this, but the main two are:</p>
<ol>
<li>We've decided to cease operations at the company where I work my day job.  Commencing 2012 I'll be officially out of work and looking for something new to do.</li>
<li>Given that I can't figure out how to commercialize Prefix, it needs to be put on the back-burner to make room for something that will pay the bills.</li>
</ol>
<p>I'd like to return to Prefix at some stage but for the moment at least it's shelved.  Besides Prefix I also have several other unpublished projects which have also been suspended - the slate needs to be cleared.</p>
<p>Having said all that, this seems to be the perfect opportunity to look for something completely different to work on.  So over the coming month(s) I think I'll try my hand at various random things to see what piques my interest.  Perhaps something in the mobile space, maybe some game development, perhaps something else.  Who knows?</p>
]]></description>
			<link>http://www.toptensoftware.com/Articles/136/Change-of-Plans-Prefix-Shelved</link>
			<guid isPermaLink="false">http://www.toptensoftware.com/Articles/136/Change-of-Plans-Prefix-Shelved</guid>
			<comments>http://www.toptensoftware.com/Articles/136/Change-of-Plans-Prefix-Shelved</comments>
			<category>Miscellaneous</category>
			<category>Prefix</category>
			</item><item>
			<title>Prefix - ForEach Statements</title>
			<author>brobinson</author>
			<pubDate>Thu, 29 Sep 2011 23:54:33 GMT</pubDate>
			<description><![CDATA[<p>Prefix now supports <code>foreach</code> loops but their not exactly as you might expect....</p>
<p><em>This post is about Prefix - a modern language that compiles to JavaScript. A language where C# is the inspiration - not the goal. Read more on the <a href="http://www.toptensoftware.com/prefix">Prefix Project Page</a>.</em></p>
<p>Prefix has had <code>for</code> loops pretty much since day one.  I'd deliberately left out <code>foreach</code> loops until now because I wanted to integrate them with some sort of enumerable/generator (eg: <code>IEnumerable&lt;T&gt;</code>) mechanism, but I've decided to put that off for now and just aim for parity with JavaScript functionality.</p>
<h2 id="enumerating-array-like-objects">Enumerating Array Like Objects</h2>
<p>First up, the Prefix <code>foreach</code> statement will work with any type that implements a <code>int length</code> variable or property and an indexer that takes an integer parameter - including obviously arrays and strings.</p>
<p>Prefix uses a temporary variable as the counter and just enumerates the collection as you'd expect:</p>
<div class="sxs">
<pre class="prettyprint lang-csharp"><code>extern dynamic Console;

var x = new string[];
x.push(&quot;Hello&quot;);
x.push(&quot;World&quot;);

foreach (var i in x)
{
    Console.WriteLine(i);
}
</code></pre>
<pre class="prettyprint lang-javascript"><code>(function() {

// Start Global Code
var $temp;
var x=[];
x.push(&quot;Hello&quot;);
x.push(&quot;World&quot;);
for ($temp=0; $temp&lt;x.length; $temp++)
{
    var i = x[$temp];
    Console.WriteLine(i);
}

})();
</code></pre>
</div>
<p>The generated code will use an additional temporary variable if the expression begin enumerated might cause side effects.  In this example, <code>$temp2</code> is used to hold the array to avoid multiple calls into <code>fn</code>:</p>
<div class="sxs">
<pre class="prettyprint lang-csharp"><code>extern dynamic Console;

string[] fn()
{
    var x = new string[];
    x.push(&quot;Hello&quot;);
    x.push(&quot;World&quot;);
    return x;
}

foreach (var i in fn())
{
    Console.WriteLine(i);
}
</code></pre>
<pre class="prettyprint lang-javascript"><code>(function() {

function fn()
{
    var x=[];
    x.push(&quot;Hello&quot;);
    x.push(&quot;World&quot;);
    return x;
};

// Start Global Code
var $temp, $temp2;
for ($temp=0, $temp2=fn(); $temp&lt;$temp2.length; $temp++)
{
    var i = $temp2[$temp];
    Console.WriteLine(i);
}

})();
</code></pre>
</div>
<p>(in case you're wondering, Prefix tracks temporary variable allocations and re-uses them, so multiple consecutive loops like this will declare the temporary variables once at the top of the scope (function) and re-use them multiple times over).</p>
<h2 id="enumerating-dictionaries">Enumerating Dictionaries</h2>
<p>I've always thought object enumeration in JavaScript to be a little messy - though I do understand the reasons for it.  In JavaScript there's two main reasons for enumerating an object - to get all the values of a associative array, or to enumerate all the methods, properties, fields of an object (say to dump/inspect it).  The differences with these two approaches relates to whether to enumerate the prototype chain or not.  
</p>
<p>The JavaScript <code>for...in</code> statement does enumerate the prototype chain. If you only want the immediate properties of the object (say the keys of a dictionary) you need to use the <code>hasOwnProperty</code> method to detect the items to exclude.</p>
<p>In Prefix, the call to <code>hasOwnProperty</code> <em>is included automatically</em> in generated <code>foreach</code> loops.  
</p>
<p>(In the following example I'm using backtick escapes to declare literal JavaScript - to better show the object layout).</p>
<div class="sxs">
<pre class="prettyprint lang-csharp"><code>extern dynamic Console;

// Purposely put something that doesn't belong in the object prototype
// This SHOULD NOT appear in the output
`Object.prototype.somecrap = 23`;

// Create a dictionary
var dict = `{apple:1, pear:2, banana:3}`;

// Dump the contents of the dictionary
foreach (var i in dict)
{
    Console.WriteLine(i);
}
</code></pre>
<pre class="prettyprint lang-javascript"><code>(function() {

// Start Global Code
Object.prototype.somecrap = 23;
var dict={apple:1, pear:2, banana:3};
for (var i in dict)
{
    if (!dict.hasOwnProperty(i))
        continue;
    Console.WriteLine(i);
}

})();
</code></pre>
</div>
<h2 id="enumerating-object-members">Enumerating Object Members</h2>
<p>The above example raises the obvious question of how to enumerate the entire prototype chain? Well, with a new form of the foreach statement:   <code>foreach member (var i in whatever)</code>.</p>
<p>The following example is the same as the above but I've added the <code>member</code> pseudo-keyword:</p>
<div class="sxs">
<pre class="prettyprint lang-csharp"><code>extern dynamic Console;

// Purposely put something that doesn't belong in the object prototype
// This SHOULD appear in the output
`Object.prototype.somecrap = 23`;

// Create a dictionary
var dict = `{apple:1, pear:2, banana:3}`;

// Dump all members of the dictionary (including the extra property in the object prototype)
foreach member (var i in dict)
{
    Console.WriteLine(i);
}
</code></pre>
<pre class="prettyprint lang-javascript"><code>(function() {

// Start Global Code
Object.prototype.somecrap = 23;
var dict={apple:1, pear:2, banana:3};
for (var i in dict)
{
    Console.WriteLine(i);
}

})();
</code></pre>
</div>
<p>The <code>member</code> modifier can also be used on arrays to enumerate the actual members of the array instead of just the items in the array. </p>
<h2 id="conclusion">Conclusion</h2>
<p>That's all for the <code>foreach</code> statement for the moment.  I do intend on addition support for something like <code>IEnumerable&lt;T&gt;</code> and <code>yield return</code> but not just yet...</p>
<p>If you've been using the experimental build of Prefix, I haven't updated it with this functionality yet - I'll post something when I do.</p>
]]></description>
			<link>http://www.toptensoftware.com/Articles/135/Prefix-ForEach-Statements</link>
			<guid isPermaLink="false">http://www.toptensoftware.com/Articles/135/Prefix-ForEach-Statements</guid>
			<comments>http://www.toptensoftware.com/Articles/135/Prefix-ForEach-Statements</comments>
			<category>JavaScript</category>
			<category>Prefix</category>
			</item><item>
			<title>Prefix - Anonymous Functions and Lambdas</title>
			<author>brobinson</author>
			<pubDate>Mon, 26 Sep 2011 04:44:52 GMT</pubDate>
			<description><![CDATA[<p>A day or two ago I wrote about Prefix' support for delegates types - which are great, but they're only half the story.  To make the most of them, you really need anonymous functions and lambda expressions.</p>
<p><em>This post is about Prefix - a modern language that compiles to JavaScript. A language where C# is the inspiration - not the goal. Read more on the <a href="http://www.toptensoftware.com/prefix">Prefix Project Page</a>.</em></p>
<p>A delegate type lets you declare the required prototype of function and pass references to matching functions around.  What we need now is an easier way to declare these functions inline - without having to create an actual &quot;function&quot; per se.  
</p>
<h3 id="anonymous-functions">Anonymous Functions</h3>
<p>An anonymous function is a function declared without a name and with an inferred return type.  It's declared using the <code>delegate</code> keyword as part of an expression.  Consider the following where an unnamed (&quot;anonymous&quot;) function is passed to a another function:</p>
<div class="sxs">
<pre class="prettyprint lang-csharp"><code>extern dynamic Console;

void DoSomething(Func&lt;int, int&gt; cb)
{
    Console.WriteLine(cb(10));
}

DoSomething(delegate(int x) { return x*88; });
</code></pre>
<pre class="prettyprint lang-javascript"><code>(function() {

function DoSomething(cb)
{
    Console.WriteLine(cb(10));
};

// Start Global Code
DoSomething(function(x) {
    return x*88;
});

})();
</code></pre>
</div>
<p>Because anonymous functions don't declare a return type, the compiler must be able to infer it from usage.  (in the above example it's infered from <code>DoSomething</code>'s <code>cb</code> parameter which is declared as <code>Func&lt;int, int&gt;</code></p>
<h3 id="lambda-expressions">Lambda Expressions</h3>
<p>Lambda expressions are an even more concise way of writing an anonymous function that directly returns the result of a single expression.  The syntax for lambda expressions is based around the <code>=&gt;</code> operator and prefix supports the same syntax formats as C#.  eg:</p>
<ul>
<li><code>()=&gt;99</code> - a lambda expression with no parameters</li>
<li><code>x=&gt;x*2</code> - a lambda expression with a single untyped parameter</li>
<li><code>(x,y)=&gt;x*y</code> - a lambda expression with multiple untyped parameters</li>
<li><code>(int x, int y)=&gt;x*y</code> - a lambda expression with multiple typed parameters</li>
</ul>
<p>A lambda expression is equivalent to a anonymous function that simply returns a value.  So this:</p>
<pre><code>(int x, int y) =&gt; x * y
</code></pre>
<p>is equivalent to:</p>
<pre><code>delegate(int x, int y) { return x * y; }
</code></pre>
<p>Note too that with lambda expressions (unlike anonymous functions) you don't have to specify type arguments for the parameters - they're inferred in the same way the return type is.</p>
<h3 id="solving-the--conundrum">Solving the <code>this</code>/<code>that</code> Conundrum</h3>
<p>In JavaScript when nesting one function inside another, the inner function doesn't inherit the <code>this</code> reference from the outer function.  In order to reference the outer class the developer must manually setup a <code>that</code> reference in the enclosing closure. (see <a href="http://javascript.crockford.com/private.html" target="_blank">here</a> for a better explanation).</p>
<p>The Prefix compiler however has enough type information to know how to set this up automatically.  So if an anonymous function inside a class method refers to a member variable of the outer class, <code>this</code> is automatically stored in a local variable <code>$this</code> and the nested function automatically uses it.</p>
<p>Here's an example showing both a lambda expression and the use of <code>$this</code>:</p>
<div class="sxs">
<pre class="prettyprint lang-csharp"><code>extern dynamic Console;

class MyClass
{
    public int Value;
    public void DoSomething(int input)
    {
        Func&lt;int, int&gt; fn = x=&gt;Value * x;
        Console.WriteLine(fn(input));
    }
}

var x = new MyClass();
x.Value = 23;
x.DoSomething(10);
</code></pre>
<pre class="prettyprint lang-javascript"><code>(function() {

// class MyClass
var MyClass = function() {};
MyClass.typeName = 'MyClass';
MyClass.prototype.Value = 0;

MyClass.prototype.DoSomething = function(input)
{
    var $this = this;
    var fn=function(x) { return $this.Value*x; };
    Console.WriteLine(fn(input));
};

// Start Global Code
var x=new MyClass();
x.Value = 23;
x.DoSomething(10);

})();
</code></pre>
</div>
<h3 id="generic-type-inference">Generic Type Inference</h3>
<p>All that's left to do in this area is type inference of generic function arguments from lambda's and anonymous functions - coming soon!</p>
]]></description>
			<link>http://www.toptensoftware.com/Articles/134/Prefix-Anonymous-Functions-and-Lambdas</link>
			<guid isPermaLink="false">http://www.toptensoftware.com/Articles/134/Prefix-Anonymous-Functions-and-Lambdas</guid>
			<comments>http://www.toptensoftware.com/Articles/134/Prefix-Anonymous-Functions-and-Lambdas</comments>
			<category>JavaScript</category>
			<category>Prefix</category>
			</item><item>
			<title>Prefix - typeof and typename operators</title>
			<author>brobinson</author>
			<pubDate>Mon, 26 Sep 2011 03:56:24 GMT</pubDate>
			<description><![CDATA[<p>Prefix does not (and will not) have an equivalent to .NET's runtime reflection capabilities.  It does however have something a little better than what JavaScript provides - introducing the <code>typename</code> and <code>typeof</code> operators...</p>
<p><em>This post is about Prefix - a modern language that compiles to JavaScript. A language where C# is the inspiration - not the goal. Read more on the <a href="http://www.toptensoftware.com/prefix">Prefix Project Page</a>.</em></p>
<p>I've always thought JavaScript's runtime type support to be rather lame - not so much in what it can provide, but simply that it's rather inconsistent.  For example, using <code>typeof</code> on any custom class/object simply yields &quot;object&quot;.  Great - not.</p>
<p>In Prefix I wanted to improve this situation a little and provide something a little more reliable.  Prefix has two type inspection operators:  
</p>
<dl>
<dt><code>typeof</code></dt>
<dd>returns the constructor of an object or value</dd>
<dt><code>typename</code></dt>
<dd>returns a descriptive name for an object type</dd>
</dl>
<p>Both operators can accept either an object instance, or a compile type type name.  
</p>
<p>For the built in types (boolean, string etc...), <code>typeof</code> returns the boxed object constructor (eg: String.constructor) while <code>typename</code> returns the equivalent of the JavaScript <code>typeof</code> operator (eg: &quot;string&quot;, &quot;boolean&quot;, &quot;number&quot; etc....)</p>
<p>For Prefix classes, including generic classes <code>typeof</code> returns the class function and <code>typename</code> returns a descriptive name of the class - with generic arguments substituted.  eg:</p>
<div class="sxs">
<pre class="prettyprint lang-csharp"><code>extern dynamic Console;

class Bar
{
}

class MyClass&lt;T&gt;
{
    public void fn()
    {
        Console.WriteLine(typename(T));
    }
}

new MyClass&lt;bool&gt;().fn();
new MyClass&lt;int&gt;().fn();
new MyClass&lt;Bar&gt;().fn();
new MyClass&lt;MyClass&lt;int&gt;&gt;().fn();
Console.WriteLine(typename(MyClass&lt;int&gt;));
</code></pre>
<pre><code>boolean
number
Bar
MyClass&lt;&gt;[number]
MyClass&lt;&gt;[number]
</code></pre>
</div>
<p>Note that although Prefix distinguished between <code>int</code> and <code>double</code> at compile time, there is no such distinction at runtime - hence the appearance <code>number</code> in the resulting typename.</p>
<p>There are a couple of runtime helper functions to support these operators but as always they're tiny, automatically generated by the compiler and only generated when actually needed.</p>
<p>(Don't forget Prefix also supports runtime type querying via the <code>is</code> and <code>as</code> keywords).</p>
]]></description>
			<link>http://www.toptensoftware.com/Articles/133/Prefix-typeof-and-typename-operators</link>
			<guid isPermaLink="false">http://www.toptensoftware.com/Articles/133/Prefix-typeof-and-typename-operators</guid>
			<comments>http://www.toptensoftware.com/Articles/133/Prefix-typeof-and-typename-operators</comments>
			<category>JavaScript</category>
			<category>Prefix</category>
			</item><item>
			<title>Porting &quot;Burst Fish&quot; to Prefix</title>
			<author>brobinson</author>
			<pubDate>Sun, 25 Sep 2011 08:05:24 GMT</pubDate>
			<description><![CDATA[<p>A couple of days ago I stumbled on this great little JavaScript game tutorial and I thought it would be interesting to port it to Prefix as an example of something a little more &quot;real world&quot; than the hundreds of unit tests I've been using.</p>
<p><em>This post is about Prefix a modern language that compiles to JavaScript. A language where C# is the inspiration - not the goal. Read more on the <a href="http://www.toptensoftware.com/prefix">Prefix Project Page</a>.</em></p>
<p>Burst Fish is a tutorial game written by Seb Lee-Delisle that I found on the excellent <a href="http://creativejs.com" target="_blank">creativejs.com</a> site.  The original tutorial can be found here <a href="http://creativejs.com/tutorials/create-an-ipad-optimised-game/" target="_blank">http://creativejs.com/tutorials/create-an-ipad-optimised-game/</a>.</p>
<div class="figure">
<img src="http://www.toptensoftware.com/Files/fishies.jpg?maxw=600" alt="fishies.jpg" width="600" height="300" />
</div>
<p>I thought this would be an excellent project to port to Prefix as both an example project and as a first experiment to see how Prefix works in the real world.  Aside from one missing piece of functionality and a few bugs in the compiler itself, porting it went remarkably well.  Here it is:</p>
<ul>
<li><a href="http://www.toptensoftware.com/prefix/samples/BurstGame/Burst.html">View the Game in your Browser</a> (You'll need a webkit based browser - Chrome or Safari)</li>
<li><a href="http://www.toptensoftware.com/downloads/BurstGame.zip">Download the Source</a></li>
</ul>
<p>(Please note I haven't released Prefix yet so although you can look at the source you can't compile it yourself yet.  If you're interested in trying the compiler ping me on Twitter or email me).</p>
<p>To show how the Prefix code looks, here's an extract of the <code>Emitter</code> class used to generate the exploding fish particles:</p>
<div class="sxs">
<pre class="prettyprint lang-csharp"><code>// Emitted is used to generate the explosion particles
class Emitter
{
    // Constructor
    public Emitter(dynamic domContainer)
    {
        this.domContainer = domContainer;
    }

    // Fields
    private dynamic domContainer;
    private Particle[] _particles = new Particle[];
    private Particle[] _spareParticles = new Particle[];

    // Called by main game loop to update particules
    public void update()
    {
        for (var i=0; i&lt;_particles.length; i++)
        {
            var particle = _particles[i]; 
            if (!particle.update())
            {
                _spareParticles.push(particle);
            }
        }
    }

    // Make an explosion at specified position
    public void makeExplosion(double xpos, double ypos, double zpos)
    {
        // Just create bunch of particles
        for (var i=0; i&lt;30; i++)
        {
            var particle = makeParticle();
            particle.init(xpos, ypos, zpos);
            particle.update(); 
        }
    }

    // Make a particle by initializing a new one, or by grabbing one from 
    // the spare list
    private Particle makeParticle()
    {
        Particle particle;
        if (_spareParticles.length&gt;0)
        {
            particle = _spareParticles.shift();
        }
        else
        {
            particle = new Particle(domContainer); 
            _particles.push(particle); 
        }

        return particle; 
    }

}
</code></pre>
<pre class="prettyprint lang-javascript"><code>// class Emitter
var Emitter = function()
{
    this._particles = [];
    this._spareParticles = [];
};
Emitter.typeName = 'Emitter';
Emitter.prototype.domContainer = null;
Emitter.prototype._particles = null;
Emitter.prototype._spareParticles = null;

Emitter.prototype.ctor$1 = function(domContainer)
{
    Emitter.call(this);
    this.domContainer = domContainer;
    return this;
};

Emitter.prototype.update = function()
{
    for (var i=0; i&lt;this._particles.length; i++)
    {
        var particle=this._particles[i];
        if (!particle.update())
        {
            this._spareParticles.push(particle);
        }
    }
};

Emitter.prototype.makeExplosion = function(xpos, ypos, zpos)
{
    for (var i=0; i&lt;30; i++)
    {
        var particle=this.makeParticle();
        particle.init(xpos, ypos, zpos);
        particle.update();
    }
};

Emitter.prototype.makeParticle = function()
{
    var particle;
    if (this._spareParticles.length&gt;0)
    {
        particle = this._spareParticles.shift();
    }
    else
    {
        particle = (new Particle().ctor$1(this.domContainer));
        this._particles.push(particle);
    }
    return particle;
};

</code></pre>
</div>
<p>The game works as well as the original and although there are a few bits in the generated code that could be cleaned up, as a first attempt I'm fairly pleased with it.</p>
]]></description>
			<link>http://www.toptensoftware.com/Articles/132/Porting-Burst-Fish-to-Prefix</link>
			<guid isPermaLink="false">http://www.toptensoftware.com/Articles/132/Porting-Burst-Fish-to-Prefix</guid>
			<comments>http://www.toptensoftware.com/Articles/132/Porting-Burst-Fish-to-Prefix</comments>
			<category>JavaScript</category>
			<category>Prefix</category>
			</item><item>
			<title>Prefix - Delegates</title>
			<author>brobinson</author>
			<pubDate>Sun, 25 Sep 2011 07:25:16 GMT</pubDate>
			<description><![CDATA[<p>In JavaScript, functions are &quot;first-class objects&quot; that can be stored in variables or passed as arguments to other functions.  Prefix delegates are similar except they're strongly typed.</p>
<p><em>This post is about Prefix a modern language that compiles to JavaScript. A language where C# is the inspiration - not the goal. Read more on the <a href="http://www.toptensoftware.com/prefix">Prefix Project Page</a>.</em></p>
<p>&quot;First-class Functions&quot; are one of those topics that most new programmers struggle with - it's a weird concept passing a function to another function, or storing it in a variable.  In JavaScript however this is a fairly common practice and the Prefix equivalent is a delegate.</p>
<h2 id="simple-delegates">Simple Delegates</h2>
<p>A delegate type declaration gives a name to a function prototype ie: the set of parameters to a function and its return type.  Once a delegate type is declared you can create variables or parameters of that type and store or pass function references in them.</p>
<p>eg:</p>
<div class="sxs">
<pre class="prettyprint lang-csharp"><code>extern dynamic Console;

// This is the delegate type - it specifies that functions
// references by it must have a single integer paramter and
// a void return type
delegate void delDoSomethingWithInt(int a);

// Here's a function that satisfies that requirement
void PrintInt(int x)
{
    Console.WriteLine(x.toString());
}

// Create a variable and store a reference to the function in it
delDoSomethingWithInt fn = PrintInt;

// Call it
fn(5);
</code></pre>
<pre class="prettyprint lang-javascript"><code>(function() {

function PrintInt(x)
{
    Console.WriteLine(x.toString());
};

// Start Global Code
var fn=PrintInt;
fn(5);

})();
</code></pre>
</div>
<p>Note that in the generated JavaScript all references to the delegate type vanish - however they've served there purpose in letting the compiler check that only matching functions are passed.  For example if the <code>PrintInt</code> function accepted a different set of parameters an error would be generated.</p>
<h2 id="binding-delegates-to-an-object-reference">Binding Delegates to an Object Reference</h2>
<p>In the above example, the function called is a simple global scope function.  Delegates however can reference a function on a specific object instance.  In this case, Prefix binds the object reference so that it's passed to the function correctly when it's invoked:</p>
<div class="sxs">
<pre class="prettyprint lang-csharp"><code>extern dynamic Console;

class MyClass
{
    public int Value;
    public void DoSomething()
    {
        Console.WriteLine(&quot;MyClass.DoSomething - &quot; + Value.toString());
    }
}

delegate void del();

var inst = new MyClass();
inst.Value=23;

del fn = inst.DoSomething;
fn();
</code></pre>
<pre class="prettyprint lang-javascript"><code>(function() {

// Prefix runtime library
var $dex = {};
$dex.bind=function(a,b){var c=a[b];return function(){c.apply(a,arguments)}} 

// class MyClass
var MyClass = function() {};
MyClass.typeName = 'MyClass';
MyClass.prototype.Value = 0;

MyClass.prototype.DoSomething = function()
{
    Console.WriteLine(&quot;MyClass.DoSomething - &quot; + this.Value.toString());
};

// Start Global Code
var inst=new MyClass();
inst.Value = 23;
var fn=$dex.bind(inst, &quot;DoSomething&quot;);
fn();

})();
</code></pre>
</div>
<p>Note that calling the delegate variable <code>fn</code> knows nothing of the <code>MyClass</code> instance, yet calling it still works thanks to the binding done by the helper function <code>$dex.bind</code>.</p>
<h2 id="generic-delegates">Generic Delegates</h2>
<p>Prefix also supports generic delegates.  Consider this example which is identical to the previous example except that the delegate is declared as a generic.  The <code>int</code> parameter type isn't resolved until the delegate is used:</p>
<div class="sxs">
<pre class="prettyprint lang-csharp"><code>extern dynamic Console;

class MyClass
{
    public int Value;
    public void DoSomething(int param)
    {
        Console.WriteLine(&quot;MyClass.DoSomething - &quot; + Value.toString() + &quot; - &quot; + param.toString());
    }
}

delegate void del&lt;T&gt;(T a);

var inst = new MyClass();
inst.Value=23;

del&lt;int&gt; fn = inst.DoSomething;
fn(5);
</code></pre>
<pre class="prettyprint lang-javascript"><code>(function() {

// Prefix runtime library
var $dex = {};
$dex.bind=function(a,b){var c=a[b];return function(){c.apply(a,arguments)}} 

// class MyClass
var MyClass = function() {};
MyClass.typeName = 'MyClass';
MyClass.prototype.Value = 0;

MyClass.prototype.DoSomething = function(param)
{
    Console.WriteLine(&quot;MyClass.DoSomething - &quot; + this.Value.toString() + &quot; - &quot; + param.toString());
};

// Start Global Code
var inst=new MyClass();
inst.Value = 23;
var fn=$dex.bind(inst, &quot;DoSomething&quot;);
fn(5);

})();
</code></pre>
</div>
<h2 id="and-"><code>Func</code> and <code>Action</code></h2>
<p>Now that Prefix has support for generic delegates, support for <code>Func</code> and <code>Action</code> are simply a matter of declaring them:</p>
<pre class="prettyprint lang-csharp"><code>delegate TResult Func&lt;TResult&gt;();
delegate TResult Func&lt;T1, TResult&gt;(T1 p1);
delegate TResult Func&lt;T1, T2, TResult&gt;(T1 p1, T2 p2);
// etc...

delegate void Action();
delegate void Action&lt;T1&gt;(T1 p1);
delegate void Action&lt;T1, T2&gt;(T1 p1, T2 p2);
// etc...
</code></pre>
<p>Prefix includes built-in declarations for Func and Action with up to 8 parameters:</p>
<div class="sxs">
<pre class="prettyprint lang-csharp"><code>extern dynamic Console;


int addem(int a, int b)
{
    return a+b;
}

Func&lt;int, int, int&gt; op = addem;

Console.WriteLine(op(10, 20).toString());
</code></pre>
<pre class="prettyprint lang-javascript"><code>(function() {

function addem(a, b)
{
    return a + b;
};

// Start Global Code
var op=addem;
Console.WriteLine(op(10, 20).toString());

})();
</code></pre>
</div>
<h2 id="type-inference-with-delegates">Type Inference with Delegates</h2>
<p>Prefix supports generic type inference with delegates.  The following example declares a generic function with two generic parameters <code>TIn</code> and <code>TOut</code>.  Note that when the function is called, it's simply called <code>fn</code> and the type are inferred from the usage.  ie: Prefix has inferred that <code>TIn</code> is <code>int</code> and <code>TOut</code> is <code>string</code>.</p>
<div class="sxs">
<pre class="prettyprint lang-csharp"><code>extern dynamic Console;

TOut fn&lt;TIn, TOut&gt;(Func&lt;TIn,TOut&gt; cb, TIn input)
{
    return cb(input);
}

string convert(int val)
{   
    return val.toString();
}

Console.WriteLine(fn(convert, 23));
</code></pre>
<pre class="prettyprint lang-javascript"><code>(function() {

function fn$2(cb, input)
{
    return cb(input);
};

function convert(val)
{
    return val.toString();
};

// Start Global Code
Console.WriteLine(fn$2(convert, 23));

})();
</code></pre>
</div>
<h2 id="conclusion">Conclusion</h2>
<p>Delegates are an important concept for Prefix as they bring the language considerably closer to JavaScript's capabilities and also lead into Lambda's and Anonymous Functions which I'm working on now.</p>
]]></description>
			<link>http://www.toptensoftware.com/Articles/131/Prefix-Delegates</link>
			<guid isPermaLink="false">http://www.toptensoftware.com/Articles/131/Prefix-Delegates</guid>
			<comments>http://www.toptensoftware.com/Articles/131/Prefix-Delegates</comments>
			<category>JavaScript</category>
			<category>Prefix</category>
			</item></channel>
</rss>		