<?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>Naming is Hard &#187; .NET</title>
	<atom:link href="http://bruceboughton.me.uk/category/dot-net/feed/" rel="self" type="application/rss+xml" />
	<link>http://bruceboughton.me.uk</link>
	<description>Written by Bruce Boughton</description>
	<lastBuildDate>Mon, 10 May 2010 15:54:22 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Assembly versioning: How to include the Subversion revision number</title>
		<link>http://bruceboughton.me.uk/2009/01/04/assembly-versioning-how-to-include-the-subversion-revision-number/</link>
		<comments>http://bruceboughton.me.uk/2009/01/04/assembly-versioning-how-to-include-the-subversion-revision-number/#comments</comments>
		<pubDate>Sun, 04 Jan 2009 17:50:45 +0000</pubDate>
		<dc:creator>Bruce Boughton</dc:creator>
				<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">http://siliconbea.ch/?p=201</guid>
		<description><![CDATA[When you build a C# project in Visual Studio, the version of the generated assembly comes from the AssemblyVersion attribute applied to the assembly. Often you want to update this version number when your code changes.
In the default project setup, this attribute is specified in AssemblyInfo.cs in the Properties directory. The version number consists of [...]]]></description>
			<content:encoded><![CDATA[<p>When you build a C# project in Visual Studio, the version of the generated assembly comes from the AssemblyVersion attribute applied to the assembly. Often you want to update this version number when your code changes.</p>
<p>In the default project setup, this attribute is specified in AssemblyInfo.cs in the Properties directory. The version number consists of four parts, nominally: <em>major version</em>, <em>minor version</em>, <em>build</em>, <em>revision</em>. If you specify an asterisk for the build or build &amp; revision parts, the compiler will update the version number at each build (based on the build time).</p>
<p>If your project is under source control, it can make more sense to link your version numbers to the version of your code at the time it was built. If you&#8217;re using Subversion, you can use the <a href="http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-subwcrev.html">subwcrev tool from TortoiseSVN</a> to generate the version number:</p>
<ol>
<li>Remove the AssemblyVersion attribute from the AssemblyInfo.cs file: <kbd><br />
[assembly: AssemblyVersion("1.0.0.0")]</kbd>.</p>
<p>Note: if you want AssemblyVersion and AssemblyFileVersion to be the same, you do not need to specify AssemblyFileVersion at all.</li>
<li>Create a new VersionInfo.cs.tmpl code file in the Properties folder. (Try adding in the project root, and dragging it into the Properties folder). Put the AssemblyVersion attribute in the file. For example:<kbd>[assembly: AssemblyVersion("1.0.0.$WCREV$")]</kbd>
<p><kbd>$WCREV$</kbd> will be replaced with the highest Subversion revision number of all files in the project at each build.</li>
<li>Add a <strong>pre</strong>-build event to the project (all on one line):<kbd>subwcrev "$(ProjectDir)." "$(ProjectDir)\Properties\VersionInfo.cs.tmpl" "$(ProjectDir)\Properties\VersionInfo.cs"</kbd>
<p>Make sure that <kbd>C:\Program Files\TortoiseSVN\bin</kbd> is on your PATH.</li>
<li>Edit the csproj file. Look for: <kbd>&lt;None Include="Properties\VersionInfo.cs.tmpl"/&gt;</kbd>Add the following after it: <kbd>&lt;Compile Include="Properties\VersionInfo.cs"/&gt;</kbd></li>
<li>Build the project. The VersionInfo.cs file will have been generated. Add it to the Subversion ignore list, as you do not want it to exist in the repository.</li>
</ol>
<p>If you want the version number to change with each build, try: <kbd>[assembly: AssemblyVersion("1.0.$WCREV$.*")]</kbd>.</p>
<h2>Build servers</h2>
<p>For this to work on a build server, you need to make sure that your code is being built inside a working copy. For example, in TeamCity you need to set the <a href="http://confluence.jetbrains.net/display/TCD4/Build+Checkout+Directory" target="_blank"><em>VCS checkout mode</em> </a>to <em>Automatically on agent</em> in the version control settings. (Thanks, <a href="http://stackoverflow.com/questions/381452/why-wont-teamcity-run-my-nant-build-file/691558#691558">Eugene Petrenko</a>)</p>
<p><strong>Update 8 Feb 2010: </strong>Added section about build servers. Also, updated pre-build command as per <a href="http://bruceboughton.me.uk/2009/01/04/assembly-versioning-how-to-include-the-subversion-revision-number/#comment-30">Tricky Dicky&#8217;s comment</a> below)</p>
]]></content:encoded>
			<wfw:commentRss>http://bruceboughton.me.uk/2009/01/04/assembly-versioning-how-to-include-the-subversion-revision-number/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Bringing OAuth to .NET developers</title>
		<link>http://bruceboughton.me.uk/2008/09/05/bringing-oauth-to-dot-net-developers/</link>
		<comments>http://bruceboughton.me.uk/2008/09/05/bringing-oauth-to-dot-net-developers/#comments</comments>
		<pubDate>Fri, 05 Sep 2008 09:00:33 +0000</pubDate>
		<dc:creator>Bruce Boughton</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[OAuth]]></category>
		<category><![CDATA[barcampbrighton3]]></category>

		<guid isPermaLink="false">http://siliconbea.ch/?p=158</guid>
		<description><![CDATA[Over the last few months, as part of Madgex&#8217;s ongoing commitment to research and development, I have been working closely with Chris Adams to build an OAuth library for .NET, which we&#8217;ve cleverly named OAuth.net.
Today, I&#8217;m delighted to announce that Madgex is open-sourcing this library for everyone to use. To mark the occasion, we&#8217;ve put [...]]]></description>
			<content:encoded><![CDATA[<p>Over the last few months, as part of Madgex&#8217;s ongoing commitment to research and development, I have been working closely with Chris Adams to build an OAuth library for .NET, which we&#8217;ve cleverly named <a href="http://lab.madgex.com/oauth-net/">OAuth.net</a>.</p>
<p>Today, I&#8217;m delighted to announce that Madgex is <strong>open-sourcing</strong> this library for everyone to use. To mark the occasion, we&#8217;ve put some demos up on the <a href="http://lab.madgex.com/oauth-net/">Madgex Lab</a> site and loaded the <a href="http://code.google.com/p/oauth-dot-net/">source code</a> on to Google Code!</p>
<h3>OAuth: simple, standard and secure API authentication</h3>
<p><a href="http://oauth.net/">OAuth</a> is a fresh new standard that allows users to share their online data between different web, desktop and mobile applications <strong>without also having to share their passwords</strong>.</p>
<p>A great example of a use case is the friend import feature that all social networks seem to have. Just give them your email address and password, and they will kindly go off and find your friends for you! Oh, and they promise not to write your password down on any post-its. Honest.</p>
<p>Hopefully, everyone can see how this is a Bad Idea. It&#8217;s so bad, in fact, that it has a big scary name: <strong>the Password Anti-Pattern</strong>. With OAuth, however, you don&#8217;t have to give the social network your password; instead they simply send you to your webmail site where you log in and issue them a special token. The token, like a valet car key, gives access to your contacts but is useless for any other purpose.</p>
<p>Of course, OAuth isn&#8217;t just for sharing address books. OAuth can (and should) be used wherever a user&#8217;s private data is to be shared between a website and a third-party web, desktop or mobile application. Other examples include location-aware applications that <a href="http://lab.madgex.com/oauth-net/gettingatarted01.aspx/">fetch your location from Fire Eagle</a>, and photo printing sites that turn your online photos into lovely printed albums.</p>
<h3>Find out more</h3>
<p>If I&#8217;ve piqued your interest (and I hope I have), here&#8217;s how to find out more. First, <strong>I will be talking about OAuth at Barcamp Brighton 3 this weekend</strong>, so if you&#8217;re lucky enough to have a ticket, pop along to my session and ask me lots of tough questions! Madgex also have a stand at dConstruct today, so feel free to pop along and grab Chris, Glenn or me for a chat. We&#8217;ll also be at ReMix UK 08 in a few weeks time, if you&#8217;re not around this weekend.</p>
<p>Next, download the <a href="http://code.google.com/p/oauth-dot-net/">source code</a> and peruse the examples on the <a href="http://lab.madgex.com/oauth-net/">Madgex Lab</a> site. For a more in-depth discussion, I&#8217;ve written a <a href="http://lab.madgex.com/oauth-net/gettingatarted01.aspx/">getting started guide</a> where I show how to build a Fire Eagle mashup with Google Maps.</p>
<p>Finally, we&#8217;d love to hear from you, so email us at <a href="mailto:oauth-dot-net@madgex.com">oauth-dot-net@madgex.com</a> or tweet <a href="http://twitter.com/bruceboughton">me</a>, <a href="http://twitter.com/glennjones">Glenn</a> or <a href="http://twitter.com/csadams">Chris</a>.</p>
<h3>Update: Barcamp Brighton 3 presentation slides</h3>
<p><a href="http://bruceboughton.me.uk/wp-content/uploads/2008/09/oauth-vs-password-antipattern.ppt"><img src="/wp-content/uploads/2008/09/screenshot.png" border="0" /></a></p>
<p>I&#8217;ve uploaded the <a href="http://bruceboughton.me.uk/wp-content/uploads/2008/09/oauth-vs-password-antipattern.ppt">presentation slides</a> here. (Although the slides are quite sparse, pretty much everything I said is in the notes for the slides)</p>
]]></content:encoded>
			<wfw:commentRss>http://bruceboughton.me.uk/2008/09/05/bringing-oauth-to-dot-net-developers/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>On Lambdas</title>
		<link>http://bruceboughton.me.uk/2008/07/24/on-lambdas/</link>
		<comments>http://bruceboughton.me.uk/2008/07/24/on-lambdas/#comments</comments>
		<pubDate>Thu, 24 Jul 2008 19:03:46 +0000</pubDate>
		<dc:creator>Bruce Boughton</dc:creator>
				<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">http://siliconbea.ch/?p=137</guid>
		<description><![CDATA[Someone at work complained today that she didn&#8217;t like the code she&#8217;d written to find an element in a collection:

public class SingletonSomething
{
	public void DoSomething()
	{
		IList list;
		// ..
		this.Host = GetHost();
		Uri item = list.Find(FindUriByHost);
	}

	public bool FindUriByHost(Uri uri)
	{
		return uri.Host == this.Host;
	}
}

On the one hand, she was using IList&#60;T&#62;.Find(Predicate&#60;T&#62; predicate) which is a neat abstraction for iterating a list to [...]]]></description>
			<content:encoded><![CDATA[<p>Someone at work complained today that she didn&#8217;t like the code she&#8217;d written to find an element in a collection:</p>
<pre lang="csharp" line="1">
public class SingletonSomething
{
	public void DoSomething()
	{
		IList<uri> list;
		// ..
		this.Host = GetHost();
		Uri item = list.Find(FindUriByHost);
	}

	public bool FindUriByHost(Uri uri)
	{
		return uri.Host == this.Host;
	}
}
</pre>
<p>On the one hand, she was using <kbd>IList&lt;T&gt;.Find(Predicate&lt;T&gt; predicate)</kbd> which is a neat abstraction for iterating a list to find an item. However, she was having to store some state in her singleton class about the condition to apply, which she wasn&#8217;t happy about (it&#8217;s clearly not thread-safe for a start).</p>
<p>First of all, thinking it was a .NET 2.0 project, I suggested she use an anonymous delegate as the predicate instead of a named method. We tried this but couldn&#8217;t convince the compiler that it satisfied the <kbd>Predicate&lt;T&gt;</kbd> type:</p>
<pre lang="csharp">
string host = GetHost();
Uri item = list.Find(delegate(Uri uri) { return uri.Host == host; });
</pre>
<p>(I thought this would work but it didn&#8217;t&#8211;I need to look into why.)</p>
<p>When I realised this was a .NET 3.5 project, I suggested a lambda instead. My colleague&#8217;s first reaction was one of skepticism&#8211;she&#8217;d not really heard good things about lambdas. But after changing the code to use a lambda, and once she&#8217;d got past the funny syntax, she was quite happy with the lambda:</p>
<pre lang="csharp">
string host = GetUri();
Uri item = list.Find(uri => uri.Host == host);
</pre>
<p>I think we can all agree that this is much more readable, once you realise <kbd>=&gt;</kbd> should be read as &#8217;such that&#8217; or &#8216;goes to&#8217;:</p>
<blockquote><p><em>Find a URI in the list such that uri.Host equals host</em></p>
</blockquote>
<p>And once you&#8217;ve seen the syntax and used it a couple of times, it&#8217;s really not that complicated: much simpler than dealing with thread safety or declaring a new method. Yet, <strong>lambdas seem to have attracted a bad name</strong>. I&#8217;m not sure why.</p>
<p>Perhaps it&#8217;s that they seem type-less, like <kbd>var</kbd> (C# developers see any attack on strong typing as tantamount to sleeping with the vicar). In fact, lambdas aren&#8217;t typeless, just as <kbd>var</kbd> isn&#8217;t variant: the compiler simple infers the type at compile time. Once compiled, it&#8217;s as if you&#8217;d typed it in yourself. Or perhaps it&#8217;s the funny syntax, which can take several different forms.</p>
<p>Either way, it&#8217;s a shame. <strong>Lambdas in C# are an extremely powerful construct</strong>. I hope C# developers can come to love lambdas just as much as they love, say, type safety.</p>
]]></content:encoded>
			<wfw:commentRss>http://bruceboughton.me.uk/2008/07/24/on-lambdas/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Debugging IEnumerable.GetEnumerator</title>
		<link>http://bruceboughton.me.uk/2008/07/06/debugging-ienumerable-getenumerator/</link>
		<comments>http://bruceboughton.me.uk/2008/07/06/debugging-ienumerable-getenumerator/#comments</comments>
		<pubDate>Sun, 06 Jul 2008 14:18:55 +0000</pubDate>
		<dc:creator>Bruce Boughton</dc:creator>
				<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">http://siliconbea.ch/?p=128</guid>
		<description><![CDATA[I&#8217;ve been working a lot recently with IEnumarable objects as generators. I think it&#8217;s a really nice pattern, which allows you to defer processing until it is needed. For example,

foreach (LogEntry entry in logreader)
    /* Do something with the log entry */

(LogReader does not need to read all lines in advance; instead [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been working a lot recently with IEnumarable objects as generators. I think it&#8217;s a really nice pattern, which allows you to defer processing until it is needed. For example,</p>
<pre lang="csharp" line="1">
foreach (LogEntry entry in logreader)
    /* Do something with the log entry */
</pre>
<p>(LogReader does not need to read all lines in advance; instead it can read each line as it is requested)</p>
<p>One irritant I&#8217;ve encountered with GetEnumerator is that it can be quite hard to debug if you access class fields. The compiler transforms the GetEnumerator method body into a nested class. In the Locals window in visual studio you can&#8217;t access your class&#8217;s fields and when hovering over variables you don&#8217;t get pop-up introspection.</p>
<p>It is possible, however, to access your class&#8217;s fields and properties via reflection. The generated GetEnumerator class stores a reference to your class in a private field which is not exposed to the Locals window. In my experience, this is the only field in the generated class so you can access its value using the Immediate window like so:</p>
<pre lang="csharp">
this.GetType().GetFields()[0].GetValue(this)
</pre>
<p>If this isn&#8217;t what you&#8217;re expecting, look at the array of fields returned and find the one that holds the reference to your class (usually named something like <code>&lt;&gt;4__this</code>).</p>
<p><ins>Update:</ins> If you want to access the member fields, properties and methods of your class you need to cast it to your type. To avoid doing this repetitively, you can create a variable holding the cast reference in the Immediate window:</p>
<pre lang="csharp">
Foo me = (Foo)this.GetType().GetFields()[0].GetValue(this);
me.Bar;
me.SomeMethod();
</pre>
]]></content:encoded>
			<wfw:commentRss>http://bruceboughton.me.uk/2008/07/06/debugging-ienumerable-getenumerator/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Emulating Java 5 enums in .NET: Part 2</title>
		<link>http://bruceboughton.me.uk/2008/06/08/emulating-java-5-enums-in-dotnet-part-2/</link>
		<comments>http://bruceboughton.me.uk/2008/06/08/emulating-java-5-enums-in-dotnet-part-2/#comments</comments>
		<pubDate>Sun, 08 Jun 2008 22:31:29 +0000</pubDate>
		<dc:creator>Bruce Boughton</dc:creator>
				<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">http://siliconbea.ch/?p=113</guid>
		<description><![CDATA[Last time, I looked at how to emulate Java 5 enums on the .NET 2 runtime. This time I&#8217;m going to allow myself to take advantage of the new features supported in the .NET 3.5 runtime.
Reminder: what we&#8217;re trying to emulate
Java 5 enums allow you to enhance your enums with data and behaviour. We&#8217;re trying [...]]]></description>
			<content:encoded><![CDATA[<p>Last time, I looked at <a href="http://siliconbea.ch/technology/2008-06-08/emulating-java-5-enums-in-dotnet/">how to emulate Java 5 enums on the .NET 2 runtime</a>. This time I&#8217;m going to allow myself to take advantage of the new features supported in the .NET 3.5 runtime.</p>
<h3>Reminder: what we&#8217;re trying to emulate</h3>
<p>Java 5 enums allow you to enhance your enums with data and behaviour. We&#8217;re trying to recreate the <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html">Planet example</a> in .NET:</p>
<pre lang="java" line="1">
public enum Planet {
    MERCURY (3.303e+23, 2.4397e6),
    VENUS   (4.869e+24, 6.0518e6),
    EARTH   (5.976e+24, 6.37814e6),
    MARS    (6.421e+23, 3.3972e6),
    JUPITER (1.9e+27,   7.1492e7),
    SATURN  (5.688e+26, 6.0268e7),
    URANUS  (8.686e+25, 2.5559e7),
    NEPTUNE (1.024e+26, 2.4746e7),
    PLUTO   (1.27e+22,  1.137e6);

    private final double mass;   // in kilograms
    private final double radius; // in meters
    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }
    public double mass()   { return mass; }
    public double radius() { return radius; }

    // universal gravitational constant  (m3 kg-1 s-2)
    public static final double G = 6.67300E-11;

    public double surfaceGravity() {
        return G * mass / (radius * radius);
    }
    public double surfaceWeight(double otherMass) {
        return otherMass * surfaceGravity();
    }
}
</pre>
<h3>Extension Methods</h3>
<p>One important new .NET feature is extension methods. Extension methods allow you to augment existing classes with new member methods. For example, the following code adds a method to <kbd>DateTime</kbd> instances to convert them to the Unix time format (the number of seconds since the Unix epoch, 1970-01-01 0:00:0.000):</p>
<pre lang="csharp" line="1">
using System;

namespace MyExtensionMethods
{
    public static class DateTimeExtensions
    {
        private static readonly DateTime UnixEpoch
            = new DateTime(1970, 1, 1, 0, 0, 0, 0, 0);

        public static long ToUnixTime(this DateTime date)
        {
            return (long)(date.ToUniversalTime() - UnixEpoch).TotalSeconds;
        }
    }
}
</pre>
<p>The extension method is then visible on any instance of a <kbd>DateTime</kbd> object once you have imported the namespace:</p>
<pre lang="csharp" line="1">
using MyExtensionMethods;

public class UnixTimeTests
{
    public void Test_UnixTimeExtensionMethod()
    {
         DateTime now = DateTime.Now;
         long unixNow = now.ToUnixTime();
    }
}
</pre>
<p>You even get Intellisense!</p>
<h3>Planet enum with Extension Methods</h3>
<p>The plan is very simple: attach extension methods to our raw <kbd>Planet</kbd> enum type. Ironically, the <kbd>Mass</kbd> and <kbd>Radius</kbd> properties have to be implemented as getter methods, just as in Java, since we can&#8217;t add extension <em>properties</em>:</p>
<pre lang="csharp" line="1">
public enum Planet
{
    Mercury,
    Venus,
    Earth,
    Mars,
    Jupiter,
    Saturn,
    Uranus,
    Neptune,
    Pluto
}

public static class PlanetExtensions
{
    public static double GetMass(this Planet planet)
    {
        switch (planet)
        {
            case Planet.Mercury: return 3.303e+23;
            case Planet.Venus: return 4.869e+24;
            case Planet.Earth: return 5.976e+24;
            case Planet.Mars: return 6.421e+23;
            case Planet.Jupiter: return 1.9e+27;
            case Planet.Saturn: return 5.688e+26;
            case Planet.Uranus: return 8.686e+25;
            case Planet.Neptune: return 1.024e+26;
            case Planet.Pluto: return 1.27e+22;
            default: throw new Exception("Illegal state");
        }
    }

    public static double GetRadius(this Planet planet)
    {
        switch (planet)
        {
            case Planet.Mercury: return 2.4397e6;
            case Planet.Venus: return 6.0518e6;
            case Planet.Earth: return 6.37814e6;
            case Planet.Mars: return 3.3972e6;
            case Planet.Jupiter: return 7.1492e7;
            case Planet.Saturn: return 6.0268e7;
            case Planet.Uranus: return 2.5559e7;
            case Planet.Neptune: return 2.4746e7;
            case Planet.Pluto: return 1.137e6;
            default: throw new Exception("Illegal state");
        }
    }

    public const double G = 6.67300E-11;

    public static double GetSurfaceGravity(this Planet planet)
    {
        return G * planet.GetMass() / (planet.GetRadius() * planet.GetRadius());
    }

    public static double SurfaceWeight(this Planet planet, double otherMass)
    {
        return otherMass * planet.GetSurfaceGravity();
    }
}
</pre>
<p>This comes pretty close to being a perfect solution. We haven&#8217;t changed the enum itself so you can use it just as if there were no extra functionality; there&#8217;s no funky switch syntax, for example. There&#8217;s still room for improvement; I don&#8217;t like having the data so far from the enum member declaration. Yet, we&#8217;ve implemented the full functionality from the Java 5 example, and I think that&#8217;s testament to the flexibility of C#.</p>
<p>What do you think?</p>
<p>The <a href="http://code.google.com/p/bruceboughton-experiments/source/browse/trunk/EnumExtensionMethods/">source code for this experiment</a> is available at Google Code as a Visual Studio 2008 project, licensed under a <a href="http://www.opensource.org/licenses/mit-license.php">MIT license</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://bruceboughton.me.uk/2008/06/08/emulating-java-5-enums-in-dotnet-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Emulating Java 5 enums in .NET</title>
		<link>http://bruceboughton.me.uk/2008/06/08/emulating-java-5-enums-in-dotnet/</link>
		<comments>http://bruceboughton.me.uk/2008/06/08/emulating-java-5-enums-in-dotnet/#comments</comments>
		<pubDate>Sun, 08 Jun 2008 17:48:33 +0000</pubDate>
		<dc:creator>Bruce Boughton</dc:creator>
				<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">http://siliconbea.ch/?p=108</guid>
		<description><![CDATA[In the C#&#8212;Java shootout, Java edges it in my opinion when it comes to support for enums. C# enums are pretty vanilla: a set of named values, with support for flags via the Flags attribute. I&#8217;m often frustrated that I can&#8217;t add functionality and extra data to my enums. For example, here&#8217;s the canonical Java [...]]]></description>
			<content:encoded><![CDATA[<p>In the C#&mdash;Java shootout, Java edges it in my opinion when it comes to support for enums. C# enums are pretty vanilla: a set of named values, with support for flags via the <kbd>Flags</kbd> attribute. I&#8217;m often frustrated that I can&#8217;t add functionality and extra data to my enums. For example, here&#8217;s the canonical <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html">Java 5 example</a>:</p>
<pre lang="java" line="1">
public enum Planet {
    MERCURY (3.303e+23, 2.4397e6),
    VENUS   (4.869e+24, 6.0518e6),
    EARTH   (5.976e+24, 6.37814e6),
    MARS    (6.421e+23, 3.3972e6),
    JUPITER (1.9e+27,   7.1492e7),
    SATURN  (5.688e+26, 6.0268e7),
    URANUS  (8.686e+25, 2.5559e7),
    NEPTUNE (1.024e+26, 2.4746e7),
    PLUTO   (1.27e+22,  1.137e6);

    private final double mass;   // in kilograms
    private final double radius; // in meters
    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }
    public double mass()   { return mass; }
    public double radius() { return radius; }

    // universal gravitational constant  (m3 kg-1 s-2)
    public static final double G = 6.67300E-11;

    public double surfaceGravity() {
        return G * mass / (radius * radius);
    }
    public double surfaceWeight(double otherMass) {
        return otherMass * surfaceGravity();
    }
}
</pre>
<p>Each planet has a mass and radius associated with it directly in the enum definition. For example, Mercury&#8217;s mass is 3.303e+23 kg and its radius is 2.4397e6 m. The enum has a constant, <kbd>G</kbd>, and public methods to calculate the surface gravity of the planet and surface weight of a mass on the planet.</p>
<h3>Emulating this in .NET 2.0</h3>
<p>Let&#8217;s try to emulate this in .NET 2.0. We want a <kbd>Planet</kbd> enum with 9 entries, each with a mass and radius. From these, we want to be able to calculate the surface gravity of the planet and surface weight of a mass.</p>
<p>How should we express this in C#? Our <kbd>Planet</kbd> can&#8217;t be an enum since we can&#8217;t poke around with them (<kbd>System.Enum</kbd> is a very special type), so it&#8217;ll have to be a struct or a class. Enums are value types so let&#8217;s go with a struct. We still want the compiler conveniences afforded to enums so let&#8217;s keep the planets as a nested enum:</p>
<pre lang="csharp" line="1">
public struct Planet
{
        public enum _
        {
            Mercury,
            Venus,
            Earth,
            Mars,
            Jupiter,
            Saturn,
            Uranus,
            Neptune,
            Pluto
        }

        private Planet._ enumValue;

        public Planet(Planet._ enumValue)
        {
            this.Value = enumValue;
        }

        public Planet._ Value
        {
            get { return this.enumValue; }
            private set { this.enumValue= value; }
        }

        public double Mass
        {
            get
            {
                /* TODO */
            }
        }

        public double Radius
        {
            get
            {
                /* TODO */
            }
        }

        public const double G = 6.67300E-11;

        public double SurfaceGravity
        {
            get { return G * this.Mass / (this.Radius * this.Radius); }
        }

        public double SurfaceWeight(double otherMass)
        {
            return otherMass * this.SurfaceGravity;
        }
}
</pre>
<p>So this is a good starting point. We can construct a <kbd>Planet</kbd> like so:</p>
<pre lang="csharp" line="1">
Planet myplanet = new Planet(Planet._.Mercury);
</pre>
<p>We can switch on its value:</p>
<pre lang="csharp" line="2">
switch (myplanet.Value)
{
        case Planet._.Mercury:
                /* ... */
                break;

        case Planet._.Venus:
                /* ... */
}
</pre>
<h4>Adding the data</h4>
<p>However, we&#8217;ve yet to add the data, so let&#8217;s do that. We&#8217;ll change the <kbd>Mass</kbd> and <kbd>Radius</kbd> properties like so:</p>
<pre lang="csharp" line="29">
        public double Mass
        {
            get
            {
                switch (this.Value)
                {
                    case _.Mercury: return 3.303e+23;
                    case _.Venus: return 4.869e+24;
                    case _.Earth: return 5.976e+24;
                    case _.Mars: return 6.421e+23;
                    case _.Jupiter: return 1.9e+27;
                    case _.Saturn: return 5.688e+26;
                    case _.Uranus: return 8.686e+25;
                    case _.Neptune: return 1.024e+26;
                    case _.Pluto: return 1.27e+22;
                    default: throw new Exception("Illegal state");
                }
            }
        }

        public double Radius
        {
            get
            {
                switch (this.Value)
                {
                    case _.Mercury: return 2.4397e6;
                    case _.Venus: return 6.0518e6;
                    case _.Earth: return 6.37814e6;
                    case _.Mars: return 3.3972e6;
                    case _.Jupiter: return 7.1492e7;
                    case _.Saturn: return 6.0268e7;
                    case _.Uranus: return 2.5559e7;
                    case _.Neptune: return 2.4746e7;
                    case _.Pluto: return 1.137e6;
                    default: throw new Exception("Illegal state");
                }
            }
        }
</pre>
<p>Finally we have a complete implementation of the Java 5 Planet enum that we can use. Two things bug me at this point:</p>
<ol>
<li>It&#8217;s a lot less terse than the Java 5 definition. Surely we can move some of this out into a base class? Also, we&#8217;ve not overridden <kbd>Equals</kbd> and <kbd>operator ==</kbd> which we really should do for a struct, or implemented <kbd>IComparable</kbd>, <kbd>IFormattable</kbd> or <kbd>IConvertible</kbd> like <kbd>System.Enum</kbd>. The full enum would be quite a bit longer</li>
<li>To get at the actual enum value, we have to type <kbd>myplanet.Value</kbd> which is less intuitive and clean than just typing <kbd>myplanet</kbd>.</li>
</ol>
<h4>Adding Syntactic Sugar</h4>
<p>Let&#8217;s create a base class, <kbd>ExtendedEnum&lt;T&gt;</kbd>, to be the base class for all our data enums. We&#8217;ll have to change our <kbd>Planet</kbd> struct into a sealed class that extends our base class.</p>
<pre lang="csharp" line="1">
public abstract class ExtendedEnum<t>
    : IComparable, IFormattable, IConvertible
    where T : struct, IComparable, IFormattable, IConvertible
{
    private T enumValue;

    public ExtendedEnum(T enumValue)
    {
        this.Value = enumValue;
    }

    public ExtendedEnum(string enumName)
    {
        this.Value = (T)Enum.Parse(typeof(T), enumName);
    }

    public T Value
    {
        get { return this.enumValue; }
        private set { this.enumValue = value; }
    }

    // Overloads the unary + operator to convert the ExtendedEnum to
    // its enum value. This is a shorthand for extendedEnum.Value
    public static T operator +(ExtendedEnum<t> extendedEnum)
    {
        return extendedEnum.Value;
    }

    // Implicit conversion from ExtendedEnum to the enum value.
    public static implicit operator T(ExtendedEnum<t> extendedEnum)
    {
        return extendedEnum.Value;
    }

    public override bool Equals(object obj)
    {
        if (obj == null)
            return false;

        if (object.ReferenceEquals(this, obj))
            return true;

        if (obj is T)
            return this.Equals((T)obj);
        else if (obj is ExtendedEnum<t>)
            return this.Equals((ExtendedEnum<t>)obj);
        else
            return false;
    }

    public static bool operator ==(ExtendedEnum<t> left,
        ExtendedEnum<t> right)
    {
        return left.Equals(right);
    }

    // public static bool operator != ...

    public bool Equals(T otherValue)
    {
        return this.Value.Equals(otherValue);
    }

    public bool Equals(ExtendedEnum<t> other)
    {
        return this.Value.Equals(other.Value);
    }

    // public override int GetHashCode() ...
    // public override string ToString() ...
    // IComparable, IFormattable, IConvertible Members ...
}
</pre>
<p>Note that the type parameter, <kbd>T</kbd>, is constrained to a value type, and not to <kbd>System.Enum</kbd>, since <a href="http://msdn.microsoft.com/en-us/library/56b2hk61(VS.80).aspx">certain special types cannot be used in type constraints</a>.</p>
<p>Now our enum looks like this:</p>
<pre lang="csharp" line="1">
public sealed class Planet
    : ExtendedEnum
<planet._>
{
    public enum _
    {
        Mercury,
        Venus,
        Earth,
        Mars,
        Jupiter,
        Saturn,
        Uranus,
        Neptune,
        Pluto
    }

    public Planet(Planet._ enumValue)
        : base(enumValue)
    {
    }

    public Planet(string enumValue)
        : base(enumValue)
    {
    }

    public double Mass
    {
        get
        {
            switch (+this)
            {
                case _.Mercury: return 3.303e+23;
                case _.Venus: return 4.869e+24;
                case _.Earth: return 5.976e+24;
                case _.Mars: return 6.421e+23;
                case _.Jupiter: return 1.9e+27;
                case _.Saturn: return 5.688e+26;
                case _.Uranus: return 8.686e+25;
                case _.Neptune: return 1.024e+26;
                case _.Pluto: return 1.27e+22;
                default: throw new Exception("Illegal state");
            }
        }
    }

    public double Radius
    {
        get
        {
            switch (+this)
            {
                case _.Mercury: return 2.4397e6;
                case _.Venus: return 6.0518e6;
                case _.Earth: return 6.37814e6;
                case _.Mars: return 3.3972e6;
                case _.Jupiter: return 7.1492e7;
                case _.Saturn: return 6.0268e7;
                case _.Uranus: return 2.5559e7;
                case _.Neptune: return 2.4746e7;
                case _.Pluto: return 1.137e6;
                default: throw new Exception("Illegal state");
            }
        }
    }

    public const double G = 6.67300E-11;

    public double SurfaceGravity
    {
        get { return G * this.Mass / (this.Radius * this.Radius);
    }

    public double SurfaceWeight(double otherMass)
    {
        return otherMass * this.SurfaceGravity;
    }
}
</pre>
<p>That looks pretty good; our &#8220;enum&#8221; class now only contains code relevant to the enumeration (plus two constructors), but it&#8217;s still not that concise. This is as far as I went with the .NET 2 implementation.</p>
<p>Let&#8217;s take a look at what we managed to do:</p>
<ul>
<li>Enumerations with data (properties) and &#8220;behaviour&#8221; (methods)</li>
<li>Syntactic sugar for accessing the enum value and casting, though the <kbd>+</kbd> operator is not very intuitive</li>
<li>Can still use the enum in a switch statement</li>
<li>Reasonably terse code</li>
</ul>
<p>All in all, not bad. I&#8217;ll be looking at a .NET 3.5 solution in the next post, and possibly some more outlandish solutions after that. Until then, how would you improve the .NET 2.0 solution?</p>
<p>The <a href="http://code.google.com/p/bruceboughton-experiments/source/browse/trunk/ExtendedEnum/?r=2">source code for this experiment</a> is available at Google Code as a Visual Studio 2008 project, licensed under a <a href="http://www.opensource.org/licenses/mit-license.php">MIT license</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://bruceboughton.me.uk/2008/06/08/emulating-java-5-enums-in-dotnet/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>LINQ at VBUG</title>
		<link>http://bruceboughton.me.uk/2007/09/06/linq-at-vbug/</link>
		<comments>http://bruceboughton.me.uk/2007/09/06/linq-at-vbug/#comments</comments>
		<pubDate>Thu, 06 Sep 2007 09:08:21 +0000</pubDate>
		<dc:creator>Bruce Boughton</dc:creator>
				<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">http://siliconbea.ch/technology/2007-09-06/linq-at-vbug/</guid>
		<description><![CDATA[A bunch of us from Madgex launched a pincer movement on the Brighton Visual Basic User Group (VBUG) on Tuesday night to listen to a talk by Ian Cooper on LINQ.
LINQ (Language Integrated Query) is a .NET 3.0 technology which provides a type-safe query language integrated directly into the various CLR languages.  It allows [...]]]></description>
			<content:encoded><![CDATA[<p>A bunch of us from <a href="http://madgex.com/">Madgex</a> launched a pincer movement on the Brighton <a href="http://www.vbug.com/">Visual Basic User Group (VBUG)</a> on Tuesday night to listen to a talk by <a href="http://iancooper.spaces.live.com/blog/cns!844BD2811F9ABE9C!483.entry">Ian Cooper</a> on LINQ.</p>
<p><a href="http://weblogs.asp.net/scottgu/archive/tags/LINQ/default.aspx">LINQ</a> (Language Integrated Query) is a .NET 3.0 technology which provides a type-safe query language integrated directly into the various CLR languages.  It allows programmers to declaratively query data sets (in memory collections, databases, XML documents and entities) and is heavily based on SQL.  For example, to query the Northwind customers database and select the names of all customers in Brighton in C# with LINQ to SQL you would write:</p>
<p><code>NorthwindDataContext db = new NorthwindDataContext();<br />
var customers = from c in db.Customers<br />
where c.City == "Brighton"<br />
select c.Name;</code></p>
<p>The advantage of LINQ is that you have compile-time safety checking for your database queries.  SQL is no longer embedded in strings.  Also, because LINQ is a general query languages, you can query in-memory collections and XML documents in the same declarative fashion&mdash;hiding lines and lines of procedural boilerplate.</p>
<p>To be able to provide this type safety, LINQ to SQL requires a mapping between the database schema and the .NET code.  Being a Microsoft technology, there are several different ways to achieve this.  First of all, you can use the visual designer to drag and drop associations between database tables and business objects.  Secondly, you can use attributes to mark up your pre-existing business objects or write database stubs.  Thirdly, you can write an XML mapping file.  Fourthly, you can run <kbd>sqlmetal</kbd> on the command line which creates database stubs based on your parameters.  Of course, it is important to make sure that your mapping stays in sync with the database schema and the business object in your application and there will be different strategies for dealing with this.</p>
<p>Anyway, LINQ looks a very promising technology and <a href="http://iancooper.spaces.live.com/">Ian</a> presented it with great enthusiasm and knowledge.  Along the way we learnt about <a href="http://www.developer.com/net/csharp/article.php/3561756">new .NET 3.0 constructs</a> such as anonymous delegates, lamda expressions, and the <a href="http://www.interact-sw.co.uk/iangblog/2005/09/23/varisntobject"><kbd>var</kbd></a> keyword, as well as the little-known .NET 2.0 <kbd>yield</kbd> keyword.  Many thanks to <a href="http://www.vbug.com">VBUG</a> for organising the event and for the drinks and pizza!</p>
]]></content:encoded>
			<wfw:commentRss>http://bruceboughton.me.uk/2007/09/06/linq-at-vbug/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
