<?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>Stefano Ricciardi &#187; C#</title>
	<atom:link href="http://stefanoricciardi.com/tag/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://stefanoricciardi.com</link>
	<description>On Software Development and Thereabouts</description>
	<lastBuildDate>Thu, 01 Jul 2010 12:16:33 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>A Fluent Builder in C#</title>
		<link>http://stefanoricciardi.com/2010/04/14/a-fluent-builder-in-c/</link>
		<comments>http://stefanoricciardi.com/2010/04/14/a-fluent-builder-in-c/#comments</comments>
		<pubDate>Wed, 14 Apr 2010 20:27:40 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Design and Patterns]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.com/?p=884</guid>
		<description><![CDATA[When it comes to the number of arguments to pass to a function, Uncle Bob is pretty clear. Quoting from Clean Code: The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided when possible. More than three (polyadic) requires [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F04%2F14%2Fa-fluent-builder-in-c%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F04%2F14%2Fa-fluent-builder-in-c%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>When it comes to the number of arguments to pass to a function, <a href="http://www.objectmentor.com/omTeam/martin_r.html">Uncle Bob</a> is pretty clear. Quoting from <a href="http://www.amazon.co.uk/gp/product/0132350882?ie=UTF8&amp;tag=stefaricci-21&amp;linkCode=as2&amp;camp=1634&amp;creative=19450&amp;creativeASIN=0132350882">Clean Code</a><img style="margin: 0px; border-style: none !important;" src="http://www.assoc-amazon.co.uk/e/ir?t=stefaricci-21&amp;l=as2&amp;o=2&amp;a=0132350882" border="0" alt="" width="1" height="1" />:</p>
<blockquote><p>The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided when possible. More than three (polyadic) requires very special justification – and then shouldn’t be used anyway.</p></blockquote>
<p>Still, some objects might have more than 3 attributes or properties and you usually need some way to initialize them via the constructor. Some attribute might not be mandatory, therefore on some occasions you can get by with a few overloads adding more parameters as needed.   </p>
<p>Consider the following (contrieved) example from the world of soccer. I have picked a few attributes that encapsulate the concept of a <code>Team</code>.</p>
<pre class="brush:csharp">
namespace Soccer
{
    public enum Color
    {
        White,
        Red,
        Green,
        Blue
    }

    public class Team
    {
        string Name { get; set; }
        string NickName { get; set; }
        Color ShirtColor { get; set; }
        string HomeTown { get; set; }
        string Ground { get; set; }

        public Team(
            string name,
            string nickName,
            Color shirtColor,
            string homeTown,
            string ground)
        {
            Name = name;
            NickName = nickName;
            ShirtColor = shirtColor;
            HomeTown = homeTown;
            Ground = ground;
        }
    }
}</pre>
<p>Let&#8217;s try initializing one team:</p>
<pre class="brush:csharp">Team team1 = new Team(
    "Manchester United",
    "The Red Devils",
    Color.Red,
    "Manchester",
    "Old Trafford");
</pre>
<p>In this case we are passing 5 arguments into the constructor. Consider that most of the parameters is a string, therefore it&#8217;s quite easy to get confused and invert the order of some parameter (the first two or the last two). The compiler would not be able to help in this case.</p>
<p>What may help here is a builder object with a <a href="http://en.wikipedia.org/wiki/Fluent_interface">fluent interface</a> which can help specifying all the attributes of the team. Something like the following:</p>
<pre class="brush:csharp">TeamBuilder tb = new TeamBuilder();
Team team2 =
    tb.CreateTeam("Real Madrid")
        .WithNickName("Los Merengues")
        .WithShirtColor(Color.White)
        .FromTown("Madrid")
        .PlayingAt("Santiago Bernabeu")
        .Build();
</pre>
<p>Let&#8217;s see the code for the <code>TeamBuilder</code> class:</p>
<pre class="brush:csharp">public class TeamBuilder
{
    private string name;
    private string nickName;
    private Color shirtColor;
    private string homeTown;
    private string ground;

    public TeamBuilder CreateTeam(string name)
    {
        this.name = name;
        return this;
    }

    public TeamBuilder WithNickName(string nickName)
    {
        this.nickName = nickName;
        return this;
    }

    public TeamBuilder WithShirtColor(Color shirtColor)
    {
        this.shirtColor = shirtColor;
        return this;
    }

    public TeamBuilder FromTown(string homeTown)
    {
        this.homeTown = homeTown;
        return this;
    }

    public TeamBuilder PlayingAt(string ground)
    {
        this.ground = ground;
        return this;
    }

    public Team Build()
    {
        return new Team(name, nickName, shirtColor, homeTown, ground);
    }
}
</pre>
<p>The only catch in the solution above is that the caller needs to call <code>Build()</code> at the end of the call chain.</p>
<p>We can improve the solution using an <a href="http://msdn.microsoft.com/en-us/library/z5z9kes2%28VS.71%29.aspx">implicit user-defined type conversion operator</a>:</p>
<pre class="brush:csharp">public class TeamBuilder
{
    private string name;
    private string nickName;
    private Color shirtColor;
    private string homeTown;
    private string ground;

    public TeamBuilder CreateTeam(string name)
    {
        this.name = name;
        return this;
    }

    public TeamBuilder WithNickName(string nickName)
    {
        this.nickName = nickName;
        return this;
    }

    public TeamBuilder WithShirtColor(Color shirtColor)
    {
        this.shirtColor = shirtColor;
        return this;
    }

    public TeamBuilder FromTown(string homeTown)
    {
        this.homeTown = homeTown;
        return this;
    }

    public TeamBuilder PlayingAt(string ground)
    {
        this.ground = ground;
        return this;
    }

    // CONVERSION OPERATOR
    public static implicit operator Team(TeamBuilder tb)
    {
        return new Team(
            tb.name,
            tb.nickName,
            tb.shirtColor,
            tb.homeTown,
            tb.ground);
    }
</pre>
<p>This allows you to create new teams in a more natural way as follows:</p>
<pre class="brush:csharp">TeamBuilder tb = new TeamBuilder();

Team team3 = tb.CreateTeam("Chelsea")
    .WithNickName("The blues")
    .WithShirtColor(Color.Blue)
    .FromTown("London")
    .PlayingAt("Stamford Bridge");
</pre>
<p>The above solution, albeit quite simple, is a good starting point. To make it ready for real-world code, you should making it more robust with some error checking (what happens if I omit some call from the chain? If I pass an invalid argument? Etc&#8230;).</p>
<p>More, you might want to hide the actual implementation from the clients and extract an interface or abstract class from the concrete <code>TeamBuilder</code>. This is left to the reader as an excercise <img src='http://stefanoricciardi.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://stefanoricciardi.com/2010/04/14/a-fluent-builder-in-c/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://stefanoricciardi.com/2010/04/14/a-fluent-builder-in-c/" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p>    <a rev="vote-for" href="http://dotnetshoutout.com/Submit?url=http://stefanoricciardi.com/2010/04/14/a-fluent-builder-in-c/"><br />
        <img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http://stefanoricciardi.com/2010/04/14/a-fluent-builder-in-c/" style="border:0px"/><br />
    </a></p>
]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2010/04/14/a-fluent-builder-in-c/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Comparing Floating Point Numbers</title>
		<link>http://stefanoricciardi.com/2010/03/02/comparing-floating-point-numbers/</link>
		<comments>http://stefanoricciardi.com/2010/03/02/comparing-floating-point-numbers/#comments</comments>
		<pubDate>Tue, 02 Mar 2010 13:29:00 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.wordpress.com/?p=807</guid>
		<description><![CDATA[Floating Points and Rounding Errors. Working with floating points number can sometimes provide some (un)pleasant surprise, since many real numbers do not have a finite representation and this can lead to rounding errors. If you need to refresh your knowledge (and have some time to spare), you can find a great treatment in the article [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F03%2F02%2Fcomparing-floating-point-numbers%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F03%2F02%2Fcomparing-floating-point-numbers%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<h2>Floating Points and Rounding Errors.</h2>
<p>Working with floating points number can sometimes provide some (un)pleasant surprise, since many real numbers do not have a finite representation and this can lead to rounding errors. </p>
<p>If you need to refresh your knowledge (and have some time to spare), you can find a great treatment in the article <a href="http://docs.sun.com/source/806-3568/ncg_goldberg.html">What Every Computer Scientist Should Know About Floating-Point Arithmetic</a>:</p>
<blockquote><p>
Squeezing infinitely many real numbers into a finite number of bits requires an approximate representation. Although there are infinitely many integers, in most programs the result of integer computations can be stored in 32 bits. In contrast, given any fixed number of bits, most calculations with real numbers will produce quantities that cannot be exactly represented using that many bits. Therefore the result of a floating-point calculation must often be rounded in order to fit back into its finite representation. This rounding error is the characteristic feature of floating-point computation.
</p></blockquote>
<p>A small example should make the problem clearly visible:</p>
<pre class="brush:csharp">
class Program
{
    static void Main(string[] args)
    {
        double a = 22.4;
        double b = a / 131;

        double c = 0;
        for (int i = 0; i < 131; i++)
        {
            c += b;
        }

        Console.WriteLine("Are they equal?: {0}", a == c);
        Console.WriteLine("Difference (a - c) is {0} ", a - c);
    }
}
</pre>
<p>Here we are taking a double (a), diving it by 131 and then creating a new number (c) by adding the result of that division 131 times. By pure math, a and c should be equal. If you try this small program yourself, this is the output that you would get:</p>
<pre>
Are they equal?: False
Difference (a - c) is -4,9737991503207E-14
</pre>
<p>As you can see, the result is not what you might expect, and it's affected by a rounding error that is building up every time b is added to the partial result c.</p>
<p>Note that this is dependent on the number that I have chosen. If you substitute 131 with 5, you will not experience this problem.</p>
<h2>Your Own Comparer</h2>
<p>Sometimes this behavior might annoy you, especially when you don't need such a high precision and a “rough” equality is all you need. A typical situation is unit testing an algorithm against some expected result: your assertions may fail because of a rounding error, even though the logic of your algorithm is formally correct.</p>
<p>In such a case, you might want to implement your own comparer. A desirable property for such a comparer is a threshold value: if the difference between two floating points is <em>below</em> that threshold they are considered equal.</p>
<p>All you need is to implement the .NET interface <code><a href="http://msdn.microsoft.com/en-us/library/ms132151.aspx">IEqualityComparer</a></code><a href="http://msdn.microsoft.com/en-us/library/ms132151.aspx"> </a>interface.</p>
<pre class="brush:csharp">
class DoubleComparer : IEqualityComparer
{
    private readonly double threshold;

    public DoubleComparer(double threshold)
    {
        this.threshold = threshold;
    }

    public bool Equals(double x, double y)
    {
        return Math.Abs(x - y) < this.threshold;
    }

    public int GetHashCode(double obj)
    {
       return obj.GetHashCode();
    }
}
</pre>
<p>I have created my own comparer to use in my unit tests. I only have to implement 2 methods: <code>Equals()</code> and <code>GetHashCode()</code>.</p>
<p>I don't care much for the actual algorithm of the hashcode implementation, so I am reusing <code>double</code> own algorithm.</p>
<p>Instead, I have applied my own logic to the Equals method: to me, two doubles are equal if the absolute value of their difference is within a given threshold (which I can pass to the comparer in the constructor).</p>
<h2>The Comparer In Use</h2>
<p>Suppose I have an algorithm to calculate the histogram of a given collection of doubles, and a unit test to validate the calculation against a collection of expected results.</p>
<p>In the example below, <em>samples</em> are the input values which I want to create the histogram for, and <em>expectedBreaks</em> is a sequence containing the left and right limits of the bins of the histogram (in the example I am requiring 5 bins, so the number of breaks is 5 + 1 = 6).</p>
<pre class="brush:csharp">
var p = new HistogramProvider();
double[] samples = { 20, 12, 4, 22, 19, 24, 9, 5, -12.2, 13, 0 };
double[] expectedBreaks = { -12.2, -4.96, 2.28, 9.52, 16.76, 24 };

var histogram = p.CreateHistogram(samples, 5);

Assert.IsTrue(expectedBreaks.SequenceEqual<double>(
                       histogram.Breaks,
                       new DoubleComparer(0.01)));
</pre>
<p>I have figured out the threshold to pass (0.01) based on the relative size of the doubles under analysis. Of course, you should use your own judgement to come up with a sensible threshold according of the range of your input data.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fstefanoricciardi.com%2f2010%2f03%2f02%2fcomparing-floating-point-numbers%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fstefanoricciardi.com%2f2010%2f03%2f02%2fcomparing-floating-point-numbers%2f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p><a rev="vote-for" href="http://dotnetshoutout.com/Comparing-Floating-Point-Numbers"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F03%2F02%2Fcomparing-floating-point-numbers%2F"></a></p>
]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2010/03/02/comparing-floating-point-numbers/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Generics With Type Uknown At Compile Time</title>
		<link>http://stefanoricciardi.com/2010/02/18/generics-with-type-uknown-at-compile-time/</link>
		<comments>http://stefanoricciardi.com/2010/02/18/generics-with-type-uknown-at-compile-time/#comments</comments>
		<pubDate>Thu, 18 Feb 2010 20:32:20 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[generics]]></category>
		<category><![CDATA[reflection]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.com/?p=773</guid>
		<description><![CDATA[The following is an example of a service containing both generic method calls and generic types. public interface IContainer&#60;T&#62; { IEnumerable&#60;IProperty&#60;T&#62;&#62; Properties { get; } } public interface IPropertyService { IContainer&#60;T&#62; GetProperties&#60;T&#62;(string propertyCode); } Now suppose that you don&#8217;t know the actual type of the data until runtime (possibly because the type is retrieved from [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F02%2F18%2Fgenerics-with-type-uknown-at-compile-time%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F02%2F18%2Fgenerics-with-type-uknown-at-compile-time%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>The following is an example of a service containing both generic method calls and generic types.</p>
<pre class="brush:csharp">
public interface IContainer&lt;T&gt;
{
    IEnumerable&lt;IProperty&lt;T&gt;&gt; Properties { get; }
}

public interface IPropertyService
{
    IContainer&lt;T&gt; GetProperties&lt;T&gt;(string propertyCode);
}
</pre>
<p>Now suppose that you don&#8217;t know the actual type of the data until runtime (possibly because the type is retrieved from a DB or from some other service). You need a way to interact with these generics, and <a href="http://msdn.microsoft.com/en-us/library/system.reflection.aspx">Reflection </a>can help you here.</p>
<p>Let&#8217;s assume that you have managed to get the <code>Type</code> of the data that you are handling (such as <code>string</code>, <code>decimal</code>, <code>double</code>, etc&#8230;) and that you have a concrete implementation of the <code>IPropertyService</code> (perhaps through Dependency Injection).</p>
<p>Once you have that, you can invoke the <code>GetProperty</code> method in the following way:</p>
<pre class="brush:csharp">
Type type = // ... this is the actual runtime type
IPropertyService service = // ... this is an instance of the service

Type serviceType = typeof(IPropertyService);
MethodInfo getPropertiesInfo =
    serviceType.GetMethod(&quot;GetProperties&quot;, new Type[] { typeof(string) });

if (getPropertiesInfo == null)
{
    // Uh-oh.... has the interface changed after we wrote this? Throw an exception...
}

Type[] genericArguments = { type }; // we only have one generic argument (&lt;t&gt;)
MethodInfo getPropertiesMethodInfo =
    getPropertiesInfo.MakeGenericMethod(genericArguments);

// Finally invoke the method to search for a price
var propertiesContainer =
    getPropertiesMethodInfo.Invoke(service, new object[] { &quot;price&quot; });
</pre>
<p>As you can see are quite a few steps to be performed, but at the end, through reflection, you end up with a container filled with all the objects that you have required.</p>
<p>Now assume that you want to access to the single properties contained in the IContainer. You need some way to invoke the C# property <code>Properties</code>. defined on <code>IContainer</code>. Similarly to the <a href="http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.aspx">MethodInfo</a> class, System.Reflection has a <a href="http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.aspx">PropertyInfo </a>class that you can use to work with Properties.</p>
<p>The following solution, despite compiling fine, will not work at run-time:</p>
<pre class="brush:csharp">
PropertyInfo containerInfo = typeof(IContainer&lt;&gt;).GetProperty(&quot;Properties&quot;); // WRONG!!!
if (containerInfo == null)
{
    // the interface has changed. Throw an exception
}

var properties = containerInfo.GetValue(container, null) as IEnumerable;
</pre>
<p>If you try to run this, you will be greeted by the following exception: <em>Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.</em></p>
<p>After scratching my head for a while, I realized that I should have first created a generic type at run-time before retrieving the <code>PropertyInfo</code>:</p>
<pre class="brush:csharp">
Type containerType = typeof(IContainer&lt;&gt;).MakeGenericType(type);
PropertyInfo containerInfo = containerType.GetProperty(&quot;Properties&quot;);
if (containerInfo == null)
{
    // the interface has changed. Throw an exception
}

var properties = containerInfo.GetValue(container, null) as IEnumerable;
</pre>
<p>At this point I have a collection of <code>IProperties</code> which I can enumerate through. If needed, since the types in this collection are also generic, I need to repeat the process above until I reach a fundamental type (such as <code>string</code>, <code>double</code>, etc&#8230;).</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fstefanoricciardi.com%2f2010%2f02%2f18%2fgenerics-with-type-uknown-at-compile-time%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fstefanoricciardi.com%2f2010%2f02%2f18%2fgenerics-with-type-uknown-at-compile-time%2f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p><a rev="vote-for" href="http://dotnetshoutout.com/Generics-With-Type-Uknown-At-Compile-Time-Stefano-Ricciardis-Blog"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F02%2F18%2Fgenerics-with-type-uknown-at-compile-time%2F"></a></p>
]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2010/02/18/generics-with-type-uknown-at-compile-time/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>See Your XML Docs As You Type With CR Documentor</title>
		<link>http://stefanoricciardi.com/2010/01/22/see-your-xml-docs-as-you-type-with-cr-documentor/</link>
		<comments>http://stefanoricciardi.com/2010/01/22/see-your-xml-docs-as-you-type-with-cr-documentor/#comments</comments>
		<pubDate>Fri, 22 Jan 2010 19:39:29 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[Tools]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Documentor]]></category>
		<category><![CDATA[Ghost-Doc]]></category>
		<category><![CDATA[Plugin]]></category>
		<category><![CDATA[Visual Studio 2008]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.wordpress.com/?p=701</guid>
		<description><![CDATA[Introduction Almost 10 years ago now I used to be a Java developer in Motorola. After a long hiatus in the embedded systems and a job change, I have come back to enterprise development, this time in .Net. I remembered that in the good ol’ days it required 2 steps to see the final rendering [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F01%2F22%2Fsee-your-xml-docs-as-you-type-with-cr-documentor%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F01%2F22%2Fsee-your-xml-docs-as-you-type-with-cr-documentor%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<h3>Introduction</h3>
<p>Almost 10 years ago now I used to be a Java developer in Motorola. After a long hiatus in the embedded systems and a job change, I have come back to enterprise development, this time in .Net.</p>
<p>I remembered that in the good ol’ days it required 2 steps to see the final rendering of the XML documentation: firing javadoc (usually from within an ANT task) and the open up the content in a browser.</p>
<p>I was quite surprised to see that in the .Net area seeing the final output of the docs was not as straightforward as I hoped for. Yes, there was <a href="http://ndoc.sourceforge.net/">NDoc</a> to parse the XML, but its development stopped around 2005 and it’s doesn’t support anything beyond C# 2.0. There’s also <a href="http://www.codeplex.com/Sandcastle">Sandcastle</a>, but to make it work for me it has required a few downloads and a bit of tweaking here and there. And integrating it into my NAnt task had not been that easy either. But somehow in the end I have pulled that out.</p>
<p>Therefore I have been pleasantly surprised when I met <strong>CR Documentor, </strong>a little plug-in for visual studio that let’s you see your XML documentation <em>as you write it</em>. It’s almost like having a WYSIWYG editor, without having to launch Sandcastle, wait for the complete build, and open up the browser.</p>
<h3>Installation</h3>
<ul>
<li><a href="http://code.google.com/p/cr-documentor/"><img style="display:inline;border-width:0;margin:0;" title="cr_documentor-logo" src="http://stefanoricciardi.files.wordpress.com/2010/01/cr_documentorlogo.gif" border="0" alt="cr_documentor-logo" width="100" height="102" align="right" /></a>Requirements:
<ul>
<li>Visual Studio 2005 or greater (I am pretty confident that you need at least a Professional version as opposed to Express). I am running it on Visual Studio Team System 2008, not sure whether it works also on 2010.</li>
<li>The DXCore plugin framework from DevExpress. Possibly the best (and only?) way to get it is to get through the excellent free <a href="http://www.devexpress.com/Products/Visual_Studio_Add-in/CodeRushX/">CodeRush Xpress for C# and VB</a></li>
</ul>
</li>
<li>Download the plugin: CR Documentor is hosted at Google Code at <a href="http://code.google.com/p/cr-documentor/">this link</a>.</li>
<li>Copy the dll in your DX-Core plugin-folder (<tt>C:\Users\&lt;username&gt;\Documents\DevExpress\IDE Tools\Community\PlugIns</tt>)</li>
<li>Restart Visual Studio</li>
</ul>
<h3>Usage</h3>
<ol>
<li>CR Documentor adds itself in the right click menu, close to the bottom. From the submenu, choose “Show CR_Documentor window”.<a href="http://69.175.59.226/~stefano3/blog/wp-content/uploads/2010/01/cr_documentor1.png"><img style="display:inline;margin-left:0;margin-right:0;border-width:0;" title="CR_documentor-1" src="http://69.175.59.226/~stefano3/blog/wp-content/uploads/2010/01/cr_documentor1_thumb.png" border="0" alt="CR_documentor-1" width="244" height="212" /></a></li>
<li>A new window opens up in floating mode (I prefer to dock-it to the right side together with my solution explorer and luckily the plug-in remembers this choice every time I open the window after closing it and at startup).<a href="http://69.175.59.226/~stefano3/blog/wp-content/uploads/2010/01/image.png"><img style="display:inline;border-width:0;" title="image" src="http://69.175.59.226/~stefano3/blog/wp-content/uploads/2010/01/image_thumb.png" border="0" alt="image" width="244" height="127" /></a></li>
<li>Now every time your cursor is on an XML doc, you can see the preview in the Documentor window. See for example when I put the cursor on the XML doc of a class: I get a complete picture of the documentation for that class and its methods all in real time.<br />
<a href="http://stefanoricciardi.files.wordpress.com/2010/01/image1.png"><img style="display:inline;border-width:0;" title="image" src="http://69.175.59.226/~stefano3/blog/wp-content/uploads/2010/01/image_thumb1.png" border="0" alt="image" width="229" height="244" /></a></li>
<li>There are a few other features that I don’t use very often. All of them are accessible by the right-click content sensitive menu:
<ul>
<li>Expand/Collapse all XML comments in the editor</li>
<li>Insert XML docs templates (<a href="http://stefanoricciardi.com/2009/06/19/must-have-vs-2008-free-plug-ins-2-ghost-doc/">I prefer to use GhostDoc for that</a>).</li>
<li></li>
</ul>
</li>
</ol>
<h3>Configuration</h3>
<p>Like all DXCore plugins, you can access to the configuration by pressing ALT+CTRL+SHIFT+O combination. I like to check all my options to Sandcastle because that’s the tool that I will be using to create the final XML documentation.</p>
<p><a href="http://69.175.59.226/~stefano3/blog/wp-content/uploads/2010/01/image2.png"><img style="display:inline;border-width:0;" title="image" src="http://69.175.59.226/~stefano3/blog/wp-content/uploads/2010/01/image_thumb2.png" border="0" alt="image" width="244" height="161" /></a></p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fstefanoricciardi.com%2f2010%2f01%2f22%2fsee-your-xml-docs-as-you-type-with-cr-documentor%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fstefanoricciardi.com%2f2010%2f01%2f22%2fsee-your-xml-docs-as-you-type-with-cr-documentor%2f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p><a rev="vote-for" href="http://dotnetshoutout.com/See-Your-XML-Docs-As-You-Type-With-CR-Documentor-Stefano-Ricciardis-Blog"><img style="border:0;" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F01%2F22%2Fsee-your-xml-docs-as-you-type-with-cr-documentor%2F" alt="Shout it" /></a></p>
<p><!-- AddThis Button BEGIN --></p>
<p><a href="http://www.addthis.com/bookmark.php?v=250"><img style="border-width:0;" src="http://s7.addthis.com/static/btn/lg-share-en.gif" alt="Bookmark and Share" width="125" height="16" /></a></p>
<div id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:e6ceeafa-fe5c-4bd6-a48d-325da43e5abc" class="wlWriterSmartContent" style="display:inline;float:none;margin:0;padding:0;">Technorati Tags: <a rel="tag" href="http://technorati.com/tags/Programming">Programming</a>,<a rel="tag" href="http://technorati.com/tags/C%23">C#</a>,<a rel="tag" href="http://technorati.com/tags/visual+Studio+2008">visual Studio 2008</a>,<a rel="tag" href="http://technorati.com/tags/Tools">Tools</a></div>
]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2010/01/22/see-your-xml-docs-as-you-type-with-cr-documentor/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A Singleton Service Locator Pattern</title>
		<link>http://stefanoricciardi.com/2009/10/29/a-singleton-service-locator-pattern/</link>
		<comments>http://stefanoricciardi.com/2009/10/29/a-singleton-service-locator-pattern/#comments</comments>
		<pubDate>Thu, 29 Oct 2009 13:40:47 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[Design and Patterns]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[OOP]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.net/?p=543</guid>
		<description><![CDATA[This is the third post of a series on the Service Locator pattern. In the first post I described how to create a basic service locator for your C# application, while in the second post I introduced lazy initialization of the services. We now add another piece to our puzzle, transforming the Service Locator class [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F10%2F29%2Fa-singleton-service-locator-pattern%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F10%2F29%2Fa-singleton-service-locator-pattern%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>This is the third post of a series on the Service Locator pattern. In the <a href="http://stefanoricciardi.com/2009/09/25/service-locator-pattern-in-csharpa-simple-example/">first post</a> I described how to create a basic service locator for your C# application, while in the <a href="http://stefanoricciardi.com/2009/10/13/service-locator-pattern-in-c-with-lazy-initialization/">second post</a> I introduced lazy initialization of the services.</p>
<p>We now add another piece to our puzzle, transforming the Service Locator class into a <a href="http://en.wikipedia.org/wiki/Singleton_pattern">singleton</a>.</p>
<h1>The Singleton Pattern</h1>
<p>The singleton is arguably the most known and controversial design pattern. Some say <a href="http://c2.com/cgi/wiki?SingletonsAreGood">singletons are good</a>, some says <a href="http://c2.com/cgi/wiki?SingletonsAreEvil">singletons are evil</a>. Eric Gamma himself (one of the <a href="http://c2.com/cgi/wiki?GangOfFour">Gang Of Four</a>) in a recent <a href="http://www.informit.com/articles/article.aspx?p=1404056">interview</a> stated that (emphasis added):</p>
<blockquote><p>When discussing which patterns to drop, we found that we still love them all. (Not really—<strong>I&#8217;m in favor of dropping Singleton. Its use is almost always a design smell.</strong>)</p></blockquote>
<p>I don&#8217;t have a strong opinion either way; I tend to use it sparingly and in the following code I will show how to apply this pattern to the service locator. There are already countless blogs discussing the pros and the cons of the singleton pattern, therefore I won&#8217;t discuss about it any further.</p>
<h1>The Singleton Service Locator</h1>
<p>The following was our initial implementation (other details of the classes have been removed for clarity). The constructor was <em>internal</em>, allowing all potential clients from within the assembly to invoke it. Clients could either pass around a reference to the created service locator, or instantiate new instances each time:</p>
<pre class="brush:csharp">
internal class ServiceLocator : IServiceLocator
{
    // a map between contracts -&gt; concrete implementation classes
    private IDictionary&lt;Type, Type&gt; servicesType;

    // a map containing references to concrete implementation already instantiated
    // (the service locator uses lazy instantiation).
    private IDictionary&lt;Type, object&gt; instantiatedServices;

    internal ServiceLocator()
    {
        this.servicesType = new Dictionary&lt;Type, Type&gt;();
        this.instantiatedServices = new Dictionary&lt;Type, object&gt;();

        this.BuildServiceTypesMap();
    }

    // rest of the methods
 }
</pre>
<p>To implement the singleton pattern, we make the constructor <em>private</em> and provide clients with a static method through which we can retrieve an instance of the service.</p>
<p>Note how the creation of the single instance of the ServiceLocator class is itself lazy and thread safe. There are a few variations on the theme when it comes to singleton thread safe initialization (see for example <a href="http://www.yoda.arachsys.com/csharp/singleton.html">this post</a> by Jon Skeet).</p>
<pre class="brush:csharp">
internal class ServiceLocator : IServiceLocator
{
        // a map between contracts -&gt; concrete implementation classes
        private IDictionary&lt;Type, Type&gt; servicesType;
        private static readonly object TheLock = new Object();

        private static IServiceLocator instance;

        // a map containing references to concrete implementation already instantiated
        // (the service locator uses lazy instantiation).
        private readonly IDictionary&lt;Type, object&gt; instantiatedServices;

        private ServiceLocator()
        {
            this.servicesType = new Dictionary&lt;Type, Type&gt;();
            this.instantiatedServices = new Dictionary&lt;Type, object&gt;();

            this.BuildServiceTypesMap();
        }

        public static IServiceLocator Instance
        {
            get
            {
                lock (TheLock) // thread safety
                {
                    if (instance == null)
                    {
                        instance = new ServiceLocator();
                    }
                }

                return instance;
            }
        }

        // rest of the methods
 }
</pre>
<p>Clients will now simply invoke the <code>GetService()</code> method through the singleton instance, without having to create a new object each time:</p>
<pre class="brush:csharp">
IServiceA service = ServiceLocator.Instance.GetService&lt;IUniverseFileServiceAdapter&gt;();
</pre>
<p><!-- Kick it BEGIN --><br />
<a href="http://www.dotnetkicks.com/kick/?url=http%3A%2F%2Fstefanoricciardi.net%2F2009%2F10%2F29%2Fa-singleton-service-locator-pattern"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3A%2F%2Fstefanoricciardi.net%2F2009%2F10%2F29%2Fa-singleton-service-locator-pattern" border="0" alt="kick it on DotNetKicks.com" /></a><br />
<!-- Kick it END --></p>
<p>    <a rev="vote-for" href="http://dotnetshoutout.com/Submit?url=http://stefanoricciardi.net/2009/10/29/a-singleton-service-locator-pattern/"><br />
        <img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http://stefanoricciardi.net/2009/10/29/a-singleton-service-locator-pattern/"><br />
    </a></p>
<p><!-- AddThis Button BEGIN --></p>
<p><a href="http://www.addthis.com/bookmark.php?v=250"><img style="border:0;" src="http://s7.addthis.com/static/btn/lg-share-en.gif" alt="Bookmark and Share" width="125" height="16" /></a></p>
<p><!-- AddThis Button END --></p>
<div id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:e6ceeafa-fe5c-4bd6-a48d-325da43e5abc" style="display:inline;float:none;margin:0;padding:0;">Technorati Tags: <a rel="tag" href="http://technorati.com/tags/Programming">Programming</a>, <a rel="tag" href="http://technorati.com/tags/C%23">C#</a>, <a rel="tag" href="http://technorati.com/tags/design">Design</a>, <a rel="tag" href="http://technorati.com/tags/ood">OOD</a></div>
]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2009/10/29/a-singleton-service-locator-pattern/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Making WCF Serializer Work with Circular References</title>
		<link>http://stefanoricciardi.com/2009/10/22/making-wcf-serializer-work-with-circular-references/</link>
		<comments>http://stefanoricciardi.com/2009/10/22/making-wcf-serializer-work-with-circular-references/#comments</comments>
		<pubDate>Thu, 22 Oct 2009 12:07:43 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[WCF]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[SOA]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.net/?p=465</guid>
		<description><![CDATA[The Problem of Circular References Recently I had to model a tree-like structure using a variation of the GoF composite design pattern and to pass this class to a WCF service for further processing. The class has circular reference as described by the following drawing: Therefore off I went to naively create my DataContract along [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F10%2F22%2Fmaking-wcf-serializer-work-with-circular-references%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F10%2F22%2Fmaking-wcf-serializer-work-with-circular-references%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<h1>The Problem of Circular References</h1>
<p>Recently I had to model a tree-like structure using a variation of the GoF <a title="Composite Design Pattern" href="http://en.wikipedia.org/wiki/Composite_pattern">composite design pattern</a> and to pass this class to a WCF service for further processing.</p>
<p>The class has circular reference as described by the following drawing:</p>
<p><img class="aligncenter size-full wp-image-474" title="Example of a Node Recursion" src="http://69.175.59.226/~stefano3/blog/wp-content/uploads/2009/10/noderecursion.gif" alt="Example of a Node Recursion" width="219" height="117" /></p>
<p>Therefore off I went to naively create my <strong>DataContract</strong> along the following lines:</p>
<pre class="brush:csharp">
[DataContract(Namespace = "http://schemas.acme.it/2009/10"]
public class Node
{
	[DataMember(Name="Children", Order=2)]
    private IList&lt;Node&gt; children;

    [DataMember(Name="Id", Order=0)]
    public string Id { get; set; }

    [DataMember(Name="Parent", Order=1)]
    public Node Parent { get; set; }

    public Node()
    {
        children = new List&lt;Node&gt;()
    }

    public void AddChild(Node node)
    {
        this.children.Add(node);
        node.Parent = this;
    }

    public IList&lt;Node&gt; Children
    {
        get
        {
            IList&lt;Node&gt; result = new List(this.children);
            foreach (Node child in this.children)
            {
                foreach (Node innerChild in child.Children)
                {
                result.Add(innerChild);
                }
            }

            return result;
        }
    }
}
</pre>
<p>Unfortunately at run time I was greeted by the following exception:<br />
<code>Object graph for type 'System.Collections.Generic.List`1[[Node ...]]' contains cycles and cannot be serialized if reference tracking is disabled.</code>.</p>
<h1>The Solution</h1>
<p>Reading around I realized that up until some time ago you had to implement your own <strong>DataContractSerializer</strong> (see for example this <a href="http://blogs.msdn.com/sowmy/archive/2006/03/26/561188.aspx">post </a> by Sowmy Srinivasan).</p>
<p>Luckily, it turns out that with NET 3.5 SP1 everything is much simpler: you just have to use the <strong>IsReference</strong> parameter in the <strong>DataContract</strong> attribute, as follows:</p>
<pre class="brush:csharp">
[DataContract(Namespace = "http://schemas.acme.it/2009/10", IsReference=true)]
public class Node
{
    // everything same as in the example above.
}
</pre>
<h1>The Catch</h1>
<p>For some reason, if you turn on the <strong>IsReference</strong> attribute, then you <em>cannot </em>set the <strong>IsRequired</strong> attribute to <code>true</code> on <em>any</em> <strong>DataMember</strong> of the DataContract. The reason is somehow explained <a href="http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/e5d38e14-31b0-4991-a988-d578c564e92d">here</a>.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3A%2F%2Fstefanoricciardi.net%2F2009%2F10%2F22%2Fmaking-wcf-serializer-work-with-circular-references"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3A%2F%2Fstefanoricciardi.net%2F2009%2F10%2F29%2Fa-singleton-service-locator-pattern" border="0" alt="kick it on DotNetKicks.com" /></a><br />
<!-- Kick it END --></p>
<p><a rev="vote-for" href="http://dotnetshoutout.com/Submit?url=http://stefanoricciardi.net/2009/10/22/making-wcf-serializer-work-with-circular-references/"><br />
<img src="http://dotnetshoutout.com/image.axd?url=http://stefanoricciardi.net/2009/10/22/making-wcf-serializer-work-with-circular-references/" alt="Shout it" /><br />
</a></p>
<p><!-- AddThis Button BEGIN --></p>
<p><a href="http://www.addthis.com/bookmark.php?v=250"><img style="border: 0;" src="http://s7.addthis.com/static/btn/lg-share-en.gif" alt="Bookmark and Share" width="125" height="16" /></a></p>
<p><!-- AddThis Button END --></p>
<div id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:e6ceeafa-fe5c-4bd6-a48d-325da43e5abc" class="wlWriterEditableSmartContent" style="display: inline; float: none; margin: 0; padding: 0;">Technorati Tags: <a rel="tag" href="http://technorati.com/tags/Programming">Programming</a>, <a rel="tag" href="http://technorati.com/tags/C%23">C#</a>, <a rel="tag" href="http://technorati.com/tags/wcf">WCF</a>, <a rel="tag" href="http://technorati.com/tags/soa">SOA</a></div>
]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2009/10/22/making-wcf-serializer-work-with-circular-references/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Service Locator Pattern in C# with Lazy Initialization</title>
		<link>http://stefanoricciardi.com/2009/10/13/service-locator-pattern-in-c-with-lazy-initialization/</link>
		<comments>http://stefanoricciardi.com/2009/10/13/service-locator-pattern-in-c-with-lazy-initialization/#comments</comments>
		<pubDate>Tue, 13 Oct 2009 12:37:35 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[Design and Patterns]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[OOP]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.net/?p=423</guid>
		<description><![CDATA[In my previous post Service Locator Pattern in C#: A Simple Example I introduced a fairly basic implementation of this pattern. In this post I will address one of the limitations of that implementation, introducing a form of lazy initialization. Defining Lazy Initialization Lazy initialization improves the performance of object creation, deferring long running initializations [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F10%2F13%2Fservice-locator-pattern-in-c-with-lazy-initialization%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F10%2F13%2Fservice-locator-pattern-in-c-with-lazy-initialization%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>In my previous post <a href="http://stefanoricciardi.net/2009/09/25/service-locator-pattern-in-csharpa-simple-example/">Service Locator Pattern in C#: A Simple Example</a> I introduced a fairly basic implementation of this pattern. In this post I will address one of the limitations of that implementation, introducing a form of <strong>lazy initialization</strong>.</p>
<h3>Defining Lazy Initialization</h3>
<p>Lazy initialization improves the performance of object creation, deferring long running initializations until they are really needed.</p>
<p>Suppose for example that some of the fields of an object need to be read from the database. If a client never access those fields, accessing the database to retrieve those fields has been useless and it has just made object initialization slower (often by a considerable factor).</p>
<p>Martin Fowler credits Kent Beck with the introduction of the lazy initialization pattern, and in <a href="http://www.amazon.co.uk/Enterprise-Application-Architecture-Addison-Wesley-signature/dp/0321127420">PoEAA </a>book he describes it in the following way:</p>
<blockquote><p>The basic idea is that every access to the field checks to see if it&#8217;s null. If so, it calculates the value of the field before returning the field. To make this work you have to ensure that the field is self-encapsulated, meaning that all access to the field, even from within the class, is done through a getting method.</p></blockquote>
<p>Fairly simple.</p>
<h3>The Improved Service Locator</h3>
<p>The following is the improved version of the service locator which uses lazy initialization of the services.</p>
<pre class="brush:csharp">
internal class ServiceLocator : IServiceLocator
{
    // a map between contracts -&gt; concrete implementation classes
    private IDictionary&lt;Type, Type&gt; servicesType;

    // a map containing references to concrete implementation already instantiated
    // (the service locator uses lazy instantiation).
    private IDictionary&lt;Type, object&gt; instantiatedServices;

    internal ServiceLocator()
    {
        this.servicesType = new Dictionary&lt;Type, Type&gt;();
        this.instantiatedServices = new Dictionary&lt;Type, object&gt;();

        this.BuildServiceTypesMap();
    }

    public T GetService&lt;T&gt;()
    {
        if (this.instantiatedServices.ContainsKey(typeof(T)))
        {
            return (T)this.instantiatedServices[typeof(T)];
        }
        else
        {
            // lazy initialization
            try
            {
                // use reflection to invoke the service
                ConstructorInfo constructor = servicesType[typeof(T)].GetConstructor(new Type[0]);
                Debug.Assert(constructor != null, &quot;Cannot find a suitable constructor for &quot; + typeof(T));

                T service = (T)constructor.Invoke(null);

                // add the service to the ones that we have already instantiated
                instantiatedServices.Add(typeof(T), service);

                return service;
            }
            catch (KeyNotFoundException)
            {
                throw new ApplicationException&quot;The requested service is not registered&quot;);
            }
        }
    }

    private void BuildServiceTypesMap()
    {
        servicesType.Add(typeof(IServiceA),
            typeof(ServiceA));

        servicesType.Add(typeof(IServiceB),
            typeof(ServiceB));

        servicesType.Add(typeof(IServiceC),
            typeof(ServiceC));
     }
}
</pre>
<p>We are now maintaining two separate maps:</p>
<ul>
<li><code>servicesType</code> maps an interface describing a service to a <em>type</em> T that implements that interface.</li>
<li><code>instantiatedServices</code> maps an interface to an <em>instantiated</em> object of class T.</li>
</ul>
<p>Both maps are initialized in the constructor. However only the first map is filled. Every time <code>GetService</code> is invoked, we check whether a concrete implementation of that service has already been created. If not, we create that service implementation retrieving its constructor via reflection, and we put a reference to that implementation in the <code>instantiatedServices</code> map.</p>
<p>For this to work, the service implementation needs to expose a default (parameterless) constructor.</p>
<p>If services creation time is significant, lazy initialization can save you quite some time during application start up, with very little cost in terms of increased complexity.</p>
<p><i>Next article in the series: <a href="http://stefanoricciardi.com/2009/10/29/a-singleton-service-locator-pattern/">A Singleton Service Locator</a></i></p>
<p>
<!-- AddThis Button BEGIN --></p>
<p><a href="http://www.addthis.com/bookmark.php?v=250"><img style="border:0;" src="http://s7.addthis.com/static/btn/lg-share-en.gif" alt="Bookmark and Share" width="125" height="16" /></a></p>
<p><!-- AddThis Button END --></p>
<div id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:e6ceeafa-fe5c-4bd6-a48d-325da43e5abc" style="display:inline;float:none;margin:0;padding:0;">Technorati Tags: <a rel="tag" href="http://technorati.com/tags/Programming">Programming</a>, <a rel="tag" href="http://technorati.com/tags/C%23">C#</a>, <a rel="tag" href="http://technorati.com/tags/design">Design</a>, <a rel="tag" href="http://technorati.com/tags/ood">OOD</a></div></p>
]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2009/10/13/service-locator-pattern-in-c-with-lazy-initialization/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Parsing Dates from CSV files with FileHelpers Library</title>
		<link>http://stefanoricciardi.com/2009/10/07/parsing-dates-from-csv-files-with-filehelpers-library/</link>
		<comments>http://stefanoricciardi.com/2009/10/07/parsing-dates-from-csv-files-with-filehelpers-library/#comments</comments>
		<pubDate>Wed, 07 Oct 2009 20:08:37 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Libraries]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.net/?p=400</guid>
		<description><![CDATA[In my current project I have found myself needing to parse a CSV file coming from a legacy C++ application. This is a fairly common task, and in the past I have always written the parsing engine myself, especially when there was some validation related to the business logic involved. This time I have chosen [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F10%2F07%2Fparsing-dates-from-csv-files-with-filehelpers-library%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F10%2F07%2Fparsing-dates-from-csv-files-with-filehelpers-library%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>In my current project I have found myself needing to parse a CSV file coming from a legacy C++ application. This is a fairly common task, and in the past I have always written the parsing engine myself, especially when there was some validation related to the business logic involved.</p>
<p>This time I have chosen to try the reportedly excellent <a href="http://www.filehelpers.com/">FileHelpers</a> library. Why reinvent the wheel yet another time? The library is well documented and in a matter of minutes I was able to start experimenting with some test data.</p>
<p>To simplify the discussion, suppose that the CSV file has the following structure:</p>
<pre>
# City, Date, Temperature
Chicago; 20090913 07:00:00; 62.23
New York; 20090913 08:00:00; 81.3
</pre>
<p>Each row of the CSV file is mapped to the following class:</p>
<pre class="brush:csharp">
[DelimitedRecord(&quot;;&quot;)]
[IgnoreEmptyLines()]
[ConditionalRecord(RecordCondition.ExcludeIfBegins, &quot;#&quot;)]
public class CsvRecord
{
    public string City;

    [FieldConverter(ConverterKind.Date, &quot;yyyyMMdd HH:mm:ss&quot;)]
    public DateTime Date;

    [FieldConverter(ConverterKind.Double, &quot;.&quot;)]
    public double Temperature;
}
</pre>
<p>The attributes are pretty self-explanatory: they specify which is the separator value and which lines can be ignored.</p>
<p>The interesting part here is the way FileHelpers allows to specify a pattern to convert a string into a <code>DateTime</code> value. In this case, the pattern used here is <code>yyyyMMdd HH:mm:ss</code> to match the CSV file.</p>
<p>Once the mapping between the CSV and the .NET object is setup, I have created a class wrapping the FileHelpers engine (just in case some day I want to change the parsing engine), with the following (simplified) method:</p>
<pre class="brush:csharp">
public IEnumerable&lt;CsvRecord&gt; GetRecordsFromFile(Stream s)
{
   FileHelperEngine engine = new FileHelperEngine(typeof(CsvRecord));
   s.Seek(0, SeekOrigin.Begin);

   CsvRecord[] records = engine.ReadStream(new StreamReader(s)) as CsvRecord[];
   return records;
}
</pre>
<p>This was working like a charm&#8230; until I moved the code to a separate test machine. All of a sudden the parser would complain that it could not parse the dates from the file. After a lot of thought, I realized that the test machine had a different regional settings: while my machine had English formats, the test machine had Italian formats. And for some reason FileHelpers was not able to work correctly in this scenario (even though I had explicitly specified the date and time pattern in the <code>CsvRecord</code> class).</p>
<p>Luckily, FileHelpers lets you specify your own converters if the predefined ones won&#8217;t do. I therefore created my custom converter for the dates as follows:</p>
<pre class="brush:csharp">
public class CustomDateTimeConverter : ConverterBase
{
    private const string DateTimeFormat = &quot;yyyyMMdd HH:mm:ss&quot;;

    public override object StringToField(string from)
    {
        return DateTime.ParseExact(from, DateTimeFormat, CultureInfo.InvariantCulture);
    }
}
</pre>
<p>and rewritten the <code>CsvRecord</code> class as follows:</p>
<pre class="brush:csharp">
[DelimitedRecord(&quot;;&quot;)]
[IgnoreEmptyLines()]
[ConditionalRecord(RecordCondition.ExcludeIfBegins, &quot;#&quot;)]
public class CsvRecord
{
    public string City;

    [FieldConverter(typeof(CustomDateTimeConverter))]
    public DateTime Date;

    [FieldConverter(ConverterKind.Double, &quot;.&quot;)]
    public double Temperature;
}
</pre>
<p>This time it worked also with Italian locale.</p>
<p>Frankly, I don&#8217;t know why the FileHelpers class had problems with the Italian locale (possibly with locales different from English ones). Probably having a look at the source code would reveal the truth.</p>
<p>I suspect that it is parsing the dates with a given format but without specifying an invariant culture format provider. But that is just a wild guess.</p>
<p><!-- AddThis Button BEGIN --></p>
<p><a href="http://www.addthis.com/bookmark.php?v=250"><img style="border:0;" src="http://s7.addthis.com/static/btn/lg-share-en.gif" alt="Bookmark and Share" width="125" height="16" /></a></p>
<p><!-- AddThis Button END --></p>
<div id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:e6ceeafa-fe5c-4bd6-a48d-325da43e5abc" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;">Technorati Tags: <a rel="tag" href="http://technorati.com/tags/Programming">Programming</a>, <a rel="tag" href="http://technorati.com/tags/C%23">C#</a></div>
]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2009/10/07/parsing-dates-from-csv-files-with-filehelpers-library/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>File Transfer with WCF: Part II</title>
		<link>http://stefanoricciardi.com/2009/10/02/file-transfer-with-wcf-part-ii/</link>
		<comments>http://stefanoricciardi.com/2009/10/02/file-transfer-with-wcf-part-ii/#comments</comments>
		<pubDate>Fri, 02 Oct 2009 12:23:22 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[WCF]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[SOA]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.net/?p=385</guid>
		<description><![CDATA[A few readers of my previous post on File Transfer with WCF have asked to share the implementation of the UploadFile and DownloadFile methods. While I can&#8217;t share the complete implemention of the service for obvious Intellectual Property reasons, I will outline the basic steps involved in implementing the service. Please refer to my previous [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F10%2F02%2Ffile-transfer-with-wcf-part-ii%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F10%2F02%2Ffile-transfer-with-wcf-part-ii%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>A few readers of my previous post on <a href="http://stefanoricciardi.com/2009/08/28/file-transfer-with-wcp/">File Transfer with WCF</a> have asked to share the implementation of the UploadFile and DownloadFile methods.</p>
<p>While I can&#8217;t share the complete implemention of the service for obvious Intellectual Property reasons, I will outline the basic steps involved in implementing the service. Please refer to my previous <a href="http://stefanoricciardi.com/2009/08/28/file-transfer-with-wcp/">post</a> for the details on the DataContracts and OperationContracts involved here.</p>
<p><em>NOTE</em>: I have extracted these portions from the actual code. I cannot verify this to work as-is, but it should give you a head-start to complete your own service. You should also add your own error checking, and any pre or post-download and/or pre or post-upload processing as required by the business.</p>
<h3>Download</h3>
<pre class="brush:csharp">
public FileDownloadReturnMessage DownloadFile(FileDownloadMessage request)
{
    // parameters validation omitted for clarity
    string localFileName = request.MetaData.LocalFileName;

    try
    {
        string basePath = ConfigurationSettings.AppSettings[&quot;FileTransferPath&quot;];
        string serverFileName = Path.Combine(basePath, request.MetaData.RemoteFileName);

        Stream fs = new FileStream(serverFileName, FileMode.Open);

        return new FileDownloadReturnMessage(new FileMetaData(localFileName, serverFileName), fs);
    }
    catch (IOException e)
    {
        throw new FaultException&lt;IOException&gt;(e);
    }
}
</pre>
<h3>Upload</h3>
<pre class="brush:csharp">
public void UploadFile(FileUploadMessage request)
{
    // parameters validation omitted for clarity
    try
    {
        string basePath = ConfigurationSettings.AppSettings[&quot;FileTransferPath&quot;];
        string serverFileName = Path.Combine(basePath, request.MetaData.RemoteFileName);

        using (FileStream outfile = new FileStream(serverFileName, FileMode.Create))
        {
            const int bufferSize = 65536; // 64K

            Byte[] buffer = new Byte[bufferSize];
            int bytesRead = request.FileByteStream.Read(buffer, 0, bufferSize);

            while (bytesRead &gt; 0)
            {
                outfile.Write(buffer, 0, bytesRead);
                bytesRead = request.FileByteStream.Read(buffer, 0, bufferSize);
            }
        }
    }
    catch (IOException e)
    {
        throw new FaultException&lt;IOException&gt;(e);
    }
}
</pre>
<p><!-- AddThis Button BEGIN --></p>
<p><a href="http://www.addthis.com/bookmark.php?v=250"><img style="border:0;" src="http://s7.addthis.com/static/btn/lg-share-en.gif" alt="Bookmark and Share" width="125" height="16" /></a></p>
<p><!-- AddThis Button END --></p>
<div id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:e6ceeafa-fe5c-4bd6-a48d-325da43e5abc" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;">Technorati Tags: <a rel="tag" href="http://technorati.com/tags/Programming">Programming</a>, <a rel="tag" href="http://technorati.com/tags/C%23">C#</a>, <a rel="tag" href="http://technorati.com/tags/wcf">WCF</a>, <a rel="tag" href="http://technorati.com/tags/soa">SOA</a></div>
]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2009/10/02/file-transfer-with-wcf-part-ii/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Service Locator Pattern in C#: A Simple Example</title>
		<link>http://stefanoricciardi.com/2009/09/25/service-locator-pattern-in-csharpa-simple-example/</link>
		<comments>http://stefanoricciardi.com/2009/09/25/service-locator-pattern-in-csharpa-simple-example/#comments</comments>
		<pubDate>Fri, 25 Sep 2009 12:24:31 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[Design and Patterns]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[OOP]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.net/?p=366</guid>
		<description><![CDATA[A Service Locator is a common design pattern that allows decoupling clients of services (described by a public interface) from the concrete class implementing those services. Martin Fowler has a great introduction on the topic in his Inversion of Control Containers and the Dependency Injection pattern. What follows is a very simple service locator implementation [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F09%2F25%2Fservice-locator-pattern-in-csharpa-simple-example%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F09%2F25%2Fservice-locator-pattern-in-csharpa-simple-example%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>A Service Locator is a common design pattern that allows decoupling clients of services (described by a public interface) from the concrete class implementing those services. Martin Fowler has a great introduction on the topic in his <a href="http://www.martinfowler.com/articles/injection.html">Inversion of Control Containers and the Dependency Injection pattern</a>.</p>
<p>What follows is a very simple service locator implementation in C# based on generics.</p>
<p>Let&#8217;s start defining the contract of a service locator.</p>
<pre class="brush:csharp">
public interface IServiceLocator
{
    T GetService&amp;lt;T&amp;gt;();
}
</pre>
<p>Now let&#8217;s see a very simple implementation of this contract:</p>
<pre class="brush:csharp">
class ServiceLocator : IServiceLocator
{
	// map that contains pairs of interfaces and
	// references to concrete implementations
	private IDictionary&amp;lt;object, object&amp;gt; services;

	internal ServiceLocator()
	{
		services = new Dictionary&amp;lt;object, object&amp;gt;();

		// fill the map
		this.services.Add(typeof(IServiceA), new ServiceA());
		this.services.Add(typeof(IServiceB), new ServiceB());
		this.services.Add(typeof(IServiceC), new ServiceC());
	}

	public T GetService&amp;lt;T&amp;gt;()
	{
		try
		{
			return (T)services[typeof(T)];
		}
		catch (KeyNotFoundException)
		{
			throw new ApplicationException(&amp;quot;The requested service is not registered&amp;quot;);
		}
	}
}
</pre>
<p>As you can see,</p>
<ul>
<li>the constructor of the class registers all the available services in a dictionary. In our example, we have 3 different services accessible through <code>IServiceA</code>, <code>IServiceB</code>, and <code>IServiceC</code>. It is assumed here that <code>ServiceA</code> implements <code>IServiceA</code> and so forth.</li>
<li>the generic GetService() method returns a reference the correct implementation fetching it from the dictionary</li>
</ul>
<p>This is how a client would invoke the service:</p>
<pre class="brush:csharp">
IServiceLocator locator = new ServiceLocator();
IServiceA myServiceA = locator.GetService&amp;lt;IServiceA&amp;gt;();
</pre>
<p>The clients do not know the actual classes implementing the service. They only have to interact with the service locator to get to an implementation.</p>
<h3>Improvements</h3>
<p>This is as simple as it gets. There are several improvements that a real-world implementation of a service locator should consider (what follows is only a partial list):</p>
<ul>
<li>The service locator itself might be a <a href="http://en.wikipedia.org/wiki/Singleton_pattern">singleton</a>. There usually is no need to have two instances of a service locator.</li>
<li><a href="http://stefanoricciardi.com/2009/10/13/service-locator-pattern-in-c-with-lazy-initialization/">Lazy initialization</a> of services might be considered. In the example above, the constructor creates new instances for all possible services; initialization might be deferred until some client actually requests a particular service.</li>
<li>The mapping between interfaces and implementation might be more flexible using metadata (e.g. through application configuration files)</li>
</ul>
<p><em>Next article in the series: <a href="http://stefanoricciardi.net/2009/10/13/service-locator-pattern-in-c-with-lazy-initialization/">Service Locator Pattern in C# with Lazy Initialization</a></em></p>
<p><!-- AddThis Button BEGIN --></p>
<p><a href="http://www.addthis.com/bookmark.php?v=250"><img style="border:0;" src="http://s7.addthis.com/static/btn/lg-share-en.gif" alt="Bookmark and Share" width="125" height="16" /></a></p>
<p><!-- AddThis Button END --></p>
<div id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:e6ceeafa-fe5c-4bd6-a48d-325da43e5abc" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;">Technorati Tags: <a rel="tag" href="http://technorati.com/tags/Programming">Programming</a>, <a rel="tag" href="http://technorati.com/tags/C%23">C#</a>, <a rel="tag" href="http://technorati.com/tags/design">Design</a>, <a rel="tag" href="http://technorati.com/tags/ood">OOD</a></div>
]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2009/09/25/service-locator-pattern-in-csharpa-simple-example/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
