<?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>Malvin Ly</title>
	<atom:link href="http://malvinly.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://malvinly.com</link>
	<description></description>
	<lastBuildDate>Fri, 25 May 2012 20:40:35 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='malvinly.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Malvin Ly</title>
		<link>http://malvinly.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://malvinly.com/osd.xml" title="Malvin Ly" />
	<atom:link rel='hub' href='http://malvinly.com/?pushpress=hub'/>
		<item>
		<title>.NET 4.0 and first chance exceptions</title>
		<link>http://malvinly.com/2012/05/25/net-4-0-and-first-chance-exceptions/</link>
		<comments>http://malvinly.com/2012/05/25/net-4-0-and-first-chance-exceptions/#comments</comments>
		<pubDate>Fri, 25 May 2012 12:55:38 +0000</pubDate>
		<dc:creator>Malvin</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://malvinly.com/?p=340</guid>
		<description><![CDATA[.NET 4.0 introduced a new event that is raised for every exception that is thrown in an application domain. The FirstChanceException event is raised as soon as an exception is thrown. This includes any handled and unhandled exceptions. This code will produce the output: However, if an exception is thrown within the event handler, the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=malvinly.com&#038;blog=20601338&#038;post=340&#038;subd=nivlam&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>.NET 4.0 introduced a new event that is raised for every exception that is thrown in an application domain.  The <a href="http://msdn.microsoft.com/en-us/library/system.appdomain.firstchanceexception.aspx" target="_blank"><code>FirstChanceException</code></a> event is raised as soon as an exception is thrown.  This includes any handled and unhandled exceptions.</p>
<p><pre class="brush: csharp;">
static void Main(string[] args)
{
	AppDomain.CurrentDomain.FirstChanceException += (sender, eventArgs) =&gt;
	{
		Console.WriteLine(&quot;First chance exception: &quot; + eventArgs.Exception.Message);
	};

	try 
	{
		Console.WriteLine(&quot;Before exception.&quot;);
		throw new Exception(&quot;Some error.&quot;);
	}
	catch
	{
		Console.WriteLine(&quot;Handled.&quot;);
	}
}
</pre></p>
<p>This code will produce the output:</p>
<p><pre class="brush: plain;">
Before exception.
First chance exception: Some error.
Handled.
</pre></p>
<p>However, if an exception is thrown within the event handler, the <code>FirstChanceException</code> event will be raised recursively.  The code below will cause a stack overflow:</p>
<p><pre class="brush: csharp;">
static void Main(string[] args)
{
	AppDomain.CurrentDomain.FirstChanceException += (sender, eventArgs) =&gt;
	{
		try
		{
			throw new Exception();
		}
		catch
		{
		}
	};

	try 
	{
		throw new Exception();
	}
	catch
	{
	}
}
</pre></p>
<p>This is important to remember if we use any third party libraries, such as a logging library like Log4Net, to log exceptions within the event handler.  These third party libraries may throw an exception internally, which will cause the <code>FirstChanceException</code> event to be raised recursively.  Even without the use of third party libraries, any code may unexpectedly thrown an exception, which will cause the event to be raised recursively and cause a stack overflow.  The MSDN documentation mentions this fact:</p>
<blockquote><p>You must handle all exceptions that occur in the event handler for the FirstChanceException event. Otherwise, FirstChanceException is raised recursively. This could result in a stack overflow and termination of the application. We recommend that you implement event handlers for this event as constrained execution regions (CERs), to keep infrastructure-related exceptions such as out-of-memory or stack overflow from affecting the virtual machine while the exception notification is being processed.</p></blockquote>
<p>Unfortunately, the documentation doesn&#8217;t provide any code samples.  I haven&#8217;t been able to figure a way to prevent stack overflows without resorting to a somewhat non-elegant solution.  What we can do is check to see if the event handler is found multiple times in the current stack trace.  If it is, we can immediately return to prevent the event from being raised again.</p>
<p><pre class="brush: csharp;">
static void Main(string[] args)
{
	AppDomain.CurrentDomain.FirstChanceException += (sender, eventArgs) =&gt;
	{
		StackFrame[] frames = new StackTrace(1).GetFrames();
		MethodBase currentMethod = MethodBase.GetCurrentMethod();

		if (frames != null &amp;&amp; frames.Any(x =&gt; x.GetMethod() == currentMethod))
			return;

		throw new Exception();
	};

	throw new Exception();
}
</pre></p>
<p>Instantiating <a href="http://msdn.microsoft.com/en-us/library/wybch8k4.aspx" target="_blank"><code>StackTrace</code></a> may throw an <code>ArgumentOutOfRangeException</code> if the parameter is negative, which is not what we&#8217;re doing here.  The <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.getframes.aspx" target="_blank"><code>GetFrames()</code></a> method may return <code>null</code>, so the <code>if</code> condition needs to check for <code>null</code>.  The <a href="http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.getcurrentmethod.aspx" target="_blank"><code>GetCurrentMethod()</code></a> method may throw a <code>TargetException</code> if the method was invoked with a late-binding mechanism, which is not what we&#8217;re doing here.</p>
<p>The code above should be relatively safe and should prevent a stack overflow if an exception is thrown within the event handler.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nivlam.wordpress.com/340/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nivlam.wordpress.com/340/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nivlam.wordpress.com/340/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nivlam.wordpress.com/340/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nivlam.wordpress.com/340/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nivlam.wordpress.com/340/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nivlam.wordpress.com/340/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nivlam.wordpress.com/340/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nivlam.wordpress.com/340/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nivlam.wordpress.com/340/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nivlam.wordpress.com/340/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nivlam.wordpress.com/340/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nivlam.wordpress.com/340/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nivlam.wordpress.com/340/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=malvinly.com&#038;blog=20601338&#038;post=340&#038;subd=nivlam&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://malvinly.com/2012/05/25/net-4-0-and-first-chance-exceptions/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5d3dde70979847001714452779e70fc4?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=PG" medium="image">
			<media:title type="html">nivlam</media:title>
		</media:content>
	</item>
		<item>
		<title>&#8220;DateTime.Now&#8221; in unit tests</title>
		<link>http://malvinly.com/2012/05/09/datetime-now-in-unit-tests/</link>
		<comments>http://malvinly.com/2012/05/09/datetime-now-in-unit-tests/#comments</comments>
		<pubDate>Wed, 09 May 2012 07:08:39 +0000</pubDate>
		<dc:creator>Malvin</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://malvinly.com/?p=333</guid>
		<description><![CDATA[Inspired by Ayende&#8217;s post about dealing with time in tests, I started using his implementation of SystemTime.Now(). We may use SystemTime.Now() anywhere in our code instead of DateTime.Now. This will allow us to control time in a deterministic fashion in order to keep our tests consistent. However, one of the downsides is that we have [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=malvinly.com&#038;blog=20601338&#038;post=333&#038;subd=nivlam&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Inspired by <a href="http://ayende.com/blog/3408/dealing-with-time-in-tests" target="_blank">Ayende&#8217;s post</a> about dealing with time in tests, I started using his implementation of <code>SystemTime.Now()</code>.  </p>
<p><pre class="brush: csharp;">
public static class SystemTime
{
    public static Func&lt;DateTime&gt; Now = () =&gt; DateTime.Now;
}
</pre></p>
<p>We may use <code>SystemTime.Now()</code> anywhere in our code instead of <code>DateTime.Now</code>. This will allow us to control time in a deterministic fashion in order to keep our tests consistent.  However, one of the downsides is that we have to remember to reset the time after each test.</p>
<p><pre class="brush: csharp;">
[TestMethod]
public void DemoTest()
{
    SystemTime.Now = () =&gt; new DateTime(1970, 1, 1);
            
    // Test code...

    SystemTime.Now = () =&gt; DateTime.Now;
}
</pre></p>
<p>We can ease the pain by implementing this as part of the tear down process that runs after each test.  I think that&#8217;s an acceptable solution, but I still prefer all my test code to be as close together as possible.  The tear down process may also run for tests that don&#8217;t deal with <code>SystemTime.Now()</code>, so that&#8217;s extra overhead for nothing.</p>
<p>Instead, I decided to add a few additions to <code>SystemTime</code>:</p>
<p><pre class="brush: csharp;">
public class SystemTime : IDisposable
{
    private static Func&lt;DateTime&gt; now = () =&gt; DateTime.Now;

    public static DateTime Now
    {
        get { return now(); }
    }

    private SystemTime()
    {
    }

    public static SystemTime Context(DateTime dateTime)
    {
        now = () =&gt; dateTime;
        return new SystemTime();
    }

    public void Dispose()
    {
        now = () =&gt; DateTime.Now;
    }
}
</pre></p>
<p>I changed the <code>Now</code> property to type <code>DateTime</code> instead of <code>Func&lt;DateTime&gt;</code> so that it more closely resembles <code>DateTime.Now</code>. Implementing <code>IDisposable</code> gives us an easy way to reset <code>SystemTime.Now</code>.</p>
<p><pre class="brush: csharp;">
[TestMethod]
public void DemoTest()
{
    using (SystemTime.Context(new DateTime(1970, 1, 1)))
    {
        // Test code...
    }
}
</pre></p>
<p>To demonstrate, we can run this code:</p>
<p><pre class="brush: csharp;">
Console.WriteLine(SystemTime.Now);

using (SystemTime.Context(new DateTime(1970, 1, 1)))
{
    Console.WriteLine(SystemTime.Now);
}

Console.WriteLine(SystemTime.Now);
</pre></p>
<p>The output is:</p>
<p><pre class="brush: plain;">
5/9/2012 2:21:08 AM
1/1/1970 12:00:00 AM
5/9/2012 2:21:08 AM
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nivlam.wordpress.com/333/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nivlam.wordpress.com/333/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nivlam.wordpress.com/333/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nivlam.wordpress.com/333/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nivlam.wordpress.com/333/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nivlam.wordpress.com/333/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nivlam.wordpress.com/333/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nivlam.wordpress.com/333/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nivlam.wordpress.com/333/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nivlam.wordpress.com/333/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nivlam.wordpress.com/333/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nivlam.wordpress.com/333/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nivlam.wordpress.com/333/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nivlam.wordpress.com/333/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=malvinly.com&#038;blog=20601338&#038;post=333&#038;subd=nivlam&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://malvinly.com/2012/05/09/datetime-now-in-unit-tests/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5d3dde70979847001714452779e70fc4?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=PG" medium="image">
			<media:title type="html">nivlam</media:title>
		</media:content>
	</item>
		<item>
		<title>ASP.NET MVC CDN UrlHelper</title>
		<link>http://malvinly.com/2012/05/06/asp-net-mvc-cdn-urlhelper/</link>
		<comments>http://malvinly.com/2012/05/06/asp-net-mvc-cdn-urlhelper/#comments</comments>
		<pubDate>Mon, 07 May 2012 03:04:19 +0000</pubDate>
		<dc:creator>Malvin</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://malvinly.com/?p=324</guid>
		<description><![CDATA[We&#8217;re starting to move static files off our production web server to a content delivery network (CDN). Most of our existing views link to static resources using the Url.Content() helper. While in development, I would like the resources to point to the local versions. In production, the resources should point to our CDN. I also [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=malvinly.com&#038;blog=20601338&#038;post=324&#038;subd=nivlam&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>We&#8217;re starting to move static files off our production web server to a content delivery network (CDN). Most of our existing views link to static resources using the <code>Url.Content()</code> helper.</p>
<p><pre class="brush: xml;">
&lt;link href=&quot;@Url.Content(&quot;~/Content/Site.css&quot;)&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;@Url.Content(&quot;~/Scripts/jquery.js&quot;)&quot;&gt;&lt;/script&gt;
</pre></p>
<p>While in development, I would like the resources to point to the local versions. In production, the resources should point to our CDN.  I also want the ability to switch to the local versions if there is a problem with our CDN.</p>
<p>I&#8217;ve added two AppSettings keys to the web.config:</p>
<p><pre class="brush: xml;">
&lt;add key=&quot;CDN.Enabled&quot; value=&quot;true&quot; /&gt;
&lt;add key=&quot;CDN.Address&quot; value=&quot;http://cdn.example.com/&quot; /&gt;
</pre></p>
<p>If we need to switch to local versions, we can flip <code>CDN.Enabled</code> to <code>false</code>.  Instead of using the default <code>Url.Content()</code> helper, we&#8217;ll update the views to use our own <code>Url.ContentFromCdn()</code> helper.</p>
<p><pre class="brush: xml;">
&lt;link href=&quot;@Url.ContentFromCdn(&quot;~/Content/Site.css&quot;)&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;@Url.ContentFromCdn(&quot;~/Scripts/jquery.js&quot;)&quot;&gt;&lt;/script&gt;
</pre></p>
<p>Here is the code for the helper:</p>
<p><pre class="brush: csharp;">
public static class UrlHelpers
{
    public static string ContentFromCdn(this UrlHelper helper, string contentPath)
    {
        bool cdnEnabled;

        Boolean.TryParse(
            ConfigurationManager.AppSettings[&quot;CDN.Enabled&quot;],
            out cdnEnabled);

        if (!cdnEnabled)
            return helper.Content(contentPath);
            
        var baseUri = new Uri(ConfigurationManager.AppSettings[&quot;CDN.Address&quot;]);
        var content = VirtualPathUtility.ToAbsolute(contentPath);

        return new Uri(baseUri, content).AbsoluteUri;
    }
}
</pre></p>
<p>The helper will fall back to the default <code>Url.Content()</code> helper if the <code>CDN.Enabled</code> setting evaluates to <code>false</code>.  If we need to use Google&#8217;s CDN (or any other public CDN), we can use a dictionary to look for specific filenames and return a specific address.</p>
<p><pre class="brush: csharp;">
public static class UrlHelpers
{
    private static Dictionary&lt;string, string&gt; cdn = 
        new Dictionary&lt;string, string&gt;(StringComparer.OrdinalIgnoreCase)
        {
            { &quot;jquery.js&quot;, &quot;https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js&quot; },
            { &quot;jquery-ui.js&quot;, &quot;https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.js&quot; }
        };

    public static string ContentFromCdn(this UrlHelper helper, string contentPath)
    {
        bool cdnEnabled;

        Boolean.TryParse(
            ConfigurationManager.AppSettings[&quot;CDN.Enabled&quot;],
            out cdnEnabled);

        // Use default Url.Content() helper.
        if (!cdnEnabled)
            return helper.Content(contentPath);

        var fileName = VirtualPathUtility.GetFileName(contentPath);

        // Use public CDN address for this file.
        if (cdn.ContainsKey(fileName))
            return cdn[fileName];
            
        var baseUri = new Uri(ConfigurationManager.AppSettings[&quot;CDN.Address&quot;]);
        var content = VirtualPathUtility.ToAbsolute(contentPath);

        return new Uri(baseUri, content).AbsoluteUri;
    }
}
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nivlam.wordpress.com/324/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nivlam.wordpress.com/324/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nivlam.wordpress.com/324/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nivlam.wordpress.com/324/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nivlam.wordpress.com/324/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nivlam.wordpress.com/324/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nivlam.wordpress.com/324/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nivlam.wordpress.com/324/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nivlam.wordpress.com/324/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nivlam.wordpress.com/324/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nivlam.wordpress.com/324/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nivlam.wordpress.com/324/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nivlam.wordpress.com/324/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nivlam.wordpress.com/324/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=malvinly.com&#038;blog=20601338&#038;post=324&#038;subd=nivlam&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://malvinly.com/2012/05/06/asp-net-mvc-cdn-urlhelper/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5d3dde70979847001714452779e70fc4?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=PG" medium="image">
			<media:title type="html">nivlam</media:title>
		</media:content>
	</item>
		<item>
		<title>Static fields and the &#8220;BeforeFieldInit&#8221; flag</title>
		<link>http://malvinly.com/2012/05/06/static-fields-and-the-beforefieldinit-flag/</link>
		<comments>http://malvinly.com/2012/05/06/static-fields-and-the-beforefieldinit-flag/#comments</comments>
		<pubDate>Mon, 07 May 2012 01:38:34 +0000</pubDate>
		<dc:creator>Malvin</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://malvinly.com/?p=321</guid>
		<description><![CDATA[While upgrading a legacy WinForm application from .NET 2.0 to .NET 4.0, I noticed some slightly different behavior. I&#8217;m working with a class that has a private static field and a few static methods. The Demo class uses field initialization to create an instance of the Expensive class. The Start method does not use any [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=malvinly.com&#038;blog=20601338&#038;post=321&#038;subd=nivlam&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>While upgrading a legacy WinForm application from .NET 2.0 to .NET 4.0, I noticed some slightly different behavior. I&#8217;m working with a class that has a private static field and a few static methods.</p>
<p><pre class="brush: csharp;">
public class Demo
{
	private static Expensive expensive = new Expensive();

	public static void Start() 
	{
	}

	public static void UseExpensive()
	{
		expensive.DoSomething();
	}
}

internal class Expensive
{
	public Expensive()
	{
		// Expensive operation
	}

	public void DoSomething()
	{
	}
}
</pre></p>
<p>The <code>Demo</code> class uses field initialization to create an instance of the <code>Expensive</code> class. The <code>Start</code> method does not use any of the static fields. </p>
<p>The WinForm application calls <code>Demo.Start()</code> in the constructor and <code>Demo.UseExpensive()</code> in a button event.  </p>
<p><pre class="brush: csharp;">
public partial class SomeForm : Form
{
	public SomeForm()
	{
		InitializeComponent();

		Demo.Start();
	}

	private void button_Click(object sender, EventArgs e)
	{
		Demo.UseExpensive();
	}
}
</pre></p>
<p>In .NET 2.0, the constructor of the <code>Expensive</code> class would execute on application start-up.  In .NET 4.0 however, the constructor of the <code>Expensive</code> class would not execute until the button event was fired.  Since the <code>Expensive</code> class is costly to create due to various operations in the constructor, the button event in .NET 4.0 was noticeably slower on the first click.</p>
<p>The reason is due to how .NET initializes types that contain static fields and/or a static constructor.  If a type does not contain a static constructor, it will be marked with the <code>BeforeFieldInit</code> flag.</p>
<p>Using ILSpy to decompile into IL, we can see the current class marked with <code>BeforeFieldInit</code>:</p>
<p><a href="http://nivlam.files.wordpress.com/2012/05/beforefieldinit.png"><img src="http://nivlam.files.wordpress.com/2012/05/beforefieldinit.png?w=600" alt="" title="BeforeFieldInit"   class="alignnone size-full wp-image-307" /></a></p>
<p>If we include a static constructor (even if it&#8217;s empty), we&#8217;ll see that the class is no longer marked with <code>BeforeFieldInit</code>:</p>
<p><a href="http://nivlam.files.wordpress.com/2012/05/withoutbeforefieldinit.png"><img src="http://nivlam.files.wordpress.com/2012/05/withoutbeforefieldinit.png?w=600" alt="" title="WithoutBeforeFieldInit"   class="alignnone size-full wp-image-308" /></a></p>
<p>When marked with <code>BeforeFieldInit</code> in .NET 2.0, static field initialization may occur at any time before a static field is used.  This means that static field initialization may occur even if a static field is never used. When marked with <code>BeforeFieldInit</code> in .NET 4.0, static field initialization only occurs before a static field is used.  To demonstrate, we can use a console application to see when events occur.</p>
<p><pre class="brush: csharp;">
class Program
{
	static void Main(string[] args)
	{
		Console.WriteLine(&quot;Started.&quot;);
		Demo.Start();
		Console.WriteLine(&quot;End.&quot;);
	}
}

public class Demo
{
	private static ExpensiveClass expensive = new ExpensiveClass();

	public static void Start()
	{
		Console.WriteLine(&quot;In Start method.&quot;);
	}

	public static void UseExpensive()
	{
		Console.WriteLine(&quot;In UseExpensive method.&quot;);
		expensive.DoSomething();
	}
}

internal class ExpensiveClass
{
	public ExpensiveClass()
	{
		Console.WriteLine(&quot;In ExpensiveClass constructor.&quot;);
	}

	public void DoSomething()
	{
	}
}
</pre></p>
<p>The console application is calling <code>Demo.Start()</code> in the <code>Main</code> method, which does not reference any static fields. The output in .NET 2.0 is:</p>
<p><pre class="brush: plain;">
In ExpensiveClass constructor.
Started.
In Start method.
End.
</pre></p>
<p>The output in .NET 4.0 is:</p>
<p><pre class="brush: plain;">
Started.
In Start method.
End.
</pre></p>
<p>Although the <code>Demo.Start()</code> method never references any static fields, static field initialization occurs anyway in .NET 2.0.  </p>
<p>We can force static field initialization to occur in .NET 4.0 by adding a call to <code>Demo.UseExpensive()</code>, which does reference a static field.</p>
<p><pre class="brush: csharp;">
static void Main(string[] args)
{
	Console.WriteLine(&quot;Started.&quot;);
	Demo.Start();
	Demo.UseExpensive();
	Console.WriteLine(&quot;End.&quot;);
}
</pre></p>
<p>The output in .NET 4.0 is:</p>
<p><pre class="brush: csharp;">
Started.
In Start method.
In ExpensiveClass constructor.
In UseExpensive method.
End.
</pre></p>
<p>As you can see, static field initialization does not occur in .NET 4.0 until a static field is first referenced.  </p>
<p>If we update the <code>Demo</code> class and add an empty static constructor, the class will no longer be marked with <code>BeforeFieldInit</code>.  If a type isn&#8217;t marked with <code>BeforeFieldInit</code>, static field initialization will occur before <em>any</em> class member is used.</p>
<p><pre class="brush: csharp;">
class Program
{
	static void Main(string[] args)
	{
		Console.WriteLine(&quot;Started.&quot;);
		Demo.Start();
		Console.WriteLine(&quot;End.&quot;);
	}
}

public class Demo
{
	public static ExpensiveClass expensive = new ExpensiveClass();

	static Demo()
	{
	}

	public static void Start()
	{
		Console.WriteLine(&quot;In Start method.&quot;);
	}

	public static void UseExpensive()
	{
		Console.WriteLine(&quot;In UseExpensive method.&quot;);
		expensive.DoSomething();
	}
}
</pre></p>
<p>The output for .NET 2.0 and .NET 4.0 will be identical:</p>
<p><pre class="brush: plain;">
Started.
In ExpensiveClass constructor.
In Start method.
End.
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nivlam.wordpress.com/321/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nivlam.wordpress.com/321/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nivlam.wordpress.com/321/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nivlam.wordpress.com/321/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nivlam.wordpress.com/321/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nivlam.wordpress.com/321/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nivlam.wordpress.com/321/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nivlam.wordpress.com/321/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nivlam.wordpress.com/321/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nivlam.wordpress.com/321/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nivlam.wordpress.com/321/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nivlam.wordpress.com/321/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nivlam.wordpress.com/321/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nivlam.wordpress.com/321/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=malvinly.com&#038;blog=20601338&#038;post=321&#038;subd=nivlam&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://malvinly.com/2012/05/06/static-fields-and-the-beforefieldinit-flag/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5d3dde70979847001714452779e70fc4?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=PG" medium="image">
			<media:title type="html">nivlam</media:title>
		</media:content>

		<media:content url="http://nivlam.files.wordpress.com/2012/05/beforefieldinit.png" medium="image">
			<media:title type="html">BeforeFieldInit</media:title>
		</media:content>

		<media:content url="http://nivlam.files.wordpress.com/2012/05/withoutbeforefieldinit.png" medium="image">
			<media:title type="html">WithoutBeforeFieldInit</media:title>
		</media:content>
	</item>
		<item>
		<title>WCF clients and IDisposable</title>
		<link>http://malvinly.com/2012/05/01/wcf-clients-and-idisposable/</link>
		<comments>http://malvinly.com/2012/05/01/wcf-clients-and-idisposable/#comments</comments>
		<pubDate>Tue, 01 May 2012 07:19:04 +0000</pubDate>
		<dc:creator>Malvin</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://malvinly.com/?p=298</guid>
		<description><![CDATA[There are numerous articles detailing the &#8220;broken&#8221; IDisposable implementation for WCF clients. Just to name a few: http://www.codeproject.com/Tips/197531/Do-not-use-using-for-WCF-Clients http://geekswithblogs.net/DavidBarrett/archive/2007/11/22/117058.aspx http://ardalis.com/idisposable-and-wcf To summarize, the Close() method will be called when the WCF client is disposed. However, if we try to dispose the client while it&#8217;s in a faulted state, an exception will be thrown. The extension [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=malvinly.com&#038;blog=20601338&#038;post=298&#038;subd=nivlam&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>There are numerous articles detailing the &#8220;broken&#8221; IDisposable implementation for WCF clients.  Just to name a few:</p>
<ul>
<li><a href="http://www.codeproject.com/Tips/197531/Do-not-use-using-for-WCF-Clients">http://www.codeproject.com/Tips/197531/Do-not-use-using-for-WCF-Clients</a></li>
<li><a href="http://geekswithblogs.net/DavidBarrett/archive/2007/11/22/117058.aspx">http://geekswithblogs.net/DavidBarrett/archive/2007/11/22/117058.aspx</a></li>
<li><a href="http://ardalis.com/idisposable-and-wcf">http://ardalis.com/idisposable-and-wcf</a></li>
</ul>
<p>To summarize, the <code>Close()</code> method will be called when the WCF client is disposed.  However, if we try to dispose the client while it&#8217;s in a faulted state, an exception will be thrown.</p>
<p>The extension method provided in the CodeProject article allows you do something like this:</p>
<p><pre class="brush: csharp;">
new MyTestClient().Using(x =&gt; x.DoSomething());
</pre></p>
<p>The <code>Using()</code> extension method will automatically close or abort the client once finished. However, I do not like this extension method.  Without any explanation, a developer may mistakenly reuse the client:</p>
<p><pre class="brush: csharp;">
var client = new MyTestClient();
client.Using(x =&gt; x.DoSomething());
client.Using(x =&gt; x.DoSomething());  // Connection is already closed.
</pre></p>
<p>Instead, I use this class:</p>
<p><pre class="brush: csharp;">
public static class Client
{
    public static void Use&lt;TClient&gt;(Action&lt;TClient&gt; action)
        where TClient : ICommunicationObject, new()
    {
        var client = new TClient();

        try
        {
            action(client);
            client.Close();
        }
        catch (Exception)
        {
            client.Abort();
            throw;
        }
    }
}
</pre></p>
<p>&#8230; and the usage:</p>
<p><pre class="brush: csharp;">
Client.Use&lt;MyTestClient&gt;(x =&gt; x.DoSomething());
</pre></p>
<p>One problem with the class above is that if we needed to instantiate the client using one of the overloaded constructors, we couldn&#8217;t due to the <code>new()</code> constraint. Instead, we can use this class:</p>
<p><pre class="brush: csharp;">
public class Client&lt;TClient&gt;
    where TClient : ICommunicationObject
{
    private readonly TClient client;

    private Client(TClient client)
    {
        this.client = client;
    }

    public static Client&lt;TClient&gt; Instantiate(Func&lt;TClient&gt; action)
    {
        return new Client&lt;TClient&gt;(action());
    }

    public void Use(Action&lt;TClient&gt; action)
    {
        try
        {
            action(client);
            client.Close();
        }
        catch (Exception)
        {
            client.Abort();
            throw;
        }
    }
}
</pre></p>
<p>&#8230; and the usage:</p>
<p><pre class="brush: csharp;">
Client&lt;MyTestClient&gt;
    .Instantiate(() =&gt; new MyTestClient(&quot;extra param&quot;))
    .Use(x =&gt; x.DoSomething());
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nivlam.wordpress.com/298/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nivlam.wordpress.com/298/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nivlam.wordpress.com/298/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nivlam.wordpress.com/298/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nivlam.wordpress.com/298/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nivlam.wordpress.com/298/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nivlam.wordpress.com/298/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nivlam.wordpress.com/298/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nivlam.wordpress.com/298/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nivlam.wordpress.com/298/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nivlam.wordpress.com/298/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nivlam.wordpress.com/298/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nivlam.wordpress.com/298/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nivlam.wordpress.com/298/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=malvinly.com&#038;blog=20601338&#038;post=298&#038;subd=nivlam&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://malvinly.com/2012/05/01/wcf-clients-and-idisposable/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5d3dde70979847001714452779e70fc4?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=PG" medium="image">
			<media:title type="html">nivlam</media:title>
		</media:content>
	</item>
		<item>
		<title>Postback and hiding fields</title>
		<link>http://malvinly.com/2012/05/01/postback-and-hiding-fields/</link>
		<comments>http://malvinly.com/2012/05/01/postback-and-hiding-fields/#comments</comments>
		<pubDate>Tue, 01 May 2012 06:35:48 +0000</pubDate>
		<dc:creator>Malvin</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://malvinly.com/?p=292</guid>
		<description><![CDATA[I recently stumbled across some ASP.NET code that looks similar to this: The code here checks if this is a normal page load and not a postback. If this is the initial page load, it&#8217;ll check if the user may see sensitive (administrative) fields and hides them if the user does not have the appropriate [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=malvinly.com&#038;blog=20601338&#038;post=292&#038;subd=nivlam&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I recently stumbled across some ASP.NET code that looks similar to this:</p>
<p><pre class="brush: csharp;">
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        if (!HasPermissions())
            HideSensitiveFields();
    }
}
</pre></p>
<p>The code here checks if this is a normal page load and not a postback.  If this is the initial page load, it&#8217;ll check if the user may see sensitive (administrative) fields and hides them if the user does not have the appropriate permissions.</p>
<p>The problem is that it assumes all initial page loads will enter the <code>!IsPostBack</code> conditional block.  Postback can be faked by passing in a few select query strings, such as __EVENTTARGET.</p>
<p>This problem can be solved using event validation, encrypted viewstate, and other better coding practices, but that&#8217;s a different subject and I won&#8217;t dive into those in this post.</p>
<p><pre class="brush: plain;">
http://localhost:8080/Default.aspx?__eventtarget=
</pre></p>
<p>By default, ASP.NET doesn&#8217;t check the HTTP verb, so we can pass a few select query string parameters and essentially spoof a postback.  The URL above would bypass the <code>!IsPostBack</code> conditional block, allowing access to the sensitive fields.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nivlam.wordpress.com/292/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nivlam.wordpress.com/292/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nivlam.wordpress.com/292/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nivlam.wordpress.com/292/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nivlam.wordpress.com/292/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nivlam.wordpress.com/292/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nivlam.wordpress.com/292/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nivlam.wordpress.com/292/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nivlam.wordpress.com/292/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nivlam.wordpress.com/292/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nivlam.wordpress.com/292/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nivlam.wordpress.com/292/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nivlam.wordpress.com/292/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nivlam.wordpress.com/292/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=malvinly.com&#038;blog=20601338&#038;post=292&#038;subd=nivlam&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://malvinly.com/2012/05/01/postback-and-hiding-fields/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5d3dde70979847001714452779e70fc4?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=PG" medium="image">
			<media:title type="html">nivlam</media:title>
		</media:content>
	</item>
		<item>
		<title>Fakes Framework in Visual Studio 11</title>
		<link>http://malvinly.com/2012/04/08/fakes-framework-in-visual-studio-11/</link>
		<comments>http://malvinly.com/2012/04/08/fakes-framework-in-visual-studio-11/#comments</comments>
		<pubDate>Mon, 09 Apr 2012 04:48:29 +0000</pubDate>
		<dc:creator>Malvin</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://malvinly.com/?p=274</guid>
		<description><![CDATA[Microsoft has introduced the Fakes Framework in Visual Studio 11, which is the replacement for both private accessors and the original Moles framework. For those that are unfamiliar with Moles, it was an isolation framework that allowed us to replace dependencies in our unit tests. For example, if our legacy code uses the static method [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=malvinly.com&#038;blog=20601338&#038;post=274&#038;subd=nivlam&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Microsoft has introduced the Fakes Framework in Visual Studio 11, which is the replacement for both private accessors and the original <a href="http://research.microsoft.com/en-us/projects/moles/">Moles</a> framework.</p>
<p>For those that are unfamiliar with Moles, it was an isolation framework that allowed us to replace dependencies in our unit tests. For example, if our legacy code uses the static method <code>Util.GetUser()</code> to retrieve information from a database, there isn&#8217;t an easy way to change or remove that behavior.  Moles allowed us to intercept the call to <code>Util.GetUser()</code> and redirect it to our own implementation.  This is important because we want to keep our unit tests isolated, free from external dependencies such as the database.  Keeping the results deterministic is also a good way to ensure that our test results are consistent.</p>
<p>The Fakes Framework introduces two types of fakes:  stubs and shims.  Stubs allow us to replace a method with our own implementation for interfaces and virtual methods.  Shims allow us to override methods that usually can&#8217;t be overridden, such as static methods and non-virtual methods.  Shims also allow us to intercept calls to types found in the .NET base class library.</p>
<p><pre class="brush: csharp;">
public class AuthenticationService
{
    private readonly IUserRepository repository;

    public AuthenticationService(IUserRepository repository)
    {
        this.repository = repository;
    }

    public bool Authenticate(string username, string password)
    {
        User user = repository.GetUser(username);
        return user.Password == password;
    }
}
</pre></p>
<p>For our test, we want to make sure that <code>Authenticate()</code> returns <code>false</code> when the password does not match what&#8217;s returned from the repository.  The <code>AuthenticationService</code> requires an instance of <code>IUserRepository</code>.  We can use a stub to replace the method call <code>GetUser()</code>.</p>
<p>The Fakes Framework will generate strongly typed fakes for each assembly that we want to fake.  For stubs, each type will be prefixed with <code>Stub</code>.  In the test below, we&#8217;ll be using the stub <code>StubIUserRepository</code>, which is an implementation of the interface <code>IUserRepository</code>.  Each method/property on the stubbed type will contain delegates that are named very similar to the original method/property.  We can change the implementation of the method <code>GetUser()</code> by assigning a delegate to the <code>GetUserString</code> field on the stubbed type.</p>
<p><pre class="brush: csharp;">
[TestMethod]
public void Demo()
{
    var repository = new StubIUserRepository();

    repository.GetUserString = 
        username =&gt; new User { Name = &quot;Malvin&quot;, Password = &quot;secret&quot; };

    var service = new AuthenticationService(repository);
    var isAuthenticated = service.Authenticate(&quot;Malvin&quot;, &quot;password&quot;);

    Assert.IsFalse(isAuthenticated);
}
</pre></p>
<p>When <code>GetUser()</code> is called from <code>AuthenticationService</code>, the repository will return our hard-coded <code>User</code> with the name &#8220;Malvin&#8221; and password &#8220;secret&#8221;.</p>
<p>However, there are cases when it isn&#8217;t possible to replace the repository:</p>
<p><pre class="brush: csharp;">
public class AuthenticationService
{
    public bool Authenticate(string username, string password)
    {
        UserRepository repository = new UserRepository();

        User user = repository.GetUser(username);

        return user.Password == password;
    }
}
</pre></p>
<p>Let&#8217;s assume that we want to run the same test again.  Instead of using stubs, we&#8217;ll use a shim to intercept the call to <code>GetUser()</code>.</p>
<p>The Fakes Framework will generate strongly typed shims for each type in the original assembly.  Each type are prefixed with <code>Shim</code>.  Before we can use shims, we must create a new context under which the shims will be active.</p>
<p>In our test, we are specifying that for all calls to <code>GetUser()</code> for any instance of <code>UserRepository</code> while inside the <code>ShimContext</code>, we want to intercept that call and return our own <code>User</code>.</p>
<p><pre class="brush: csharp;">
[TestMethod]
public void Demo()
{
    using (ShimsContext.Create())
    {
        ShimUserRepository.AllInstances.GetUserString =
            (repository, username) =&gt; new User { Name = &quot;Malvin&quot;, Password = &quot;secret&quot; };

        var service = new AuthenticationService();
        var isAuthenticated = service.Authenticate(&quot;Malvin&quot;, &quot;password&quot;);

        Assert.IsFalse(isAuthenticated);    
    }
}
</pre></p>
<p>For cases where we may not want to override the behavior for all instances of a type, we can create individual instances:</p>
<p><pre class="brush: csharp;">
var repository = new ShimUserRepository();
repository.GetUserString = username =&gt; new User();
</pre></p>
<p>We can also replace static methods with our own implemention.</p>
<p><pre class="brush: csharp;">
public static class Util
{
    public static User GetUser(string username)
    {
        // ...
    }
}
</pre></p>
<p>The shim:</p>
<p><pre class="brush: csharp;">
ShimUtil.GetUserString = username =&gt; new User();
</pre></p>
<p>Shims also allow us to override the behavior of base classes.  Here we have a <code>CachedUserRepository</code>, which caches any users returned from <code>UserRepository</code>.  If a user is found in the cache, the cached user will be returned.  If a user is not found in the cache, we will use the base class to retrieve the user and add it to the cache.</p>
<p><pre class="brush: csharp;">
public class CachedUserRepository : UserRepository
{
    private static List&lt;User&gt; cache = new List&lt;User&gt;();

    public new User GetUser(string username)
    {
        User cachedUser = cache.FirstOrDefault(x =&gt; x.Name == username);
            
        if (cachedUser != null)
            return cachedUser;

        User user = base.GetUser(username);

        if (user != null)
            cache.Add(user);

        return user;
    }
}
</pre></p>
<p>Using shims, we can replace the the base method <code>base.GetUser()</code>. By creating a shim for the base class and passing the inheriting class to the shim&#8217;s constructor, we can override the base class&#8217;s behavior.</p>
<p><pre class="brush: csharp;">
[TestMethod]
public void Demo()
{
    using (ShimsContext.Create())
    {
        var cachedRepo = new CachedUserRepository();
        var baseClass = new ShimUserRepository(cachedRepo);

        baseClass.GetUserString = 
            username =&gt; new User { Name = &quot;Malvin&quot;, Password = &quot;password&quot; };

        var user = cachedRepo.GetUser(&quot;x&quot;);

        Assert.AreEqual(&quot;Malvin&quot;, user.Name);
    }
}
</pre></p>
<p>The new Fakes Framework is definitely a great tool for testing legacy code, but I would be hesitant to use it for anything else.  Most existing mocking frameworks have a much cleaner API.  Refactoring can be difficult since the framework generates strongly typed stubs and shims for an assembly.  Renaming methods or classes in the original assembly will cause your tests to fail.  I would also suggest that if you&#8217;re using shims extensively in a new project, there&#8217;s probably something wrong with your design.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nivlam.wordpress.com/274/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nivlam.wordpress.com/274/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nivlam.wordpress.com/274/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nivlam.wordpress.com/274/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nivlam.wordpress.com/274/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nivlam.wordpress.com/274/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nivlam.wordpress.com/274/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nivlam.wordpress.com/274/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nivlam.wordpress.com/274/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nivlam.wordpress.com/274/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nivlam.wordpress.com/274/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nivlam.wordpress.com/274/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nivlam.wordpress.com/274/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nivlam.wordpress.com/274/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=malvinly.com&#038;blog=20601338&#038;post=274&#038;subd=nivlam&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://malvinly.com/2012/04/08/fakes-framework-in-visual-studio-11/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5d3dde70979847001714452779e70fc4?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=PG" medium="image">
			<media:title type="html">nivlam</media:title>
		</media:content>
	</item>
		<item>
		<title>Executing code in a new application domain</title>
		<link>http://malvinly.com/2012/04/08/executing-code-in-a-new-application-domain/</link>
		<comments>http://malvinly.com/2012/04/08/executing-code-in-a-new-application-domain/#comments</comments>
		<pubDate>Sun, 08 Apr 2012 07:44:14 +0000</pubDate>
		<dc:creator>Malvin</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://malvinly.com/?p=259</guid>
		<description><![CDATA[A coworker recently mentioned a scenario where he needs to use legacy code in a multi-threaded environment. The class in-question is written in such a way that it holds state and needs to be reset before the class itself can be used again, therefore preventing it from being used in multiple threads at the same [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=malvinly.com&#038;blog=20601338&#038;post=259&#038;subd=nivlam&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>A coworker recently mentioned a scenario where he needs to use legacy code in a multi-threaded environment. The class in-question is written in such a way that it holds state and needs to be reset before the class itself can be used again, therefore preventing it from being used in multiple threads at the same time.  Although it may not be the most efficient method, we can create a new application domain for each thread and execute the code in there.  </p>
<p>Just prototyping out some ideas, an API like this may be useful:</p>
<p><pre class="brush: csharp;">
NewAppDomain.Execute(() =&gt;
{
	// Run code in here
});
</pre></p>
<p>Each call to <code>Execute</code> would create a new application domain. </p>
<p><pre class="brush: csharp;">
AppDomain domain = AppDomain.CreateDomain(&quot;New App Domain: &quot; + Guid.NewGuid());
</pre></p>
<p>To execute our <code>Action</code> that we&#8217;re passing to the <code>Execute</code> method, we&#8217;ll need to create a new instance of <code>Action</code> in our new application domain.  However, trying to call the <code>CreateInstanceAndUnwrap</code> method on the new application domain will throw an exception:</p>
<p><pre class="brush: plain;">
Unhandled Exception: System.MissingMethodException: Constructor on type 'System.Action' not found.
</pre></p>
<p>Instead, we&#8217;ll need to create a new class that can be instantiated in the new application domain.  This new class  <code>AppDomainDelegate</code> will act as a delgate and execute the <code>Action</code> that we pass to it.</p>
<p><pre class="brush: csharp;">
public static class NewAppDomain
{
    public static void Execute(Action action)
    {
        AppDomain domain = null;

        try
        {
            domain = AppDomain.CreateDomain(&quot;New App Domain: &quot; + Guid.NewGuid());

            var domainDelegate = (AppDomainDelegate)domain.CreateInstanceAndUnwrap(
                typeof(AppDomainDelegate).Assembly.FullName,
                typeof(AppDomainDelegate).FullName);

            domainDelegate.Execute(action);
        }
        finally
        {
            if (domain != null)
                AppDomain.Unload(domain);
        }
    }

    private class AppDomainDelegate : MarshalByRefObject
    {
        public void Execute(Action action)
        {
            action();
        }
    }
}
</pre></p>
<p>Now we can use this class to execute code in another application domain.</p>
<p><pre class="brush: csharp;">
NewAppDomain.Execute(() =&gt;
{
    Console.WriteLine(&quot;Hello World&quot;);
});
</pre></p>
<p><strong>Parameters</strong></p>
<p>Trying to use variables declared outside the scope of the lambda will throw a serialization exception.</p>
<p><pre class="brush: csharp;">
int i = 0;

NewAppDomain.Execute(() =&gt;
{
	Console.WriteLine(&quot;Hello World &quot; + i);
});
</pre></p>
<p>We can update the code to receive parameters across application domains by adding an overload for the <code>Execute</code> method:</p>
<p><pre class="brush: csharp;">
public static class NewAppDomain
{
    public static void Execute(Action action) { ... }

    public static void Execute&lt;T&gt;(T parameter, Action&lt;T&gt; action)
    {
        AppDomain domain = null;

        try
        {
            domain = AppDomain.CreateDomain(&quot;New App Domain: &quot; + Guid.NewGuid());

            var domainDelegate = (AppDomainDelegate)domain.CreateInstanceAndUnwrap(
                typeof(AppDomainDelegate).Assembly.FullName,
                typeof(AppDomainDelegate).FullName);

            domainDelegate.Execute(parameter, action);
        }
        finally
        {
            if (domain != null)
                AppDomain.Unload(domain);
        }
    }

    private class AppDomainDelegate : MarshalByRefObject
    {
        public void Execute(Action action) { ... }

        public void Execute&lt;T&gt;(T parameter, Action&lt;T&gt; action)
        {
            action(parameter);
        }
    }
}
</pre></p>
<p>Now we can pass parameters to the method.  We&#8217;ll need to make sure that any parameters we pass are marked as <code>Serializable</code> since they will be serialized and deserialized across application domains.</p>
<p><pre class="brush: csharp;">
int i = 0;

NewAppDomain.Execute(i, x =&gt;
{
    Console.WriteLine(&quot;Hello World &quot; + x);
});
</pre></p>
<p><strong>Returning Results</strong></p>
<p>In cases where we want the <code>Execute</code> method to return results, we can add two additional method overloads that use <code>Func&lt;T&gt;</code> instead of <code>Action</code>:</p>
<p><pre class="brush: csharp;">
public static T Execute&lt;T&gt;(Func&lt;T&gt; action)
{
    AppDomain domain = null;

    try
    {
        domain = AppDomain.CreateDomain(&quot;New App Domain: &quot; + Guid.NewGuid());

        var domainDelegate = (AppDomainDelegate)domain.CreateInstanceAndUnwrap(
            typeof(AppDomainDelegate).Assembly.FullName,
            typeof(AppDomainDelegate).FullName);

        return domainDelegate.Execute(action);
    }
    finally
    {
        if (domain != null)
            AppDomain.Unload(domain);
    }
}

public static TResult Execute&lt;T, TResult&gt;(T parameter, Func&lt;T, TResult&gt; action)
{
    AppDomain domain = null;

    try
    {
        domain = AppDomain.CreateDomain(&quot;New App Domain: &quot; + Guid.NewGuid());

        var domainDelegate = (AppDomainDelegate)domain.CreateInstanceAndUnwrap(
            typeof(AppDomainDelegate).Assembly.FullName,
            typeof(AppDomainDelegate).FullName);

        return domainDelegate.Execute(parameter, action);
    }
    finally
    {
        if (domain != null)
            AppDomain.Unload(domain);
    }
}
</pre></p>
<p>&#8230; and the same overloads for the delegate class <code>AppDomainDelegate</code>:</p>
<p><pre class="brush: csharp;">
public T Execute&lt;T&gt;(Func&lt;T&gt; action)
{
    return action();
}

public TResult Execute&lt;T, TResult&gt;(T parameter, Func&lt;T, TResult&gt; action)
{
    return action(parameter);
}
</pre></p>
<p>We can now get results back.  We&#8217;ll need to make sure that any results we return are marked as <code>Serializable</code>.</p>
<p><pre class="brush: csharp;">
Result first = NewAppDomain.Execute(() =&gt; new Result());
Result second = NewAppDomain.Execute(parameter, x =&gt; new Result());
</pre></p>
<p><strong>Using The Class</strong></p>
<p>The entire class can be found <a href="https://gist.github.com/2335382" target="_blank">here</a>.  To demonstrate, we&#8217;ll create a class that uses a <code>public static</code> field as a counter.</p>
<p><pre class="brush: csharp;">
public class SharedClass : MarshalByRefObject
{
    public static int Counter = 1;

    public void Print()
    {
        Console.WriteLine(AppDomain.CurrentDomain.FriendlyName + &quot; - &quot; + Counter);
        Counter++;
    }
}
</pre></p>
<p>We&#8217;ll call the <code>Print</code> method in another application domain using our <code>NewAppDomain</code> class:</p>
<p><pre class="brush: csharp;">
NewAppDomain.Execute(() =&gt;
{
	new SharedClass().Print();
	new SharedClass().Print();
});

NewAppDomain.Execute(() =&gt;
{
	new SharedClass().Print();
	new SharedClass().Print();
	new SharedClass().Print();
	new SharedClass().Print();
});
</pre></p>
<p>The result:</p>
<p><pre class="brush: plain;">
New App Domain: 3ca2e6de-a5bd-40ef-b471-edb8c19024c2 - 1
New App Domain: 3ca2e6de-a5bd-40ef-b471-edb8c19024c2 - 2
New App Domain: 2037d461-79fe-48c1-abf1-2c58bb6b02cf - 1
New App Domain: 2037d461-79fe-48c1-abf1-2c58bb6b02cf - 2
New App Domain: 2037d461-79fe-48c1-abf1-2c58bb6b02cf - 3
New App Domain: 2037d461-79fe-48c1-abf1-2c58bb6b02cf - 4
</pre></p>
<p>If the application domain was the same, we would have seen the counter increment to 6.  Notice that <code>SharedClass</code> inherits from <code>MarshalByRefObject</code>.  If we instantiate a new instance of <code>SharedClass</code> and pass it as a parameter to our <code>Execute</code> method, this object is now shared across application domains via remoting.  To demonstrate, we can use the <code>Execute</code> overload that takes a parameter:</p>
<p><pre class="brush: csharp;">
var sharedClass = new SharedClass();

sharedClass.Print();
sharedClass.Print();

NewAppDomain.Execute(sharedClass, x =&gt; x.Print());

sharedClass.Print();
</pre></p>
<p>The result:</p>
<p><pre class="brush: plain;">
AppDomainDemo.exe - 1
AppDomainDemo.exe - 2
AppDomainDemo.exe - 3
AppDomainDemo.exe - 4
</pre></p>
<p>As expected, the counter did not reset.  However, if we change <code>SharedClass</code> by removing <code>MarshalByRefObject</code> and marking the class as <code>Serializable</code>, we&#8217;ll see a different result:</p>
<p><pre class="brush: plain;">
AppDomainDemo.exe - 1
AppDomainDemo.exe - 2
New App Domain: b9404ee9-f4fc-4937-84ad-9d0369e36bb6 - 1
AppDomainDemo.exe - 3
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nivlam.wordpress.com/259/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nivlam.wordpress.com/259/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nivlam.wordpress.com/259/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nivlam.wordpress.com/259/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nivlam.wordpress.com/259/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nivlam.wordpress.com/259/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nivlam.wordpress.com/259/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nivlam.wordpress.com/259/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nivlam.wordpress.com/259/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nivlam.wordpress.com/259/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nivlam.wordpress.com/259/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nivlam.wordpress.com/259/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nivlam.wordpress.com/259/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nivlam.wordpress.com/259/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=malvinly.com&#038;blog=20601338&#038;post=259&#038;subd=nivlam&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://malvinly.com/2012/04/08/executing-code-in-a-new-application-domain/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5d3dde70979847001714452779e70fc4?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=PG" medium="image">
			<media:title type="html">nivlam</media:title>
		</media:content>
	</item>
		<item>
		<title>Logging lambda expressions</title>
		<link>http://malvinly.com/2012/03/30/logging-lambda-expressions/</link>
		<comments>http://malvinly.com/2012/03/30/logging-lambda-expressions/#comments</comments>
		<pubDate>Fri, 30 Mar 2012 05:42:30 +0000</pubDate>
		<dc:creator>Malvin</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://malvinly.com/?p=254</guid>
		<description><![CDATA[When working with lambda expressions, there are scenarios where I need to log when a Func&#60;bool&#62; returns false. In the example below, just logging &#8220;condition was not met&#8221; doesn&#8217;t give me very much information. If I called the method like so: &#8230; I would like to be able to turn that lambda expression into a [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=malvinly.com&#038;blog=20601338&#038;post=254&#038;subd=nivlam&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>When working with lambda expressions, there are scenarios where I need to log when a <code>Func&lt;bool&gt;</code> returns false.  In the example below, just logging &#8220;condition was not met&#8221; doesn&#8217;t give me very much information.</p>
<p><pre class="brush: csharp;">
public void SomeMethod(Func&lt;Person, bool&gt; condition)
{
	if (!condition(person))
	{
		Log.Info(&quot;Condition was not met.&quot;);
		return;
	}

	// Do something
}
</pre></p>
<p>If I called the method like so:</p>
<p><pre class="brush: csharp;">
obj.SomeMethod(x =&gt; x.Name == &quot;Malvin&quot;);
</pre></p>
<p>&#8230; I would like to be able to turn that lambda expression into a meaningful string.  </p>
<p>Unfortunately, there doesn&#8217;t appear to be an easy way to turn a lambda expression into a readable string.  Instead, I had to use expression trees.</p>
<p><pre class="brush: csharp;">
public void SomeMethod(Expression&lt;Func&lt;Person, bool&gt;&gt; expression)
{
	if (!expression.Compile()(person))
	{
		Log.Info(&quot;Condition was not met: &quot; + expression);
		return;
	}

	// Do something
}
</pre></p>
<p>Now if I call the method and the condition fails, I should see:</p>
<p><pre class="brush: plain;">
Condition was not met: x =&gt; (x.Name == &quot;Malvin&quot;)
</pre></p>
<p>However, expression trees are much more expensive than lambda expressions.  Running a non-scientific benchmark on my Core i7 @ 3.2 GHz yields some fairly obvious results.</p>
<p><pre class="brush: csharp;">
void Main()
{
	Stopwatch sw = Stopwatch.StartNew();
	
	for (int i = 0; i &lt; 100000; i++)
		UsingExpression(() =&gt; false);
	
	sw.Stop();
	
	Console.WriteLine (&quot;Expression: &quot; + sw.ElapsedMilliseconds);
	
	sw.Restart();
	
	for (int i = 0; i &lt; 100000; i++)
		UsingLambda(() =&gt; false);
		
	sw.Stop();
	
	Console.WriteLine (&quot;Lambda: &quot; + sw.ElapsedMilliseconds);
}

public void UsingExpression(Expression&lt;Func&lt;bool&gt;&gt; expression)
{
	if (expression.Compile()())
		Console.WriteLine (&quot;hello world&quot;);
}

public void UsingLambda(Func&lt;bool&gt; condition)
{
	if (condition())
		Console.WriteLine (&quot;hello world&quot;);
}
</pre> </p>
<p>Output:</p>
<p><pre class="brush: plain;">
Expression: 4154
Lambda: 0
</pre></p>
<p>This may be a problem for high volume systems, but I don&#8217;t think the extra overhead will be an issue for most cases.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nivlam.wordpress.com/254/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nivlam.wordpress.com/254/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nivlam.wordpress.com/254/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nivlam.wordpress.com/254/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nivlam.wordpress.com/254/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nivlam.wordpress.com/254/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nivlam.wordpress.com/254/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nivlam.wordpress.com/254/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nivlam.wordpress.com/254/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nivlam.wordpress.com/254/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nivlam.wordpress.com/254/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nivlam.wordpress.com/254/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nivlam.wordpress.com/254/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nivlam.wordpress.com/254/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=malvinly.com&#038;blog=20601338&#038;post=254&#038;subd=nivlam&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://malvinly.com/2012/03/30/logging-lambda-expressions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5d3dde70979847001714452779e70fc4?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=PG" medium="image">
			<media:title type="html">nivlam</media:title>
		</media:content>
	</item>
		<item>
		<title>Casting and converting to strings</title>
		<link>http://malvinly.com/2012/03/13/casting-and-converting-to-strings/</link>
		<comments>http://malvinly.com/2012/03/13/casting-and-converting-to-strings/#comments</comments>
		<pubDate>Tue, 13 Mar 2012 05:42:07 +0000</pubDate>
		<dc:creator>Malvin</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://malvinly.com/?p=246</guid>
		<description><![CDATA[One thing that makes me nervous while looking through a code base is the liberal use of the ToString() method everywhere. There are a couple different ways to convert/cast to a string: Explicit cast: ToString() method: Convert.ToString() method: as operator: Explicit casts should be used at times when you are sure that someObj is a [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=malvinly.com&#038;blog=20601338&#038;post=246&#038;subd=nivlam&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>One thing that makes me nervous while looking through a code base is the liberal use of the <code>ToString()</code> method everywhere.  There are a couple different ways to convert/cast to a string:</p>
<p>Explicit cast:<br />
<pre class="brush: csharp;">
string str = (string)someObj;
</pre></p>
<p><code>ToString()</code> method:<br />
<pre class="brush: csharp;">
string str = someObj.ToString();
</pre></p>
<p><code>Convert.ToString()</code> method:<br />
<pre class="brush: csharp;">
string str = Convert.ToString(someObj);
</pre></p>
<p><code>as</code> operator:<br />
<pre class="brush: csharp;">
string str = someObj as string;
</pre></p>
<p>Explicit casts should be used at times when you are sure that <code>someObj</code> is a string. It also doubles as an assertion since an <code>InvalidCastException</code> will be thrown at runtime if the cast fails.  The result will be <code>null</code> if attempting to cast a <code>null</code> object.</p>
<p>The <code>ToString()</code> method returns the string representation of an object.  If <code>someObj</code> is null, a <code>NullReferenceException</code> will be thrown.</p>
<p>The <code>Convert.ToString()</code> method behaves differently depending on the type of object passed to the method.  When an <code>object</code> is passed to the method, it calls the <code>ToString()</code> method on the object:</p>
<p><pre class="brush: csharp;">
public static string ToString(Object value) 
{
	return ToString(value, null);
} 

public static string ToString(Object value, IFormatProvider provider) 
{ 
	IConvertible ic = value as IConvertible; 
	
	if (ic != null)
		return ic.ToString(provider); 
		
	IFormattable formattable = value as IFormattable;
	
	if (formattable != null)
		return formattable.ToString(null, provider);
		
	return value == null ? String.Empty : value.ToString(); 
}
</pre></p>
<p>When a string is passed to the <code>Convert.ToString()</code>, it simply passes through:</p>
<p><pre class="brush: csharp;">
public static String ToString(String value) 
{
	Contract.Ensures(Contract.Result&lt;string&gt;() == value);
	return value; 
}
</pre></p>
<p>This is important to remember because if a <code>null</code> object is passed to the <code>Convert.ToString()</code> method, an empty string is returned.  However, if a <code>null</code> string is passed to the method, a <code>null</code> is returned.</p>
<p>The <code>as</code> operator provides a way to cast an object without throwing an exception if the cast fails.  If a cast fails, the result will be <code>null</code>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nivlam.wordpress.com/246/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nivlam.wordpress.com/246/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nivlam.wordpress.com/246/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nivlam.wordpress.com/246/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nivlam.wordpress.com/246/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nivlam.wordpress.com/246/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nivlam.wordpress.com/246/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nivlam.wordpress.com/246/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nivlam.wordpress.com/246/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nivlam.wordpress.com/246/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nivlam.wordpress.com/246/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nivlam.wordpress.com/246/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nivlam.wordpress.com/246/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nivlam.wordpress.com/246/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=malvinly.com&#038;blog=20601338&#038;post=246&#038;subd=nivlam&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://malvinly.com/2012/03/13/casting-and-converting-to-strings/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5d3dde70979847001714452779e70fc4?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=PG" medium="image">
			<media:title type="html">nivlam</media:title>
		</media:content>
	</item>
	</channel>
</rss>
