<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Code Blitz</title>
	<atom:link href="https://codeblitz.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>https://codeblitz.wordpress.com</link>
	<description>Separation of Concerns</description>
	<lastBuildDate>Tue, 30 Sep 2014 12:11:05 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='codeblitz.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>https://secure.gravatar.com/blavatar/f3f2a824f01901a3b977420baafbac406d70ab93c816b0c629796d430b047192?s=96&#038;d=https%3A%2F%2Fs0.wp.com%2Fi%2Fbuttonw-com.png</url>
		<title>Code Blitz</title>
		<link>https://codeblitz.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="https://codeblitz.wordpress.com/osd.xml" title="Code Blitz" />
	<atom:link rel='hub' href='https://codeblitz.wordpress.com/?pushpress=hub'/>
	<item>
		<title>F# Project Euler Problem 2</title>
		<link>https://codeblitz.wordpress.com/2014/09/30/f-project-euler-problem-2/</link>
					<comments>https://codeblitz.wordpress.com/2014/09/30/f-project-euler-problem-2/#respond</comments>
		
		<dc:creator><![CDATA[Ed Foh]]></dc:creator>
		<pubDate>Tue, 30 Sep 2014 11:59:25 +0000</pubDate>
				<category><![CDATA[F#]]></category>
		<guid isPermaLink="false">http://codeblitz.wordpress.com/2014/09/30/f-project-euler-problem-2/</guid>

					<description><![CDATA[Solving second problem for Project Euler Problem 2 is an interesting one. Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, &#8230; By considering the terms in [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Solving second problem for <a href="https://projecteuler.net/problem=2">Project Euler Problem 2</a> is an interesting one.</p>
<blockquote><p>
  Each new term in the Fibonacci sequence is generated by<br />
  adding the previous two terms. By starting with 1 and 2, the first<br />
  10 terms will be:</p>
<p>  1, 2, 3, 5, 8, 13, 21, 34, 55, 89, &#8230;<br />
  By considering the terms in the Fibonacci sequence whose<br />
  values do not exceed four million, find the sum of the even<br />
  valued terms.
</p></blockquote>
<p>Challenge here is to generate a fibonacci sequence, which is the fib(n-1) + fib(n-2) formula. This generates a evaluation tree during recursion and becomes quite large when generating a large N fibonacci value, and stackoverflow happens. To tackle this problem in a more efficient way, we shouldn&#8217;t generate the number for N re-cursing backwards, but generate the number from summation forwards.</p>
<p>Here&#8217;s my first F# solution I came up with.</p>
<pre class="brush: fsharp; title: ; notranslate">
let initiniteFib =
    let rec fib1 n1 n2 =
        seq {
            yield n1
            yield! fib1 n2 (n1+n2)
        }
    fib1 0I 1I

let answer = initiniteFib 
                |&gt; Seq.takeWhile (fun x -&gt; x &lt; 4000000I)
                |&gt; Seq.filter (fun x -&gt; x % 2I = 0I)
                |&gt; Seq.sum
</pre>
<p>Another way to solve the same problem, is using <a href="http://msdn.microsoft.com/en-us/library/ee340363.aspx">Seq.unfold</a>.</p>
<pre class="brush: fsharp; title: ; notranslate">
let answer = Seq.unfold (fun (first, second) -&gt; Some(second, (second, first+second))) (0I, 1I)
                |&gt; Seq.takeWhile (fun x-&gt; x &lt; 4000000I)
                |&gt; Seq.filter (fun x -&gt; x % 2I = 0I)
                |&gt; Seq.sum
</pre>
<p>If you have more interesting ways to solve this, please share.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codeblitz.wordpress.com/2014/09/30/f-project-euler-problem-2/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		
		<media:content url="https://0.gravatar.com/avatar/37a2937ce6b55556bc8628cb36aade6e5701a3d9225bac921b5345485ca9afc3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Ed Foh</media:title>
		</media:content>
	</item>
		<item>
		<title>F# Project Euler Problem 1</title>
		<link>https://codeblitz.wordpress.com/2014/09/30/f-project-euler-problem-1-2/</link>
					<comments>https://codeblitz.wordpress.com/2014/09/30/f-project-euler-problem-1-2/#respond</comments>
		
		<dc:creator><![CDATA[Ed Foh]]></dc:creator>
		<pubDate>Tue, 30 Sep 2014 04:27:08 +0000</pubDate>
				<category><![CDATA[F#]]></category>
		<category><![CDATA[Project Euler]]></category>
		<guid isPermaLink="false">http://codeblitz.wordpress.com/2014/09/30/f-project-euler-problem-1-2/</guid>

					<description><![CDATA[Recently I have started getting more exposure about F# at work. Another developer and myself managed woto build a scheduling service purely written in F#, and it was a very humbling experience. I&#8217;ve gotten much more confidence now writing in F#, and starting to actually enjoy it more than C#. It&#8217;s a very different mindset [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Recently I have started getting more exposure about F# at work. Another developer and myself managed woto build a scheduling service purely written in F#, and it was a very humbling experience.</p>
<p>I&#8217;ve gotten much more confidence now writing in F#, and starting to actually enjoy it more than C#. It&#8217;s a very different mindset and paradigm to write functionally.</p>
<p>We&#8217;ve also started a small community at work learning, sharing and practicing in F#. One of the interesting exercises is solving mathematical problems in F# from <a href="https://projecteuler.net/">Project Euler</a>.</p>
<p>Here&#8217;s my solution in solving <a href="https://projecteuler.net/problem=1">Problem 1</a>.</p>
<blockquote><p>
  If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.<br />
  Find the sum of all the multiples of 3 or 5 below 1000.
</p></blockquote>
<pre class="brush: fsharp; title: ; notranslate">
let answer = seq {1..999}
|&gt; Seq.filter (fun n -&gt; n % 3 = 0 || n % 5 = 0)
|&gt; Seq.sum
</pre>
<p>Simple enough <img src="https://s0.wp.com/wp-content/mu-plugins/wpcom-smileys/twemoji/2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
]]></content:encoded>
					
					<wfw:commentRss>https://codeblitz.wordpress.com/2014/09/30/f-project-euler-problem-1-2/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		
		<media:content url="https://0.gravatar.com/avatar/37a2937ce6b55556bc8628cb36aade6e5701a3d9225bac921b5345485ca9afc3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Ed Foh</media:title>
		</media:content>
	</item>
		<item>
		<title>RetryTask using Task Parallel Library</title>
		<link>https://codeblitz.wordpress.com/2013/12/24/retrytask-using-task-parallel-library/</link>
					<comments>https://codeblitz.wordpress.com/2013/12/24/retrytask-using-task-parallel-library/#respond</comments>
		
		<dc:creator><![CDATA[Ed Foh]]></dc:creator>
		<pubDate>Mon, 23 Dec 2013 14:54:05 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[EdLib]]></category>
		<category><![CDATA[TPL]]></category>
		<guid isPermaLink="false">http://codeblitz.wordpress.com/?p=1221</guid>

					<description><![CDATA[Have you ever had to implement some form of retry functionality? I have, a couple of times in fact. Common scenarios would be to retry web service requests in the event of CommunicationException, or retry some time consuming method invocation. The parameters for these retry logic would be to wait a specified amount of time [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Have you ever had to implement some form of retry functionality? I have, a couple of times in fact. Common scenarios would be to retry web service requests in the event of <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.communicationexception(v=vs.110).aspx" target="_blank">CommunicationException</a>, or retry some time consuming method invocation. The parameters for these retry logic would be to wait a specified amount of time and to retry a specified number of times.</p>
<p>A very common retry logic I&#8217;ve seen to implement the retry logic is using a while loop to enforce the maximum number of retries, and a Thread.Sleep to perform the wait time. This is an example below.</p>
<p><span id="more-1221"></span></p>
<pre class="brush: csharp; title: ; notranslate">
public class Calculate
{
    private readonly Calculator _calculator;

    public Calculate(Calculator calculator)
    {
        _calculator = calculator;
    }

    public int CalculateWithRetry()
    {
        const int maxRetryAttemps = 2;
        int retryAttempts = 0;
        while (retryAttempts &lt;= maxRetryAttemps)
        {
            try
            {
                return _calculator.Calculate();
            }
            catch (InvalidOperationException)
            {
                retryAttempts++;
                Thread.Sleep(TimeSpan.FromSeconds(2));
            }
        }
        return 0;
    }
}
</pre>
<p>There is absolutely nothing wrong with doing that in my opinion, it&#8217;s straightforward and the simplest implementation I can think of.</p>
<p>I thought to myself though, if there is another way to write a retry task. I explored different opinions, and found one option to be both interesting and intriguing. I decided to try and implement the retry logic using the <a href="http://msdn.microsoft.com/en-us/library/dd537609(v=vs.110).aspx" target="_blank">Task Parallelism Library (TPL)</a> in .NET Framework 4.5.</p>
<p>I created a generic RetryTask, that is able to take in an Action as well as a Func&lt;T&gt; as retry-able actions, first being a void and other returning a result. The RetryTask also takes in a generic <em>TException</em>, which triggers the retry when that exception is being thrown. For instance, you can create a RetryTask with a CommunicationException, so in the event of timeouts, the web service request can be retried.</p>
<pre class="brush: csharp; title: ; notranslate">
public class RetryTask : IRetryTask
{
    private readonly ILogger _logger;
    private int _retryWaitIntervalSeconds;
    private int _retryAttempts;

    public RetryTask() : this(new ConsoleLogger())
    {}

    public RetryTask(ILogger logger)
    {
        _logger = logger;
    }

    public bool Execute&lt;TException&gt;(Action action, int retryWaitIntervalSeconds, int retryAttempts)
        where TException : Exception
    {
        _retryWaitIntervalSeconds = retryWaitIntervalSeconds;
        _retryAttempts = retryAttempts;
        int result;
        Func&lt;int&gt; actionFuncWrapper = () =&gt;
            {
                action();
                return 0;
            };
        return StartTaskWithRetryRecursive&lt;int, TException&gt;(actionFuncWrapper, out result);
    }

    public bool Execute&lt;TResult, TException&gt;(Func&lt;TResult&gt; action, int retryWaitIntervalSeconds, int retryAttempts, out TResult result)
        where TException : Exception
    {
        _retryWaitIntervalSeconds = retryWaitIntervalSeconds;
        _retryAttempts = retryAttempts;
        return StartTaskWithRetryRecursive&lt;TResult, TException&gt;(action, out result);
    }

    private bool StartTaskWithRetryRecursive&lt;TResult, TException&gt;(Func&lt;TResult&gt; action, out TResult result, int retryAttemptNumber = 1)
        where TException : Exception
    {
        result = default(TResult);

        var taskCompletionSource = new TaskCompletionSource&lt;bool&gt;();

        Task&lt;TResult&gt; task = StartNewTask&lt;TResult, TException&gt;(action, taskCompletionSource);

        WaitForTaskCompletion(taskCompletionSource);
        if (taskCompletionSource.Task.Result) 
        {
            result = task.Result;
            return true;
        }

        StartDelay(retryAttemptNumber);
        if (retryAttemptNumber &lt;= _retryAttempts)
            return StartTaskWithRetryRecursive&lt;TResult, TException&gt;(action, out result, retryAttemptNumber + 1);

        return false;
    }

    private void WaitForTaskCompletion(TaskCompletionSource&lt;bool&gt; taskCompletionSource) 
    {
        try 
        {
            taskCompletionSource.Task.Wait();
        } 
        catch (AggregateException ex) 
        {
            _logger.Error(&quot;unexpected error encountered whilst invoking action, {0}&quot;, ex.ToString());
            throw;
        }
    }

    private void StartDelay(int attemptNumber) 
    {
        _logger.Info(&quot;attempting retry number {0} after delay of {1} seconds...&quot;, attemptNumber, _retryWaitIntervalSeconds);
        Task.Delay(TimeSpan.FromSeconds(_retryWaitIntervalSeconds)).Wait();
    }

    private Task&lt;TResult&gt; StartNewTask&lt;TResult, TException&gt;(Func&lt;TResult&gt; action, TaskCompletionSource&lt;bool&gt; taskCompletionSource)
        where TException : Exception
    {
        Func&lt;object, TResult&gt; taskFunc = obj =&gt; action();  
        var startTask = new Task&lt;TResult&gt;(taskFunc, taskCompletionSource);

        // creates two mutually exclusive continuation tasks, one that will only run if startTask is successful, and another that will run if startTaskFails.
        startTask.ContinueWith&lt;TResult&gt;(ContinueWithOnCompletionTask, taskCompletionSource, TaskContinuationOptions.OnlyOnRanToCompletion);
        startTask.ContinueWith&lt;TResult&gt;(ContinueWithOnFaultedTask&lt;TResult, TException&gt;, taskCompletionSource, TaskContinuationOptions.OnlyOnFaulted);

        startTask.Start();
        return startTask;
    }

    private TResult ContinueWithOnFaultedTask&lt;TResult, TException&gt;(Task&lt;TResult&gt; antecedantTask, object taskCompletionSource) 
        where TException : Exception
    {
        if (antecedantTask.Exception != null)
        {
            if (antecedantTask.Exception.InnerException.GetType() == typeof(TException)) 
            {
                _logger.Warning(&quot;{0} exception occurred: {1}&quot;, typeof(TException).Name, antecedantTask.Exception.InnerException.ToString());
                ((TaskCompletionSource&lt;bool&gt;)taskCompletionSource).SetResult(false); // signal that a TException error occurred and we should retry
            } 
            else
            {
                ((TaskCompletionSource&lt;bool&gt;)taskCompletionSource).SetException(antecedantTask.Exception);
            }
        }
        return default(TResult);
    }

    private TResult ContinueWithOnCompletionTask&lt;TResult&gt;(Task&lt;TResult&gt; antecedantTask, object taskCompletionSource) 
    {
        ((TaskCompletionSource&lt;bool&gt;)taskCompletionSource).SetResult(true); // signals all went well
        return antecedantTask.Result;
    }
}
</pre>
<p>Comparatively, the RetryTask is far more complex and also harder to read for someone who&#8217;s unfamiliar with the TPL. For myself, this is a more of a learning exercise; Also I&#8217;m not a big fan of using while loops and Thread.Sleep in production code, and using TPL is an alternative.</p>
<p>Some of the TPL functions used in the RetryTask are:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/dd449174(v=vs.110).aspx" target="_blank">TaskCompletionSource</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/dd321576(v=vs.110).aspx" target="_blank">Task.ContinueWith</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskcontinuationoptions(v=vs.110).aspx" target="_blank">TaskContinuationOptions</a> (See OnlyRanToCompletion and OnlyOnFaulted)</li>
<li><a href="http://msdn.microsoft.com/en-us/library/hh194873(v=vs.110).aspx" target="_blank">Task.Delay</a></li>
</ul>
<p>The source code can be found in <a href="https://github.com/edfoh/EdLib" target="_blank">EdLib</a>.</p>
<p>Let me know how you would implement a Retry implementation <img src="https://s0.wp.com/wp-content/mu-plugins/wpcom-smileys/twemoji/2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
]]></content:encoded>
					
					<wfw:commentRss>https://codeblitz.wordpress.com/2013/12/24/retrytask-using-task-parallel-library/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		
		<media:content url="https://0.gravatar.com/avatar/37a2937ce6b55556bc8628cb36aade6e5701a3d9225bac921b5345485ca9afc3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Ed Foh</media:title>
		</media:content>
	</item>
		<item>
		<title>String.Format and IFormatProvider</title>
		<link>https://codeblitz.wordpress.com/2013/12/13/string-format-and-iformatprovider/</link>
					<comments>https://codeblitz.wordpress.com/2013/12/13/string-format-and-iformatprovider/#respond</comments>
		
		<dc:creator><![CDATA[Ed Foh]]></dc:creator>
		<pubDate>Fri, 13 Dec 2013 11:45:24 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[IFormatProvider]]></category>
		<guid isPermaLink="false">http://codeblitz.wordpress.com/?p=1204</guid>

					<description><![CDATA[Have you ever noticed this overload of String.Format(IFormatProvider, String, Object[])? IFormatProvider is actually a very useful interface that allows us to create custom formats to transform our inputs. The IFormatProvider link has examples on how to do it. This is my version on how to create a custom formatter factory that understand custom formats we [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Have you ever noticed this overload of <a href="http://msdn.microsoft.com/en-us/library/1ksz8yb7(v=vs.110).aspx" target="_blank">String.Format(IFormatProvider, String, Object[])</a>? <a href="http://msdn.microsoft.com/en-us/library/system.iformatprovider(v=vs.110).aspx" target="_blank">IFormatProvider </a>is actually a very useful interface that allows us to create custom formats to transform our inputs. The IFormatProvider link has examples on how to do it.</p>
<p>This is my version on how to create a custom formatter factory that understand custom formats we create, and routes to the appropriate formatter. If a non-custom format is used, the conversion will still be performed as normal. In the example, I&#8217;m trying to create custom formats &#8220;<em>bsb</em>&#8221; and &#8220;<em>acctno</em>&#8221; which will convert numbers to a &#8220;999-999&#8221; format and &#8220;1234-56789&#8221; format using the <strong>CustomFormatProvider</strong>.</p>
<p><span id="more-1204"></span></p>
<p>Here is my <strong>CustomFormatProvider</strong> class.</p>
<pre class="brush: csharp; title: ; notranslate">
public class CustomFormatProvider : IFormatProvider, ICustomFormatter
{
    private readonly IStringFormatterFactory _stringFormatterFactory;

    public CustomFormatProvider() : this(new StringFormatterFactory())
    {
    }

    public CustomFormatProvider(IStringFormatterFactory stringFormatterFactory)
    {
        _stringFormatterFactory = stringFormatterFactory;
    }

    public object GetFormat(Type formatType)
    {
        if (formatType == typeof(ICustomFormatter))
            return this;
        return null;
    }

    public string Format(string format, object arg, IFormatProvider formatProvider)
    {
        IStringFormatter stringFormatter = _stringFormatterFactory.GetFormatter(format);
        return stringFormatter.Format(arg, format);
    }
}
</pre>
<p>Here is my <strong>StringFormatterFactory</strong></p>
<pre class="brush: csharp; title: ; notranslate">
public class StringFormatterFactory : IStringFormatterFactory
{
    public IStringFormatter GetFormatter(string format)
    {
        if (format == CustomStringFormat.Bsb)
            return new BsbStringFormatter();

        if (format == CustomStringFormat.AccountNumber)
            return new AccountNumberStringFormatter();

        return new DefaultStringFormatter();
    }
}
</pre>
<p>Now here are my <strong>StringFormatter</strong> implementations for bsb and acctno, and a default one.</p>
<pre class="brush: csharp; title: ; notranslate">
public class BsbStringFormatter : IStringFormatter
{
    private const string ValidFormat = &quot;^[0-9]{6}$&quot;;

    public string Format(object arg, string format)
    {
        string input = arg.ToString();
        if (Regex.IsMatch(input, ValidFormat))
        {
            return string.Format(&quot;{0}-{1}&quot;, input.Substring(0, 3), input.Substring(3, 3));
        }
        throw new FormatException(
            string.Format(&quot;unable to format input value {0} to {1} format&quot;, input, format));
    }
}

public class AccountNumberStringFormatter : IStringFormatter
{
    private const string ValidFormat = &quot;^[0-9]{9}$&quot;;

    public string Format(object arg, string format) {
        string input = arg.ToString();
        if (Regex.IsMatch(input, ValidFormat)) {
            return string.Format(&quot;{0}-{1}&quot;, input.Substring(0, 5), input.Substring(5, 4));
        }
        throw new FormatException(
            string.Format(&quot;unable to format input value {0} to {1} format&quot;, input, format));
    }
}

public class DefaultStringFormatter : IStringFormatter
{
    public string Format(object arg, string format)
    {
        if (arg is IFormattable)
            return ((IFormattable)arg).ToString(format, CultureInfo.CurrentCulture);

        if (arg != null)
            return arg.ToString();

        return String.Empty;
    }
}
</pre>
<p>Now this is how one would use the <strong>CustomFormatProvider</strong></p>
<pre class="brush: csharp; title: ; notranslate">
var customFormatProvider = new CustomFormatProvider();

string message =
    string.Format(customFormatProvider, &quot;BSB:{0:bsb}, ACCT:{1:acctno}, BALANCE:{2:C2}&quot;, &quot;013987&quot;, &quot;123456789&quot;, 450.22);
// will display &quot;BSB:013-987, ACCT:12345-6789, BALANCE:$450.22&quot;
</pre>
<p>Download code sample <a href="http://sdrv.ms/1bCqHjJ" target="_blank">here</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codeblitz.wordpress.com/2013/12/13/string-format-and-iformatprovider/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		
		<media:content url="https://0.gravatar.com/avatar/37a2937ce6b55556bc8628cb36aade6e5701a3d9225bac921b5345485ca9afc3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Ed Foh</media:title>
		</media:content>
	</item>
		<item>
		<title>XPath Extensions is cool!</title>
		<link>https://codeblitz.wordpress.com/2013/12/12/xpath-extensions-is-cool/</link>
					<comments>https://codeblitz.wordpress.com/2013/12/12/xpath-extensions-is-cool/#respond</comments>
		
		<dc:creator><![CDATA[Ed Foh]]></dc:creator>
		<pubDate>Thu, 12 Dec 2013 12:14:47 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[xml]]></category>
		<category><![CDATA[xpath]]></category>
		<guid isPermaLink="false">http://codeblitz.wordpress.com/?p=1187</guid>

					<description><![CDATA[I&#8217;m been using XDocument and it&#8217;s API for some time, but I wasn&#8217;t aware of an XPath Extensions in the .NET Framework. Thanks to my co-worker Lucy, she&#8217;s shared with me some good tips and in turn I&#8217;m sharing it with you. Consider this XML. This would have been typically how I would dig into [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>I&#8217;m been using <a href="http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument(v=vs.110).aspx" target="_blank">XDocument </a>and it&#8217;s API for some time, but I wasn&#8217;t aware of an <a href="http://msdn.microsoft.com/en-us/library/system.xml.xpath.extensions_methods(v=vs.110).aspx" target="_blank">XPath Extensions</a> in the .NET Framework. Thanks to my co-worker Lucy, she&#8217;s shared with me some good tips and in turn I&#8217;m sharing it with you.</p>
<p>Consider this XML.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt;
&lt;Order&gt;
 &lt;Product id=&quot;1&quot; name=&quot;Nexus 5&quot;&gt;
 &lt;Price&gt;400.00&lt;/Price&gt;
 &lt;Qty&gt;1&lt;/Qty&gt;
 &lt;/Product&gt;
 &lt;Product id=&quot;5&quot; name=&quot;Wireless Charger&quot;&gt;
 &lt;Price&gt;50.00&lt;/Price&gt;
 &lt;Qty&gt;1&lt;/Qty&gt;
 &lt;/Product&gt;
&lt;/Order&gt;
</pre>
<p>This would have been typically how I would dig into the XML to find certain data using XDocument, in a safe way of course.</p>
<p><span id="more-1187"></span></p>
<pre class="brush: csharp; title: ; notranslate">
public string FindPriceForProduct(XDocument xDoc, string productName)
{
    XElement orderElement = xDoc.Element(&quot;Order&quot;);
    if (orderElement != null)
    {
        XElement productElement = orderElement.Elements(&quot;Product&quot;)
                                .FirstOrDefault(product=&gt; product.Attribute(&quot;name&quot;) != null
                                            &amp;&amp; product.Attribute(&quot;name&quot;).Value == productName);
        if (productElement != null)
        {
            XElement priceElement = productElement.Element(&quot;Price&quot;);
            return priceElement != null ? priceElement.Value : string.Empty;
        }
    }
    return string.Empty;
}

public decimal FindTotalCost(XDocument xDoc)
{
    XElement orderElement = xDoc.Element(&quot;Order&quot;);
    if (orderElement != null)
    {
        IEnumerable productPrices = orderElement.Elements(&quot;Product&quot;)
                                        .SelectMany(product =&gt; product.Elements(&quot;Price&quot;))
                                        .Select(price =&gt; decimal.Parse(price.Value));
        return productPrices.Sum();
    }
    return 0;
}
</pre>
<p>As you can see from the code above, it&#8217;s defensive and unsightly, even with the Linq extensions. With XPath Extensions, all you need is to add <strong><em>using System.Xml.XPath</em></strong> and new extension methods will be available on XDocument object. Let&#8217;s rewrite the code above with XPath Extensions.</p>
<pre class="brush: csharp; title: ; notranslate">
using System;
using System.Xml.Linq;
using System.Xml.XPath;

public string FindPriceForProduct(XDocument xDoc, string productName)
{
    string xpath = string.Format(&quot;/Order/Product[@name='{0}']/Price&quot;, productName);
    XElement productElement = xDoc.XPathSelectElement(xpath);
    return productElement != null ? productElement.Value : string.Empty;
}

public decimal FindTotalCost(XDocument xDoc)
{
    object prices = xDoc.XPathEvaluate(&quot;sum(/Order//Product/Price/text())&quot;);
    return prices != null ? Convert.ToDecimal(prices) : 0;
}
</pre>
<p>This new code is much neater, and there isn&#8217;t any need to check for nulls. If any part of the xpath expression has invalid nodes, the result will be null. There is only one method call, and not to mention the cool XPath conditions and functions you can use with the extension method. This greatly simplifies unnecessary complexity with code.</p>
<p>Here are some <a href="http://msdn.microsoft.com/en-us/library/ms256086(v=vs.110).aspx" target="_blank">XPath examples</a> you can use. Enjoy.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codeblitz.wordpress.com/2013/12/12/xpath-extensions-is-cool/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		
		<media:content url="https://0.gravatar.com/avatar/37a2937ce6b55556bc8628cb36aade6e5701a3d9225bac921b5345485ca9afc3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Ed Foh</media:title>
		</media:content>
	</item>
		<item>
		<title>String.Split throws OutOfMemoryException</title>
		<link>https://codeblitz.wordpress.com/2013/11/14/string-split-throws-outofmemoryexception/</link>
					<comments>https://codeblitz.wordpress.com/2013/11/14/string-split-throws-outofmemoryexception/#respond</comments>
		
		<dc:creator><![CDATA[Ed Foh]]></dc:creator>
		<pubDate>Thu, 14 Nov 2013 11:43:41 +0000</pubDate>
				<category><![CDATA[EdLib]]></category>
		<category><![CDATA[memory]]></category>
		<guid isPermaLink="false">http://codeblitz.wordpress.com/?p=1165</guid>

					<description><![CDATA[Recently I&#8217;ve been doing a fair bit of memory profiling and fixing memory issues at work. One interesting cause of an OutOfMemoryException I&#8217;ve encountered occurred when using String.Split for several large csv files concurrently. Of course the size and number of lines in the file that triggers the OutOfMemoryException is subjected to the memory capacity [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Recently I&#8217;ve been doing a fair bit of memory profiling and fixing memory issues at work. One interesting cause of an <a href="http://msdn.microsoft.com/en-us/library/system.outofmemoryexception(v=vs.110).aspx" target="_blank">OutOfMemoryException</a> I&#8217;ve encountered occurred when using <a href="http://msdn.microsoft.com/en-us/library/system.string.split(v=vs.110).aspx" target="_blank">String.Split</a> for several large csv files concurrently. Of course the size and number of lines in the file that triggers the OutOfMemoryException is subjected to the memory capacity of your computer. To reproduce this, it&#8217;s relatively easy, first you need to create a large csv file.</p>
<p>Here&#8217;s some code to do it.</p>
<p><span id="more-1165"></span></p>
<pre class="brush: csharp; title: ; notranslate">
const int fiftyMillionsLines = 50000000;
using (var fileStream = File.CreateText(@&quot;C:\temp\large.csv&quot;))
{
    for (int i = 1; i &lt;= fiftyMillionsLines; i++)          {                   fileStream.WriteLine(&quot;line {0}&quot;, i);          }          fileStream.Close();  }  </pre>
<p>I have 16GB of physical memory on my machine, so 50 millions lines was the breaking point for me. You can adjust that to create a csv large enough that will break String.Split. Next here&#8217;s a simple NUnit test that will illustrate the exception being thrown using the file we generated.</p>
<pre class="brush: csharp; title: ; notranslate">  [Test]  public void StringSplit_ForLargeCsv_WillThrowOutOfMemoryException()  {          var fileContents = File.ReadAllText(@&quot;C:\temp\large.csv&quot;);         Assert.Throws(() =&gt; fileContents.Split(new[] {&quot;\r\n&quot;, &quot;\n&quot;}, StringSplitOptions.RemoveEmptyEntries));
}
</pre>
<p>Obviously, some form of processing is required for each line you split, and it seems somewhat inefficient to get a collection of split lines upfront. Instead, it would seem more pragmatic to yield each line and perform processing one line at a time. A StringReader would seem fit for that purpose. Here&#8217;s a LineSplitter class I created to replace the use of String.Split.</p>
<pre class="brush: csharp; title: ; notranslate">
public class LineSplitter : ILineSplitter
{
    protected readonly string[] RowDelimiter = new[] { &quot;\r\n&quot;, &quot;\n&quot; };

    public IEnumerable SplitYield(string input)
    {
        using (var stringReader = new StringReader(input))
        {
            int rowIndex = 0;
            string rowString;
            while (!string.IsNullOrEmpty(rowString = stringReader.ReadLine()))
            {
                rowIndex++;
                yield return new StringLine(rowString, rowIndex);
            }
            stringReader.Close();
        }
    }
}

public class StringLine
{
    internal StringLine(string line, int rowIndex)
    {
        Value = line;
        RowIndex = rowIndex;
    }

    public string Value { get; private set; }

    public int RowIndex { get; private set; }
}
</pre>
<p>Using the same csv file generated, we can now run a test against that using LineSplitter.</p>
<pre class="brush: csharp; title: ; notranslate">
[Test]
public void UsingLineSplitter_ForLargeCsv_WillNotThrowOutOfMemoryException()
{
    var fileContents = File.ReadAllText(@&quot;C:\temp\large.csv&quot;);

    var lineSplitter = new LineSplitter();
    Assert.DoesNotThrow(()=&gt;lineSplitter.SplitYield(fileContents)
        .Select(stringLine =&gt; stringLine.Value).ToList());
}
</pre>
<p>That test passes, and all contents of the large csv can be loaded into memory without memory exception.</p>
<p>LineSplitter code can be found @ <a href="https://github.com/edfoh/EdLib" target="_blank">EdLib</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codeblitz.wordpress.com/2013/11/14/string-split-throws-outofmemoryexception/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		
		<media:content url="https://0.gravatar.com/avatar/37a2937ce6b55556bc8628cb36aade6e5701a3d9225bac921b5345485ca9afc3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Ed Foh</media:title>
		</media:content>
	</item>
		<item>
		<title>Object Proxy</title>
		<link>https://codeblitz.wordpress.com/2013/10/29/object-proxy/</link>
					<comments>https://codeblitz.wordpress.com/2013/10/29/object-proxy/#respond</comments>
		
		<dc:creator><![CDATA[Ed Foh]]></dc:creator>
		<pubDate>Tue, 29 Oct 2013 12:07:16 +0000</pubDate>
				<category><![CDATA[EdLib]]></category>
		<category><![CDATA[Proxy]]></category>
		<guid isPermaLink="false">http://codeblitz.wordpress.com/?p=1153</guid>

					<description><![CDATA[Consider this simplistic example, which uses a stream reader. The problem I have with this class is that it isn&#8217;t exactly unit testable. First of all, it uses a stream reader and it&#8217;s not straightforward to be able to mock a stream reader due to the lack of an interface. Secondly what I reckon most [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Consider this simplistic example, which uses a stream reader.</p>
<pre class="brush: csharp; title: ; notranslate">
public class FileLoader
{
    private readonly StreamReader _streamReader;

    public FileLoader(StreamReader streamReader)
    {
        _streamReader = streamReader;
    }

    public IEnumerable&lt;string&gt; Read()
    {
        var output = new List&lt;string&gt;();
        string line;
        while (!string.IsNullOrEmpty(line = _streamReader.ReadLine()))
        {
            output.Add(line);
        }
        _streamReader.Close();
        _streamReader.Dispose();
        return output;
    }
}
</pre>
<p>The problem I have with this class is that it isn&#8217;t exactly unit testable. First of all, it uses a stream reader and it&#8217;s not straightforward to be able to mock a stream reader due to the lack of an interface. Secondly what I reckon most developers would do is pass a real stream reader into the class and write tests in that fashion, which would be more of an integration test.</p>
<p><span id="more-1153"></span></p>
<p>Personally that is not proper unit testing as the class dependencies are not mocked. It is somewhat unavoidable we would be using un-mockable classes from the .NET framework, such as ConfigurationManager, Environment.GetVariable, etc.</p>
<p>The way I would solve this problem is create an interface for StreamReader, so I can mock it. As for the concrete implementation, I would create a wrapper class for StreamReader which implements that interface. So that makes my class unit testable like so.</p>
<pre class="brush: csharp; title: ; notranslate">
public interface IStreamReader
{
    string ReadLine();
    void Close();
    void Dispose();
}

public class FileLoader
{
    private readonly IStreamReader _streamReader;

    public FileLoader(IStreamReader streamReader)
    {
        _streamReader = streamReader;
    }

    public IEnumerable&lt;string&gt; Read()
    {
        var output = new List&lt;string&gt;();
        string line;
        while (!string.IsNullOrEmpty(line = _streamReader.ReadLine()))
        {
            output.Add(line);
        }
        _streamReader.Close();
        _streamReader.Dispose();
        return output;
    }
}
</pre>
<p>Is this too extreme? I would actually write wrappers for many un-mockable classes so I can unit test them. This brings me another unfortunate side-effect, which is I end up writing lots of wrapper classes. This is not ideal, so I came up with an ObjectProxy which could create a proxy object that implements an interface I specify and delegate interface calls to the real object. Referencing the StreamReader example, I would create an IStreamReader like so.</p>
<pre class="brush: csharp; title: ; notranslate">
public IEnumerable&lt;string&gt; ReadFile()
{
    var streamReader = new StreamReader(@&quot;C:\somefile.txt&quot;);
    var fileLoader = new FileLoader(ObjectProxy&lt;IStreamReader&gt;.Create(streamReader));
    return fileLoader.Read();
}
</pre>
<p>There are other ways to achieve the same result. For instance, I believe you could use <a href="http://www.castleproject.org/projects/dynamicproxy/" target="_blank">Castle DynamicProxy libaries</a>, or using <a href="http://msdn.microsoft.com/en-us/library/3y322t50.aspx" target="_blank">.NET Reflection Emit</a>. My approach is just simply another method, and one I prefer over the others. Here&#8217;s the ObjectProxy.</p>
<pre class="brush: csharp; title: ; notranslate">
using System;
using System.Reflection;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Proxies;

namespace EdLib.Objects.Proxy
{
    public class ObjectProxy&lt;TInterface&gt; : RealProxy where TInterface : class
    {
        private readonly object _instance;

        private ObjectProxy(object instance) : base(typeof(TInterface))
        {
            _instance = instance;
        }

        public static TInterface Create(object instance)
        {
            return (TInterface)new ObjectProxy&lt;TInterface&gt;(instance).GetTransparentProxy();
        }

        public override IMessage Invoke(IMessage msg)
        {
            var methodCall = (IMethodCallMessage)msg;
            var method = (MethodInfo)methodCall.MethodBase;

            try
            {
                var returnValue = TryInvokeMethodFromRealInstance(methodCall, method);
                return new ReturnMessage(returnValue, null, 0, methodCall.LogicalCallContext, methodCall);
            }
            catch (Exception ex)
            {
                if (ex is TargetInvocationException &amp;&amp; ex.InnerException != null)
                {
                    return new ReturnMessage(ex.InnerException, methodCall);
                }
                return new ReturnMessage(ex, methodCall);
            }
        }

        private object TryInvokeMethodFromRealInstance(IMethodCallMessage methodCall, MethodInfo methodInfo)
        {
            var instanceMethodInfo = _instance.GetType().GetMethod(methodInfo.Name);
            if (instanceMethodInfo != null)
            {
                return instanceMethodInfo.Invoke(_instance, methodCall.InArgs);
            }
            throw new Exception(string.Format(&quot;unable to find method {0} from real instance&quot;, methodInfo.Name));
        }
    }
}
</pre>
<p>This can also be from in <a href="https://github.com/edfoh/EdLib" target="_blank">EdLib @ Github</a>, my code library.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codeblitz.wordpress.com/2013/10/29/object-proxy/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		
		<media:content url="https://0.gravatar.com/avatar/37a2937ce6b55556bc8628cb36aade6e5701a3d9225bac921b5345485ca9afc3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Ed Foh</media:title>
		</media:content>
	</item>
		<item>
		<title>EdLib</title>
		<link>https://codeblitz.wordpress.com/2013/10/22/edlib/</link>
					<comments>https://codeblitz.wordpress.com/2013/10/22/edlib/#comments</comments>
		
		<dc:creator><![CDATA[Ed Foh]]></dc:creator>
		<pubDate>Tue, 22 Oct 2013 11:29:13 +0000</pubDate>
				<category><![CDATA[EdLib]]></category>
		<category><![CDATA[Expressions]]></category>
		<guid isPermaLink="false">http://codeblitz.wordpress.com/?p=1145</guid>

					<description><![CDATA[Over the years as a developer, I&#8217;ve come to realise that I have encountered similar problems and have had to write same kind of code. I&#8217;m sure most of us would have gone through that kind of experience, when we wished we had saved the code snippet or functions in a central area so we [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Over the years as a developer, I&#8217;ve come to realise that I have encountered similar problems and have had to write same kind of code. I&#8217;m sure most of us would have gone through that kind of experience, when we wished we had saved the code snippet or functions in a central area so we can re-use it.</p>
<p>I&#8217;ve decided to do exactly that. I&#8217;ve created a personal library where I want to store useful, reusable code that helps me in my everyday work, and hopefully will be useful to others too. Coming up with a name was hard, so I&#8217;ve decide to concatenate my name and the work &#8220;Lib&#8221; together, which becomes EdLib.</p>
<p><span id="more-1145"></span></p>
<p>For the first addition, I&#8217;ve decided to solve a common problem all of us would have encountered at some point. For instance, you have to access a property that&#8217;s nested, and you end up writing many ifs to check for null, like so</p>
<pre class="brush: csharp; title: ; notranslate">
if (person != null)
{
    if (person.Membership != null)
    {
        if (person.Membership.Account != null)
        {
            return person.Membership.Account.AccountNumber;
        }
    }
}
return 0;
</pre>
<p>It sucks to have to write code like that, and would be great to be able to compress that into a single line, evaluate if the account number can be retrieved otherwise return 0.</p>
<p>I&#8217;ve used <a href="http://msdn.microsoft.com/en-us/library/system.linq.expressions.expression.aspx" target="_blank">Expression </a>to achieve that. I&#8217;ve added extension methods for getting and setting nested property values using Expressions.</p>
<pre class="brush: csharp; title: ; notranslate">
public static bool TrySetValue&lt;T, TResult&gt;(this T instance, Expression&lt;Func&lt;T, TResult&gt;&gt; expression, TResult value) where T : class

public static void SetValue&lt;T, TResult&gt;(this T instance, Expression&lt;Func&lt;T, TResult&gt;&gt; expression, TResult value) where T : class

public static TResult GetValueOrDefault&lt;T, TResult&gt;(this T instance, Expression&lt;Func&lt;T, TResult&gt;&gt; expression) where T : class

public static TResult GetValue&lt;T, TResult&gt;(this T instance, Expression&lt;Func&lt;T, TResult&gt;&gt; expression) where T : class
</pre>
<p><strong><span style="text-decoration:underline;">GetValueOrDefault</span> </strong>will evaluate the expression; if any of nested object references are null, the default value will be returned.<br />
<span style="text-decoration:underline;"><strong>GetValue</strong> </span>will evaluate the expression; if any of the nested object references are null, an exception will be thrown.<br />
<span style="text-decoration:underline;"><strong>SetValue</strong> </span>will set the value for the expression; if it cannot evaluate the expression, an exception will be thrown.<br />
<span style="text-decoration:underline;"><strong>TrySetValue</strong> </span>will set the value for the expression, if it cannot evaluate the expression, it returns false.</p>
<p>Usage of the GetValueOrDefault extension method would vastly simplify the nested if code snippet above, like so&#8230;</p>
<pre class="brush: csharp; title: ; notranslate">

return person.GetValueOrDefault(x=&gt;x.Membership.Account.AccountNumber);

</pre>
<p>You can get the source and unit tests for this @ <a href="https://github.com/edfoh/EdLib" target="_blank">Github</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codeblitz.wordpress.com/2013/10/22/edlib/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		
		<media:content url="https://0.gravatar.com/avatar/37a2937ce6b55556bc8628cb36aade6e5701a3d9225bac921b5345485ca9afc3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Ed Foh</media:title>
		</media:content>
	</item>
		<item>
		<title>Linqify your code.</title>
		<link>https://codeblitz.wordpress.com/2013/10/12/linqify-your-code/</link>
					<comments>https://codeblitz.wordpress.com/2013/10/12/linqify-your-code/#respond</comments>
		
		<dc:creator><![CDATA[Ed Foh]]></dc:creator>
		<pubDate>Sat, 12 Oct 2013 12:58:41 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[Refactoring]]></category>
		<guid isPermaLink="false">http://codeblitz.wordpress.com/?p=1134</guid>

					<description><![CDATA[I&#8217;m sure most programmers are familiar with Linq, and agree with me that it&#8217;s great. I personally really enjoying using Linq, mostly in the form o f Linq to SQL and Linq to Objects. It also helps with simplifying your code and makes it easier to read. Some of the most useful Linq functions I [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>I&#8217;m sure most programmers are familiar with Linq, and agree with me that it&#8217;s great. I personally really enjoying using Linq, mostly in the form o f Linq to SQL and Linq to Objects. It also helps with simplifying your code and makes it easier to read. Some of the most useful Linq functions I find are FirstOrDefault, Any, All and Where. However sometimes I still come across developers writing loops to do work when Linq can be utilized to simplify it. So here are some simple code samples on how to use Linq to eliminate writing foreach loops.</p>
<p><span id="more-1134"></span></p>
<p>Example 1: simple loop through strings to print to console</p>
<pre class="brush: csharp; title: ; notranslate">
public void PrintStrings(IEnumerable inputs)
{
    foreach (var input in inputs)
    {
        Console.WriteLine(input);
    }
}

public void PrintStringsLinq(IEnumerable inputs)
{
    inputs.ToList().ForEach(Console.WriteLine);
}
</pre>
<p>Example 2: Only print string if condition is matched</p>
<pre class="brush: csharp; title: ; notranslate">
public void PrintStrings(IEnumerable inputs)
{
    foreach (var input in inputs)
    {
        if (input.Contains(&quot;some string&quot;))
        {
            Console.WriteLine(input);
        }
    }
}

public void PrintStringsLinq(IEnumerable inputs)
{
   inputs.Where(input=&gt;input.Contains(&quot;some string&quot;)).ToList().ForEach(Console.WriteLine);
}
</pre>
<p>Example 3: Break printing loop if a condition is met</p>
<pre class="brush: csharp; title: ; notranslate">
public void PrintStrings(IEnumerable inputs)
{
    foreach (var input in inputs)
    {
        if (!input.Contains(&quot;some string&quot;))
        {
            break;
        }
        Console.WriteLine(input);
    }
}

public void PrintStringsLinq(IEnumerable inputs)
{
    inputs.TakeWhile(input =&gt; input.Contains(&quot;some string&quot;)).ToList().ForEach(Console.WriteLine);
}
</pre>
<p>Example 4: Make a list of strings comma separated</p>
<pre class="brush: csharp; title: ; notranslate">
public void PrintStrings(IEnumerable inputs)
{
    var inputList = inputs.ToList();
    var output = string.Empty;
    for (var index = 0; index &lt; inputList.Count; index++)
    {
        if (index == 0)
            output = inputList[index];
        else
            output = string.Format(&quot;{0},{1}&quot;, output, inputList[index]);
    }
    Console.WriteLine(output);
}

public void PrintStringsLinq(IEnumerable inputs)
{
    var output = inputs.Aggregate((first, second) =&gt; string.Format(&quot;{0},{1}&quot;, first, second));
    Console.WriteLine(output);
}
</pre>
<p>Example 5: Converting list of strings to XElements</p>
<pre class="brush: csharp; title: ; notranslate">
public IEnumerable GetXElements(IEnumerable inputs)
{
    var xElements = new List();
    foreach (var input in inputs)
    {
        xElements.Add(new XElement(new XElement(input)));
    }
    return xElements;
}

public IEnumerable GetXElementsLinq(IEnumerable inputs)
{
    return inputs.Select(input =&gt; new XElement(input));
}
</pre>
<p>Example 6: Printing list of objects within a list of objects</p>
<pre class="brush: csharp; title: ; notranslate">
public class Fruit
{
    public string Name { get; set; }
}

public class Basket
{
    public IEnumerable Fruits { get; set; }
}

public void PrintFruits(IEnumerable baskets)
{
    foreach (var basket in baskets)
    {
        foreach (var fruit in basket.Fruits)
        {
            Console.WriteLine(fruit.Name);
        }
    }
}

public void PrintFruitsLinq(IEnumerable baskets)
{
    baskets.SelectMany(x=&gt;x.Fruits).ToList().ForEach(fruit =&gt; Console.WriteLine(fruit.Name));
}
</pre>
<p>Linq is capable of much more than the examples above but I find these are the common usages in my day to day coding. I do hope you will explore Linq more and unravel the power within in your code.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codeblitz.wordpress.com/2013/10/12/linqify-your-code/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		
		<media:content url="https://0.gravatar.com/avatar/37a2937ce6b55556bc8628cb36aade6e5701a3d9225bac921b5345485ca9afc3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Ed Foh</media:title>
		</media:content>
	</item>
		<item>
		<title>ASP.NET MVC 3: Agnostic Inversion of Control</title>
		<link>https://codeblitz.wordpress.com/2012/03/19/asp-net-mvc-3-agnostic-inversion-of-control/</link>
					<comments>https://codeblitz.wordpress.com/2012/03/19/asp-net-mvc-3-agnostic-inversion-of-control/#comments</comments>
		
		<dc:creator><![CDATA[Ed Foh]]></dc:creator>
		<pubDate>Mon, 19 Mar 2012 10:47:04 +0000</pubDate>
				<category><![CDATA[ASP.NET MVC 3]]></category>
		<category><![CDATA[Castle Windsor]]></category>
		<category><![CDATA[Unity]]></category>
		<category><![CDATA[Inversion of Control]]></category>
		<guid isPermaLink="false">http://codeblitz.wordpress.com/?p=1106</guid>

					<description><![CDATA[ASP.NET MVC has matured over the years and I&#8217;ve had the fortune to be able to do some development work recently on this. One of the first things I explored was to setup an Inversion of Control (IoC) container. One of the biggest benefits of using an IoC is to accommodate for the ease of unit testing [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>ASP.NET MVC has matured over the years and I&#8217;ve had the fortune to be able to do some development work recently on this. One of the first things I explored was to setup an Inversion of Control (IoC) container. One of the biggest benefits of using an IoC is to accommodate for the ease of unit testing using a mocking framework.</p>
<p>Anyways we use Castle Windsor on our project, but in theory we should be able to use any IoC framework.  I started to think about how to decouple the project from a specific IoC framework, so if we ever wanted to change to a different one, it would be easy and straightforward. Perhaps this is overkill in the real world, but would be a good exercise to go through.</p>
<p><span id="more-1106"></span></p>
<p>For this example, I&#8217;ve decided to use Castle Windsor and Unity, both of which I&#8217;m pretty familiar with. The idea behind this is to create an interface library on which the Castle and Unity libraries will implement, essentially a plug-in mechanism.</p>
<p>Here is the interface for IContainer, essentially a contract for the IoC Container we will be utilizing.</p>
<pre class="brush: csharp; title: ; notranslate">
public interface IContainer : IRegister, IResolve, IDisposable
{
}

public interface IResolve
{
    T Resolve&lt;T&gt;();

    T Resolve&lt;T&gt;(string key);

    bool CanResolve&lt;T&gt;();

    bool CanResolve&lt;T&gt;(string key);

    void Release(object instance);
}

public interface IRegister
{
    IRegister Register&lt;TInterface, TClass&gt;(Lifetime lifetime)
        where TInterface : class
        where TClass : TInterface;

    IRegister Register&lt;TInterface, TClass&gt;(string key, Lifetime lifetime)
        where TInterface : class
        where TClass : TInterface;

    IRegister RegisterAllClassesBasedOn&lt;TInterface&gt;(Lifetime lifetime) where TInterface : class;
}
</pre>
<p>There&#8217;s also an interface for IInstaller, which is a contract for installing or registering your components. This is based on the installer concept in Castle Windsor which I find useful.</p>
<pre class="brush: csharp; title: ; notranslate">
public interface IInstaller
{
    void Install(IContainer container);
}
</pre>
<p>Lastly there&#8217;s a IoC static class which allows you to register your selected IoC implementation based on the specification from a configuration section, like so.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;configSections&gt;
    &lt;section name=&quot;iocConfiguration&quot; type=&quot;IoC.IocConfiguration, IoC&quot;/&gt;
&lt;/configSections&gt;

&lt;iocConfiguration assemblyName=&quot;Unity&quot; /&gt;
</pre>
<p>&nbsp;</p>
<pre class="brush: csharp; title: ; notranslate">
public static class Ioc
{
    public static IContainer Initialize(IInstaller installer)
    {
        var assemblyWithLocation = GetAssemblyNameWithLocation();
        var assembly = Assembly.LoadFrom(assemblyWithLocation);

        var containerType =
            assembly.GetTypes().Single(x =&gt; x.GetInterface(typeof(IContainer).FullName) != null);
        var container = (IContainer)Activator.CreateInstance(containerType);
        installer.Install(container);
        return container;
    }

    private static string GetAssemblyNameWithLocation()
    {
        var location = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
        var assemblyNameWithLocation = Path.Combine(location, GetAssemblyName()).Replace(&quot;file:\\&quot;, &quot;&quot;);

        if (!File.Exists(assemblyNameWithLocation))
            throw new FileNotFoundException(&quot;unable to find assembly&quot;);
        return assemblyNameWithLocation;
    }

    private static string GetAssemblyName()
    {
        return string.Format(&quot;{0}.dll&quot;, IocConfiguration.Settings.AssemblyName);
    }
}
</pre>
<p>You just have to specify the name of the assembly you want to plug in. You also have to ensure that the assembly is present in the folder containing your executing assembly, I achieved this using a post build event.</p>
<p>As for the implementation details of Castle and Unity, I won&#8217;t be going into details. You can download the sample to have a look if interested. In the MVC application, I&#8217;ve created an Installer to register the HomeController. If there are other dependencies you need, register them here.</p>
<pre class="brush: csharp; title: ; notranslate">
public class Installer : IInstaller
{
    public void Install(IContainer container)
    {
        container.Register&lt;IController, HomeController&gt;(&quot;Home&quot;, Lifetime.Transient);
    }
}
</pre>
<p>Next I create a ControllerFactory that uses our IContainer to register dependencies, instead of the default one from MVC.</p>
<pre class="brush: csharp; title: ; notranslate">
public class ControllerFactory : IControllerFactory
{
    private readonly IContainer _container;
    private readonly IControllerFactory _defaultControllerFactory;

    public ControllerFactory(IContainer container) : this(container, new DefaultControllerFactory())
    {}

    public ControllerFactory(IContainer container, IControllerFactory defaultControllerFactory)
    {
        _container = container;
        _defaultControllerFactory = defaultControllerFactory;
    }

    public IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName)
    {
        if (_container.CanResolve&lt;IController&gt;(controllerName))
            return _container.Resolve&lt;IController&gt;(controllerName);
        return _defaultControllerFactory.CreateController(requestContext, controllerName);
    }

    public System.Web.SessionState.SessionStateBehavior GetControllerSessionBehavior(System.Web.Routing.RequestContext requestContext, string controllerName)
    {
        return _defaultControllerFactory.GetControllerSessionBehavior(requestContext, controllerName);
    }

    public void ReleaseController(IController controller)
    {
        _container.Release(controller);
    }
}
</pre>
<p>Last of all, we set everything up in the Global.asax application start method, like so.</p>
<pre class="brush: csharp; title: ; notranslate">
public class MvcApplication : System.Web.HttpApplication
{
    private IContainer _container;

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }

    public static void RegisterRoutes(RouteCollection routes)
    {
         routes.IgnoreRoute(&quot;{resource}.axd/{*pathInfo}&quot;);
         routes.IgnoreRoute(&quot;{*favicon}&quot;, new { favicon = @&quot;(.*/)?favicon.ico(/.*)?&quot; });

         routes.MapRoute(
            &quot;Default&quot;, // Route name
            &quot;{controller}/{action}/{id}&quot;, // URL with parameters
            new { controller = &quot;Home&quot;, action = &quot;Index&quot;, id = UrlParameter.Optional } // Parameter defaults
        );

    }

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);

        _container = IoC.Ioc.Initialize(new Installer());
        var controllerFactory = new ControllerFactory(_container);
        ControllerBuilder.Current.SetControllerFactory(controllerFactory);

    }

    protected void Application_End()
    {
         _container.Dispose();
    }
}
</pre>
<p>So here we have an agnostic IoC container. In theory you can create pluggable libraries for any IoC framework and bootstrap that into your MVC application. The beauty of this is that the IoC framework becomes transparent to the MVC application, and it will always be dealing with it&#8217;s IContainer interface and not an external dependency.</p>
<p>If you are interested in how to implement Castle with ASP.NET MVC 3, see this <a href="http://stw.castleproject.org/Default.aspx?Page=Windsor-tutorial-ASP-NET-MVC-3-application-To-be-Seen&amp;NS=Windsor&amp;AspxAutoDetectCookieSupport=1" target="_blank">link</a>.</p>
<p>If you are interested in how to implement Unity with ASP.NET MVC 3, see this <a href="http://bradwilson.typepad.com/blog/2010/07/service-location-pt2-controllers.html" target="_blank">link</a>.</p>
<p>Download code sample <a href="https://skydrive.live.com/?cid=2c6600f1c1d5e3be&amp;id=2C6600F1C1D5E3BE%21296" target="_blank">here</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codeblitz.wordpress.com/2012/03/19/asp-net-mvc-3-agnostic-inversion-of-control/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		
		<media:content url="https://0.gravatar.com/avatar/37a2937ce6b55556bc8628cb36aade6e5701a3d9225bac921b5345485ca9afc3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Ed Foh</media:title>
		</media:content>
	</item>
	</channel>
</rss>
